[GRASS-SVN] r30915 - in grass/trunk/gui/wxpython: . gui_modules

svn_grass at osgeo.org svn_grass at osgeo.org
Wed Apr 9 11:46:19 EDT 2008


Author: martinl
Date: 2008-04-09 11:46:19 -0400 (Wed, 09 Apr 2008)
New Revision: 30915

Modified:
   grass/trunk/gui/wxpython/gui_modules/menudata.py
   grass/trunk/gui/wxpython/gui_modules/workspace.py
   grass/trunk/gui/wxpython/gui_modules/wxgui_utils.py
   grass/trunk/gui/wxpython/wxgui.py
Log:
wxGUI: basic prototype of GRC file loader implemented (trac, #80)


Modified: grass/trunk/gui/wxpython/gui_modules/menudata.py
===================================================================
--- grass/trunk/gui/wxpython/gui_modules/menudata.py	2008-04-09 11:31:53 UTC (rev 30914)
+++ grass/trunk/gui/wxpython/gui_modules/menudata.py	2008-04-09 15:46:19 UTC (rev 30915)
@@ -41,6 +41,11 @@
                                  "self.OnWorkspaceLoad",
                                  ""),
 
+                                (_("Load GRC file (Tcl/Tk GUI)"),
+                                 _("Load map layers from GRC file to layer tree (not fully implemented)"),
+                                 "self.OnWorkspaceLoadGrcFile",
+                                 ""),
+
                                 (_("Save workspace"),
                                  _("Save current workspace to file"),
                                  "self.OnWorkspaceSave",

Modified: grass/trunk/gui/wxpython/gui_modules/workspace.py
===================================================================
--- grass/trunk/gui/wxpython/gui_modules/workspace.py	2008-04-09 11:31:53 UTC (rev 30914)
+++ grass/trunk/gui/wxpython/gui_modules/workspace.py	2008-04-09 15:46:19 UTC (rev 30915)
@@ -5,6 +5,7 @@
 
 Classes:
  - ProcessWorkspaceFile
+ - ProcessGrcFile
 
 (C) 2007-2008 by the GRASS Development Team
 This program is free software under the GNU General Public
@@ -16,6 +17,10 @@
 @date 2007-2008
 """
 
+import os
+
+import wx
+
 ### for gxw (workspace file) parsering
 # xmlproc not available on Mac OS
 # from xml.parsers.xmlproc import xmlproc
@@ -144,3 +149,243 @@
         if self.inValue:
             self.value += ch
 
+class ProcessGrcFile(object):
+    def __init__(self, filename):
+        """Process GRC file"""
+        self.filename = filename
+
+        # elements
+        self.inGroup = False
+        self.inRaster = False
+        self.inVector = False
+
+        # list of layers
+        self.layers = []
+
+        # error message
+        self.error = ''
+        self.num_error = 0
+
+    def read(self, parent):
+        """Read GRC file
+
+        @param parent parent window
+
+        @return list of map layers
+        """
+        try:
+            file = open(self.filename, "r")
+        except IOError:
+            wx.MessageBox(parent=parent,
+                          message=_("Unable to open file <%s> for reading.") % self.filename,
+                          caption=_("Error"), style=wx.OK | wx.ICON_ERROR)
+            return []
+
+        line_id = 1
+        for line in file.readlines():
+            self.process_line(line.rstrip('\n'), line_id)
+            line_id +=1
+
+        file.close()
+
+        if self.num_error > 0:
+            wx.MessageBox(parent=parent,
+                          message=_("Some lines were skipped when reading settings "
+                                    "from file <%s>.\nSee 'Command output' window for details.\n\n"
+                                    "Number of skipped lines: %d" % \
+                                        (self.filename, self.num_error)),
+                          caption=_("Warning"), style=wx.OK | wx.ICON_EXCLAMATION)
+            parent.goutput.WriteLog('Map layers loaded from GRC file <%s>' % self.filename)
+            parent.goutput.WriteLog('Skipped lines:\n%s' % self.error)
+
+        return self.layers
+
+    def process_line(self, line, line_id):
+        """Process line definition"""
+        element = self._get_element(line)
+        if element == 'Group':
+            self.groupName = self._get_value(line)
+            self.layers.append({
+                    "type"    : 'group',
+                    "name"    : self.groupName,
+                    "checked" : None,
+                    "opacity" : None,
+                    "cmd"     : None,
+                    "group"   : self.inGroup,
+                    "display" : 0 })
+            self.inGroup = True
+
+        elif element == '_check':
+            if int(self._get_value(line)) ==  1:
+                self.layers[-1]['checked'] = True
+            else:
+                self.layers[-1]['checked'] = False
+            
+        elif element == 'End':
+            if self.inRaster:
+                self.inRaster = False
+            elif self.inVector:
+                self.inVector = False
+            elif self.inGroup:
+                self.inGroup = False
+
+        elif element == 'opacity':
+            self.layers[-1]['opacity'] = float(self._get_value(line))
+
+        # raster
+        elif element == 'Raster':
+            self.inRaster = True
+            self.layers.append({
+                    "type"    : 'raster',
+                    "name"    : self._get_value(line),
+                    "checked" : None,
+                    "opacity" : None,
+                    "cmd"     : ['d.rast'],
+                    "group"   : self.inGroup,
+                    "display" : 0})
+
+        elif element == 'map' and self.inRaster:
+            self.layers[-1]['cmd'].append('map=%s' % self._get_value(line))
+            
+        elif element == 'overlay' and self.inRaster:
+            if int(self._get_value(line)) == 1:
+                self.layers[-1]['cmd'].append('-o')
+            
+        elif element == 'rastquery' and self.inRaster:
+            value = self._get_value(line)
+            if value != '':
+                self.layers[-1]['cmd'].append('catlist=%s' % value)
+            
+        elif element == 'bkcolor' and self.inRaster:
+            value = self._get_value(line)
+            if value != '':
+                self.layers[-1]['cmd'].append('bg=%s' % value)
+
+        # vector
+        elif element == 'Vector':
+            self.inVector = True
+            self.layers.append({
+                    "type"    : 'vector',
+                    "name"    : self._get_value(line),
+                    "checked" : None,
+                    "opacity" : None,
+                    "cmd"     : ['d.vect'],
+                    "group"   : self.inGroup,
+                    "display" : 0})
+
+        elif element == 'vect' and self.inVector:
+            self.layers[-1]['cmd'].append('map=%s' % self._get_value(line))
+                
+        elif element in ('display_shape',
+                         'display_cat',
+                         'display_topo',
+                         'display_dir',
+                         'display_attr',
+                         'type_point',
+                         'type_line',
+                         'type_boundary',
+                         'type_centroid',
+                         'type_area',
+                         'type_face') and self.inVector:
+            
+            if int(self._get_value(line)) == 1:
+                name = element.split('_')[0]
+                type = element.split('_')[1]
+                paramId = self._get_cmd_param_index(self.layers[-1]['cmd'], name)
+                if paramId == -1:
+                    self.layers[-1]['cmd'].append('%s=%s' % (name, type))
+                else:
+                    self.layers[-1]['cmd'][paramId] += ',%s' % type
+
+        elif element in ('color',
+                         'fcolor',
+                         'lcolor') and self.inVector:
+            value = self._get_value(line)
+            if value != '':
+                self.layers[-1]['cmd'].append('%s=%s' % (element,
+                                                         self._color_name_to_rgb(value)))
+
+        elif element == 'rdmcolor' and self.inVector:
+            if int(self._get_value(line)) == 1:
+                self.layers[-1]['cmd'].append('-c')
+
+        elif element == 'sqlcolor' and self.inVector:
+            if int(self._get_value(line)) == 1:
+                self.layers[-1]['cmd'].append('-a')
+
+        elif element in ('icon',
+                         'size',
+                         'layer',
+                         'xref',
+                         'yref',
+                         'lsize',
+                         'where',
+                         'minreg',
+                         'maxreg') and self.inVector:
+            value = self._get_value(line)
+            if value != '':
+                self.layers[-1]['cmd'].append('%s=%s' % (element,
+                                                         value))
+        
+        elif element == 'lwidth':
+            value = self._get_value(line)
+            if value != '':
+                self.layers[-1]['cmd'].append('width=%s' % value)
+
+        elif element == 'lfield':
+            value = self._get_value(line)
+            if value != '':
+                self.layers[-1]['cmd'].append('llayer=%s' % value)
+                                        
+        elif element == 'attribute':
+            value = self._get_value(line)
+            if value != '':
+                self.layers[-1]['cmd'].append('attrcol=%s' % value)
+
+        elif element == 'cat':
+            value = self._get_value(line)
+            if value != '':
+                self.layers[-1]['cmd'].append('cats=%s' % value)
+
+        else:
+            self.error += _(' row %d:') % line_id + line + os.linesep
+            self.num_error += 1
+
+    def _get_value(self, line):
+        """Get value of element"""
+        try:
+            return line.strip(' ').split(' ')[1].strip(' ')
+        except:
+            return ''
+
+    def _get_element(self, line):
+        """Get element tag"""
+        return line.strip(' ').split(' ')[0].strip(' ')
+
+    def _get_cmd_param_index(self, cmd, name):
+        """Get index of parameter in cmd list
+
+        @param cmd cmd list
+        @param name parameter name
+
+        @return index
+        @return -1 if not found
+        """
+        i = 0
+        for param in cmd:
+            if '=' not in param:
+                i += 1
+                continue
+            if param.split('=')[0] == name:
+                return i
+
+            i += 1
+
+        return -1
+
+    def _color_name_to_rgb(self, value):
+        """Convert color name (#) to rgb values"""
+        col = wx.NamedColour(value)
+        return str(col.Red()) + ':' + \
+            str(col.Green()) + ':' + \
+            str(col.Blue())

Modified: grass/trunk/gui/wxpython/gui_modules/wxgui_utils.py
===================================================================
--- grass/trunk/gui/wxpython/gui_modules/wxgui_utils.py	2008-04-09 11:31:53 UTC (rev 30914)
+++ grass/trunk/gui/wxpython/gui_modules/wxgui_utils.py	2008-04-09 15:46:19 UTC (rev 30915)
@@ -454,9 +454,11 @@
                     layer = self.AppendItem(parentId=self.root,
                                             text='', ct_type=1, wnd=ctrl)
                 elif lgroup is None or lgroup is True:
-                    # insert item on given position
+                    # insert item as last child
                     parent = self.GetItemParent(self.layer_selected)
-                    layer = self.InsertItem(parentId=parent, input=self.GetPrevSibling(self.layer_selected),
+                    # layer = self.InsertItem(parentId=parent, input=self.GetPrevSibling(self.layer_selected),
+                    #                        text='', ct_type=1, wnd=ctrl)
+                    layer = self.AppendItem(parentId=parent,
                                             text='', ct_type=1, wnd=ctrl)
 
             else: # group (first child of self.layer_selected)

Modified: grass/trunk/gui/wxpython/wxgui.py
===================================================================
--- grass/trunk/gui/wxpython/wxgui.py	2008-04-09 11:31:53 UTC (rev 30914)
+++ grass/trunk/gui/wxpython/wxgui.py	2008-04-09 15:46:19 UTC (rev 30915)
@@ -660,6 +660,43 @@
 
             busy.Destroy()
 
+    def OnWorkspaceLoadGrcFile(self, event):
+        """Load map layers from GRC file (Tcl/Tk GUI) into map layer tree"""
+        dlg = wx.FileDialog(parent=self, message=_("Choose GRC file to load"),
+                            defaultDir=os.getcwd(), wildcard="*.grc")
+
+        filename = ''
+        if dlg.ShowModal() == wx.ID_OK:
+            filename = dlg.GetPath()
+
+        if filename == '':
+            return
+
+        Debug.msg(4, "GMFrame.OnWorkspaceLoadGrcFile(): filename=%s" % filename)
+
+        # start new map display if no display is available
+        if not self.curr_page:
+            self.NewDisplay()
+
+        busy = wx.BusyInfo(message=_("Please wait, loading map layers into layer tree..."),
+                           parent=self)
+        wx.Yield()
+
+        for layer in workspace.ProcessGrcFile(filename).read(self):
+            maptree = self.gm_cb.GetPage(layer['display']).maptree
+            newItem = maptree.AddLayer(ltype=layer['type'],
+                                       lname=layer['name'],
+                                       lchecked=layer['checked'],
+                                       lopacity=layer['opacity'],
+                                       lcmd=layer['cmd'],
+                                       lgroup=layer['group'])
+
+            busy.Destroy()
+            
+        if maptree:
+            # reverse list of map layers
+            maptree.Map.ReverseListOfLayers()
+
     def OnWorkspaceSaveAs(self, event=None):
         """Save workspace definition to selected file"""
 



More information about the grass-commit mailing list