[GRASS-SVN] r37832 - in grass/branches/develbranch_6/gui/wxpython: . gui_modules xml

svn_grass at osgeo.org svn_grass at osgeo.org
Thu Jun 11 16:18:46 EDT 2009


Author: martinl
Date: 2009-06-11 16:18:46 -0400 (Thu, 11 Jun 2009)
New Revision: 37832

Modified:
   grass/branches/develbranch_6/gui/wxpython/gui_modules/gcmd.py
   grass/branches/develbranch_6/gui/wxpython/gui_modules/menuform.py
   grass/branches/develbranch_6/gui/wxpython/gui_modules/nviz_mapdisp.py
   grass/branches/develbranch_6/gui/wxpython/gui_modules/nviz_tools.py
   grass/branches/develbranch_6/gui/wxpython/gui_modules/utils.py
   grass/branches/develbranch_6/gui/wxpython/gui_modules/workspace.py
   grass/branches/develbranch_6/gui/wxpython/wxgui.py
   grass/branches/develbranch_6/gui/wxpython/xml/grass-gxw.dtd
Log:
wxGUI: use ElementTree for parsing workspace files
       (merge from trunk, r37826 & r37831)


Modified: grass/branches/develbranch_6/gui/wxpython/gui_modules/gcmd.py
===================================================================
--- grass/branches/develbranch_6/gui/wxpython/gui_modules/gcmd.py	2009-06-11 20:15:08 UTC (rev 37831)
+++ grass/branches/develbranch_6/gui/wxpython/gui_modules/gcmd.py	2009-06-11 20:18:46 UTC (rev 37832)
@@ -64,14 +64,14 @@
 class GException(Exception):
     """!Generic exception"""
     def __init__(self, message, title=_("Error"), parent=None):
-        self.message = message
+        self.msg = message
         self.parent = parent
         self.title = title
         
     def Show(self):
         dlg = wx.MessageDialog(parent=self.parent,
                                caption=self.title,
-                               message=self.message,
+                               message=self.msg,
                                style=wx.ICON_ERROR | wx.CENTRE)
         dlg.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass_error.ico'), wx.BITMAP_TYPE_ICO))
         if self.parent:

Modified: grass/branches/develbranch_6/gui/wxpython/gui_modules/menuform.py
===================================================================
--- grass/branches/develbranch_6/gui/wxpython/gui_modules/menuform.py	2009-06-11 20:15:08 UTC (rev 37831)
+++ grass/branches/develbranch_6/gui/wxpython/gui_modules/menuform.py	2009-06-11 20:18:46 UTC (rev 37832)
@@ -142,11 +142,6 @@
             label = _('Select Color')
     return (rgb, label)
 
-
-def normalize_whitespace(text):
-    """!Remove redundant whitespace from a string"""
-    return string.join( string.split(text), ' ')
-
 def text_beautify( someString , width=70):
     """
     Make really long texts shorter, clean up whitespace and
@@ -154,10 +149,10 @@
     """
     if width > 0:
         return escape_ampersand( string.strip(
-                os.linesep.join( textwrap.wrap( normalize_whitespace(someString), width ) ),
+                os.linesep.join( textwrap.wrap( utils.normalize_whitespace(someString), width ) ),
                 ".,;:" ) )
     else:
-        return escape_ampersand( string.strip(normalize_whitespace(someString ), ".,;:" ))
+        return escape_ampersand( string.strip(utils.normalize_whitespace(someString ), ".,;:" ))
     
 def escape_ampersand(text):
     """!Escapes ampersands with additional ampersand for GUI"""
@@ -498,7 +493,7 @@
         """!Get node text"""
         p = node.find(tag)
         if p is not None:
-            return normalize_whitespace(p.text)
+            return utils.normalize_whitespace(p.text)
         
         return default
     

Modified: grass/branches/develbranch_6/gui/wxpython/gui_modules/nviz_mapdisp.py
===================================================================
--- grass/branches/develbranch_6/gui/wxpython/gui_modules/nviz_mapdisp.py	2009-06-11 20:15:08 UTC (rev 37831)
+++ grass/branches/develbranch_6/gui/wxpython/gui_modules/nviz_mapdisp.py	2009-06-11 20:18:46 UTC (rev 37832)
@@ -35,6 +35,7 @@
 from mapdisp_window import MapWindow
 from goutput import wxCmdOutput
 from preferences import globalSettings as UserSettings
+from workspace import Nviz as NvizDefault
 
 sys.path.append(os.path.join(globalvar.ETCWXDIR, "nviz"))
 import grass6_wxnviz as wxnviz
@@ -115,7 +116,8 @@
         #
         self.view = copy.deepcopy(UserSettings.Get(group='nviz', key='view')) # copy
         self.iview = UserSettings.Get(group='nviz', key='view', internal=True)
-
+        self.nvizDefault = NvizDefault()
+        
         self.size = None
         self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
         self.Bind(wx.EVT_SIZE, self.OnSize)
@@ -442,38 +444,26 @@
             data = self.tree.GetPyData(item)[0]['nviz']
 
             if type == 'raster':
-                data[nvizType] = {}
-                for sec in ('attribute', 'draw', 'mask', 'position'):
-                    data[nvizType][sec] = {}
-
                 # reset to default properties
-                self.SetSurfaceDefaultProp(data[nvizType])
+                data[nvizType] = self.nvizDefault.SetSurfaceDefaultProp()
                         
             elif type == 'vector':
-                data['vector'] = {}
-                for sec in ('lines', 'points'):
-                    data['vector'][sec] = {}
-                
                 # reset to default properties (lines/points)
-                self.SetVectorDefaultProp(data['vector'])
+                data['vector'] = self.nvizDefault.SetVectorDefaultProp()
 
             elif type == '3d-raster':
-                data[nvizType] = {}
-                for sec in ('attribute', 'draw', 'position'):
-                    data[nvizType][sec] = {}
-                for sec in ('isosurface', 'slice'):
-                    data[nvizType][sec] = []
-
                 # reset to default properties 
-                self.SetVolumeDefaultProp(data[nvizType])
+                data[nvizType] = self.nvizDefault.SetVolumeDefaultProp()
         
         else:
-            # check data
+            # complete data (use default values)
+            if type == 'raster':
+                data['surface'] = self.nvizDefault.SetSurfaceDefaultProp()
             if type == 'vector':
                 if not data['vector']['lines']:
-                    self.SetVectorLinesDefaultProp(data['vector']['lines'])
+                    self.nvizDefault.SetVectorLinesDefaultProp(data['vector']['lines'])
                 if not data['vector']['points']:
-                    self.SetVectorPointsDefaultProp(data['vector']['points'])
+                    self.nvizDefault.SetVectorPointsDefaultProp(data['vector']['points'])
                     
             # set updates
             for sec in data.keys():
@@ -725,230 +715,6 @@
                 toolWin.page['surface']['id'] = -1
                 toolWin.page['settings']['id'] = 1
         
-    def GetDrawMode(self, mode=None, style=None, shade=None, string=False):
-        """!Get surface draw mode (value) from description/selection
-
-        @param mode,style,shade modes
-        @param string if True input parameters are strings otherwise
-        selections
-        """
-        value = 0
-        desc = {}
-
-        if string:
-            if mode is not None:
-                if mode == 'coarse':
-                    value |= wxnviz.DM_WIRE
-                elif mode == 'fine':
-                    value |= wxnviz.DM_POLY
-                else: # both
-                    value |= wxnviz.DM_WIRE_POLY
-
-            if style is not None:
-                if style == 'wire':
-                    value |= wxnviz.DM_GRID_WIRE
-                else: # surface
-                    value |= wxnviz.DM_GRID_SURF
-                    
-            if shade is not None:
-                if shade == 'flat':
-                    value |= wxnviz.DM_FLAT
-                else: # surface
-                    value |= wxnviz.DM_GOURAUD
-
-            return value
-
-        # -> string is False
-        if mode is not None:
-            if mode == 0: # coarse
-                value |= wxnviz.DM_WIRE
-                desc['mode'] = 'coarse'
-            elif mode == 1: # fine
-                value |= wxnviz.DM_POLY
-                desc['mode'] = 'fine'
-            else: # both
-                value |= wxnviz.DM_WIRE_POLY
-                desc['mode'] = 'both'
-
-        if style is not None:
-            if style == 0: # wire
-                value |= wxnviz.DM_GRID_WIRE
-                desc['style'] = 'wire'
-            else: # surface
-                value |= wxnviz.DM_GRID_SURF
-                desc['style'] = 'surface'
-
-        if shade is not None:
-            if shade == 0:
-                value |= wxnviz.DM_FLAT
-                desc['shading'] = 'flat'
-            else: # surface
-                value |= wxnviz.DM_GOURAUD
-                desc['shading'] = 'gouraud'
-        
-        return (value, desc)
-    
-    def SetSurfaceDefaultProp(self, data):
-        """!Set default surface data properties"""
-        #
-        # attributes
-        #
-        for attrb in ('shine', ):
-            data['attribute'][attrb] = {}
-            for key, value in UserSettings.Get(group='nviz', key='volume',
-                                               subkey=attrb).iteritems():
-                data['attribute'][attrb][key] = value
-            data['attribute'][attrb]['update'] = None
-        
-        #
-        # draw
-        #
-        data['draw']['all'] = False # apply only for current surface
-        for control, value in UserSettings.Get(group='nviz', key='surface', subkey='draw').iteritems():
-            if control[:3] == 'res':
-                if not data['draw'].has_key('resolution'):
-                    data['draw']['resolution'] = {}
-                if not data['draw']['resolution'].has_key('update'):
-                    data['draw']['resolution']['update'] = None
-                data['draw']['resolution'][control[4:]] = value
-                continue
-            
-            if control == 'wire-color':
-                value = str(value[0]) + ':' + str(value[1]) + ':' + str(value[2])
-            elif control in ('mode', 'style', 'shading'):
-                if not data['draw'].has_key('mode'):
-                    data['draw']['mode'] = {}
-                continue
-
-            data['draw'][control] = { 'value' : value }
-            data['draw'][control]['update'] = None
-            
-        value, desc = self.GetDrawMode(UserSettings.Get(group='nviz', key='surface', subkey=['draw', 'mode']),
-                                       UserSettings.Get(group='nviz', key='surface', subkey=['draw', 'style']),
-                                       UserSettings.Get(group='nviz', key='surface', subkey=['draw', 'shading']))
-
-        data['draw']['mode'] = { 'value' : value,
-                                 'desc' : desc, 
-                                 'update': None }
-
-    def SetVolumeDefaultProp(self, data):
-        """!Set default volume data properties"""
-        #
-        # draw
-        #
-        for control, value in UserSettings.Get(group='nviz', key='volume', subkey='draw').iteritems():
-            if control == 'mode':
-                continue
-            if control == 'shading':
-                sel = UserSettings.Get(group='nviz', key='surface', subkey=['draw', 'shading'])
-                value, desc = self.GetDrawMode(shade=sel, string=False)
-
-                data['draw']['shading'] = { 'value' : value,
-                                            'desc' : desc['shading'] }
-            elif control == 'mode':
-                sel = UserSettings.Get(group='nviz', key='volume', subkey=['draw', 'mode'])
-                if sel == 0:
-                    desc = 'isosurface'
-                else:
-                    desc = 'slice'
-                data['draw']['mode'] = { 'value' : sel,
-                                         'desc' : desc, }
-            else:
-                data['draw'][control] = { 'value' : value }
-
-            if not data['draw'][control].has_key('update'):
-                data['draw'][control]['update'] = None
-        
-        #
-        # isosurface attributes
-        #
-        for attrb in ('shine', ):
-            data['attribute'][attrb] = {}
-            for key, value in UserSettings.Get(group='nviz', key='volume',
-                                               subkey=attrb).iteritems():
-                data['attribute'][attrb][key] = value
-        
-    def SetVectorDefaultProp(self, data):
-        """!Set default vector data properties"""
-        self.SetVectorLinesDefaultProp(data['lines'])
-        self.SetVectorPointsDefaultProp(data['points'])
-
-    def SetVectorLinesDefaultProp(self, data):
-        """!Set default vector properties -- lines"""
-        # width
-        data['width'] = {'value' : UserSettings.Get(group='nviz', key='vector',
-                                                    subkey=['lines', 'width']) }
-        
-        # color
-        value = UserSettings.Get(group='nviz', key='vector',
-                                 subkey=['lines', 'color'])
-        color = str(value[0]) + ':' + str(value[1]) + ':' + str(value[2])
-        data['color'] = { 'value' : color }
-
-        # mode
-        if UserSettings.Get(group='nviz', key='vector',
-                            subkey=['lines', 'flat']):
-            type = 'flat'
-            map  = None
-        else:
-            rasters = self.GetLayerNames('raster')
-            if len(rasters) > 0:
-                type = 'surface'
-                map  = rasters[0]
-            else:
-                type = 'flat'
-                map = None
-
-        data['mode'] = {}
-        data['mode']['type'] = type
-        data['mode']['update'] = None
-        if map:
-            data['mode']['surface'] = map
-
-        # height
-        data['height'] = { 'value' : UserSettings.Get(group='nviz', key='vector',
-                                                      subkey=['lines', 'height']) }
-
-        if data.has_key('object'):
-            for attrb in ('color', 'width', 'mode', 'height'):
-                data[attrb]['update'] = None
-        
-    def SetVectorPointsDefaultProp(self, data):
-        """!Set default vector properties -- points"""
-        # size
-        data['size'] = { 'value' : UserSettings.Get(group='nviz', key='vector',
-                                                    subkey=['points', 'size']) }
-
-        # width
-        data['width'] = { 'value' : UserSettings.Get(group='nviz', key='vector',
-                                                     subkey=['points', 'width']) }
-
-        # marker
-        data['marker'] = { 'value' : UserSettings.Get(group='nviz', key='vector',
-                                                      subkey=['points', 'marker']) }
-
-        # color
-        value = UserSettings.Get(group='nviz', key='vector',
-                                 subkey=['points', 'color'])
-        color = str(value[0]) + ':' + str(value[1]) + ':' + str(value[2])
-        data['color'] = { 'value' : color }
-
-        # mode
-        data['mode'] = { 'type' : 'surface',
-                         'surface' : '', }
-        rasters = self.GetLayerNames('raster')
-        if len(rasters) > 0:
-            data['mode']['surface'] = rasters[0]
-        
-        # height
-        data['height'] = { 'value' : UserSettings.Get(group='nviz', key='vector',
-                                                      subkey=['points', 'height']) }
-
-        if data.has_key('object'):
-            for attrb in ('size', 'width', 'marker',
-                          'color', 'surface', 'height'):
-                data[attrb]['update'] = None
-        
     def Reset(self):
         """!Reset (unload data)"""
         for item in self.layers:
@@ -1080,10 +846,10 @@
         if data['draw']['mode'].has_key('update'):
             if data['draw']['mode']['value'] < 0: # need to calculate
                 data['draw']['mode']['value'] = \
-                    self.GetDrawMode(mode=data['draw']['mode']['desc']['mode'],
-                                        style=data['draw']['mode']['desc']['style'],
-                                        shade=data['draw']['mode']['desc']['shading'],
-                                        string=True)
+                    self.nvizDefault.GetDrawMode(mode=data['draw']['mode']['desc']['mode'],
+                                                 style=data['draw']['mode']['desc']['style'],
+                                                 shade=data['draw']['mode']['desc']['shading'],
+                                                 string=True)
             style = data['draw']['mode']['value']
             if data['draw']['all']:
                 self.nvizClass.SetSurfaceStyle(-1, style)
@@ -1120,8 +886,8 @@
         if data['draw']['shading'].has_key('update'):
             if data['draw']['shading']['value'] < 0: # need to calculate
                 data['draw']['shading']['value'] = \
-                    self.GetDrawMode(shade=data['draw']['shading'],
-                                     string=False)
+                    self.nvizDefault.GetDrawMode(shade=data['draw']['shading'],
+                                                 string=False)
             data['draw']['shading'].pop('update')
         
         #

Modified: grass/branches/develbranch_6/gui/wxpython/gui_modules/nviz_tools.py
===================================================================
--- grass/branches/develbranch_6/gui/wxpython/gui_modules/nviz_tools.py	2009-06-11 20:15:08 UTC (rev 37831)
+++ grass/branches/develbranch_6/gui/wxpython/gui_modules/nviz_tools.py	2009-06-11 20:18:46 UTC (rev 37832)
@@ -1703,7 +1703,7 @@
 
         shade = self.FindWindowById(self.win['surface']['draw']['shading']).GetSelection()
 
-        value, desc = self.mapWindow.GetDrawMode(mode, style, shade)
+        value, desc = self.mapWindow.nvizDefault.GetDrawMode(mode, style, shade)
 
         return value, desc
 

Modified: grass/branches/develbranch_6/gui/wxpython/gui_modules/utils.py
===================================================================
--- grass/branches/develbranch_6/gui/wxpython/gui_modules/utils.py	2009-06-11 20:15:08 UTC (rev 37831)
+++ grass/branches/develbranch_6/gui/wxpython/gui_modules/utils.py	2009-06-11 20:18:46 UTC (rev 37832)
@@ -17,6 +17,7 @@
 import os
 import sys
 import platform
+import string
 
 import globalvar
 grassPath = os.path.join(globalvar.ETCDIR, "python")
@@ -31,6 +32,10 @@
     sys.path.append(compatPath)
     import subprocess
 
+def normalize_whitespace(text):
+    """!Remove redundant whitespace from a string"""
+    return string.join( string.split(text), ' ')
+
 def GetTempfile(pref=None):
     """
     Creates GRASS temporary file using defined prefix.

Modified: grass/branches/develbranch_6/gui/wxpython/gui_modules/workspace.py
===================================================================
--- grass/branches/develbranch_6/gui/wxpython/gui_modules/workspace.py	2009-06-11 20:15:08 UTC (rev 37831)
+++ grass/branches/develbranch_6/gui/wxpython/gui_modules/workspace.py	2009-06-11 20:18:46 UTC (rev 37832)
@@ -1,10 +1,11 @@
-"""
+"""!
 @package workspace.py
 
 @brief Open/save workspace definition file
 
 Classes:
  - ProcessWorkspaceFile
+ - Nviz
  - WriteWorkspaceFile
  - ProcessGrcFile
 
@@ -17,6 +18,7 @@
 """
 
 import os
+import sys
 
 import wx
 
@@ -25,322 +27,593 @@
 # from xml.parsers.xmlproc import xmlproc
 # from xml.parsers.xmlproc import xmlval
 # from xml.parsers.xmlproc import xmldtd
-import xml.sax
-import xml.sax.handler
-HandlerBase=xml.sax.handler.ContentHandler
-from xml.sax import make_parser
+try:
+    import xml.etree.ElementTree as etree
+except ImportError:
+    import elementtree.ElementTree as etree # Python <= 2.4
 
+import utils
+import globalvar
 from preferences import globalSettings as UserSettings
 
-class ProcessWorkspaceFile(HandlerBase):
-    """
-    A SAX handler for the GXW XML file, as
-    defined in grass-gxw.dtd.
-    """
-    def __init__(self):
-        self.inTag = {}
-        for tag in ('gxw', 'layer', 'task', 'parameter',
-                    'flag', 'value', 'group', 'display',
-                    'layer_manager',
-                    'nviz',
-                    # surface
-                    'surface', 'attribute', 'draw', 'resolution',
-                    'wire_color', 'position', 'x', 'y', 'z',
-                    # vector lines
-                    'vlines', 'color', 'width', 'mode',
-                    'map', 'height',
-                    # vector points
-                    'vpoints', 'size'):
-            self.inTag[tag] = False
+sys.path.append(os.path.join(globalvar.ETCWXDIR, "nviz"))
+try:
+    import grass6_wxnviz as wxnviz
+except ImportError:
+    wxnviz = None
 
+class ProcessWorkspaceFile():
+    def __init__(self, tree):
+        """!A ElementTree handler for the GXW XML file, as defined in
+        grass-gxw.dtd.
+        """
+        self.tree = tree
+        self.root = self.tree.getroot()
+        
         #
         # layer manager properties
         #
         self.layerManager = {}
-        self.layerManager['pos'] = None # window position
+        self.layerManager['pos']  = None # window position
         self.layerManager['size'] = None # window size
-
+        
+        #
         # list of mapdisplays
+        #
         self.displays = []
+        #
         # list of map layers
+        #
         self.layers = []
-
-        self.cmd    = []
+        
         self.displayIndex = -1 # first display has index '0'
-
+        
+        self.__processFile()
+        
+        self.nvizDefault = Nviz()
+        
     def __filterValue(self, value):
-        """!Translate value"""
+        """!Filter value
+        
+        @param value
+        """
         value = value.replace('&lt;', '<')
         value = value.replace('&gt;', '>')
         
         return value
+
+    def __getNodeText(self, node, tag, default = ''):
+        """!Get node text"""
+        p = node.find(tag)
+        if p is not None:
+            return utils.normalize_whitespace(p.text)
+        
+        return default
     
-    def startElement(self, name, attrs):
-        if name == 'display':
+    def __processFile(self):
+        """!Process workspace file"""
+        #
+        # layer manager
+        #
+        node_lm = self.root.find('layer_manager')
+        if node_lm is not None:
+            posAttr = node_lm.get('dim', '')
+            if posAttr:
+                posVal = map(int, posAttr.split(','))
+                try:
+                    self.layerManager['pos']  = (posVal[0], posVal[1])
+                    self.layerManager['size'] = (posVal[2], posVal[3])
+                except:
+                    pass
+        
+        #
+        # displays
+        #
+        for display in self.root.findall('display'):
             self.displayIndex += 1
-
+            
             # window position and size
-            posAttr = attrs.get('dim', '')
+            posAttr = display.get('dim', '')
             if posAttr:
                 posVal = map(int, posAttr.split(','))
                 try:
-                    pos = (posVal[0], posVal[1])
+                    pos  = (posVal[0], posVal[1])
                     size = (posVal[2], posVal[3])
                 except:
-                    pos = None
+                    pos  = None
                     size = None
             else:
-                pos = None
+                pos  = None
                 size = None
-
-            extentAttr = attrs.get('extent', '')
+            
+            extentAttr = display.get('extent', '')
             if extentAttr:
                 # w, s, e, n
                 extent = map(float, extentAttr.split(','))
             else:
                 extent = None
-
-            self.displays.append({
-                "render"         : bool(int(attrs.get('render', "0"))),
-                "mode"           : int(attrs.get('mode', 0)),
-                "showCompExtent" : bool(int(attrs.get('showCompExtent', "0"))),
-                "pos"            : pos,
-                "size"           : size,
-                "extent"         : extent,
-                "constrainRes"   : bool(int(attrs.get('constrainRes', "0")))})
             
-        elif name == 'group':
-            self.groupName    = attrs.get('name', None)
-            self.groupChecked = attrs.get('checked', None)
-            self.layers.append({
-                "type"    : 'group',
-                "name"    : self.groupName,
-                "checked" : int(self.groupChecked),
-                "opacity" : None,
-                "cmd"     : None,
-                "group"   : self.inTag['group'],
-                "display" : self.displayIndex,
-                "nviz"    : None})
+            self.displays.append( {
+                    "render"         : bool(int(display.get('render', "0"))),
+                    "mode"           : int(display.get('mode', 0)),
+                    "showCompExtent" : bool(int(display.get('showCompExtent', "0"))),
+                    "pos"            : pos,
+                    "size"           : size,
+                    "extent"         : extent,
+                    "constrainRes"   : bool(int(display.get('constrainRes', "0"))) } )
+            
+            # process all layers/groups in the display
+            self.__processLayers(display)
 
-        elif name == 'layer':
-            self.layerType     = attrs.get('type', None)
-            self.layerName     = attrs.get('name', None)
-            self.layerChecked  = attrs.get('checked', None)
-            self.layerOpacity  = attrs.get('opacity', None)
-            self.layerSelected = False
-            self.layerNviz     = None
-            self.cmd = []
+    def __processLayers(self, node):
+        """!Process layers/groups of selected display
 
-        elif name == 'task':
-            name = attrs.get('name', None)
-            self.cmd.append(name)
+        @todo Fix group flag
+        
+        @param node display tree node
+        """
+        for item in node.getchildren():
+            if item.tag == 'group':
+                # -> group
+                self.layers.append( {
+                        "type"    : 'group',
+                        "name"    : item.get('name', ''),
+                        "checked" : bool(int(item.get('checked', "0"))),
+                        "opacity" : None,
+                        "cmd"     : None,
+                        "group"   : False, #### self.inTag['group'], # ???
+                        "display" : self.displayIndex,
+                        "nviz"    : None})
+                
+            elif item.tag == 'layer':
+                cmd, selected, nviz = self.__processLayer(item)
+                
+                self.layers.append( {
+                        "type"     : item.get('type', None),
+                        "name"     : item.get('name', None),
+                        "checked"  : bool(int(item.get('checked', "0"))),
+                        "opacity"  : float(item.get('opacity', '1.0')),
+                        "cmd"      : cmd,
+                        "group"    : False, #### self.inTag['group'], # ???
+                        "display"  : self.displayIndex,
+                        "selected" : selected,
+                        "nviz"     : nviz } )
+        
+    def __processLayer(self, layer):
+        """!Process layer item
 
-        elif name == 'parameter':
-            self.parameterName = attrs.get('name', None)
+        @param layer tree node
+        """
+        cmd = list()
+        
+        #
+        # layer attributes (task) - 2D settings
+        #
+        node_task = layer.find('task')
+        cmd.append(node_task.get('name', "unknown"))
+        
+        # flags
+        flags = ''
+        for p in node_task.findall('flag'):
+            flags += p.get('name', '')
+        cmd.append('-' + flags)
+        
+        # parameters
+        for p in node_task.findall('parameter'):
+            cmd.append('%s=%s' % (p.get('name', ''),
+                                  self.__filterValue(self.__getNodeText(p, 'value'))))
+        
+        if layer.find('selected') is not None:
+            selected = True
+        else:
+            selected = False
+        
+        #
+        # Nviz (3D settings)
+        #
+        node_nviz = layer.find('nviz')
+        if node_nviz is not None:
+            nviz = self.__processLayerNviz(node_nviz)
+        else:
+            nviz = None
+        
+        return (cmd, selected, nviz)
 
-        elif name in ('value', 'x', 'y', 'z', 'map'):
-            self.value = ''
+    def __processLayerNviz(self, node_nviz):
+        """!Process 3D layer settings
 
-        elif name == 'flag':
-            name = attrs.get('name', None)
-            self.cmd.append('-' + name)
-
-        elif name == 'selected':
-            if self.inTag['layer']:
-                self.layerSelected = True;
-
-        elif name == 'layer_manager':
-            posAttr = attrs.get('dim', '')
-            if posAttr:
-                posVal = map(int, posAttr.split(','))
+        @param node_nviz nviz node
+        """
+        # init nviz layer properties
+        nviz = {}
+        if node_nviz.find('surface') is not None: # -> raster
+            nviz['surface'] = {}
+            for sec in ('attribute', 'draw', 'mask', 'position'):
+                nviz['surface'][sec] = {}
+        elif node_nviz.find('vlines') is not None or \
+                node_nviz.find('vpoints') is not None: # -> vector
+            nviz['vector'] = {}
+            for sec in ('lines', 'points'):
+                nviz['vector'][sec] = {}
+        
+        if nviz.has_key('surface'):
+            node_surface = node_nviz.find('surface')
+            # attributes
+            for attrb in node_surface.findall('attribute'):
+                tagName = str(attrb.tag)
+                attrbName = attrb.get('name', '')
+                dc = nviz['surface'][tagName][attrbName] = {}
+                if attrb.get('map', '0') == '0':
+                    dc['map'] = False
+                else:
+                    dc['map'] = True
+                value = self.__getNodeText(attrb, 'value')
                 try:
-                    self.layerManager['pos'] = (posVal[0], posVal[1])
-                    self.layerManager['size'] = (posVal[2], posVal[3])
-                except:
-                    pass
+                    dc['value'] = int(value)
+                except ValueError:
+                    try:
+                        dc['value'] = float(value)
+                    except ValueError:
+                        dc['value'] = str(value)
+            
+            # draw
+            node_draw = node_surface.find('draw')
+            if node_draw is not None:
+                tagName = str(node_draw.tag)
+                nviz['surface'][tagName]['all'] = False
+                nviz['surface'][tagName]['mode'] = {}
+                nviz['surface'][tagName]['mode']['value'] = -1 # to be calculated
+                nviz['surface'][tagName]['mode']['desc'] = {}
+                nviz['surface'][tagName]['mode']['desc']['shading'] = \
+                    str(node_draw.get('shading', ''))
+                nviz['surface'][tagName]['mode']['desc']['style'] = \
+                    str(node_draw.get('style', ''))
+                nviz['surface'][tagName]['mode']['desc']['mode'] = \
+                    str(node_draw.get('mode', ''))
+                
+                # resolution
+                for node_res in node_draw.findall('resolution'):
+                    resType = str(node_res.get('type', ''))
+                    if not nviz['surface']['draw'].has_key('resolution'):
+                        nviz['surface']['draw']['resolution'] = {}
+                    value = int(self.__getNodeText(node_res, 'value'))
+                    nviz['surface']['draw']['resolution'][resType] = value
+                
+                # wire-color
+                node_wire_color = node_draw.find('wire_color')
+                if node_wire_color is not None:
+                    nviz['surface']['draw']['wire-color'] = {}
+                    value = str(self.__getNodeText(node_wire_color, 'value'))
+                    nviz['surface']['draw']['wire-color']['value'] = value
+                
+            # position
+            node_pos = node_surface.find('position')
+            if node_pos is not None:
+                dc = self.nviz['surface']['position'] = {}
+                for coor in ['x', 'y', 'z']:
+                    node = node_pos.find(coor)
+                    if node is None:
+                        continue
+                    value = int(self.__getNodeText(node, 'value'))
+                    dc[coor] = value
+            
+        elif nviz.has_key('vector'):
+            # vpoints
+            node_vpoints = node_nviz.find('vpoints')
+            if node_vpoints is not None:
+                marker = str(node_vpoints.get('marker', ''))
+                markerId = list(UserSettings.Get(group='nviz', key='vector',
+                                                 subkey=['points', 'marker'], internal=True)).index(marker)
+                nviz['vector']['points']['marker'] = markerId
+                
+                node_mode = node_vpoints.find('mode')
+                if node_mode is not None:
+                    nviz['vector']['points']['mode'] = {}
+                    nviz['vector']['points']['mode']['type'] = str(node_mode.get('type', ''))
+                    nviz['vector']['points']['mode']['surface'] = ''
+                    
+                    # map
+                    nviz['vector']['points']['mode']['surface'] = \
+                        self.__processLayerNvizNode(node_vpoints, 'map', str)
+                
+                # color
+                self.__processLayerNvizNode(node_vpoints, 'color', str,
+                                            nviz['vector']['points'])
+                
+                # width
+                self.__processLayerNvizNode(node_vpoints, 'width', int,
+                                            nviz['vector']['points'])
+                
+                # height
+                self.__processLayerNvizNode(node_vpoints, 'height', int,
+                                            nviz['vector']['points'])
+                
+                # height
+                self.__processLayerNvizNode(node_vpoints, 'size', int,
+                                            nviz['vector']['points'])
+            
+            # vlines
+            node_vlines = node_nviz.find('vlines')
+            if node_vlines is not None:
+                node_mode = node_vlines.find('mode')
+                if node_mode is not None:
+                    nviz['vector']['lines']['mode'] = {}
+                    nviz['vector']['lines']['mode']['type'] = str(node_mode.get('type', ''))
+                    nviz['vector']['lines']['mode']['surface'] = ''
+                    
+                    # map
+                    nviz['vector']['lines']['mode']['surface'] = \
+                        self.__processLayerNvizNode(node_mode, 'map', str)
+                
+                # color
+                self.__processLayerNvizNode(node_vlines, 'color', str,
+                                            nviz['vector']['lines'])
+                
+                # width
+                self.__processLayerNvizNode(node_vlines, 'width', int,
+                                            nviz['vector']['lines'])
+                
+                # height
+                self.__processLayerNvizNode(node_vlines, 'height', int,
+                                            nviz['vector']['lines'])
+            
+        return nviz
+    
+    def __processLayerNvizNode(self, node, tag, cast, dc = None):
+        """!Process given tag nviz/vector"""
+        node_tag = node.find(tag)
+        if node_tag is not None:
+            value = cast(self.__getNodeText(node_tag, 'value'))
+            if dc:
+                dc[tag] = dict()
+                dc[tag]['value'] = value
             else:
-                pass
-
+                return value
+    
+class Nviz:
+    def __init__(self):
+        """Default 3D settings"""
+        pass
+    
+    def SetSurfaceDefaultProp(self):
+        """Set default surface data properties"""
+        data = dict()
+        for sec in ('attribute', 'draw', 'mask', 'position'):
+            data[sec] = {}
+        
         #
-        # Nviz section
+        # attributes
         #
-        elif name == 'nviz':
-            # init nviz layer properties
-            self.layerNviz = {}
-            if self.layerType == 'raster':
-                self.layerNviz['surface'] = {}
-                for sec in ('attribute', 'draw', 'mask', 'position'):
-                    self.layerNviz['surface'][sec] = {}
-            elif self.layerType == 'vector':
-                self.layerNviz['vector'] = {}
-                for sec in ('lines', 'points'):
-                    self.layerNviz['vector'][sec] = {}
+        for attrb in ('shine', ):
+            data['attribute'][attrb] = {}
+            for key, value in UserSettings.Get(group='nviz', key='volume',
+                                               subkey=attrb).iteritems():
+                data['attribute'][attrb][key] = value
+            data['attribute'][attrb]['update'] = None
+        
+        #
+        # draw
+        #
+        data['draw']['all'] = False # apply only for current surface
+        for control, value in UserSettings.Get(group='nviz', key='surface', subkey='draw').iteritems():
+            if control[:3] == 'res':
+                if not data['draw'].has_key('resolution'):
+                    data['draw']['resolution'] = {}
+                if not data['draw']['resolution'].has_key('update'):
+                    data['draw']['resolution']['update'] = None
+                data['draw']['resolution'][control[4:]] = value
+                continue
+            
+            if control == 'wire-color':
+                value = str(value[0]) + ':' + str(value[1]) + ':' + str(value[2])
+            elif control in ('mode', 'style', 'shading'):
+                if not data['draw'].has_key('mode'):
+                    data['draw']['mode'] = {}
+                continue
 
-        elif name == 'attribute':
-            if self.inTag['nviz'] and self.inTag['surface']:
-                tagName = str(name)
-                attrbName = str(attrs.get('name', ''))
-                self.layerNviz['surface'][tagName][attrbName] = {}
-                if attrs.get('map', '0') == '0':
-                    self.layerNviz['surface'][tagName][attrbName]['map'] = False
-                else:
-                    self.layerNviz['surface'][tagName][attrbName]['map'] = True
+            data['draw'][control] = { 'value' : value }
+            data['draw'][control]['update'] = None
+            
+        value, desc = self.GetDrawMode(UserSettings.Get(group='nviz', key='surface', subkey=['draw', 'mode']),
+                                       UserSettings.Get(group='nviz', key='surface', subkey=['draw', 'style']),
+                                       UserSettings.Get(group='nviz', key='surface', subkey=['draw', 'shading']))
 
-                self.refAttribute = self.layerNviz['surface'][tagName][attrbName]
+        data['draw']['mode'] = { 'value' : value,
+                                 'desc' : desc, 
+                                 'update': None }
         
-        elif name == 'draw':
-            if self.inTag['nviz'] and self.inTag['surface']:
-                tagName = str(name)
-                self.layerNviz['surface'][tagName]['all'] = False
-                self.layerNviz['surface'][tagName]['mode'] = {}
-                self.layerNviz['surface'][tagName]['mode']['value'] = -1 # to be calculated
-                self.layerNviz['surface'][tagName]['mode']['desc'] = {}
-                self.layerNviz['surface'][tagName]['mode']['desc']['shading'] = \
-                    str(attrs.get('shading', ''))
-                self.layerNviz['surface'][tagName]['mode']['desc']['style'] = \
-                    str(attrs.get('style', ''))
-                self.layerNviz['surface'][tagName]['mode']['desc']['mode'] = \
-                    str(attrs.get('mode', ''))
+        return data
+    
+    def SetVolumeDefaultProp(self):
+        """Set default volume data properties"""
+        data = dict()
+        for sec in ('attribute', 'draw', 'position'):
+            data[sec] = dict()
+            for sec in ('isosurface', 'slice'):
+                    data[sec] = list()
+        
+        #
+        # draw
+        #
+        for control, value in UserSettings.Get(group='nviz', key='volume', subkey='draw').iteritems():
+            if control == 'mode':
+                continue
+            if control == 'shading':
+                sel = UserSettings.Get(group='nviz', key='surface', subkey=['draw', 'shading'])
+                value, desc = self.GetDrawMode(shade=sel, string=False)
 
-        elif name == 'resolution':
-            if self.inTag['nviz'] and self.inTag['surface']:
-                self.resolutionType = str(attrs.get('type', ''))
-                if not self.layerNviz['surface']['draw'].has_key(str(name)):
-                    self.layerNviz['surface']['draw'][str(name)] = {}
+                data['draw']['shading'] = { 'value' : value,
+                                            'desc' : desc['shading'] }
+            elif control == 'mode':
+                sel = UserSettings.Get(group='nviz', key='volume', subkey=['draw', 'mode'])
+                if sel == 0:
+                    desc = 'isosurface'
+                else:
+                    desc = 'slice'
+                data['draw']['mode'] = { 'value' : sel,
+                                         'desc' : desc, }
+            else:
+                data['draw'][control] = { 'value' : value }
 
-        elif name == 'position':
-            if self.inTag['nviz'] and inTag['surface']:
-                self.layerNviz['surface']['position'] = {}
+            if not data['draw'][control].has_key('update'):
+                data['draw'][control]['update'] = None
         
-        elif name == 'mode':
-            if self.inTag['nviz']:
-                if self.inTag['vlines']:
-                    self.layerNviz['vector']['lines']['mode'] = {}
-                    self.layerNviz['vector']['lines']['mode']['type'] = str(attrs.get('type', ''))
-                    self.layerNviz['vector']['lines']['mode']['surface'] = ''
-                elif self.inTag['vpoints']:
-                    self.layerNviz['vector']['points']['mode'] = {}
-                    self.layerNviz['vector']['points']['mode']['type'] = str(attrs.get('type', ''))
-                    self.layerNviz['vector']['points']['mode']['surface'] = ''
-
-        elif name == 'vpoints':
-            if self.inTag['nviz']:
-                marker = str(attrs.get('marker', ''))
-                markerId = list(UserSettings.Get(group='nviz', key='vector',
-                                                 subkey=['points', 'marker'], internal=True)).index(marker)
-                self.layerNviz['vector']['points']['marker'] = markerId
+        #
+        # isosurface attributes
+        #
+        for attrb in ('shine', ):
+            data['attribute'][attrb] = {}
+            for key, value in UserSettings.Get(group='nviz', key='volume',
+                                               subkey=attrb).iteritems():
+                data['attribute'][attrb][key] = value
         
-        self.inTag[name] = True
+        return data
+    
+    def SetVectorDefaultProp(self):
+        """Set default vector data properties"""
+        data = dict()
+        for sec in ('lines', 'points'):
+            data[sec] = {}
         
-    def endElement(self, name):
-        if name == 'group':
-            self.groupName = self.groupChecked = None
+        self.SetVectorLinesDefaultProp(data['lines'])
+        self.SetVectorPointsDefaultProp(data['points'])
 
-        elif name == 'layer':
-            self.layers.append({
-                    "type"     : self.layerType,
-                    "name"     : self.layerName,
-                    "checked"  : int(self.layerChecked),
-                    "opacity"  : 1.0,
-                    "cmd"      : None,
-                    "group"    : self.inTag['group'],
-                    "display"  : self.displayIndex,
-                    "selected" : self.layerSelected,
-                    "nviz"     : self.layerNviz})
-            
-            if self.layerOpacity:
-                self.layers[-1]["opacity"] = float(self.layerOpacity)
-            if self.cmd:
-                self.layers[-1]["cmd"] = self.cmd
-            
-            self.layerType = self.layerName = self.Checked = \
-                self.Opacity = self.cmd = None
+        return data
+    
+    def SetVectorLinesDefaultProp(self, data):
+        """Set default vector properties -- lines"""
+        # width
+        data['width'] = {'value' : UserSettings.Get(group='nviz', key='vector',
+                                                    subkey=['lines', 'width']) }
+        
+        # color
+        value = UserSettings.Get(group='nviz', key='vector',
+                                 subkey=['lines', 'color'])
+        color = str(value[0]) + ':' + str(value[1]) + ':' + str(value[2])
+        data['color'] = { 'value' : color }
 
-        elif name == 'parameter':
-            self.cmd.append('%s=%s' % (self.parameterName,
-                                       self.__filterValue(self.value)))
-            self.parameterName = self.value = None
+        # mode
+        if UserSettings.Get(group='nviz', key='vector',
+                            subkey=['lines', 'flat']):
+            type = 'flat'
+            map  = None
+        else:
+            type = 'flat'
+            map = None
 
-        #
-        # Nviz section
-        #
-        elif name == 'attribute':
-            if self.inTag['nviz'] and self.inTag['surface']:
-                try:
-                    self.refAttribute['value'] = int(self.value)
-                except ValueError:
-                    try:
-                        self.refAttribute['value'] = float(self.value)
-                    except ValueError:
-                        self.refAttribute['value'] = str(self.value)
+        data['mode'] = {}
+        data['mode']['type'] = type
+        data['mode']['update'] = None
+        if map:
+            data['mode']['surface'] = map
 
-        elif name == 'resolution':
-            if self.inTag['nviz'] and self.inTag['surface']:
-                self.layerNviz['surface']['draw']['resolution'][self.resolutionType] = int(self.value)
-                del self.resolutionType
+        # height
+        data['height'] = { 'value' : UserSettings.Get(group='nviz', key='vector',
+                                                      subkey=['lines', 'height']) }
 
-        elif name == 'wire_color':
-            if self.inTag['nviz'] and self.inTag['surface']:
-                self.layerNviz['surface']['draw']['wire-color'] = {}
-                self.layerNviz['surface']['draw']['wire-color']['value'] = str(self.value)
+        if data.has_key('object'):
+            for attrb in ('color', 'width', 'mode', 'height'):
+                data[attrb]['update'] = None
+        
+    def SetVectorPointsDefaultProp(self, data):
+        """Set default vector properties -- points"""
+        # size
+        data['size'] = { 'value' : UserSettings.Get(group='nviz', key='vector',
+                                                    subkey=['points', 'size']) }
 
-        elif name == 'x':
-            if self.inTag['nviz'] and self.inTag['surface']:
-                self.layerNviz['surface']['position']['x'] = int(self.value)
+        # width
+        data['width'] = { 'value' : UserSettings.Get(group='nviz', key='vector',
+                                                     subkey=['points', 'width']) }
 
-        elif name == 'y':
-            if self.inTag['nviz'] and self.inTag['surface']:
-                self.layerNviz['surface']['position']['y'] = int(self.value)
+        # marker
+        data['marker'] = { 'value' : UserSettings.Get(group='nviz', key='vector',
+                                                      subkey=['points', 'marker']) }
 
-        elif name == 'z':
-            if self.inTag['nviz'] and self.inTag['surface']:
-                self.layerNviz['surface']['position']['z'] = int(self.value)
+        # color
+        value = UserSettings.Get(group='nviz', key='vector',
+                                 subkey=['points', 'color'])
+        color = str(value[0]) + ':' + str(value[1]) + ':' + str(value[2])
+        data['color'] = { 'value' : color }
+
+        # mode
+        data['mode'] = { 'type' : 'surface',
+                         'surface' : '', }
         
-        elif name == 'color':
-            if self.inTag['nviz']:
-                if self.inTag['vlines']:
-                    self.layerNviz['vector']['lines']['color'] = str(self.value)
-                elif self.inTag['vpoints']:
-                    self.layerNviz['vector']['points']['color'] = str(self.value)
-                    
-        elif name == 'width':
-            if self.inTag['nviz']:
-                if self.inTag['vlines']:
-                    self.layerNviz['vector']['lines']['width'] = int(self.value)
-                elif self.inTag['vpoints']:
-                    self.layerNviz['vector']['points']['width'] = int(self.value)
+        # height
+        data['height'] = { 'value' : UserSettings.Get(group='nviz', key='vector',
+                                                      subkey=['points', 'height']) }
 
-        elif name == 'height':
-            if self.inTag['nviz']:
-                if self.inTag['vlines']:
-                    self.layerNviz['vector']['lines']['height'] = int(self.value)
-                elif self.inTag['vpoints']:
-                    self.layerNviz['vector']['points']['height'] = int(self.value)
+        if data.has_key('object'):
+            for attrb in ('size', 'width', 'marker',
+                          'color', 'surface', 'height'):
+                data[attrb]['update'] = None
         
-        elif name == 'size':
-            if self.inTag['nviz'] and self.inTag['vpoints']:
-                self.layerNviz['vector']['points']['size'] = int(self.value)
+    def GetDrawMode(self, mode=None, style=None, shade=None, string=False):
+        """Get surface draw mode (value) from description/selection
 
-        elif name == 'map':
-            if self.inTag['nviz']:
-                if self.inTag['vlines']:
-                    self.layerNviz['vector']['lines']['mode']['surface'] = str(self.value)
-                elif self.inTag['vpoints']:
-                    self.layerNviz['vector']['points']['mode']['surface'] = str(self.value)
+        @param mode,style,shade modes
+        @param string if True input parameters are strings otherwise
+        selections
+        """
+        if not wxnviz:
+            return None
+        
+        value = 0
+        desc = {}
 
-        self.inTag[name] = False
+        if string:
+            if mode is not None:
+                if mode == 'coarse':
+                    value |= wxnviz.DM_WIRE
+                elif mode == 'fine':
+                    value |= wxnviz.DM_POLY
+                else: # both
+                    value |= wxnviz.DM_WIRE_POLY
 
-    def characters(self, ch):
-        self.my_characters(ch)
+            if style is not None:
+                if style == 'wire':
+                    value |= wxnviz.DM_GRID_WIRE
+                else: # surface
+                    value |= wxnviz.DM_GRID_SURF
+                    
+            if shade is not None:
+                if shade == 'flat':
+                    value |= wxnviz.DM_FLAT
+                else: # surface
+                    value |= wxnviz.DM_GOURAUD
 
-    def my_characters(self, ch):
-        if self.inTag['value'] or \
-                self.inTag['x'] or \
-                self.inTag['y'] or \
-                self.inTag['z'] or \
-                self.inTag['map']:
-            self.value += ch
+            return value
 
+        # -> string is False
+        if mode is not None:
+            if mode == 0: # coarse
+                value |= wxnviz.DM_WIRE
+                desc['mode'] = 'coarse'
+            elif mode == 1: # fine
+                value |= wxnviz.DM_POLY
+                desc['mode'] = 'fine'
+            else: # both
+                value |= wxnviz.DM_WIRE_POLY
+                desc['mode'] = 'both'
+
+        if style is not None:
+            if style == 0: # wire
+                value |= wxnviz.DM_GRID_WIRE
+                desc['style'] = 'wire'
+            else: # surface
+                value |= wxnviz.DM_GRID_SURF
+                desc['style'] = 'surface'
+
+        if shade is not None:
+            if shade == 0:
+                value |= wxnviz.DM_FLAT
+                desc['shading'] = 'flat'
+            else: # surface
+                value |= wxnviz.DM_GOURAUD
+                desc['shading'] = 'gouraud'
+        
+        return (value, desc)
+    
 class WriteWorkspaceFile(object):
     """!Generic class for writing workspace file"""
     def __init__(self, lmgr, file):
@@ -591,7 +864,7 @@
                 else:
                     self.file.write('%s<%s>\n' % (' ' * self.indent, name))
                     self.indent += 4
-                    self.file.write('%s<value>%s</value>\n' % (' ' * self.indent, data[attrb][name]))
+                    self.file.write('%s<value>%s</value>\n' % (' ' * self.indent, data[attrb][name]['value']))
                     self.indent -= 4
                     self.file.write('%s</%s>\n' % (' ' * self.indent, name))
             self.indent -= 4

Modified: grass/branches/develbranch_6/gui/wxpython/wxgui.py
===================================================================
--- grass/branches/develbranch_6/gui/wxpython/wxgui.py	2009-06-11 20:15:08 UTC (rev 37831)
+++ grass/branches/develbranch_6/gui/wxpython/wxgui.py	2009-06-11 20:18:46 UTC (rev 37832)
@@ -30,10 +30,10 @@
 import platform
 
 ### XML 
-import xml.sax
-import xml.sax.handler
-HandlerBase=xml.sax.handler.ContentHandler
-from xml.sax import make_parser
+try:
+    import xml.etree.ElementTree as etree
+except ImportError:
+    import elementtree.ElementTree as etree # Python <= 2.4
 
 ### i18N
 import gettext
@@ -591,150 +591,104 @@
     def LoadWorkspaceFile(self, filename):
         """!Load layer tree definition stored in GRASS Workspace XML file (gxw)
 
-        Return True on success
-        Return False on error"""
-
+        @todo Validate against DTD
+        
+        @return True on success
+        @return False on error
+        """
         # dtd
         dtdFilename = os.path.join(globalvar.ETCWXDIR, "xml", "grass-gxw.dtd")
-
-        # validate xml agains dtd
-        #         dtd = xmldtd.load_dtd(dtdFilename)
-        #         parser = xmlproc.XMLProcessor()
-        #         parser.set_application(xmlval.ValidatingApp(dtd, parser))
-        #         parser.dtd = dtd
-        #         parser.ent = dtd
-        #         try:
-        #             # TODO: set_error_handler(self,err)
-        #             parser.parse_resource(filename)
-        #         except:
-        #             dlg = wx.MessageDialog(self, _("Unable to open workspace file <%s>. "
-        #                                            "It is not valid GRASS Workspace File.") % filename,
-        #                                    _("Error"), wx.OK | wx.ICON_ERROR)
-        #             dlg.ShowModal()
-        #             dlg.Destroy()
-        #             return False
-
-        # read file and fix patch to dtd
+        
+        # parse workspace file
         try:
-            file = open(filename, "r")
+            gxwXml = workspace.ProcessWorkspaceFile(etree.parse(filename))
+        except Exception, err:
+            raise gcmd.GStdError(_("Reading workspace file <%s> failed.\n"
+                                   "Invalid file, unable to parse XML document."
+                                   "\n\n%s") % (filename, err),
+                                 parent = self)
+        
+        busy = wx.BusyInfo(message=_("Please wait, loading workspace..."),
+                           parent=self)
+        wx.Yield()
 
-            fileStream = ''.join(file.readlines())
-            p = re.compile('(grass-gxw.dtd)')
-            p.search(fileStream)
-            if platform.system() == 'Windows':
-                # FIXME mixing '\' and '/' causes error in p.sub
-                dtdFilename = dtdFilename.replace("\\", "/") 
-            fileStream = p.sub(dtdFilename, fileStream)
-
-            # sax
-            gxwXml = workspace.ProcessWorkspaceFile()
+        #
+        # load layer manager window properties
+        #
+        if UserSettings.Get(group='workspace', key='posManager', subkey='enabled') is False:
+            if gxwXml.layerManager['pos']:
+                self.SetPosition(gxwXml.layerManager['pos'])
+            if gxwXml.layerManager['size']:
+                self.SetSize(gxwXml.layerManager['size'])
+        
+        #
+        # start map displays first (list of layers can be empty)
+        #
+        displayId = 0
+        mapdisplay = []
+        for display in gxwXml.displays:
+            mapdisplay.append(self.NewDisplay(show=False))
+            maptree = self.gm_cb.GetPage(displayId).maptree
             
-            try:
-                xml.sax.parseString(fileStream, gxwXml)
-            except xml.sax.SAXParseException, err:
-                raise gcmd.GStdError(_("Reading workspace file <%s> failed. "
-                                       "Invalid file, unable to parse XML document.") % filename + \
-                                         "\n\n%s" % err,
-                                     parent=self)
-            except ValueError, err:
-                raise gcmd.GStdError(_("Reading workspace file <%s> failed. "
-                                       "Invalid file, unable to parse XML document.") % filename + \
-                                         "\n\n%s" % err,
-                                     parent=self)
-
-            busy = wx.BusyInfo(message=_("Please wait, loading workspace..."),
-                               parent=self)
-            wx.Yield()
-
-            #
-            # load layer manager window properties
-            #
-            if UserSettings.Get(group='workspace', key='posManager', subkey='enabled') is False:
-                if gxwXml.layerManager['pos']:
-                    self.SetPosition(gxwXml.layerManager['pos'])
-                if gxwXml.layerManager['size']:
-                    self.SetSize(gxwXml.layerManager['size'])
-
-            #
-            # start map displays first (list of layers can be empty)
-            #
-            displayId = 0
-            mapdisplay = []
-            for display in gxwXml.displays:
-                mapdisplay.append(self.NewDisplay(show=False))
-                maptree = self.gm_cb.GetPage(displayId).maptree
-
-                # set windows properties
-                mapdisplay[-1].SetProperties(render=display['render'],
-                                             mode=display['mode'],
-                                             showCompExtent=display['showCompExtent'],
-                                             constrainRes=display['constrainRes'])
-
-                # set position and size of map display
-                if UserSettings.Get(group='workspace', key='posDisplay', subkey='enabled') is False:
-                    if display['pos']:
-                        mapdisplay[-1].SetPosition(display['pos'])
-                    if display['size']:
-                        mapdisplay[-1].SetSize(display['size'])
-
-                # set extent if defined
-                if display['extent']:
-                    w, s, e, n = display['extent']
-                    maptree.Map.region = maptree.Map.GetRegion(w=w, s=s, e=e, n=n)
+            # set windows properties
+            mapdisplay[-1].SetProperties(render=display['render'],
+                                         mode=display['mode'],
+                                         showCompExtent=display['showCompExtent'],
+                                         constrainRes=display['constrainRes'])
+            
+            # set position and size of map display
+            if UserSettings.Get(group='workspace', key='posDisplay', subkey='enabled') is False:
+                if display['pos']:
+                    mapdisplay[-1].SetPosition(display['pos'])
+                if display['size']:
+                    mapdisplay[-1].SetSize(display['size'])
                     
-                mapdisplay[-1].Show()
-
-                displayId += 1
+            # set extent if defined
+            if display['extent']:
+                w, s, e, n = display['extent']
+                maptree.Map.region = maptree.Map.GetRegion(w=w, s=s, e=e, n=n)
+                
+            mapdisplay[-1].Show()
+            
+            displayId += 1
     
-            maptree = None 
-            selected = [] # list of selected layers
-            # 
-            # load list of map layers
-            #
-            for layer in gxwXml.layers:
-                display = layer['display']
-                maptree = self.gm_cb.GetPage(display).maptree
-
-                newItem = maptree.AddLayer(ltype=layer['type'],
-                                           lname=layer['name'],
-                                           lchecked=layer['checked'],
-                                           lopacity=layer['opacity'],
-                                           lcmd=layer['cmd'],
-                                           lgroup=layer['group'],
-                                           lnviz=layer['nviz'])
+        maptree = None 
+        selected = [] # list of selected layers
+        # 
+        # load list of map layers
+        #
+        for layer in gxwXml.layers:
+            display = layer['display']
+            maptree = self.gm_cb.GetPage(display).maptree
+            
+            newItem = maptree.AddLayer(ltype=layer['type'],
+                                       lname=layer['name'],
+                                       lchecked=layer['checked'],
+                                       lopacity=layer['opacity'],
+                                       lcmd=layer['cmd'],
+                                       lgroup=layer['group'],
+                                       lnviz=layer['nviz'])
+            
+            if layer.has_key('selected'):
+                if layer['selected']:
+                    selected.append((maptree, newItem))
+                else:
+                    maptree.SelectItem(newItem, select=False)
+            
+        for maptree, layer in selected:
+            if not maptree.IsSelected(layer):
+                maptree.SelectItem(layer, select=True)
+                maptree.layer_selected = layer
                 
-                # tag 'selected' added 2008/04
-                if layer.has_key('selected'):
-                    if layer['selected']:
-                        selected.append((maptree, newItem))
-                    else:
-                        maptree.SelectItem(newItem, select=False)
-                    
-            for maptree, layer in selected:
-                if not maptree.IsSelected(layer):
-                    maptree.SelectItem(layer, select=True)
-                    maptree.layer_selected = layer
+        busy.Destroy()
+        
+        if maptree:
+            # reverse list of map layers
+            maptree.Map.ReverseListOfLayers()
 
-            busy.Destroy()
-            
-            if maptree:
-                # reverse list of map layers
-                maptree.Map.ReverseListOfLayers()
+        for mdisp in mapdisplay:
+            mdisp.MapWindow2D.UpdateMap()
 
-            for mdisp in mapdisplay:
-                mdisp.MapWindow2D.UpdateMap()
-
-            file.close()
-        except IOError, err:
-            wx.MessageBox(parent=self,
-                          message="%s <%s>. %s%s" % (_("Unable to read workspace file"),
-                                                     filename, os.linesep, err),
-                          caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
-            return False
-        except gcmd.GStdError, e:
-            print e
-            return False
-                               
         return True
 
     def OnWorkspaceLoad(self, event=None):

Modified: grass/branches/develbranch_6/gui/wxpython/xml/grass-gxw.dtd
===================================================================
--- grass/branches/develbranch_6/gui/wxpython/xml/grass-gxw.dtd	2009-06-11 20:15:08 UTC (rev 37831)
+++ grass/branches/develbranch_6/gui/wxpython/xml/grass-gxw.dtd	2009-06-11 20:18:46 UTC (rev 37832)
@@ -34,8 +34,10 @@
 <!ATTLIST display  render	   (0 | 1) #IMPLIED>
 <!ATTLIST display  mode            (0 | 1 | 2 | 3 | 4 | 5 | 6) #IMPLIED>
 <!ATTLIST display  showCompExtent  (0 | 1) #IMPLIED>
+<!ATTLIST display  constrainRes    (0 | 1) #IMPLIED>
 <!-- window dimenstion (x, y (ur), width, heigth -->
 <!ATTLIST display  dim             CDATA   #IMPLIED>
+<!ATTLIST display  extent          CDATA   #IMPLIED>
 
 <!--    group of map layers
 -->



More information about the grass-commit mailing list