[GRASS-SVN] r37826 - in grass/trunk/gui/wxpython: . gui_modules xml
svn_grass at osgeo.org
svn_grass at osgeo.org
Thu Jun 11 12:19:44 EDT 2009
Author: martinl
Date: 2009-06-11 12:19:43 -0400 (Thu, 11 Jun 2009)
New Revision: 37826
Modified:
grass/trunk/gui/wxpython/gui_modules/gcmd.py
grass/trunk/gui/wxpython/gui_modules/menuform.py
grass/trunk/gui/wxpython/gui_modules/utils.py
grass/trunk/gui/wxpython/gui_modules/workspace.py
grass/trunk/gui/wxpython/wxgui.py
grass/trunk/gui/wxpython/xml/grass-gxw.dtd
Log:
wxGUI: use ElementTree for parsing workspace files
Modified: grass/trunk/gui/wxpython/gui_modules/gcmd.py
===================================================================
--- grass/trunk/gui/wxpython/gui_modules/gcmd.py 2009-06-11 15:57:00 UTC (rev 37825)
+++ grass/trunk/gui/wxpython/gui_modules/gcmd.py 2009-06-11 16:19:43 UTC (rev 37826)
@@ -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/trunk/gui/wxpython/gui_modules/menuform.py
===================================================================
--- grass/trunk/gui/wxpython/gui_modules/menuform.py 2009-06-11 15:57:00 UTC (rev 37825)
+++ grass/trunk/gui/wxpython/gui_modules/menuform.py 2009-06-11 16:19:43 UTC (rev 37826)
@@ -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/trunk/gui/wxpython/gui_modules/utils.py
===================================================================
--- grass/trunk/gui/wxpython/gui_modules/utils.py 2009-06-11 15:57:00 UTC (rev 37825)
+++ grass/trunk/gui/wxpython/gui_modules/utils.py 2009-06-11 16:19:43 UTC (rev 37826)
@@ -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/trunk/gui/wxpython/gui_modules/workspace.py
===================================================================
--- grass/trunk/gui/wxpython/gui_modules/workspace.py 2009-06-11 15:57:00 UTC (rev 37825)
+++ grass/trunk/gui/wxpython/gui_modules/workspace.py 2009-06-11 16:19:43 UTC (rev 37826)
@@ -1,4 +1,4 @@
-"""
+"""!
@package workspace.py
@brief Open/save workspace definition file
@@ -25,322 +25,333 @@
# 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
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
-
+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()
+
def __filterValue(self, value):
- """!Translate value"""
+ """!Filter value
+
+ @param value
+ """
value = value.replace('<', '<')
value = value.replace('>', '>')
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"))) } )
+
+ 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)
+ @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)
+ #
+ 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
- elif name in ('value', 'x', 'y', 'z', 'map'):
- self.value = ''
+ #
+ # 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 == 'flag':
- name = attrs.get('name', None)
- self.cmd.append('-' + name)
+ def __processLayerNviz(self, node_nviz):
+ """!Process 3D layer settings
- 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(','))
- try:
- self.layerManager['pos'] = (posVal[0], posVal[1])
- self.layerManager['size'] = (posVal[2], posVal[3])
- except:
- pass
- else:
- pass
-
- #
- # Nviz section
- #
- 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'] = {}
+ @param node_nviz nviz node
+ """
+ # init nviz layer properties
+ nviz = {}
+ node = node_nviz.find('surface')
+ if node: # -> raster
+ nviz['surface'] = {}
+ for sec in ('attribute', 'draw', 'mask', 'position'):
+ nviz['surface'][sec] = {}
+ else:
+ node = node_nviz.find('vector')
+ if node: # -> vector
+ nviz['vector'] = {}
for sec in ('lines', 'points'):
- self.layerNviz['vector'][sec] = {}
-
- 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
+ nviz['vector'][sec] = {}
+
+ if nviz.has_key('surface'):
+ # attributes
+ for attrb in node.find_all('attributes'):
+ tagName = str(attrb.tag)
+ attrbName = attrb.get('name', '')
+ self.nviz['surface'][tagName][attrbName] = {}
+ if attrb.get('map', '0') == '0':
+ self.nviz['surface'][tagName][attrbName]['map'] = False
else:
- self.layerNviz['surface'][tagName][attrbName]['map'] = True
+ self.nviz['surface'][tagName][attrbName]['map'] = True
+
+ self.refAttribute = self.nviz['surface'][tagName][attrbName]
- self.refAttribute = self.layerNviz['surface'][tagName][attrbName]
-
- 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'] = \
+ # draw
+ node_draw = node.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(attrs.get('shading', ''))
- self.layerNviz['surface'][tagName]['mode']['desc']['style'] = \
+ nviz['surface'][tagName]['mode']['desc']['style'] = \
str(attrs.get('style', ''))
- self.layerNviz['surface'][tagName]['mode']['desc']['mode'] = \
+ nviz['surface'][tagName]['mode']['desc']['mode'] = \
str(attrs.get('mode', ''))
-
- 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)] = {}
-
- elif name == 'position':
- if self.inTag['nviz'] and inTag['surface']:
- self.layerNviz['surface']['position'] = {}
+
+ for node_pos in node_draw.findall('resolution'):
+ self.resolutionType = str(node_pos.get('type', ''))
+ if not nviz['surface']['draw'].has_key('reaolution'):
+ nviz['surface']['draw']['resolution'] = {}
+
+ # position
+ node_pos = node.find('position')
+ if node_pos is not None:
+ self.nviz['surface']['position'] = {}
- 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', ''))
+ elif nviz.has_key('vector'):
+ # vpoints
+ node_vpoints = node.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)
- self.layerNviz['vector']['points']['marker'] = markerId
-
- self.inTag[name] = True
-
- def endElement(self, name):
- if name == 'group':
- self.groupName = self.groupChecked = None
-
- 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})
+ nviz['vector']['points']['marker'] = markerId
+
+ node_mode = node.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'] = ''
- 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
+ # vlines
+ node_vlines = node.find('vlines')
+ if node_vlines is not None:
+ node_mode = node.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'] = ''
- elif name == 'parameter':
- self.cmd.append('%s=%s' % (self.parameterName,
- self.__filterValue(self.value)))
- self.parameterName = self.value = None
+# 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)
- #
- # 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)
+# elif name == 'resolution':
+# if self.inTag['nviz'] and self.inTag['surface']:
+# self.layerNviz['surface']['draw']['resolution'][self.resolutionType] = int(self.value)
+# del self.resolutionType
- elif name == 'resolution':
- if self.inTag['nviz'] and self.inTag['surface']:
- self.layerNviz['surface']['draw']['resolution'][self.resolutionType] = int(self.value)
- del self.resolutionType
+# 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)
- 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)
+# elif name == 'x':
+# if self.inTag['nviz'] and self.inTag['surface']:
+# self.layerNviz['surface']['position']['x'] = int(self.value)
- elif name == 'x':
- if self.inTag['nviz'] and self.inTag['surface']:
- self.layerNviz['surface']['position']['x'] = int(self.value)
+# elif name == 'y':
+# if self.inTag['nviz'] and self.inTag['surface']:
+# self.layerNviz['surface']['position']['y'] = int(self.value)
- elif name == 'y':
- if self.inTag['nviz'] and self.inTag['surface']:
- self.layerNviz['surface']['position']['y'] = int(self.value)
-
- elif name == 'z':
- if self.inTag['nviz'] and self.inTag['surface']:
- self.layerNviz['surface']['position']['z'] = int(self.value)
+# elif name == 'z':
+# if self.inTag['nviz'] and self.inTag['surface']:
+# self.layerNviz['surface']['position']['z'] = int(self.value)
- 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 == '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)
+# 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)
- 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)
+# 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)
- elif name == 'size':
- if self.inTag['nviz'] and self.inTag['vpoints']:
- self.layerNviz['vector']['points']['size'] = int(self.value)
+# elif name == 'size':
+# if self.inTag['nviz'] and self.inTag['vpoints']:
+# self.layerNviz['vector']['points']['size'] = int(self.value)
- 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)
+# 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)
- self.inTag[name] = False
+ return nviz
- def characters(self, ch):
- self.my_characters(ch)
-
- 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
-
class WriteWorkspaceFile(object):
"""!Generic class for writing workspace file"""
def __init__(self, lmgr, file):
Modified: grass/trunk/gui/wxpython/wxgui.py
===================================================================
--- grass/trunk/gui/wxpython/wxgui.py 2009-06-11 15:57:00 UTC (rev 37825)
+++ grass/trunk/gui/wxpython/wxgui.py 2009-06-11 16:19:43 UTC (rev 37826)
@@ -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/trunk/gui/wxpython/xml/grass-gxw.dtd
===================================================================
--- grass/trunk/gui/wxpython/xml/grass-gxw.dtd 2009-06-11 15:57:00 UTC (rev 37825)
+++ grass/trunk/gui/wxpython/xml/grass-gxw.dtd 2009-06-11 16:19:43 UTC (rev 37826)
@@ -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