[GRASS-SVN] r42589 - grass-addons/gui/wxpython/data_catalog

svn_grass at osgeo.org svn_grass at osgeo.org
Sat Jun 19 10:15:21 EDT 2010


Author: rashadkm
Date: 2010-06-19 14:15:21 +0000 (Sat, 19 Jun 2010)
New Revision: 42589

Added:
   grass-addons/gui/wxpython/data_catalog/TODO
Modified:
   grass-addons/gui/wxpython/data_catalog/LayerTree.py
   grass-addons/gui/wxpython/data_catalog/catalog.py
   grass-addons/gui/wxpython/data_catalog/mapdisplay.py
Log:
removed use of full class

Modified: grass-addons/gui/wxpython/data_catalog/LayerTree.py
===================================================================
--- grass-addons/gui/wxpython/data_catalog/LayerTree.py	2010-06-19 12:23:55 UTC (rev 42588)
+++ grass-addons/gui/wxpython/data_catalog/LayerTree.py	2010-06-19 14:15:21 UTC (rev 42589)
@@ -38,9 +38,10 @@
 
 import utils
 from grass.script import core as grass
+import gui_modules.layertree as layertree
 
 
-class LayerTree(treemixin.DragAndDrop, CT.CustomTreeCtrl):
+class LayerTree(layertree.LayerTree):
 
 
 
@@ -49,177 +50,150 @@
                  size=(300,300), style=wx.SUNKEN_BORDER,
                  ctstyle=CT.TR_HAS_BUTTONS | CT.TR_HAS_VARIABLE_ROW_HEIGHT |
                  CT.TR_HIDE_ROOT | CT.TR_FULL_ROW_HIGHLIGHT |
-                 CT.TR_MULTIPLE,mapdisplay=None,frame=None,panel=None,Map=None,lmgr=None,gisdbase=None):
-		self.items = []
-		self.itemCounter = 0
+                 CT.TR_MULTIPLE,**kwargs):
 
-		super(LayerTree, self).__init__(parent, id, pos, size, style=style, ctstyle=ctstyle)
-		self.SetName("LayerTree")
-		self.lmgr = lmgr
+        if 'style' in kwargs:
+            ctstyle |= kwargs['style']
+            del kwargs['style']
 
-		self.frame =  frame
+        self.frame = kwargs['frame']
+        del kwargs['frame']
 
+        self.Map = kwargs['Map']
+        del kwargs['Map']
 
-		self.itemFont = wx.Font(pointSize=9,weight=0, family=wx.FONTFAMILY_DEFAULT ,style=wx.FONTSTYLE_ITALIC)
+        self.lmgr = kwargs['lmgr']
 
-		self.gisdbase = gisdbase
+        self.gisdbase = kwargs['gisdbase']
+        del kwargs['gisdbase']
 
-		self.layer_selected = None 
+        if globalvar.hasAgw:
+            CT.CustomTreeCtrl.__init__(self,parent, id, agwStyle = ctstyle)
+        else:
+            CT.CustomTreeCtrl.__init__(self,parent,id,style=ctstyle)
+        self.SetName("LayerTree")
 
-		self.l_selected = None
 
-		self.rerender = False                # layer change requires a rerendering if auto render
-		self.reorder = False 
 
-		il = wx.ImageList(16, 16, mask=False)
+        self.layer_selected = None 
 
-		trart = wx.ArtProvider.GetBitmap(wx.ART_FOLDER_OPEN, wx.ART_OTHER, (16, 16))
-		self.folder_open = il.Add(trart)
-		trart = wx.ArtProvider.GetBitmap(wx.ART_FOLDER, wx.ART_OTHER, (16, 16))
-		self.folder = il.Add(trart)
+        self.rerender = False                # layer change requires a rerendering if auto render
+        self.reorder = False 
 
-		bmpsize = (16, 16)
-		trgif = Icons["addrast"].GetBitmap(bmpsize)
-		self.rast_icon = il.Add(trgif)
+        il = wx.ImageList(16, 16, mask=False)
 
-		trgif = Icons["addrast3d"].GetBitmap(bmpsize)
-		self.rast3d_icon = il.Add(trgif)
+        trart = wx.ArtProvider.GetBitmap(wx.ART_FOLDER_OPEN, wx.ART_OTHER, (16, 16))
+        self.folder_open = il.Add(trart)
+        trart = wx.ArtProvider.GetBitmap(wx.ART_FOLDER, wx.ART_OTHER, (16, 16))
+        self.folder = il.Add(trart)
 
-		trgif = Icons["addrgb"].GetBitmap(bmpsize)
-		self.rgb_icon = il.Add(trgif)
+        bmpsize = (16, 16)
+        trgif = Icons["addrast"].GetBitmap(bmpsize)
+        self.rast_icon = il.Add(trgif)
 
-		trgif = Icons["addhis"].GetBitmap(bmpsize)
-		self.his_icon = il.Add(trgif)
+        trgif = Icons["addrast3d"].GetBitmap(bmpsize)
+        self.rast3d_icon = il.Add(trgif)
 
-		trgif = Icons["addshaded"].GetBitmap(bmpsize)
-		self.shaded_icon = il.Add(trgif)
+        trgif = Icons["addrgb"].GetBitmap(bmpsize)
+        self.rgb_icon = il.Add(trgif)
 
-		trgif = Icons["addrarrow"].GetBitmap(bmpsize)
-		self.rarrow_icon = il.Add(trgif)
+        trgif = Icons["addhis"].GetBitmap(bmpsize)
+        self.his_icon = il.Add(trgif)
 
-		trgif = Icons["addrnum"].GetBitmap(bmpsize)
-		self.rnum_icon = il.Add(trgif)
+        trgif = Icons["addshaded"].GetBitmap(bmpsize)
+        self.shaded_icon = il.Add(trgif)
 
-		trgif = Icons["addvect"].GetBitmap(bmpsize)
-		self.vect_icon = il.Add(trgif)
+        trgif = Icons["addrarrow"].GetBitmap(bmpsize)
+        self.rarrow_icon = il.Add(trgif)
 
-		trgif = Icons["addthematic"].GetBitmap(bmpsize)
-		self.theme_icon = il.Add(trgif)
+        trgif = Icons["addrnum"].GetBitmap(bmpsize)
+        self.rnum_icon = il.Add(trgif)
 
-		trgif = Icons["addchart"].GetBitmap(bmpsize)
-		self.chart_icon = il.Add(trgif)
+        trgif = Icons["addvect"].GetBitmap(bmpsize)
+        self.vect_icon = il.Add(trgif)
 
-		trgif = Icons["addgrid"].GetBitmap(bmpsize)
-		self.grid_icon = il.Add(trgif)
+        trgif = Icons["addthematic"].GetBitmap(bmpsize)
+        self.theme_icon = il.Add(trgif)
 
-		trgif = Icons["addgeodesic"].GetBitmap(bmpsize)
-		self.geodesic_icon = il.Add(trgif)
+        trgif = Icons["addchart"].GetBitmap(bmpsize)
+        self.chart_icon = il.Add(trgif)
 
-		trgif = Icons["addrhumb"].GetBitmap(bmpsize)
-		self.rhumb_icon = il.Add(trgif)
+        trgif = Icons["addgrid"].GetBitmap(bmpsize)
+        self.grid_icon = il.Add(trgif)
 
-		trgif = Icons["addlabels"].GetBitmap(bmpsize)
-		self.labels_icon = il.Add(trgif)
+        trgif = Icons["addgeodesic"].GetBitmap(bmpsize)
+        self.geodesic_icon = il.Add(trgif)
 
-		trgif = Icons["addcmd"].GetBitmap(bmpsize)
-		self.cmd_icon = il.Add(trgif)
+        trgif = Icons["addrhumb"].GetBitmap(bmpsize)
+        self.rhumb_icon = il.Add(trgif)
 
-		self.AssignImageList(il) 
+        trgif = Icons["addlabels"].GetBitmap(bmpsize)
+        self.labels_icon = il.Add(trgif)
 
+        trgif = Icons["addcmd"].GetBitmap(bmpsize)
+        self.cmd_icon = il.Add(trgif)
 
-		self.Map = Map
-        #if self.Map is not None:
-        #    print self.Map.width
+        self.AssignImageList(il) 
 
-		
-		self.mapname = None
-		self.layertype=None
 
-		self.ID_COPY = wx.NewId()
-		self.ID_OSSIM = wx.NewId()
-		self.ID_OSSIM2 = wx.NewId()
-		self.ID_INFO = wx.NewId()
-		self.ID_REPORT = wx.NewId()
-		self.ID_AREA = 200
-		self.ID_LENGTH = 201
-		self.ID_COOR = 202
-		self.ID_REN = wx.NewId()
-		self.ID_DEL = wx.NewId()
 
-		self.root = self.AddRoot("Map Layers")
-		self.SetPyData(self.root, (None,None))
 
 
-		self.dict = {}
+        self.ID_COPY = wx.NewId()
+        self.ID_OSSIM = wx.NewId()
+        self.ID_OSSIM2 = wx.NewId()
+        self.ID_INFO = wx.NewId()
+        self.ID_REPORT = wx.NewId()
+        self.ID_AREA = 200
+        self.ID_LENGTH = 201
+        self.ID_COOR = 202
+        self.ID_REN = wx.NewId()
+        self.ID_DEL = wx.NewId()
 
-		self.colour = '0:0:0'  #default colour for vector lines
-		self.colour_selected = False
+        self.root = self.AddRoot("Map Layers")
+        self.SetPyData(self.root, (None,None))
 
-		self.layer = []
 
-		d = self.GetParent()
-		notebook = d.GetParent()
 
 
-		child=notebook.GetChildren()
-		for panel in child:
-			  if panel.GetName() == "MapWindow":
-				self.mapdisplay = panel
+        d = self.GetParent()
+        notebook = d.GetParent()
 
 
-		self.Bind(CT.EVT_TREE_ITEM_CHECKED, self.OnLayerChecked)
-		# self.Bind(CT.EVT_TREE_ITEM_ACTIVATED,     self.ChooseColour)
+        child=notebook.GetChildren()
+        for panel in child:
+	          if panel.GetName() == "MapWindow":
+		        self.mapdisplay = panel
 
-		#self.Bind(wx.EVT_TREE_ITEM_RIGHT_CLICK,self.OnTreePopUp)
-		self.Bind(wx.EVT_TREE_END_LABEL_EDIT, self.OnEndRename)
-		self.Bind(wx.EVT_TREE_BEGIN_LABEL_EDIT, self.OnBeginRename)
 
-		#Event bindings for tree menu
-		self.Bind(wx.EVT_MENU,self.OnCopy,id=self.ID_COPY)
-		self.Bind(wx.EVT_MENU,self.OnRenameMap,id=self.ID_REN)
-		self.Bind(wx.EVT_MENU,self.OnDeleteMap,id=self.ID_DEL)
-		self.Bind(wx.EVT_MENU,self.OnOssim,id=self.ID_OSSIM)
-		self.Bind(wx.EVT_MENU,self.OnOssim2,id=self.ID_OSSIM2)
+        self.Bind(CT.EVT_TREE_ITEM_CHECKED, self.OnLayerChecked)
+        # self.Bind(CT.EVT_TREE_ITEM_ACTIVATED,     self.ChooseColour)
 
+        #self.Bind(wx.EVT_TREE_ITEM_RIGHT_CLICK,self.OnTreePopUp)
+        self.Bind(wx.EVT_TREE_END_LABEL_EDIT, self.OnEndRename)
+        self.Bind(wx.EVT_TREE_BEGIN_LABEL_EDIT, self.OnBeginRename)
 
+        #Event bindings for tree menu
+        self.Bind(wx.EVT_MENU,self.OnCopy,id=self.ID_COPY)
+        self.Bind(wx.EVT_MENU,self.OnRenameMap,id=self.ID_REN)
+        self.Bind(wx.EVT_MENU,self.OnDeleteMap,id=self.ID_DEL)
+        self.Bind(wx.EVT_MENU,self.OnOssim,id=self.ID_OSSIM)
+        self.Bind(wx.EVT_MENU,self.OnOssim2,id=self.ID_OSSIM2)
 
-		self.Bind(wx.EVT_TREE_ITEM_EXPANDING,   self.OnExpandNode)
-		self.Bind(wx.EVT_TREE_ITEM_COLLAPSED,   self.OnCollapseNode)
-		self.Bind(wx.EVT_TREE_ITEM_ACTIVATED,   self.OnActivateLayer)
-		self.Bind(wx.EVT_TREE_SEL_CHANGED,      self.OnChangeSel)
-		self.Bind(wx.EVT_TREE_DELETE_ITEM,      self.OnDeleteMap)
-		self.Bind(wx.EVT_TREE_ITEM_RIGHT_CLICK, self.OnLayerContextMenu)
-		self.Bind(wx.EVT_TREE_END_DRAG,         self.OnEndDrag)
-		self.Bind(wx.EVT_KEY_UP,                self.OnKeyUp)
-		self.Bind(wx.EVT_IDLE,                  self.OnIdle)
 
-    def GetMap(self):
-        """!Get map instace"""
-        return self.Map
-    
-    def GetMapDisplay(self):
-        """!Get associated MapFrame"""
-        return self.mapdisplay
-    
-    def OnIdle(self, event):
-        """
-        Only re-order and re-render a composite map image from GRASS during
-        idle time instead of multiple times during layer changing.
-        """
-        if self.rerender:
-            if self.mapdisplay.statusbarWin['render'].GetValue():
-                self.mapdisplay.MapWindow.UpdateMap(render=True)
 
-        event.Skip()
-        
-    def OnKeyUp(self, event):
-        """!Key pressed"""
-        key = event.GetKeyCode()
-        
-        if key == wx.WXK_DELETE and self.lmgr:
-            self.lmgr.OnDeleteLayer(None)
+        self.Bind(wx.EVT_TREE_ITEM_EXPANDING,   self.OnExpandNode)
+        self.Bind(wx.EVT_TREE_ITEM_COLLAPSED,   self.OnCollapseNode)
+        self.Bind(wx.EVT_TREE_ITEM_ACTIVATED,   self.OnActivateLayer)
+        self.Bind(wx.EVT_TREE_SEL_CHANGED,      self.OnChangeSel)
+        self.Bind(wx.EVT_TREE_DELETE_ITEM,      self.OnDeleteMap)
+        self.Bind(wx.EVT_TREE_ITEM_RIGHT_CLICK, self.OnLayerContextMenu)
+        self.Bind(wx.EVT_TREE_END_DRAG,         self.OnEndDrag)
+        self.Bind(wx.EVT_KEY_UP,                self.OnKeyUp)
+        self.Bind(wx.EVT_IDLE,                  self.OnIdle)
 
-        event.Skip()
+  
+   
 
 
     def Minimal(self,item):
@@ -394,1056 +368,8 @@
         self.PopupMenu(self.popupMenu)
         self.popupMenu.Destroy()
 
-    def OnMetadata(self, event):
-        """!Print metadata of raster/vector map layer
-        TODO: Dialog to modify metadata
-        """
-        mapLayer = self.GetPyData(self.layer_selected)[0]['maplayer']
-        mltype = self.GetPyData(self.layer_selected)[0]['type']
 
-        if mltype == 'raster':
-            cmd = ['r.info']
-        elif mltype == 'vector':
-            cmd = ['v.info']
-        cmd.append('map=%s' % mapLayer.name)
 
-        # print output to command log area
-        self.lmgr.goutput.RunCmd(cmd, switchPage=True)
-
-    def OnSetCompRegFromRaster(self, event):
-        """!Set computational region from selected raster map (ignore NULLs)"""
-        mapLayer = self.GetPyData(self.layer_selected)[0]['maplayer']
-        
-        cmd = ['g.region',
-               '-p',
-               'zoom=%s' % mapLayer.name]
-        
-        # print output to command log area
-        self.lmgr.goutput.RunCmd(cmd)
-         
-    def OnSetCompRegFromMap(self, event):
-        """!Set computational region from selected raster/vector map"""
-        rast = []
-        vect = []
-        rast3d = []
-        for layer in self.GetSelections():
-            mapLayer = self.GetPyData(layer)[0]['maplayer']
-            mltype = self.GetPyData(layer)[0]['type']
-                
-            if mltype == 'raster':
-                rast.append(mapLayer.name)
-            elif mltype == 'vector':
-                vect.append(mapLayer.name)
-            elif mltype == '3d-raster':
-                rast3d.append(mapLayer.name)
-
-        cmd = ['g.region']
-        if rast:
-            cmd.append('rast=%s' % ','.join(rast))
-        if vect:
-            cmd.append('vect=%s' % ','.join(vect))
-        if rast3d:
-            cmd.append('rast3d=%s' % ','.join(rast3d))
-        
-        # print output to command log area
-        if len(cmd) > 1:
-            cmd.append('-p')
-            self.lmgr.goutput.RunCmd(cmd)
-        
-    def OnProfile(self, event):
-        """!Plot profile of given raster map layer"""
-        mapLayer = self.GetPyData(self.layer_selected)[0]['maplayer']
-        if not mapLayer.name:
-            wx.MessageBox(parent=self,
-                          message=_("Unable to create profile of "
-                                    "raster map."),
-                          caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
-            return False
-
-        if not hasattr (self, "profileFrame"):
-            self.profileFrame = None
-
-        if hasattr (self.mapdisplay, "profile") and self.mapdisplay.profile:
-            self.profileFrame = self.mapdisplay.profile
-
-        if not self.profileFrame:
-            self.profileFrame = profile.ProfileFrame(self.mapdisplay,
-                                                     id=wx.ID_ANY, pos=wx.DefaultPosition, size=(700,300),
-                                                     style=wx.DEFAULT_FRAME_STYLE, rasterList=[mapLayer.name])
-            # show new display
-            self.profileFrame.Show()
-        
-    def OnColorTable(self, event):
-        """!Set color table for raster map"""
-        name = self.GetPyData(self.layer_selected)[0]['maplayer'].name
-        menuform.GUI().ParseCommand(['r.colors',
-                                     'map=%s' % name],
-                                    parentframe=self)
-        
-    def OnHistogram(self, event):
-        """
-        Plot histogram for given raster map layer
-        """
-        mapLayer = self.GetPyData(self.layer_selected)[0]['maplayer']
-        if not mapLayer.name:
-            wx.MessageBox(parent=self,
-                          message=_("Unable to display histogram of "
-                                    "raster map."),
-                          caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
-            return False
-
-        if not hasattr (self, "histogramFrame"):
-            self.histogramFrame = None
-
-        if hasattr (self.mapdisplay, "histogram") and self.mapdisplay.histogram:
-            self.histogramFrame = self.mapdisplay.histogram
-
-        if not self.histogramFrame:
-            self.histogramFrame = histogram.HistFrame(self,
-                                                      id=wx.ID_ANY,
-                                                      pos=wx.DefaultPosition, size=globalvar.HIST_WINDOW_SIZE,
-                                                      style=wx.DEFAULT_FRAME_STYLE)
-            # show new display
-            self.histogramFrame.Show()
-
-        self.histogramFrame.SetHistLayer(mapLayer.name)
-        self.histogramFrame.HistWindow.UpdateHist()
-        self.histogramFrame.Refresh()
-        self.histogramFrame.Update()
-
-        return True
-
-    def OnStartEditing(self, event):
-        """
-        Start editing vector map layer requested by the user
-        """
-        if not haveVDigit:
-            from vdigit import errorMsg
-            msg = _("Unable to start vector digitizer.\nThe VDigit python extension "
-                    "was not found or loaded properly.\n"
-                    "Switching back to 2D display mode.\n\nDetails: %s" % errorMsg)
-            
-            self.mapdisplay.toolbars['map'].combo.SetValue (_("2D view"))
-            wx.MessageBox(parent=self.mapdisplay,
-                          message=msg,
-                          caption=_("Error"),
-                          style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
-            return
-        
-        try:
-            maplayer = self.GetPyData(self.layer_selected)[0]['maplayer']
-        except:
-            event.Skip()
-            return
-
-        if not self.mapdisplay.toolbars['vdigit']: # enable tool
-            self.mapdisplay.AddToolbar('vdigit')
-        else: # tool already enabled
-            pass
-
-        # mark layer as 'edited'
-        self.mapdisplay.toolbars['vdigit'].StartEditing (maplayer)
-
-    def OnStopEditing(self, event):
-        """
-        Stop editing the current vector map layer
-        """
-        maplayer = self.GetPyData(self.layer_selected)[0]['maplayer']
-        
-        self.mapdisplay.toolbars['vdigit'].OnExit()
-        self.mapdisplay.imgVectorMap = None
-        
-    def OnSetBgMap(self, event):
-        """!Set background vector map for editing sesstion"""
-        if event.IsChecked():
-            mapName = self.GetPyData(self.layer_selected)[0]['maplayer'].GetName()
-            UserSettings.Set(group='vdigit', key='bgmap', subkey='value',
-                             value=str(mapName), internal=True)
-        else:
-            UserSettings.Set(group='vdigit', key='bgmap', subkey='value',
-                             value='', internal=True)
-        
-    def OnPopupProperties (self, event):
-        """!Popup properties dialog"""
-        self.PropertiesDialog(self.layer_selected)
-
-    def OnPopupOpacityLevel(self, event):
-        """!Popup opacity level indicator"""
-        if not self.GetPyData(self.layer_selected)[0]['ctrl']:
-            return
-
-        #win = self.FindWindowById(self.GetPyData(self.layer_selected)[0]['ctrl'])
-        #type = win.GetName()
-        #
-        #self.layer_selected.DeleteWindow()
-
-        maplayer = self.GetPyData(self.layer_selected)[0]['maplayer']
-        current_opacity = maplayer.GetOpacity()
-        
-        dlg = gdialogs.SetOpacityDialog(self, opacity=current_opacity,
-                                        title=_("Set opacity <%s>") % maplayer.GetName())
-        dlg.CentreOnParent()
-
-        if dlg.ShowModal() == wx.ID_OK:
-            new_opacity = dlg.GetOpacity() # string
-            self.Map.ChangeOpacity(maplayer, new_opacity)
-            maplayer.SetOpacity(new_opacity)
-            opacity_pct = int(new_opacity * 100)
-            layername = self.GetItemText(self.layer_selected)
-            layerbase = layername.split('(')[0].strip()
-            self.SetItemText(self.layer_selected,
-                             layerbase + ' (opacity: ' + str(opacity_pct) + '%)')
-            
-            # vector layer currently edited
-            if self.mapdisplay.toolbars['vdigit'] and \
-                    self.mapdisplay.toolbars['vdigit'].GetLayer() == maplayer:   
-                alpha = int(new_opacity * 255)
-                self.mapdisplay.digit.driver.UpdateSettings(alpha)
-                
-            # redraw map if auto-rendering is enabled
-            self.rerender = True
-            self.reorder = True
-            #if self.mapdisplay.statusbarWin['render'].GetValue():
-            #    print "*** Opacity OnRender *****"
-            #    self.mapdisplay.OnRender(None)
-
-    def OnNvizProperties(self, event):
-        """!Nviz-related properties (raster/vector/volume)
-
-        @todo vector/volume
-        """
-        self.lmgr.notebook.SetSelection(3)
-        ltype = self.GetPyData(self.layer_selected)[0]['type']
-        if ltype == 'raster':
-            self.lmgr.nviz.SetPage('surface')
-        elif ltype == 'vector':
-            self.lmgr.nviz.SetPage('vector')
-        elif ltype == 'raster3d':
-            self.lmgr.nviz.SetPage('volume')
-        
-    def RenameLayer (self, event):
-        """!Rename layer"""
-        self.EditLabel(self.layer_selected)
-
-    def AddLayer(self, ltype, lname=None, lchecked=None,
-                 lopacity=1.0, lcmd=None, lgroup=None, lvdigit=None, lnviz=None):
-        """!Add new item to the layer tree, create corresponding MapLayer instance.
-        Launch property dialog if needed (raster, vector, etc.)
-
-        @param ltype layer type (raster, vector, 3d-raster, ...)
-        @param lname layer name
-        @param lchecked if True layer is checked
-        @param lopacity layer opacity level
-        @param lcmd command (given as a list)
-        @param lgroup index of group item (-1 for root) or None
-        @param lvdigit vector digitizer settings (eg. geometry attributes)
-        @param lnviz layer Nviz properties
-        """
-        self.first = True
-        params = {} # no initial options parameters
-
-        # deselect active item
-        if self.layer_selected:
-            self.SelectItem(self.layer_selected, select=False)
-
-        Debug.msg (3, "LayerTree().AddLayer(): ltype=%s" % (ltype))
-        
-        if ltype == 'command':
-            # generic command item
-            ctrl = wx.TextCtrl(self, id=wx.ID_ANY, value='',
-                               pos=wx.DefaultPosition, size=(self.GetSize()[0]-100,25),
-                               # style=wx.TE_MULTILINE|wx.TE_WORDWRAP)
-                               style=wx.TE_PROCESS_ENTER | wx.TE_DONTWRAP)
-            ctrl.Bind(wx.EVT_TEXT_ENTER, self.OnCmdChanged)
-            # ctrl.Bind(wx.EVT_TEXT,       self.OnCmdChanged)
-        elif ltype == 'group':
-            # group item
-            ctrl = None
-            grouptext = _('Layer group:') + str(self.groupnode)
-            self.groupnode += 1
-        else:
-            btnbmp = Icons["layeropts"].GetBitmap((16,16))
-            ctrl = buttons.GenBitmapButton(self, id=wx.ID_ANY, bitmap=btnbmp, size=(24,24))
-            ctrl.SetToolTipString(_("Click to edit layer settings"))
-            self.Bind(wx.EVT_BUTTON, self.OnLayerContextMenu, ctrl)
-        # add layer to the layer tree
-        if self.layer_selected and self.layer_selected != self.GetRootItem():
-            if self.GetPyData(self.layer_selected)[0]['type'] == 'group' \
-                and self.IsExpanded(self.layer_selected):
-                # add to group (first child of self.layer_selected) if group expanded
-                layer = self.PrependItem(parent=self.layer_selected,
-                                         text='', ct_type=1, wnd=ctrl)
-            else:
-                # prepend to individual layer or non-expanded group
-                if lgroup == -1:
-                    # -> last child of root (loading from workspace)
-                    layer = self.AppendItem(parentId=self.root,
-                                            text='', ct_type=1, wnd=ctrl)
-                elif lgroup > -1:
-                    # -> last child of group (loading from workspace)
-                    parent = self.FindItemByIndex(index = lgroup)
-                    if not parent:
-                        parent = self.root
-                    layer = self.AppendItem(parentId=parent,
-                                            text='', ct_type=1, wnd=ctrl)
-                elif lgroup is None:
-                    # -> previous sibling of selected layer
-                    parent = self.GetItemParent(self.layer_selected)
-                    layer = self.InsertItem(parentId=parent,
-                                            input=self.GetPrevSibling(self.layer_selected),
-                                            text='', ct_type=1, wnd=ctrl)
-        else: # add first layer to the layer tree (first child of root)
-            layer = self.PrependItem(parent=self.root, text='', ct_type=1, wnd=ctrl)
-
-        # layer is initially unchecked as inactive (beside 'command')
-        # use predefined value if given
-        if lchecked is not None:
-            checked = lchecked
-        else:
-            checked = True
-
-       # self.CheckItem(layer, checked=checked)
-
-        # select new item
-        self.SelectItem(layer, select=True)
-        self.layer_selected = layer
-        
-        # add text and icons for each layer ltype
-        if ltype == 'raster':
-            self.SetItemImage(layer, self.rast_icon)
-            self.SetItemText(layer, '%s %s' % (_('raster'), _('(double click to set properties)')))
-        elif ltype == '3d-raster':
-            self.SetItemImage(layer, self.rast3d_icon)
-            self.SetItemText(layer, '%s %s' % (_('3d raster'), _('(double click to set properties)')))
-        elif ltype == 'rgb':
-            self.SetItemImage(layer, self.rgb_icon)
-            self.SetItemText(layer, '%s %s' % (_('RGB'), _('(double click to set properties)')))
-        elif ltype == 'his':
-            self.SetItemImage(layer, self.his_icon)
-            self.SetItemText(layer, '%s %s' % (_('HIS'), _('(double click to set properties)')))
-        elif ltype == 'shaded':
-            self.SetItemImage(layer, self.shaded_icon)
-            self.SetItemText(layer, '%s %s' % (_('Shaded relief'), _('(double click to set properties)')))
-        elif ltype == 'rastnum':
-            self.SetItemImage(layer, self.rnum_icon)
-            self.SetItemText(layer, '%s %s' % (_('raster cell numbers'), _('(double click to set properties)')))
-        elif ltype == 'rastarrow':
-            self.SetItemImage(layer, self.rarrow_icon)
-            self.SetItemText(layer, '%s %s' % (_('raster flow arrows'), _('(double click to set properties)')))
-        elif ltype == 'vector':
-            self.SetItemImage(layer, self.vect_icon)
-            self.SetItemText(layer, '%s %s' % (_('vector'), _('(double click to set properties)')))
-        elif ltype == 'thememap':
-            self.SetItemImage(layer, self.theme_icon)
-            self.SetItemText(layer, '%s %s' % (_('thematic map'), _('(double click to set properties)')))
-        elif ltype == 'themechart':
-            self.SetItemImage(layer, self.chart_icon)
-            self.SetItemText(layer, '%s %s' % (_('thematic charts'), _('(double click to set properties)')))
-        elif ltype == 'grid':
-            self.SetItemImage(layer, self.grid_icon)
-            self.SetItemText(layer, '%s %s' % (_('grid'), _('(double click to set properties)')))
-        elif ltype == 'geodesic':
-            self.SetItemImage(layer, self.geodesic_icon)
-            self.SetItemText(layer, '%s %s' % (_('geodesic line'), _('(double click to set properties)')))
-        elif ltype == 'rhumb':
-            self.SetItemImage(layer, self.rhumb_icon)
-            self.SetItemText(layer, '%s %s' % (_('rhumbline'), _('(double click to set properties)')))
-        elif ltype == 'labels':
-            self.SetItemImage(layer, self.labels_icon)
-            self.SetItemText(layer, '%s %s' % (_('vector labels'), _('(double click to set properties)')))
-        elif ltype == 'command':
-            self.SetItemImage(layer, self.cmd_icon)
-        elif ltype == 'group':
-            self.SetItemImage(layer, self.folder)
-            self.SetItemText(layer, grouptext)
-
-        self.first = False
-
-        if ltype != 'group':
-            if lcmd and len(lcmd) > 1:
-                cmd = lcmd
-                render = False
-                name = utils.GetLayerNameFromCmd(lcmd)
-            else:
-                cmd = []
-                if ltype == 'command' and lname:
-                    for c in lname.split(';'):
-                        cmd.append(c.split(' '))
-                
-                render = False
-                name = None
-
-            if ctrl:
-                ctrlId = ctrl.GetId()
-            else:
-                ctrlId = None
-                
-            # add a data object to hold the layer's command (does not apply to generic command layers)
-            self.SetPyData(layer, ({'cmd'      : cmd,
-                                    'type'     : ltype,
-                                    'ctrl'     : ctrlId,
-                                    'maplayer' : None,
-                                    'vdigit'   : lvdigit,
-                                    'nviz'     : lnviz,
-                                    'propwin'  : None}, 
-                                   None))
-            
-            # find previous map layer instance 
-            prevItem = self.GetFirstChild(self.root)[0]
-            prevMapLayer = None 
-            pos = -1
-            while prevItem and prevItem.IsOk() and prevItem != layer: 
-                if self.GetPyData(prevItem)[0]['maplayer']: 
-                    prevMapLayer = self.GetPyData(prevItem)[0]['maplayer'] 
-                
-                prevItem = self.GetNextSibling(prevItem) 
-                
-                if prevMapLayer: 
-                    pos = self.Map.GetLayerIndex(prevMapLayer)
-                else: 
-                    pos = -1
-            
-            maplayer = self.Map.AddLayer(pos=pos,
-                                         type=ltype, command=self.GetPyData(layer)[0]['cmd'], name=name,
-                                         l_active=checked, l_hidden=False,
-                                         l_opacity=lopacity, l_render=render)
-            self.GetPyData(layer)[0]['maplayer'] = maplayer
-
-            # run properties dialog if no properties given
-            if len(cmd) == 0:
-                self.PropertiesDialog(layer, show=True)
-                
-            if ltype == '3d-raster' and \
-                    not self.mapdisplay.toolbars['nviz']:
-                self.EnableItem(layer, False)
-            
-        else: # group
-            self.SetPyData(layer, ({'cmd': None,
-                                    'type' : ltype,
-                                    'ctrl' : None,
-                                    'maplayer' : None,
-                                    'propwin' : None}, 
-                                   None))
-
-        # use predefined layer name if given
-        if lname:
-            if ltype == 'group':
-                self.SetItemText(layer, lname)
-            elif ltype == 'command':
-                ctrl.SetValue(lname)
-            else:
-                name = lname + ' (opacity: ' + \
-                       str(self.GetPyData(layer)[0]['maplayer'].GetOpacity()) + '%)'
-                self.SetItemText(layer, name)
-                
-        # updated progress bar range (mapwindow statusbar)
-        if checked is True:
-            self.mapdisplay.statusbarWin['progress'].SetRange(len(self.Map.GetListOfLayers(l_active=True)))
-
-        # layer.SetHeight(TREE_ITEM_HEIGHT)
-
-        return layer
-
-    def PropertiesDialog (self, layer, show=True):
-        """!Launch the properties dialog"""
-        if self.GetPyData(layer)[0].has_key('propwin') and \
-                self.GetPyData(layer)[0]['propwin'] is not None:
-            # recycle GUI dialogs
-            win = self.GetPyData(layer)[0]['propwin']
-            # update properties (columns, layers)
-            win.notebookpanel.OnUpdateSelection(None)
-            if win.IsShown():
-                win.SetFocus()
-            else:
-                win.Show()
-            
-            return
-        
-        completed = ''
-        params = self.GetPyData(layer)[1]
-        ltype  = self.GetPyData(layer)[0]['type']
-                
-        Debug.msg (3, "LayerTree.PropertiesDialog(): ltype=%s" % \
-                   ltype)
-
-        if self.GetPyData(layer)[0]['cmd']:
-            module = menuform.GUI()
-            module.ParseCommand(self.GetPyData(layer)[0]['cmd'],
-                                completed=(self.GetOptData,layer,params),
-                                parentframe=self, show=show)
-            
-            self.GetPyData(layer)[0]['cmd'] = module.GetCmd()
-        elif ltype == 'raster':
-            cmd = ['d.rast']
-            
-            if UserSettings.Get(group='cmd', key='rasterOverlay', subkey='enabled'):
-                cmd.append('-o')
-            menuform.GUI().ParseCommand(cmd, completed=(self.GetOptData,layer,params),
-                                        parentframe=self)
-        elif ltype == '3d-raster':
-            cmd = ['d.rast3d']
-            menuform.GUI().ParseCommand(cmd, completed=(self.GetOptData,layer,params),
-                                        parentframe=self)
-        elif ltype == 'rgb':
-            menuform.GUI().ParseCommand(['d.rgb'], completed=(self.GetOptData,layer,params),
-                                        parentframe=self)
-        elif ltype == 'his':
-            menuform.GUI().ParseCommand(['d.his'], completed=(self.GetOptData,layer,params),
-                                        parentframe=self)
-        elif ltype == 'shaded':
-            menuform.GUI().ParseCommand(['d.shadedmap'], completed=(self.GetOptData,layer,params),
-                                        parentframe=self)
-        elif ltype == 'rastarrow':
-            menuform.GUI().ParseCommand(['d.rast.arrow'], completed=(self.GetOptData,layer,params),
-                                        parentframe=self)
-        elif ltype == 'rastnum':
-            menuform.GUI().ParseCommand(['d.rast.num'], completed=(self.GetOptData,layer,params),
-                                        parentframe=self)
-        elif ltype == 'vector':
-            types = ''
-            for type in UserSettings.Get(group='cmd', key='showType').keys():
-                if UserSettings.Get(group='cmd', key='showType', subkey=[type, 'enabled']):
-                    types += type + ','
-            types = types.rstrip(',')
-            
-            menuform.GUI().ParseCommand(['d.vect', 'type=%s' % types],
-                                         completed=(self.GetOptData,layer,params),
-                                         parentframe=self)
-        elif ltype == 'thememap':
-            # -s flag requested, otherwise only first thematic category is displayed
-            # should be fixed by C-based d.thematic.* modules
-            menuform.GUI().ParseCommand(['d.vect.thematic', '-s'], 
-                                        completed=(self.GetOptData,layer,params),
-                                        parentframe=self)
-        elif ltype == 'themechart':
-            menuform.GUI().ParseCommand(['d.vect.chart'],
-                                        completed=(self.GetOptData,layer,params),
-                                        parentframe=self)
-        elif ltype == 'grid':
-            menuform.GUI().ParseCommand(['d.grid'], completed=(self.GetOptData,layer,params),
-                                        parentframe=self)
-        elif ltype == 'geodesic':
-            menuform.GUI().ParseCommand(['d.geodesic'], completed=(self.GetOptData,layer,params),
-                                        parentframe=self)
-        elif ltype == 'rhumb':
-            menuform.GUI().ParseCommand(['d.rhumbline'], completed=(self.GetOptData,layer,params),
-                                        parentframe=self)
-        elif ltype == 'labels':
-            menuform.GUI().ParseCommand(['d.labels'], completed=(self.GetOptData,layer,params),
-                                        parentframe=self)
-        elif ltype == 'cmdlayer':
-            pass
-        elif ltype == 'group':
-            pass
-        
-    def OnActivateLayer(self, event):
-        """!Double click on the layer item.
-        Launch property dialog, or expand/collapse group of items, etc.
-        """
-        self.lmgr.WorkspaceChanged()
-        layer = event.GetItem()
-        self.layer_selected = layer
-        
-        self.PropertiesDialog (layer)
-        
-        if self.GetPyData(layer)[0]['type'] == 'group':
-            if self.IsExpanded(layer):
-                self.Collapse(layer)
-            else:
-                self.Expand(layer)
-        
-    def OnDeleteLayer(self, event):
-        """!Remove selected layer item from the layer tree"""
-        self.lmgr.WorkspaceChanged()
-        item = event.GetItem()
-        
-        try:
-            item.properties.Close(True)
-        except:
-            pass
-
-        if item != self.root:
-            Debug.msg (3, "LayerTree.OnDeleteLayer(): name=%s" % \
-                           (self.GetItemText(item)))
-        else:
-            self.root = None
-
-        # unselect item
-        self.Unselect()
-        self.layer_selected = None
-
-        try:
-            if self.GetPyData(item)[0]['type'] != 'group':
-                self.Map.DeleteLayer( self.GetPyData(item)[0]['maplayer'])
-        except:
-            pass
-
-        # redraw map if auto-rendering is enabled
-        self.rerender = True
-        self.reorder = True
-        #if self.mapdisplay.statusbarWin['render'].GetValue():
-        #    print "*** Delete OnRender *****"
-        #    self.mapdisplay.OnRender(None)
-
-        if self.mapdisplay.toolbars['vdigit']:
-            self.mapdisplay.toolbars['vdigit'].UpdateListOfLayers (updateTool=True)
-
-        # update progress bar range (mapwindow statusbar)
-        self.mapdisplay.statusbarWin['progress'].SetRange(len(self.Map.GetListOfLayers(l_active=True)))
-
-        event.Skip()
-
-    def OnLayerChecked(self, event):
-        """!Enable/disable data layer"""
-
-        item    = event.GetItem()
-        checked = self.IsItemChecked(item)
-        self.SelectItem(item)
-
-
-
-    def OnCmdChanged(self, event):
-        """!Change command string"""
-        ctrl = event.GetEventObject().GetId()
-        cmd = event.GetString()
-        
-        layer = self.GetFirstVisibleItem()
-
-        while layer and layer.IsOk():
-            if self.GetPyData(layer)[0]['ctrl'] == ctrl:
-                break
-            
-            layer = self.GetNextVisible(layer)
-
-        # change parameters for item in layers list in render.Map
-        self.ChangeLayer(layer)
-        
-        event.Skip()
-
-    def OnChangeSel(self, event):
-        """!Selection changed"""
-        oldlayer = event.GetOldItem()
-        layer = event.GetItem()
-        if layer == oldlayer:
-            event.Veto()
-            return
-        
-        self.layer_selected = layer
-        
-        try:
-            if self.IsSelected(oldlayer):
-                self.SetItemWindowEnabled(oldlayer, True)
-            else:
-                self.SetItemWindowEnabled(oldlayer, False)
-
-            if self.IsSelected(layer):
-                self.SetItemWindowEnabled(layer, True)
-            else:
-                self.SetItemWindowEnabled(layer, False)
-        except:
-            pass
-
-        try:
-            self.RefreshLine(oldlayer)
-            self.RefreshLine(layer)
-        except:
-            pass
-
-        #
-        # update statusbar -> show command string
-        #
-        if self.GetPyData(layer) and self.GetPyData(layer)[0]['maplayer']:
-            cmd = self.GetPyData(layer)[0]['maplayer'].GetCmd(string=True)
-            if len(cmd) > 0:
-                self.lmgr.SetStatusText(cmd)
-
-        # set region if auto-zooming is enabled
-        if self.GetPyData(layer) and self.GetPyData(layer)[0]['cmd'] and \
-               UserSettings.Get(group = 'display', key = 'autoZooming', subkey = 'enabled'):
-            mapLayer = self.GetPyData(layer)[0]['maplayer']
-            if mapLayer.GetType() in ('raster', 'vector'):
-                render = self.mapdisplay.statusbarWin['render'].IsChecked()
-                self.mapdisplay.MapWindow.ZoomToMap(layers = [mapLayer,],
-                                                    render = render)
-        
-        #
-        # update nviz tools
-        #
-        if self.mapdisplay.toolbars['nviz'] and \
-                self.GetPyData(self.layer_selected) is not None:
-
-            if self.layer_selected.IsChecked():
-                # update Nviz tool window
-                type = self.GetPyData(self.layer_selected)[0]['maplayer'].type
-
-                if type == 'raster':
-                    self.lmgr.nviz.UpdatePage('surface')
-                    self.lmgr.nviz.SetPage('surface')
-                elif type == 'vector':
-                    self.lmgr.nviz.UpdatePage('vector')
-                    self.lmgr.nviz.SetPage('vector')
-                elif type == '3d-raster':
-                    self.lmgr.nviz.UpdatePage('volume')
-                    self.lmgr.nviz.SetPage('volume')
-            else:
-                for page in ('surface', 'vector', 'volume'):
-                    pageId = self.lmgr.nviz.page[page]['id']
-                    if pageId > -1:
-                        self.lmgr.nviz.notebook.RemovePage(pageId)
-                        self.lmgr.nviz.page[page]['id'] = -1
-                        self.lmgr.nviz.page['settings']['id'] = 1 
-
-    def OnCollapseNode(self, event):
-        """!Collapse node
-        """
-        if self.GetPyData(self.layer_selected)[0]['type'] == 'group':
-            self.SetItemImage(self.layer_selected, self.folder)
-
-    def OnExpandNode(self, event):
-        """!Expand node
-        """
-        self.layer_selected = event.GetItem()
-        if self.GetPyData(self.layer_selected)[0]['type'] == 'group':
-            self.SetItemImage(self.layer_selected, self.folder_open)
-    
-    def OnEndDrag(self, event):
-        self.StopDragging()
-        dropTarget = event.GetItem()
-        self.flag = self.HitTest(event.GetPoint())[1]
-        if self.IsValidDropTarget(dropTarget):
-            self.UnselectAll()
-            if dropTarget != None:
-                self.SelectItem(dropTarget)
-            self.OnDrop(dropTarget, self._dragItem)
-        elif dropTarget == None:
-            self.OnDrop(dropTarget, self._dragItem)
-
-    def OnDrop(self, dropTarget, dragItem):
-        # save everthing associated with item to drag
-        try:
-            old = dragItem  # make sure this member exists
-        except:
-            return
-
-        Debug.msg (4, "LayerTree.OnDrop(): layer=%s" % \
-                   (self.GetItemText(dragItem)))
-        
-        # recreate data layer, insert copy of layer in new position, and delete original at old position
-        newItem  = self.RecreateItem (dragItem, dropTarget)
-
-        # if recreated layer is a group, also recreate its children
-        if  self.GetPyData(newItem)[0]['type'] == 'group':
-            (child, cookie) = self.GetFirstChild(dragItem)
-            if child:
-                while child:
-                    self.RecreateItem(child, dropTarget, parent=newItem)
-                    self.Delete(child)
-                    child = self.GetNextChild(old, cookie)[0]
-            #self.Expand(newItem)
-
-        # delete layer at original position
-        try:
-            self.Delete(old) # entry in render.Map layers list automatically deleted by OnDeleteLayer handler
-        except AttributeError:
-            # FIXME being ugly (item.SetWindow(None))
-            pass
-
-        # reorder layers in render.Map to match new order after drag and drop
-        #self.ReorderLayers()
-
-        # redraw map if auto-rendering is enabled
-        self.rerender = True
-        self.reorder = True
-        #if self.mapdisplay.statusbarWin['render'].GetValue():
-        #    print "*** Drop OnRender *****"
-        #    self.mapdisplay.OnRender(None)
-
-        # select new item
-        self.SelectItem(newItem)
-        
-    def RecreateItem (self, dragItem, dropTarget, parent=None):
-        """
-        Recreate item (needed for OnEndDrag())
-        """
-        Debug.msg (4, "LayerTree.RecreateItem(): layer=%s" % \
-                   self.GetItemText(dragItem))
-
-        # fetch data (dragItem)
-        checked = self.IsItemChecked(dragItem)
-        image   = self.GetItemImage(dragItem, 0)
-        text    = self.GetItemText(dragItem)
-        if self.GetPyData(dragItem)[0]['ctrl']:
-            # recreate data layer
-            btnbmp = Icons["layeropts"].GetBitmap((16,16))
-            newctrl = buttons.GenBitmapButton(self, id=wx.ID_ANY, bitmap=btnbmp, size=(24, 24))
-            newctrl.SetToolTipString(_("Click to edit layer settings"))
-            self.Bind(wx.EVT_BUTTON, self.OnLayerContextMenu, newctrl)
-            data    = self.GetPyData(dragItem)
-        
-        elif self.GetPyData(dragItem)[0]['type'] == 'command':
-            # recreate command layer
-            oldctrl = None
-            newctrl = wx.TextCtrl(self, id=wx.ID_ANY, value='',
-                                  pos=wx.DefaultPosition, size=(250,25),
-                                  style=wx.TE_MULTILINE|wx.TE_WORDWRAP)
-            try:
-                newctrl.SetValue(self.GetPyData(dragItem)[0]['maplayer'].GetCmd(string=True))
-            except:
-                pass
-            newctrl.Bind(wx.EVT_TEXT_ENTER, self.OnCmdChanged)
-            newctrl.Bind(wx.EVT_TEXT,       self.OnCmdChanged)
-            data    = self.GetPyData(dragItem)
-
-        elif self.GetPyData(dragItem)[0]['type'] == 'group':
-            # recreate group
-            newctrl = None
-            data    = None
-            
-        # decide where to put recreated item
-        if dropTarget != None and dropTarget != self.GetRootItem():
-            if parent:
-                # new item is a group
-                afteritem = parent
-            else:
-                # new item is a single layer
-                afteritem = dropTarget
-
-            # dragItem dropped on group
-            if  self.GetPyData(afteritem)[0]['type'] == 'group':
-                newItem = self.PrependItem(afteritem, text=text, \
-                                      ct_type=1, wnd=newctrl, image=image, \
-                                      data=data)
-                self.Expand(afteritem)
-            else:
-                #dragItem dropped on single layer
-                newparent = self.GetItemParent(afteritem)
-                newItem = self.InsertItem(newparent, self.GetPrevSibling(afteritem), \
-                                       text=text, ct_type=1, wnd=newctrl, \
-                                       image=image, data=data)
-        else:
-            # if dragItem not dropped on a layer or group, append or prepend it to the layer tree
-            if self.flag & wx.TREE_HITTEST_ABOVE:
-                newItem = self.PrependItem(self.root, text=text, \
-                                      ct_type=1, wnd=newctrl, image=image, \
-                                      data=data)
-            elif (self.flag &  wx.TREE_HITTEST_BELOW) or (self.flag & wx.TREE_HITTEST_NOWHERE) \
-                     or (self.flag & wx.TREE_HITTEST_TOLEFT) or (self.flag & wx.TREE_HITTEST_TORIGHT):
-                newItem = self.AppendItem(self.root, text=text, \
-                                      ct_type=1, wnd=newctrl, image=image, \
-                                      data=data)
-
-        #update new layer 
-        self.SetPyData(newItem, self.GetPyData(dragItem))
-        if newctrl:
-            self.GetPyData(newItem)[0]['ctrl'] = newctrl.GetId()
-        else:
-            self.GetPyData(newItem)[0]['ctrl'] = None
-            
-        self.CheckItem(newItem, checked=checked) # causes a new render
-
-        # newItem.SetHeight(TREE_ITEM_HEIGHT)
-
-        return newItem
-
-    def GetOptData(self, dcmd, layer, params, propwin):
-        """!Process layer data"""
-        # set layer text to map name
-        if dcmd:
-            mapLayer = self.GetPyData(layer)[0]['maplayer']
-            opacity = int(mapLayer.GetOpacity(float=True) * 100)
-            mapname = utils.GetLayerNameFromCmd(dcmd, layerType=mapLayer.type,
-                                                fullyQualified=True)
-            if not mapname:
-                GMessage(parent=self,
-                         message=_("Map <%s> not found.") % utils.GetLayerNameFromCmd(dcmd))
-                return
-            
-            self.SetItemText(layer, mapname + ' (opacity: ' + str(opacity) + '%)')
-        
-        # update layer data
-        if params:
-            self.SetPyData(layer, (self.GetPyData(layer)[0], params))
-        if dcmd:
-            self.GetPyData(layer)[0]['cmd'] = dcmd
-        self.GetPyData(layer)[0]['propwin'] = propwin
-        
-        # change parameters for item in layers list in render.Map
-        self.ChangeLayer(layer)
-
-        # set region if auto-zooming is enabled
-        if dcmd and UserSettings.Get(group = 'display', key = 'autoZooming', subkey = 'enabled'):
-            mapLayer = self.GetPyData(layer)[0]['maplayer']
-            if mapLayer.GetType() in ('raster', 'vector'):
-                render = UserSettings.Get(group = 'display', key = 'autoRendering', subkey = 'enabled')
-                self.mapdisplay.MapWindow.ZoomToMap(layers = [mapLayer,],
-                                                    render = render)
-        
-        if self.mapdisplay.toolbars['nviz'] and dcmd:
-            # update nviz session
-            mapLayer = self.GetPyData(layer)[0]['maplayer']
-            mapWin = self.mapdisplay.MapWindow
-            if len(mapLayer.GetCmd()) > 0:
-                id = -1
-                if mapLayer.type == 'raster':
-                    if mapWin.IsLoaded(layer):
-                        mapWin.UnloadRaster(layer)
-                    
-                    mapWin.LoadRaster(layer)
-                    
-                elif mapLayer.type == '3d-raster':
-                    if mapWin.IsLoaded(layer):
-                        mapWin.UnloadRaster3d(layer)
-                    
-                    mapWin.LoadRaster3d(layer)
-                    
-                elif mapLayer.type == 'vector':
-                    if mapWin.IsLoaded(layer):
-                        mapWin.UnloadVector(layer)
-                    
-                    mapWin.LoadVector(layer)
-
-                # reset view when first layer loaded
-                nlayers = len(mapWin.Map.GetListOfLayers(l_type=('raster', 'vector'),
-                                                         l_active=True))
-                if nlayers < 2:
-                    mapWin.ResetView()
-        
-    def ReorderLayers(self):
-        """!Add commands from data associated with
-        any valid layers (checked or not) to layer list in order to
-        match layers in layer tree."""
-
-        # make a list of visible layers
-        treelayers = []
-
-        vislayer = self.GetFirstVisibleItem()
-
-        if not vislayer or self.GetPyData(vislayer) is None:
-            return
-
-        itemList = ""
-
-        for item in range(self.GetCount()):
-            itemList += self.GetItemText(vislayer) + ','
-            if self.GetPyData(vislayer)[0]['type'] != 'group':
-                treelayers.append(self.GetPyData(vislayer)[0]['maplayer'])
-
-            if not self.GetNextVisible(vislayer):
-                break
-            else:
-                vislayer = self.GetNextVisible(vislayer)
-
-        Debug.msg (4, "LayerTree.ReorderLayers(): items=%s" % \
-                   (itemList))
-
-        # reorder map layers
-        treelayers.reverse()
-        self.Map.ReorderLayers(treelayers)
-        self.reorder = False
-
-    def ChangeLayer(self, item):
-        """!Change layer"""
-        type = self.GetPyData(item)[0]['type']
-        layerName = None
-        
-        if type == 'command':
-            win = self.FindWindowById(self.GetPyData(item)[0]['ctrl'])
-            if win.GetValue() != None:
-                cmd = win.GetValue().split(';')
-                cmdlist = []
-                for c in cmd:
-                    cmdlist.append(c.split(' '))
-                opac = 1.0
-                chk = self.IsItemChecked(item)
-                hidden = not self.IsVisible(item)
-        elif type != 'group':
-            if self.GetPyData(item)[0] is not None:
-                cmdlist = self.GetPyData(item)[0]['cmd']
-                opac = self.GetPyData(item)[0]['maplayer'].GetOpacity(float=True)
-                chk = self.IsItemChecked(item)
-                hidden = not self.IsVisible(item)
-                # determine layer name
-                layerName = utils.GetLayerNameFromCmd(cmdlist, fullyQualified=True)
-                if not layerName:
-                    layerName = self.GetItemText(item)
-        
-        maplayer = self.Map.ChangeLayer(layer=self.GetPyData(item)[0]['maplayer'], type=type,
-                                        command=cmdlist, name=layerName,
-                                        l_active=chk, l_hidden=hidden, l_opacity=opac, l_render=False)
-        
-        self.GetPyData(item)[0]['maplayer'] = maplayer
-        
-        # if digitization tool enabled -> update list of available vector map layers
-        if self.mapdisplay.toolbars['vdigit']:
-            self.mapdisplay.toolbars['vdigit'].UpdateListOfLayers(updateTool=True)
-        
-        # redraw map if auto-rendering is enabled
-        self.rerender = True
-        self.reorder = True
-        #if self.mapdisplay.statusbarWin['render'].GetValue():
-        #    print "*** Change OnRender *****"
-        #    self.mapdisplay.OnRender(None)
-        
-    def OnCloseWindow(self, event):
-        pass
-        # self.Map.Clean()
-
-    def FindItemByData(self, key, value):
-        """!Find item based on key and value (see PyData[0])
-        
-        @return item instance
-        @return None not found
-        """
-        item = self.GetFirstChild(self.root)[0]
-        return self.__FindSubItemByData(item, key, value)
-
-    def FindItemByIndex(self, index):
-        """!Find item by index (starting at 0)
-
-        @return item instance
-        @return None not found
-        """
-        item = self.GetFirstChild(self.root)[0]
-        i = 0
-        while item and item.IsOk():
-            if i == index:
-                return item
-            
-            item = self.GetNextVisible(item)
-            i += 1
-        
-        return None
-    
-    def EnableItemType(self, type, enable=True):
-        """!Enable/disable items in layer tree"""
-        item = self.GetFirstChild(self.root)[0]
-        while item and item.IsOk():
-            mapLayer = self.GetPyData(item)[0]['maplayer']
-            if mapLayer and type == mapLayer.type:
-                self.EnableItem(item, enable)
-            
-            item = self.GetNextSibling(item)
-        
-    def __FindSubItemByData(self, item, key, value):
-        """!Support method for FindItemByValue"""
-        while item and item.IsOk():
-            try:
-                itemValue = self.GetPyData(item)[0][key]
-            except KeyError:
-                return None
-            
-            if value == itemValue:
-                return item
-            if self.GetPyData(item)[0]['type'] == 'group':
-                subItem = self.GetFirstChild(item)[0]
-                found = self.__FindSubItemByData(subItem, key, value)
-                if found:
-                    return found
-            item = self.GetNextSibling(item)
-
-        return None
-
-
 	def ChooseColour(self,event):
 
 		colourdialog = wx.ColourDialog(self)
@@ -1468,27 +394,21 @@
 			self.CheckItem(parent)
 
 
-	def OnInfo(self,event):
+    def OnEndRename(self,event):
+		"""
+		Rename mapset using grass commands
+		"""
+		item = event.GetItem()
+		oldName = self.GetItemText(item) 
+		try:
+			newName =  self.GetEditControl().GetValue()
+		except:
+			return
+	
+    def OnBeginRename(self,event):
 
-		item =  self.GetSelection()
-		parent = self.GetItemParent(item)
-		pText = self.GetItemText(parent)
+		item = self.GetItemText(event.GetItem())
 
-		leftpanel=self.GetParent()
-		notebook = leftpanel.GetParent()
-		frame = notebook.GetParent()
-
-		if not self.ItemHasChildren(item):
-			self.mapname =  self.GetItemText(item) + "@" + frame.cmbMapset.GetValue()
-
-		if pText == "Raster Map" :
-			command = ["r.info", 'map=' +  self.mapname]
-			frame.goutput.RunCmd(command)
-		if pText == "Vector Map" :
-			command = ["v.info", 'map=' +  self.mapname]
-			frame.goutput.RunCmd(command)
-
-
     def OnReport(self,event):
 
         item =  self.GetSelection()
@@ -1506,23 +426,7 @@
 
 	
         
-    def OnBeginRename(self,event):
 
-		item = self.GetItemText(event.GetItem())
-
-    def OnEndRename(self,event):
-		"""
-		Rename mapset using grass commands
-		"""
-		item = event.GetItem()
-		oldName = self.GetItemText(item) 
-		try:
-			newName =  self.GetEditControl().GetValue()
-		except:
-			return
-	
-
-
     def OnCopy( self,event ):
 		#print "copy"
 		item =  self.GetSelection()

Added: grass-addons/gui/wxpython/data_catalog/TODO
===================================================================
--- grass-addons/gui/wxpython/data_catalog/TODO	                        (rev 0)
+++ grass-addons/gui/wxpython/data_catalog/TODO	2010-06-19 14:15:21 UTC (rev 42589)
@@ -0,0 +1,3 @@
+def onossim
+def onossim2
+def ondeletemap

Modified: grass-addons/gui/wxpython/data_catalog/catalog.py
===================================================================
--- grass-addons/gui/wxpython/data_catalog/catalog.py	2010-06-19 12:23:55 UTC (rev 42588)
+++ grass-addons/gui/wxpython/data_catalog/catalog.py	2010-06-19 14:15:21 UTC (rev 42589)
@@ -118,8 +118,10 @@
 from   gui_modules.ghelp import AboutWindow
 from   gui_modules.toolbars import LayerManagerToolbar
 from   gui_modules.ghelp import InstallExtensionWindow
+from wxgui import GMFrame
+from grass.script import core as grass
 
-class DataCatalog(wx.Frame):
+class DataCatalog(GMFrame):
 
 
     def __init__(self, parent=None, id=wx.ID_ANY, title=_("Data Catalog Beta"),
@@ -169,18 +171,11 @@
 
 
 
-        self.g_catalog=None
-
         self.locationchange = True
 
-        self.menucmd       = dict() 
-        
-        self.mapfile = []  
-        self.mapname = None
-        self.cmd = None
-        self.newmap = None
 
 
+
      #creating sizers    
         self.cmbSizer = wx.BoxSizer(wx.HORIZONTAL) 
         self.mSizer = wx.BoxSizer(wx.VERTICAL)
@@ -236,20 +231,14 @@
         self.curr_page = self.notebook.GetCurrentPage()    
  
 
-        #self.goutput.Redirect()
+        self.cmbLocation.SetValue(grass.gisenv()['LOCATION_NAME'])
+        self.cmbMapset.SetValue(grass.gisenv()['MAPSET'])
 
-
+        
         self.doBindings()
         self.doLayout()
 
-    def OnInstallExtension(self, event):
-        """!Install extension from GRASS Addons SVN repository"""
-        win = InstallExtensionWindow(self, size = (550, 400))
-        win.CentreOnScreen()
-        win.Show()
-        
 
-
     def __createNoteBook(self):
         """!Creates notebook widgets"""
 
@@ -269,7 +258,6 @@
         
         self.notebook.SetTabAreaColour(globalvar.FNPageColor)
 
-       # self._lmgr=wx.aui.AuiManager(self)
         self.pg_panel = MapFrame(parent=self.notebook, id=wx.ID_ANY, Map=render.Map(), size=globalvar.MAP_WINDOW_SIZE,flag=False,frame=self)
         
         self.disp_idx = self.disp_idx + 1
@@ -278,13 +266,6 @@
         self.goutput = goutput.GMConsole(self, pageid=1)
         self.outpage = self.notebook.AddPage(self.goutput, text=_("Command console"))
 
-        #self.notebook.SetSelection(0)
-
-
-       # self.notebook.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChanged)
-       # self.notebook.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CLOSING, self.OnPageClosed)
-
-
         self.notebook.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnCBPageChanged)
         self.notebook.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CLOSING, self.OnCBPageClosed)
 
@@ -292,929 +273,7 @@
         return self.notebook
 
         
-    def AddNviz(self):
-        """!Add nviz notebook page"""
-        self.nviz = nviz_tools.NvizToolWindow(parent = self,
-                                              display = self.curr_page.maptree.GetMapDisplay()) 
-        self.notebook.AddPage(self.nviz, text = _("3D view"))
-        self.notebook.SetSelection(self.notebook.GetPageCount() - 1)
-        
-    def RemoveNviz(self):
-        """!Remove nviz notebook page"""
-        # print self.notebook.GetPage(1)
-        self.notebook.RemovePage(3)
-        del self.nviz
-        self.notebook.SetSelection(0)
-        
-    def WorkspaceChanged(self):
-        """!Update window title"""
-        if not self.workspaceChanged:
-            self.workspaceChanged = True
-        
-        if self.workspaceFile:
-            self.SetTitle(self.baseTitle + " - " +  os.path.basename(self.workspaceFile) + '*')
-        
-    def OnGeorectify(self, event):
-        """!Launch georectifier module
-        """
-        georect.GeorectWizard(self)
-
-    def OnGModeler(self, event):
-        """!Launch Graphical Modeler"""
-        win = gmodeler.ModelFrame(parent = self)
-        win.CentreOnScreen()
-        
-        win.Show()
-        
-    def OnDone(self, returncode):
-        """Command execution finised"""
-        if hasattr(self, "model"):
-            self.model.DeleteIntermediateData(log = self.goutput)
-            del self.model
-        self.SetStatusText('')
-        
-    def OnRunModel(self, event):
-        """!Run model"""
-        filename = ''
-        dlg = wx.FileDialog(parent = self, message=_("Choose model to run"),
-                            defaultDir = os.getcwd(),
-                            wildcard=_("GRASS Model File (*.gxm)|*.gxm"))
-        if dlg.ShowModal() == wx.ID_OK:
-            filename = dlg.GetPath()
-        
-        if not filename:
-            return
-        
-        self.model = gmodeler.Model()
-        self.model.LoadModel(filename)
-        self.SetStatusText(_('Validating model...'), 0)
-        result =  self.model.Validate()
-        if result:
-            dlg = wx.MessageDialog(parent = self,
-                                   message = _('Model is not valid. Do you want to '
-                                               'run the model anyway?\n\n%s') % '\n'.join(errList),
-                                   caption=_("Run model?"),
-                                   style = wx.YES_NO | wx.NO_DEFAULT |
-                                   wx.ICON_QUESTION | wx.CENTRE)
-            ret = dlg.ShowModal()
-            if ret != wx.ID_YES:
-                return
-        
-        self.SetStatusText(_('Running model...'), 0)
-        self.model.Run(log = self.goutput,
-                       onDone = self.OnDone)
-        
-    def OnMapsets(self, event):
-        """
-        Launch mapset access dialog
-        """
-        dlg = preferences.MapsetAccess(parent=self, id=wx.ID_ANY)
-        dlg.CenterOnScreen()
-
-        # if OK is pressed...
-        if dlg.ShowModal() == wx.ID_OK:
-            ms = dlg.GetMapsets()
-            # run g.mapsets with string of accessible mapsets
-            gcmd.RunCommand('g.mapsets',
-                            parent = self,
-                            mapset = '%s' % ','.join(ms))
-            
-    def OnRDigit(self, event):
-        """
-        Launch raster digitizing module
-        """
-        pass
-
-    def OnCBPageChanged(self, event):
-        """!Page in notebook (display) changed"""
-        old_pgnum = event.GetOldSelection()
-        new_pgnum = event.GetSelection()
-        
-        self.curr_page   = self.notebook.GetCurrentPage()
-        self.curr_pagenum = self.notebook.GetSelection()
-        
-        try:
-            self.curr_page.maptree.mapdisplay.SetFocus()
-            self.curr_page.maptree.mapdisplay.Raise()
-        except:
-            pass
-        
-        event.Skip()
-
-    def OnPageChanged(self, event):
-        """!Page in notebook changed"""
-        page = event.GetSelection()
-        if page == self.goutput.pageid:
-            # remove '(...)'
-            self.notebook.SetPageText(page, _("Command console"))
-            self.goutput.cmd_prompt.SetSTCFocus(True)
-        self.SetStatusText('', 0)
-        
-        event.Skip()
-
-    def OnCBPageClosed(self, event):
-        """!Page of notebook closed
-        Also close associated map display
-        """
-        if UserSettings.Get(group='manager', key='askOnQuit', subkey='enabled'):
-            maptree = self.curr_page.maptree
-            
-            if self.workspaceFile:
-                message = _("Do you want to save changes in the workspace?")
-            else:
-                message = _("Do you want to store current settings "
-                            "to workspace file?")
-            
-            # ask user to save current settings
-            if maptree.GetCount() > 0:
-                dlg = wx.MessageDialog(self,
-                                       message=message,
-                                       caption=_("Close Map Display %d") % (self.curr_pagenum + 1),
-                                       style=wx.YES_NO | wx.YES_DEFAULT |
-                                       wx.CANCEL | wx.ICON_QUESTION | wx.CENTRE)
-                ret = dlg.ShowModal()
-                if ret == wx.ID_YES:
-                    if not self.workspaceFile:
-                        self.OnWorkspaceSaveAs()
-                    else:
-                        self.SaveToWorkspaceFile(self.workspaceFile)
-                elif ret == wx.ID_CANCEL:
-                    event.Veto()
-                    dlg.Destroy()
-                    return
-                dlg.Destroy()
-
-        self.gm_cb.GetPage(event.GetSelection()).maptree.Map.Clean()
-        self.gm_cb.GetPage(event.GetSelection()).maptree.Close(True)
-
-        self.curr_page = None
-
-        event.Skip()
-
-    def GetLogWindow(self):
-        """!Get widget for command output"""
-        return self.goutput
-    
-    def GetMenuCmd(self, event):
-        """!Get GRASS command from menu item
-
-        Return command as a list"""
-        layer = None
-        
-        if event:
-            cmd = self.menucmd[event.GetId()]
-        
-        try:
-            cmdlist = cmd.split(' ')
-        except: # already list?
-            cmdlist = cmd
-            
-        # check list of dummy commands for GUI modules that do not have GRASS
-        # bin modules or scripts. 
-        if cmd in ['vcolors']:
-            return cmdlist
-
-        try:
-            layer = self.curr_page.maptree.layer_selected
-            name = self.curr_page.maptree.GetPyData(layer)[0]['maplayer'].name
-            type = self.curr_page.maptree.GetPyData(layer)[0]['type']
-        except:
-            layer = None
-        if layer and len(cmdlist) == 1: # only if no paramaters given
-            if (type == 'raster' and cmdlist[0][0] == 'r' and cmdlist[0][1] != '3') or \
-                    (type == 'vector' and cmdlist[0][0] == 'v'):
-                input = menuform.GUI().GetCommandInputMapParamKey(cmdlist[0])
-                if input:
-                    cmdlist.append("%s=%s" % (input, name))
-
-        return cmdlist
-
-    def RunMenuCmd(self, event, cmd = ''):
-        """!Run command selected from menu"""
-        if event:
-            cmd = self.GetMenuCmd(event)
-        self.goutput.RunCmd(cmd, switchPage=False)
-
-    def OnMenuCmd(self, event, cmd = ''):
-        """!Parse command selected from menu"""
-        if event:
-            cmd = self.GetMenuCmd(event)
-        menuform.GUI().ParseCommand(cmd, parentframe=self)
-
-    def OnRunScript(self, event):
-        """!Run script"""
-        # open dialog and choose script file
-        dlg = wx.FileDialog(parent = self, message = _("Choose script file"),
-                            defaultDir = os.getcwd(), wildcard = _("Bash script (*.sh)|*.sh|Python script (*.py)|*.py"))
-        
-        filename = None
-        if dlg.ShowModal() == wx.ID_OK:
-            filename = dlg.GetPath()
-        
-        if not filename:
-            return False
-
-        if not os.path.exists(filename):
-            wx.MessageBox(parent = self,
-                          message = _("Script file '%s' doesn't exist. Operation cancelled.") % filename,
-                          caption = _("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
-            return
-        
-        self.goutput.WriteCmdLog(_("Launching script '%s'...") % filename)
-        self.goutput.RunCmd(filename, switchPage = True)
-        
-    def OnChangeLocation(self, event):
-        """Change current location"""
-        dlg = gdialogs.LocationDialog(parent = self)
-        if dlg.ShowModal() == wx.ID_OK:
-            location, mapset = dlg.GetValues()
-            if location and mapset:
-                ret = gcmd.RunCommand("g.gisenv",
-                                      set = "LOCATION_NAME=%s" % location)
-                ret += gcmd.RunCommand("g.gisenv",
-                                       set = "MAPSET=%s" % mapset)
-                if ret > 0:
-                    wx.MessageBox(parent = self,
-                                  message = _("Unable to switch to location <%(loc)s> mapset <%(mapset)s>.") % \
-                                      { 'loc' : location, 'mapset' : mapset },
-                                  caption = _("Error"), style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
-                else:
-                    # close workspace
-                    self.OnWorkspaceClose()
-                    self.OnWorkspaceNew()
-                    wx.MessageBox(parent = self,
-                                  message = _("Current location is <%(loc)s>.\n"
-                                              "Current mapset is <%(mapset)s>.") % \
-                                      { 'loc' : location, 'mapset' : mapset },
-                                  caption = _("Info"), style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
-                    
-    def OnChangeMapset(self, event):
-        """Change current mapset"""
-        dlg = gdialogs.MapsetDialog(parent = self)
-        if dlg.ShowModal() == wx.ID_OK:
-            mapset = dlg.GetMapset()
-            if mapset:
-                if gcmd.RunCommand("g.gisenv",
-                                   set = "MAPSET=%s" % mapset) != 0:
-                    wx.MessageBox(parent = self,
-                                  message = _("Unable to switch to mapset <%s>.") % mapset,
-                                  caption = _("Error"), style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
-                else:
-                    wx.MessageBox(parent = self,
-                                  message = _("Current mapset is <%s>.") % mapset,
-                                  caption = _("Info"), style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
-        
-    def OnNewVector(self, event):
-        """!Create new vector map layer"""
-        name, add = gdialogs.CreateNewVector(self, log = self.goutput,
-                                             cmd = (('v.edit',
-                                                     { 'tool' : 'create' },
-                                                     'map')))
-        
-        if name and add:
-            # add layer to map layer tree
-            self.curr_page.maptree.AddLayer(ltype='vector',
-                                            lname=name,
-                                            lchecked=True,
-                                            lopacity=1.0,
-                                            lcmd=['d.vect', 'map=%s' % name])
-        
-    def OnAboutGRASS(self, event):
-        """!Display 'About GRASS' dialog"""
-        win = AboutWindow(self)
-        win.CentreOnScreen()
-        win.Show(True)  
-        
-    def OnWorkspace(self, event):
-        """!Workspace menu (new, load)"""
-        point = wx.GetMousePosition()
-        menu = wx.Menu()
-
-        # Add items to the menu
-        new = wx.MenuItem(menu, wx.ID_ANY, Icons["workspaceNew"].GetLabel())
-        new.SetBitmap(Icons["workspaceNew"].GetBitmap(self.iconsize))
-        menu.AppendItem(new)
-        self.Bind(wx.EVT_MENU, self.OnWorkspaceNew, new)
-
-        load = wx.MenuItem(menu, wx.ID_ANY, Icons["workspaceLoad"].GetLabel())
-        load.SetBitmap(Icons["workspaceLoad"].GetBitmap(self.iconsize))
-        menu.AppendItem(load)
-        self.Bind(wx.EVT_MENU, self.OnWorkspaceLoad, load)
-
-        # create menu
-        self.PopupMenu(menu)
-        menu.Destroy()
-
-    def OnWorkspaceNew(self, event = None):
-        """!Create new workspace file
-
-        Erase current workspace settings first
-        """
-        Debug.msg(4, "GMFrame.OnWorkspaceNew():")
-        
-        # start new map display if no display is available
-        if not self.curr_page:
-            self.NewDisplay()
-        
-        maptree = self.curr_page.maptree
-        maptree.root = maptree.AddRoot("Map Layers")
-        self.curr_page.maptree.SetPyData(maptree.root, (None,None))
-        
-        # ask user to save current settings
-        if self.workspaceFile and self.workspaceChanged:
-            self.OnWorkspaceSave()
-        elif self.workspaceFile is None and maptree.GetCount() > 0:
-             dlg = wx.MessageDialog(self, message=_("Current workspace is not empty. "
-                                                    "Do you want to store current settings "
-                                                    "to workspace file?"),
-                                    caption=_("Create new workspace?"),
-                                    style=wx.YES_NO | wx.YES_DEFAULT | \
-                                        wx.CANCEL | wx.ICON_QUESTION)
-             ret = dlg.ShowModal()
-             if ret == wx.ID_YES:
-                 self.OnWorkspaceSaveAs()
-             elif ret == wx.ID_CANCEL:
-                 dlg.Destroy()
-                 return
-             
-             dlg.Destroy()
-        
-        # delete all items
-        maptree.DeleteAllItems()
-        
-        # add new root element
-        maptree.root = maptree.AddRoot("Map Layers")
-        self.curr_page.maptree.SetPyData(maptree.root, (None,None))
-        
-        # no workspace file loaded
-        self.workspaceFile = None
-        self.workspaceChanged = False
-        self.SetTitle(self.baseTitle)
-        
-    def OnWorkspaceOpen(self, event=None):
-        """!Open file with workspace definition"""
-        dlg = wx.FileDialog(parent=self, message=_("Choose workspace file"),
-                            defaultDir=os.getcwd(), wildcard=_("GRASS Workspace File (*.gxw)|*.gxw"))
-
-        filename = ''
-        if dlg.ShowModal() == wx.ID_OK:
-            filename = dlg.GetPath()
-
-        if filename == '':
-            return
-
-        Debug.msg(4, "GMFrame.OnWorkspaceOpen(): filename=%s" % filename)
-
-        # delete current layer tree content
-        self.OnWorkspaceClose()
-        
-        self.LoadWorkspaceFile(filename)
-
-        self.workspaceFile = filename
-        self.SetTitle(self.baseTitle + " - " +  os.path.basename(self.workspaceFile))
-
-    def LoadWorkspaceFile(self, filename):
-        """!Load layer tree definition stored in GRASS Workspace XML file (gxw)
-
-        @todo Validate against DTD
-        
-        @return True on success
-        @return False on error
-        """
-        # dtd
-        dtdFilename = os.path.join(globalvar.ETCWXDIR, "xml", "grass-gxw.dtd")
-        
-        # parse workspace file
-        try:
-            gxwXml = workspace.ProcessWorkspaceFile(etree.parse(filename))
-        except Exception, err:
-            raise gcmd.GStdError(_("Reading workspace file <%(file)s> failed.\n"
-                                   "Invalid file, unable to parse XML document."
-                                   "\n\n%(err)s") % \
-                                     { 'file' : filename, 'err' : 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 = list()
-        for display in gxwXml.displays:
-            mapdisp = self.NewDisplay(show=False)
-            mapdisplay.append(mapdisp)
-            maptree = self.gm_cb.GetPage(displayId).maptree
-            
-            # set windows properties
-            mapdisp.SetProperties(render=display['render'],
-                                  mode=display['mode'],
-                                  showCompExtent=display['showCompExtent'],
-                                  constrainRes=display['constrainRes'],
-                                  projection=display['projection']['enabled'])
-
-            if display['projection']['enabled']:
-                if display['projection']['epsg']:
-                    UserSettings.Set(group = 'display', key = 'projection', subkey = 'epsg',
-                                     value = display['projection']['epsg'])
-                    if display['projection']['proj']:
-                        UserSettings.Set(group = 'display', key = 'projection', subkey = 'proj4',
-                                         value = display['projection']['proj'])
-            
-            # set position and size of map display
-            if UserSettings.Get(group='workspace', key='posDisplay', subkey='enabled') is False:
-                if display['pos']:
-                    mapdisp.SetPosition(display['pos'])
-                if display['size']:
-                    mapdisp.SetSize(display['size'])
-                    
-            # set extent if defined
-            if display['extent']:
-                w, s, e, n = display['extent']
-                region = maptree.Map.region = maptree.Map.GetRegion(w=w, s=s, e=e, n=n)
-                mapdisp.GetWindow().ResetZoomHistory()
-                mapdisp.GetWindow().ZoomHistory(region['n'],
-                                                region['s'],
-                                                region['e'],
-                                                region['w'])
-                
-            mapdisp.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'],
-                                       lvdigit=layer['vdigit'])
-            
-            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()
-            
-        for mdisp in mapdisplay:
-            mdisp.MapWindow2D.UpdateMap()
-
-        return True
-
-    def OnWorkspaceLoad(self, event=None):
-        """!Load given map layers into layer tree"""
-        dialog = gdialogs.LoadMapLayersDialog(parent=self, title=_("Load map layers into layer tree"))
-
-        if dialog.ShowModal() == wx.ID_OK:
-            # start new map display if no display is available
-            if not self.curr_page:
-                self.NewDisplay()
-
-            maptree = self.curr_page.maptree
-            busy = wx.BusyInfo(message=_("Please wait, loading workspace..."),
-                               parent=self)
-            wx.Yield()
-            
-            for layerName in dialog.GetMapLayers():
-                if dialog.GetLayerType() == 'raster':
-                    cmd = ['d.rast', 'map=%s' % layerName]
-                elif dialog.GetLayerType() == 'vector':
-                    cmd = ['d.vect', 'map=%s' % layerName]
-                newItem = maptree.AddLayer(ltype=dialog.GetLayerType(),
-                                           lname=layerName,
-                                           lchecked=False,
-                                           lopacity=1.0,
-                                           lcmd=cmd,
-                                           lgroup=None)
-
-            busy.Destroy()
-
-    def OnWorkspaceLoadGrcFile(self, event):
-        """!Load map layers from GRC file (Tcl/Tk GUI) into map layer tree"""
-        dlg = wx.FileDialog(parent=self, message=_("Choose GRC file to load"),
-                            defaultDir=os.getcwd(), wildcard=_("Old GRASS Workspace File (*.grc)|*.grc"))
-
-        filename = ''
-        if dlg.ShowModal() == wx.ID_OK:
-            filename = dlg.GetPath()
-
-        if filename == '':
-            return
-
-        Debug.msg(4, "GMFrame.OnWorkspaceLoadGrcFile(): filename=%s" % filename)
-
-        # start new map display if no display is available
-        if not self.curr_page:
-            self.NewDisplay()
-
-        busy = wx.BusyInfo(message=_("Please wait, loading workspace..."),
-                           parent=self)
-        wx.Yield()
-
-        maptree = None
-        for layer in workspace.ProcessGrcFile(filename).read(self):
-            maptree = self.gm_cb.GetPage(layer['display']).maptree
-            newItem = maptree.AddLayer(ltype=layer['type'],
-                                       lname=layer['name'],
-                                       lchecked=layer['checked'],
-                                       lopacity=layer['opacity'],
-                                       lcmd=layer['cmd'],
-                                       lgroup=layer['group'])
-
-            busy.Destroy()
-            
-        if maptree:
-            # reverse list of map layers
-            maptree.Map.ReverseListOfLayers()
-
-    def OnWorkspaceSaveAs(self, event=None):
-        """!Save workspace definition to selected file"""
-        dlg = wx.FileDialog(parent=self, message=_("Choose file to save current workspace"),
-                            defaultDir=os.getcwd(), wildcard=_("GRASS Workspace File (*.gxw)|*.gxw"), style=wx.FD_SAVE)
-
-        filename = ''
-        if dlg.ShowModal() == wx.ID_OK:
-            filename = dlg.GetPath()
-
-        if filename == '':
-            return False
-
-        # check for extension
-        if filename[-4:] != ".gxw":
-            filename += ".gxw"
-
-        if os.path.exists(filename):
-            dlg = wx.MessageDialog(self, message=_("Workspace file <%s> already exists. "
-                                                   "Do you want to overwrite this file?") % filename,
-                                   caption=_("Save workspace"), style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
-            if dlg.ShowModal() != wx.ID_YES:
-                dlg.Destroy()
-                return False
-
-        Debug.msg(4, "GMFrame.OnWorkspaceSaveAs(): filename=%s" % filename)
-
-        self.SaveToWorkspaceFile(filename)
-        self.workspaceFile = filename
-        self.SetTitle(self.baseTitle + " - " + os.path.basename(self.workspaceFile))
-
-    def OnWorkspaceSave(self, event=None):
-        """!Save file with workspace definition"""
-        if self.workspaceFile:
-            dlg = wx.MessageDialog(self, message=_("Workspace file <%s> already exists. "
-                                                   "Do you want to overwrite this file?") % \
-                                       self.workspaceFile,
-                                   caption=_("Save workspace"), style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
-            if dlg.ShowModal() == wx.ID_NO:
-                dlg.Destroy()
-            else:
-                Debug.msg(4, "GMFrame.OnWorkspaceSave(): filename=%s" % self.workspaceFile)
-                self.SaveToWorkspaceFile(self.workspaceFile)
-                self.SetTitle(self.baseTitle + " - " + os.path.basename(self.workspaceFile))
-        else:
-            self.OnWorkspaceSaveAs()
-
-    def SaveToWorkspaceFile(self, filename):
-        """!Save layer tree layout to workspace file
-
-        Return True on success, False on error
-        """
-
-        try:
-            file = open(filename, "w")
-        except IOError:
-            wx.MessageBox(parent=self,
-                          message=_("Unable to open workspace file <%s> for writing.") % filename,
-                          caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
-            return False
-
-        try:
-            workspace.WriteWorkspaceFile(lmgr=self, file=file)
-        except StandardError, e:
-            file.close()
-            wx.MessageBox(parent=self,
-                          message=_("Writing current settings to workspace file failed (%s)." % e),
-                          caption=_("Error"),
-                          style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
-            return False
-
-        file.close()
-        
-        return True
-    
-    def OnWorkspaceClose(self, event = None):
-        """!Close file with workspace definition
-        
-        If workspace has been modified ask user to save the changes.
-        """
-        Debug.msg(4, "GMFrame.OnWorkspaceClose(): file=%s" % self.workspaceFile)
-        
-        displays = list()
-        for page in range(0, self.gm_cb.GetPageCount()):
-            displays.append(self.gm_cb.GetPage(page).maptree.mapdisplay)
-        
-        for display in displays:
-            display.OnCloseWindow(event)
-        
-        self.workspaceFile = None
-        self.workspaceChanged = False
-        self.SetTitle(self.baseTitle)
-        self.disp_idx = 0
-        self.curr_page = None
-        
-    def RulesCmd(self, event, cmd = ''):
-        """
-        Launches dialog for commands that need rules
-        input and processes rules
-        """
-        if event:
-            cmd = self.GetMenuCmd(event)
-                
-        if cmd[0] == 'r.colors' or cmd[0] == 'vcolors':
-            ctable = colorrules.ColorTable(self, cmd=cmd[0])
-            ctable.Show()
-        else:
-            dlg = rules.RulesText(self, cmd=cmd)
-            dlg.CenterOnScreen()
-            if dlg.ShowModal() == wx.ID_OK:
-                gtemp = utils.GetTempfile()
-                output = open(gtemp, "w")
-                try:
-                    output.write(dlg.rules)
-                finally:
-                    output.close()
-    
-                cmdlist = [cmd[0],
-                           'input=%s' % dlg.inmap,
-                           'output=%s' % dlg.outmap,
-                           'rules=%s' % gtemp]
-    
-                if dlg.overwrite == True:
-                    cmdlist.append('--o')
-    
-                dlg.Destroy()
-    
-                self.goutput.RunCmd(cmdlist)
-
-    def OnXTermNoXMon(self, event):
-        """!
-        Run commands that need xterm
-        """
-        self.OnXTerm(event, need_xmon = False)
-        
-    def OnXTerm(self, event, need_xmon = True):
-        """!
-        Run commands that need interactive xmon
-
-        @param need_xmon True to start X monitor
-        """
-        # unset display mode
-        del os.environ['GRASS_RENDER_IMMEDIATE']
-        
-        if need_xmon:
-            # open next available xmon
-            xmonlist = []
-            
-            # make list of xmons that are not running
-            ret = gcmd.RunCommand('d.mon',
-                                  flags = 'L',
-                                  read = True)
-            
-            for line in ret.split('\n'):               
-                line = line.strip()
-                if line.startswith('x') and 'not running' in line:
-                    xmonlist.append(line[0:2])
-            
-            # find available xmon
-            xmon = xmonlist[0]
-            
-            # bring up the xmon
-            cmdlist = ['d.mon', xmon]
-            p = gcmd.Command(cmdlist, wait=False)
-        
-        # run the command        
-        command = self.GetMenuCmd(event)
-        command = ' '.join(command)
-        
-        gisbase = os.environ['GISBASE']
-        
-        if sys.platform == "win32":
-            runbat = os.path.join(gisbase,'etc','grass-run.bat')
-            cmdlist = ["start", runbat, runbat, command]
-        else:
-            if sys.platform == "darwin":
-                xtermwrapper = os.path.join(gisbase,'etc','grass-xterm-mac')
-            else:
-                xtermwrapper = os.path.join(gisbase,'etc','grass-xterm-wrapper')
-            
-            grassrun = os.path.join(gisbase,'etc','grass-run.sh')
-            cmdlist = [xtermwrapper, '-e', grassrun, command]
-        
-        p = gcmd.Command(cmdlist, wait=False)
-        
-        # reset display mode
-        os.environ['GRASS_RENDER_IMMEDIATE'] = 'TRUE'
-        
-    def OnPreferences(self, event):
-        """!General GUI preferences/settings"""
-        if not self.dialogs['preferences']:
-            dlg = preferences.PreferencesDialog(parent=self)
-            self.dialogs['preferences'] = dlg
-            self.dialogs['preferences'].CenterOnScreen()
-
-        self.dialogs['preferences'].ShowModal()
-        
-    def DispHistogram(self, event):
-        """
-        Init histogram display canvas and tools
-        """
-        self.histogram = histogram.HistFrame(self,
-                                             id=wx.ID_ANY, pos=wx.DefaultPosition, size=(400,300),
-                                             style=wx.DEFAULT_FRAME_STYLE)
-
-        #show new display
-        self.histogram.Show()
-        self.histogram.Refresh()
-        self.histogram.Update()
-
-    def DispProfile(self, event):
-        """
-        Init profile canvas and tools
-        """
-        self.profile = profile.ProfileFrame(self,
-                                           id=wx.ID_ANY, pos=wx.DefaultPosition, size=(400,300),
-                                           style=wx.DEFAULT_FRAME_STYLE)
-        self.profile.Show()
-        self.profile.Refresh()
-        self.profile.Update()
-        
-    def OnMapCalculator(self, event, cmd = ''):
-        """!Init map calculator for interactive creation of mapcalc statements
-        """
-
-        if event:
-            cmd = self.GetMenuCmd(event)
-
-        win = mapcalculator.MapCalcFrame(parent = self, title = _('GRASS GIS Map Calculator'),
-                                         cmd=cmd[0])
-        win.CentreOnScreen()
-        win.Show()
-        
-    def OnMapCalculator3D(self, event, cmd =''):
-        """!Init map calculator for interactive creation of mapcalc statements
-        """
-        if event:
-            cmd = self.GetMenuCmd(event)
-
-        win = mapcalculator.MapCalcFrame(parent = self, title = _('GRASS GIS Map Calculator (3D raster)'),
-                                         cmd=cmd[0])
-        win.CentreOnScreen()
-        win.Show()
-        
-    def OnVectorCleaning(self, event, cmd = ''):
-        """!Init interactive vector cleaning
-        """
-        
-        if event:
-            cmd = self.GetMenuCmd(event)
-
-        win = vclean.VectorCleaningFrame(parent = self, cmd = cmd[0])
-        win.CentreOnScreen()
-        win.Show()
-        
-    def OnImportDxfFile(self, event):
-        """!Convert multiple DXF layers to GRASS vector map layers"""
-        dlg = gdialogs.DxfImportDialog(parent=self)
-        dlg.ShowModal()
-
-    def OnImportGdalLayers(self, event):
-        """!Convert multiple GDAL layers to GRASS raster map layers"""
-        dlg = gdialogs.GdalImportDialog(parent=self)
-        dlg.ShowModal()
-
-    def OnLinkGdalLayers(self, event):
-        """!Link multiple GDAL layers to GRASS raster map layers"""
-        dlg = gdialogs.GdalImportDialog(parent=self, link = True)
-        dlg.ShowModal()
-        
-    def OnImportOgrLayers(self, event):
-        """!Convert multiple OGR layers to GRASS vector map layers"""
-        dlg = gdialogs.GdalImportDialog(parent=self, ogr = True)
-        dlg.ShowModal()
-        
-    def OnLinkOgrLayers(self, event):
-        """!Links multiple OGR layers to GRASS vector map layers"""
-        dlg = gdialogs.GdalImportDialog(parent=self, ogr = True, link = True)
-        dlg.ShowModal()
-        
-    def OnImportWMS(self, event):
-        """!Import data from OGC WMS server"""
-        dlg = ogc_services.WMSDialog(parent = self, service = 'wms')
-        dlg.CenterOnScreen()
-        
-        if dlg.ShowModal() == wx.ID_OK: # -> import layers
-            layers = dlg.GetLayers()
-            
-            if len(layers.keys()) > 0:
-                for layer in layers.keys():
-                    cmd = ['r.in.wms',
-                           'mapserver=%s' % dlg.GetSettings()['server'],
-                           'layers=%s' % layer,
-                           'output=%s' % layer]
-                    styles = ','.join(layers[layer])
-                    if styles:
-                        cmd.append('styles=%s' % styles)
-                    self.goutput.RunCmd(cmd, switchPage = True)
-            else:
-                self.goutput.WriteWarning(_("Nothing to import. No WMS layer selected."))
-        
-        dlg.Destroy()
-        
-    def OnShowAttributeTable(self, event):
-        """
-        Show attribute table of the given vector map layer
-        """
-        if not self.curr_page:
-            self.MsgNoLayerSelected()
-            return
-        
-        layer = self.curr_page.maptree.layer_selected
-        # no map layer selected
-        if not layer:
-            self.MsgNoLayerSelected()
-            return
-        
-        # available only for vector map layers
-        try:
-            maptype = self.curr_page.maptree.GetPyData(layer)[0]['maplayer'].type
-        except:
-            maptype = None
-        
-        if not maptype or maptype != 'vector':
-            wx.MessageBox(parent=self,
-                          message=_("Attribute management is available only "
-                                    "for vector maps."),
-                          caption=_("Message"),
-                          style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
-            return
-        
-        if not self.curr_page.maptree.GetPyData(layer)[0]:
-            return
-        dcmd = self.curr_page.maptree.GetPyData(layer)[0]['cmd']
-        if not dcmd:
-            return
-        
-        busy = wx.BusyInfo(message=_("Please wait, loading attribute data..."),
-                           parent=self)
-        wx.Yield()
-        
-        dbmanager = dbm.AttributeManager(parent=self, id=wx.ID_ANY,
-                                         size=wx.Size(500, 300),
-                                         item=layer, log=self.goutput)
-        
-        busy.Destroy()
-        
-        # register ATM dialog
-        self.dialogs['atm'].append(dbmanager)
-        
-        # show ATM window
-        dbmanager.Show()
-        
-    def OnNewDisplay(self, event=None):
-        """!Create new layer tree and map display instance"""
-        self.NewDisplay()
-
+ 
     def NewDisplay(self, show=True):
         """!Create new layer tree, which will
         create an associated map display frame
@@ -1225,334 +284,11 @@
         """
         Debug.msg(1, "GMFrame.NewDisplay(): idx=%d" % self.disp_idx)
         
-        # make a new page in the bookcontrol for the layer tree (on page 0 of the notebook)
-
         self.disp_idx = self.disp_idx + 1
-#        self.curr_pagenum  = self.disp_idx
-        self.locationchange = True
-
-#        self.cb_loclist.append( str(self.cmbLocation.GetValue()) )
- #       self.cb_maplist.append( str(self.cmbMapset.GetValue()) )
-    
-        #print self.cb_maplist
-        #print self.cb_loclist
-
         
         self.page = MapFrame(parent=self.notebook, id=wx.ID_ANY, Map=render.Map(),  size=globalvar.MAP_WINDOW_SIZE,frame=self)
         self.notebook.InsertPage(self.disp_idx,self.page, text="Display "+ str(self.disp_idx), select = True)
 
-
-    # toolBar button handlers
-    def OnAddRaster(self, event):
-        """!Add raster map layer"""
-        # start new map display if no display is available
-        if not self.curr_page:
-            self.NewDisplay(show=False)
-        
-        self.AddRaster(event)
-        
-    def OnAddRasterMisc(self, event):
-        """!Add raster menu"""
-        # start new map display if no display is available
-        if not self.curr_page:
-            self.NewDisplay(show=False)
-
-        point = wx.GetMousePosition()
-        rastmenu = wx.Menu()
-
-        # add items to the menu
-        if self.curr_page.maptree.mapdisplay.toolbars['nviz']:
-            addrast3d = wx.MenuItem(rastmenu, -1, Icons ["addrast3d"].GetLabel())
-            addrast3d.SetBitmap(Icons["addrast3d"].GetBitmap (self.iconsize))
-            rastmenu.AppendItem(addrast3d)
-            self.Bind(wx.EVT_MENU, self.AddRaster3d, addrast3d)
-
-        addshaded = wx.MenuItem(rastmenu, -1, Icons ["addshaded"].GetLabel())
-        addshaded.SetBitmap(Icons["addshaded"].GetBitmap (self.iconsize))
-        rastmenu.AppendItem(addshaded)
-        self.Bind(wx.EVT_MENU, self.AddShaded, addshaded)
-
-        addrgb = wx.MenuItem(rastmenu, -1, Icons["addrgb"].GetLabel())
-        addrgb.SetBitmap(Icons["addrgb"].GetBitmap(self.iconsize))
-        rastmenu.AppendItem(addrgb)
-        self.Bind(wx.EVT_MENU, self.AddRGB, addrgb)
-
-        addhis = wx.MenuItem(rastmenu, -1, Icons ["addhis"].GetLabel())
-        addhis.SetBitmap(Icons["addhis"].GetBitmap (self.iconsize))
-        rastmenu.AppendItem(addhis)
-        self.Bind(wx.EVT_MENU, self.AddHIS, addhis)
-
-        addrastarrow = wx.MenuItem(rastmenu, -1, Icons ["addrarrow"].GetLabel())
-        addrastarrow.SetBitmap(Icons["addrarrow"].GetBitmap (self.iconsize))
-        rastmenu.AppendItem(addrastarrow)
-        self.Bind(wx.EVT_MENU, self.AddRastarrow, addrastarrow)
-
-        addrastnums = wx.MenuItem(rastmenu, -1, Icons ["addrnum"].GetLabel())
-        addrastnums.SetBitmap(Icons["addrnum"].GetBitmap (self.iconsize))
-        rastmenu.AppendItem(addrastnums)
-        self.Bind(wx.EVT_MENU, self.AddRastnum, addrastnums)
-
-        # Popup the menu.  If an item is selected then its handler
-        # will be called before PopupMenu returns.
-        self.PopupMenu(rastmenu)
-        rastmenu.Destroy()
-        
-        # show map display
-        self.curr_page.maptree.mapdisplay.Show()
-
-    def OnAddVector(self, event):
-        """!Add vector map layer"""
-        # start new map display if no display is available
-        if not self.curr_page:
-            self.NewDisplay(show=False)
-        
-        self.AddVector(event)
-        
-    def OnAddVectorMisc(self, event):
-        """!Add vector menu"""
-        # start new map display if no display is available
-        if not self.curr_page:
-            self.NewDisplay(show=False)
-
-        point = wx.GetMousePosition()
-        vectmenu = wx.Menu()
-        
-        addtheme = wx.MenuItem(vectmenu, -1, Icons["addthematic"].GetLabel())
-        addtheme.SetBitmap(Icons["addthematic"].GetBitmap(self.iconsize))
-        vectmenu.AppendItem(addtheme)
-        self.Bind(wx.EVT_MENU, self.AddThemeMap, addtheme)
-
-        addchart = wx.MenuItem(vectmenu, -1, Icons["addchart"].GetLabel())
-        addchart.SetBitmap(Icons["addchart"].GetBitmap(self.iconsize))
-        vectmenu.AppendItem(addchart)
-        self.Bind(wx.EVT_MENU, self.AddThemeChart, addchart)
-
-        # Popup the menu.  If an item is selected then its handler
-        # will be called before PopupMenu returns.
-        self.PopupMenu(vectmenu)
-        vectmenu.Destroy()
-
-        # show map display
-        self.curr_page.maptree.mapdisplay.Show()
-
-    def OnAddOverlay(self, event):
-        """!Add decoration overlay menu""" 
-        # start new map display if no display is available
-        if not self.curr_page:
-            self.NewDisplay(show=False)
-
-        point = wx.GetMousePosition()
-        ovlmenu = wx.Menu()
-
-        addgrid = wx.MenuItem(ovlmenu, wx.ID_ANY, Icons["addgrid"].GetLabel())
-        addgrid.SetBitmap(Icons["addgrid"].GetBitmap(self.iconsize))
-        ovlmenu.AppendItem(addgrid)
-        self.Bind(wx.EVT_MENU, self.AddGrid, addgrid)
-        
-        addlabels = wx.MenuItem(ovlmenu, wx.ID_ANY, Icons["addlabels"].GetLabel())
-        addlabels.SetBitmap(Icons["addlabels"].GetBitmap(self.iconsize))
-        ovlmenu.AppendItem(addlabels)
-        self.Bind(wx.EVT_MENU, self.OnAddLabels, addlabels)
-        
-        addgeodesic = wx.MenuItem(ovlmenu, wx.ID_ANY, Icons["addgeodesic"].GetLabel())
-        addgeodesic.SetBitmap(Icons["addgeodesic"].GetBitmap(self.iconsize))
-        ovlmenu.AppendItem(addgeodesic)
-        self.Bind(wx.EVT_MENU, self.AddGeodesic, addgeodesic)
-        
-        addrhumb = wx.MenuItem(ovlmenu, wx.ID_ANY, Icons["addrhumb"].GetLabel())
-        addrhumb.SetBitmap(Icons["addrhumb"].GetBitmap(self.iconsize))
-        ovlmenu.AppendItem(addrhumb)
-        self.Bind(wx.EVT_MENU, self.AddRhumb, addrhumb)
-
-        # Popup the menu.  If an item is selected then its handler
-        # will be called before PopupMenu returns.
-        self.PopupMenu(ovlmenu)
-        ovlmenu.Destroy()
-
-        # show map display
-        self.curr_page.maptree.mapdisplay.Show()
-
-    def AddRaster(self, event):
-        #self.notebook.SetSelection(0)
-        self.curr_page.maptree.AddLayer('raster')
-
-    def AddRaster3d(self, event):
-        #self.notebook.SetSelection(0)
-        self.curr_page.maptree.AddLayer('3d-raster')
-
-    def AddRGB(self, event):
-        """!Add RGB layer"""
-        #self.notebook.SetSelection(0)
-        self.curr_page.maptree.AddLayer('rgb')
-
-    def AddHIS(self, event):
-        """!Add HIS layer"""
-        #self.notebook.SetSelection(0)
-        self.curr_page.maptree.AddLayer('his')
-
-    def AddShaded(self, event):
-        """!Add shaded relief map layer"""
-        #self.notebook.SetSelection(0)
-        self.curr_page.maptree.AddLayer('shaded')
-
-    def AddRastarrow(self, event):
-        """!Add raster flow arrows map"""
-        #self.notebook.SetSelection(0)
-        self.curr_page.maptree.AddLayer('rastarrow')
-
-    def AddRastnum(self, event):
-        """!Add raster map with cell numbers"""
-        #self.notebook.SetSelection(0)
-        self.curr_page.maptree.AddLayer('rastnum')
-
-    def AddVector(self, event):
-        """!Add vector layer"""
-        #self.notebook.SetSelection(0)
-        self.curr_page.maptree.AddLayer('vector')
-
-    def AddThemeMap(self, event):
-        """!Add thematic map layer"""
-        #self.notebook.SetSelection(0)
-        self.curr_page.maptree.AddLayer('thememap')
-
-    def AddThemeChart(self, event):
-        """!Add thematic chart layer"""
-        #self.notebook.SetSelection(0)
-        self.curr_page.maptree.AddLayer('themechart')
-
-    def OnAddCommand(self, event):
-        """!Add command line layer"""
-        # start new map display if no display is available
-        if not self.curr_page:
-            self.NewDisplay(show=False)
-
-        #self.notebook.SetSelection(0)
-        self.curr_page.maptree.AddLayer('command')
-
-        # show map display
-        self.curr_page.maptree.mapdisplay.Show()
-
-    def OnAddGroup(self, event):
-        """!Add layer group"""
-        # start new map display if no display is available
-        if not self.curr_page:
-            self.NewDisplay(show=False)
-
-        self.notebook.SetSelection(0)
-        self.curr_page.maptree.AddLayer('group')
-
-        # show map display
-        self.curr_page.maptree.mapdisplay.Show()
-
-    def AddGrid(self, event):
-        """!Add layer grid"""
-        #self.notebook.SetSelection(0)
-        self.curr_page.maptree.AddLayer('grid')
-
-    def AddGeodesic(self, event):
-        """!Add layer geodesic"""
-        #self.notebook.SetSelection(0)
-        self.curr_page.maptree.AddLayer('geodesic')
-
-    def AddRhumb(self, event):
-        """!Add layer rhumb"""
-        #self.notebook.SetSelection(0)
-        self.curr_page.maptree.AddLayer('rhumb')
-
-    def OnAddLabels(self, event):
-        """!Add layer vector labels"""
-        # start new map display if no display is available
-        if not self.curr_page:
-            self.NewDisplay(show=False)
-
-        #self.notebook.SetSelection(0)
-        self.curr_page.maptree.AddLayer('labels')
-
-        # show map display
-        self.curr_page.maptree.mapdisplay.Show()
-
-    def OnDeleteLayer(self, event):
-        """
-        Delete selected map display layer in GIS Manager tree widget
-        """
-        if not self.curr_page or not self.curr_page.maptree.layer_selected:
-            self.MsgNoLayerSelected()
-            return
-
-        if UserSettings.Get(group='manager', key='askOnRemoveLayer', subkey='enabled'):
-            layerName = ''
-            for item in self.curr_page.maptree.GetSelections():
-                name = str(self.curr_page.maptree.GetItemText(item))
-                idx = name.find('(opacity')
-                if idx > -1:
-                    layerName += '<' + name[:idx].strip(' ') + '>,\n'
-                else:
-                    layerName += '<' + name + '>,\n'
-            layerName = layerName.rstrip(',\n')
-            
-            if len(layerName) > 2: # <>
-                message = _("Do you want to remove map layer(s)\n%s\n"
-                            "from layer tree?") % layerName
-            else:
-                message = _("Do you want to remove selected map layer(s) "
-                            "from layer tree?")
-
-            dlg = wx.MessageDialog (parent=self, message=message,
-                                    caption=_("Remove map layer"),
-                                    style=wx.YES_NO | wx.YES_DEFAULT | wx.CANCEL | wx.ICON_QUESTION)
-
-            if dlg.ShowModal() in [wx.ID_NO, wx.ID_CANCEL]:
-                dlg.Destroy()
-                return
-
-            dlg.Destroy()
-
-        for layer in self.curr_page.maptree.GetSelections():
-            if self.curr_page.maptree.GetPyData(layer)[0]['type'] == 'group':
-                self.curr_page.maptree.DeleteChildren(layer)
-            self.curr_page.maptree.Delete(layer)
-        
-    def OnKeyDown(self, event):
-        """!Key pressed"""
-        kc = event.GetKeyCode()
-        
-        if event.ControlDown():
-            if kc == wx.WXK_TAB:
-                # switch layer list / command output
-                if self.notebook.GetSelection() == 0:
-                    self.notebook.SetSelection(1)
-                else:
-                    self.notebook.SetSelection(0)
-        
-        try:
-            ckc = chr(kc)
-        except ValueError:
-            event.Skip()
-            return
-        
-        if event.CtrlDown():
-            if kc == 'R':
-                self.OnAddRaster(None)
-            elif kc == 'V':
-                self.OnAddVector(None)
-        
-        event.Skip()
-
-    def OnQuit(self, event):
-        """!Quit GRASS session (wxGUI and shell)"""
-        # quit wxGUI session
-        self.OnCloseWindow(event)
-
-        # quit GRASS shell
-        try:
-            pid = int(os.environ['GIS_LOCK'])
-        except (KeyError, ValueError):
-            sys.stderr.write('\n')
-            sys.stderr.write(_("WARNING: Unable to quit GRASS, uknown GIS_LOCK"))
-            return
-        
-        os.kill(pid, signal.SIGQUIT)
-        
     def OnCloseWindow(self, event):
         """!Cleanup when wxGUI is quit"""
         if not self.curr_page:
@@ -1599,14 +335,6 @@
         
         self._auimgr.UnInit()
         self.Destroy()
-        
-    def MsgNoLayerSelected(self):
-        """!Show dialog message 'No layer selected'"""
-        wx.MessageBox(parent=self,
-                      message=_("No map layer selected. Operation cancelled."),
-                      caption=_("Message"),
-                      style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
-    
 
     def OnMapsetChange(self,event):
         """
@@ -1636,36 +364,14 @@
             self.cb_loclist.append( str(self.cmbLocation.GetValue()) )
             self.cb_maplist.append( str(self.cmbMapset.GetValue()) )
 
-            #self.cb_mapfile.append( self.page.Map)
-            self.locationchange = False
 
-    
-
-    
-        
-             
-
-
-
-        
-    def OnRunScript():
-        print "for grass7"
-
-    def OnQuit():
-        print "for grass7"
-
     def OnLocationChange(self,event):
         """
         Populate mapset combobox with selected location.
         """
-
-
-
         self.cmbMapset.Clear()
         self.cmbMapset.SetValue("Select Mapset")
-        #self.ltree.DeleteAllItems()
 
-
         maplists = self.GetMapsets(self.cmbLocation.GetValue())
         for mapsets in maplists:
 	        self.cmbMapset.Append(str(mapsets))
@@ -1697,14 +403,8 @@
 	    #Event bindings for combo boxes
         self.Bind(wx.EVT_COMBOBOX,self.OnMapsetChange,self.cmbMapset)
         self.Bind(wx.EVT_COMBOBOX,self.OnLocationChange,self.cmbLocation)
-
-
-
         self.Bind(wx.EVT_CLOSE,    self.OnCloseWindow)
 
-	    #Event bindings for v/r.info checkbox
-	    #self.Bind(wx.EVT_CHECKBOX, self.OnToggleInfo,self.chkInfo)
-       
  
     def doLayout(self):
 
@@ -1714,14 +414,10 @@
         self.cmbSizer.Add(self.mInfo)
         self.cmbSizer.Add(self.radiobox)
         self.mSizer.Add(self.cmbPanel,flag=wx.EXPAND)
-        #self.mSizer.Add(self.win, 1, wx.EXPAND)
-        #self.leftSizer.Add(self.ltree,1,wx.EXPAND)
         self.mSizer.Add(self.notebook,1,wx.EXPAND)
 
         self.cmbPanel.SetSizer(self.cmbSizer)
         self.SetSizer(self.mSizer)
-       # self.pLeft.SetSizer(self.leftSizer)
-        #self.pRight.SetSizer(self.rightSizer)
 
 
 

Modified: grass-addons/gui/wxpython/data_catalog/mapdisplay.py
===================================================================
--- grass-addons/gui/wxpython/data_catalog/mapdisplay.py	2010-06-19 12:23:55 UTC (rev 42588)
+++ grass-addons/gui/wxpython/data_catalog/mapdisplay.py	2010-06-19 14:15:21 UTC (rev 42589)
@@ -106,9 +106,9 @@
 # for standalone app
 cmdfilename = None
 from mapdisp_window import BufferedWindow
+from mapdisp import MapFrame
 
-
-class MapFrame(wx.Panel):
+class MapFrame(wx.Panel,MapFrame):
     """
     Main frame for map display window. Drawing takes place in child double buffered
     drawing window.
@@ -141,9 +141,7 @@
         self.statusFlag = flag
         self.statusbar = None
 
-        #FIX THIS
-
-        
+   
         #
         # available cursors
         #
@@ -163,30 +161,11 @@
         wx.Panel.__init__(self, parent, id, pos, size, style)
         self.SetName("MapWindow")
 
-        #
-        # set the size & system icon
-        #
-        #self.SetClientSize(size)
-        self.iconsize = (16, 16)
 
-
-
-
-        #self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass_map.ico'), wx.BITMAP_TYPE_ICO))
-
-        #
-        # Fancy gui
-        #
-        # self._mgr = auimgr
-
-      
-
         self._mgr = wx.aui.AuiManager(self)
         self._layerManager = self.frame
-        
-        #self._layerManager.goutput = goutput.GMConsole(self.parent.GetParent(), pageid=1)
-        #self._layerManager.goutput.Hide()
 
+
         #
         # Add toolbars
         #
@@ -313,7 +292,8 @@
         self.maptree = LayerTree(self, id=wx.ID_ANY, pos=wx.DefaultPosition,
                                                       size=wx.DefaultSize, style=wx.TR_HAS_BUTTONS
                                                       |wx.TR_LINES_AT_ROOT|wx.TR_HIDE_ROOT,
-                                                      gisdbase=self.gisdbase,Map = self.Map,lmgr=self.gismanager,frame=frame)
+                                                      gisdbase=self.gisdbase,Map = self.Map,lmgr=self.gismanager,frame=frame,idx=0,
+                                                      notebook=self.layerbook,auimgr=None,showMapDisplay=True)
 
 
 
@@ -433,1721 +413,3 @@
 
 
 
-    def AddToolbar(self, name):
-        """!Add defined toolbar to the window
-        
-        Currently known toolbars are:
-         - 'map'     - basic map toolbar
-         - 'vdigit'  - vector digitizer
-         - 'georect' - georectifier
-         - 'nviz'    - 3D view mode
-        """
-        # default toolbar
-        if name == "map":
-            self.toolbars['map'] = toolbars.MapToolbar(self, self.Map)
-
-            self._mgr.AddPane(self.toolbars['map'],
-                              wx.aui.AuiPaneInfo().
-                              Name("maptoolbar").Caption(_("Map Toolbar")).
-                              ToolbarPane().Top().
-                              LeftDockable(False).RightDockable(False).
-                              BottomDockable(False).TopDockable(True).
-                              CloseButton(False).Layer(2).
-                              BestSize((self.toolbars['map'].GetSize())))
-	
-        # vector digitizer
-        elif name == "vdigit":
-            from vdigit import haveVDigit
-            if not haveVDigit:
-                from vdigit import errorMsg
-                msg = _("Unable to start vector digitizer.\nThe VDigit python extension "
-                        "was not found or loaded properly.\n"
-                        "Switching back to 2D display mode.\n\nDetails: %s" % errorMsg)
-                
-                self.toolbars['map'].combo.SetValue (_("2D view"))
-                wx.MessageBox(parent=self,
-                              message=msg,
-                              caption=_("Error"),
-                              style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
-                return
-            
-            if self._layerManager:
-                log = self._layerManager.goutput
-            else:
-                log = None
-            self.toolbars['vdigit'] = toolbars.VDigitToolbar(parent=self, mapcontent=self.Map,
-                                                             layerTree=self.tree,
-                                                             log=log)
-            
-            self._mgr.AddPane(self.toolbars['vdigit'],
-                              wx.aui.AuiPaneInfo().
-                              Name("vdigittoolbar").Caption(_("Vector digitizer toolbar")).
-                              ToolbarPane().Top().Row(1).
-                              LeftDockable(False).RightDockable(False).
-                              BottomDockable(False).TopDockable(True).
-                              CloseButton(False).Layer(2).
-                              BestSize((self.toolbars['vdigit'].GetSize())))
-            
-            # change mouse to draw digitized line
-            self.MapWindow.mouse['box'] = "point"
-            self.MapWindow.zoomtype = 0
-            self.MapWindow.pen     = wx.Pen(colour='red',   width=2, style=wx.SOLID)
-            self.MapWindow.polypen = wx.Pen(colour='green', width=2, style=wx.SOLID)
-        # georectifier
-        elif name == "georect":
-            self.toolbars['georect'] = toolbars.GRToolbar(self, self.Map)
-
-            self._mgr.AddPane(self.toolbars['georect'],
-                              wx.aui.AuiPaneInfo().
-                              Name("georecttoolbar").Caption(_("Georectification toolbar")).
-                              ToolbarPane().Top().
-                              LeftDockable(False).RightDockable(False).
-                              BottomDockable(False).TopDockable(True).
-                              CloseButton(False).Layer(2))
-        # nviz
-        elif name == "nviz":
-            import nviz
-            
-            # check for GLCanvas and OpenGL
-            msg = None
-            if not nviz.haveGLCanvas:
-                msg = _("Unable to switch to 3D display mode.\nThe GLCanvas class has not been "
-                        "included with this build "
-                        "of wxPython!\nSwitching back to "
-                        "2D display mode.\n\nDetails: %s" % nviz.errorMsg)
-            if not nviz.haveNviz:
-                msg = _("Unable to switch to 3D display mode.\nThe Nviz python extension "
-                        "was not found or loaded properly.\n"
-                        "Switching back to 2D display mode.\n\nDetails: %s" % nviz.errorMsg)
-            
-            if msg:
-                self.toolbars['map'].combo.SetValue (_("2D view"))
-                wx.MessageBox(parent=self,
-                              message=msg,
-                              caption=_("Error"),
-                              style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
-                return
-            
-            # add Nviz toolbar and disable 2D display mode tools
-            self.toolbars['nviz'] = toolbars.NvizToolbar(self, self.Map)
-            self.toolbars['map'].Enable2D(False)
-            
-            # update layer tree (-> enable 3d-rasters)
-            if self.tree:
-                self.tree.EnableItemType(type='3d-raster', enable=True)
-            
-            # update status bar
-            self.statusbarWin['toggle'].Enable(False)
-
-            # erase map window
-            self.MapWindow.EraseMap()
-
-            self.statusbar.SetStatusText(_("Please wait, loading data..."), 0)
-            
-            # create GL window & NVIZ toolbar
-            if not self.MapWindow3D:
-                self.MapWindow3D = nviz.GLWindow(self, id=wx.ID_ANY,
-                                                 Map=self.Map, tree=self.tree, lmgr=self._layerManager)
-                self.MapWindow = self.MapWindow3D
-                
-                # add Nviz notebookpage
-                self._layerManager.AddNviz()
-                
-                self.MapWindow3D.OnPaint(None) # -> LoadData
-                self.MapWindow3D.Show()
-                self.MapWindow3D.UpdateView(None)
-            else:
-                self.MapWindow = self.MapWindow3D
-                # add Nviz notebookpage
-                self._layerManager.AddNviz()
-            
-            # switch from MapWindow to MapWindowGL
-            # add nviz toolbar
-            self._mgr.DetachPane(self.MapWindow2D)
-            self.MapWindow2D.Hide()
-            self._mgr.AddPane(self.MapWindow3D, wx.aui.AuiPaneInfo().CentrePane().
-                              Dockable(False).BestSize((-1,-1)).
-                              CloseButton(False).DestroyOnClose(True).
-                              Layer(0))
-            self._mgr.AddPane(self.toolbars['nviz'],
-                              wx.aui.AuiPaneInfo().
-                              Name("nviztoolbar").Caption(_("Nviz toolbar")).
-                              ToolbarPane().Top().Row(1).
-                              LeftDockable(False).RightDockable(False).
-                              BottomDockable(False).TopDockable(True).
-                              CloseButton(False).Layer(2))
-            
-            self.SetStatusText("", 0)
-            
-        self._mgr.Update()
-
-    def RemoveToolbar (self, name):
-        """!Removes toolbar from the window
-
-        @todo Only hide, activate by calling AddToolbar()
-        """
-        # cannot hide main toolbar
-        if name == "map":
-            return
-        elif name == "vdigit":
-            # TODO: not destroy only hide
-            self._mgr.DetachPane(self.toolbars['vdigit'])
-            self.toolbars['vdigit'].Destroy()
-        else:
-            self._mgr.DetachPane (self.toolbars[name])
-            self.toolbars[name].Destroy()
-
-        self.toolbars[name] = None
-
-        if name == 'nviz':
-            # unload data
-            #            self.MapWindow3D.Reset()
-            # switch from MapWindowGL to MapWindow
-            self._mgr.DetachPane(self.MapWindow3D)
-            self.MapWindow3D.Hide()
-            self.MapWindow2D.Show()
-            self._mgr.AddPane(self.MapWindow2D, wx.aui.AuiPaneInfo().CentrePane().
-                              Dockable(False).BestSize((-1,-1)).
-                              CloseButton(False).DestroyOnClose(True).
-                              Layer(0))
-            self.MapWindow = self.MapWindow2D
-            # remove nviz notebook page
-            self._layerManager.RemoveNviz()
-            
-            # update layer tree (-> disable 3d-rasters)
-            if self.tree:
-                self.tree.EnableItemType(type='3d-raster', enable=False)
-            
-           
-            self.MapWindow.UpdateMap()
-            
-        self.toolbars['map'].combo.SetValue (_("2D view"))
-        self.toolbars['map'].Enable2D(True)
-        self.statusbarWin['toggle'].Enable(True)
-
-        self._mgr.Update()
-
-    def __InitDisplay(self):
-        """
-        Initialize map display, set dimensions and map region
-        """
-        self.width, self.height = self.GetClientSize()
-
-        Debug.msg(2, "MapFrame.__InitDisplay():")
-        self.Map.ChangeMapSize(self.GetClientSize())
-        self.Map.region = self.Map.GetRegion() # g.region -upgc
-        # self.Map.SetRegion() # adjust region to match display window
-
-    def OnUpdateProgress(self, event):
-        """
-        Update progress bar info
-        """
-        self.statusbarWin['progress'].SetValue(event.value)
-        
-        event.Skip()
-        
-    def OnFocus(self, event):
-        """
-        Change choicebook page to match display.
-        Or set display for georectifying
-        """
-        if self._layerManager and \
-                self._layerManager.georectifying:
-            # in georectifying session; display used to get get geographic
-            # coordinates for GCPs
-            self.OnPointer(event)
-        else:
-            # change bookcontrol page to page associated with display
-            if self.page:
-                pgnum = self.layerbook.GetPageIndex(self.page)
-                if pgnum > -1:
-                    self.layerbook.SetSelection(pgnum)
-        
-        event.Skip()
-
-    def OnMotion(self, event):
-        """
-        Mouse moved
-        Track mouse motion and update status bar
-        """
-        # update statusbar if required
-        if self.statusbarWin['toggle'].GetSelection() == 0: # Coordinates
-            precision = int(UserSettings.Get(group = 'projection', key = 'format',
-                                             subkey = 'precision'))
-            format = UserSettings.Get(group = 'projection', key = 'format',
-                                      subkey = 'll')
-            try:
-                e, n = self.MapWindow.Pixel2Cell(event.GetPositionTuple())
-            except AttributeError:
-                return
-            if self.toolbars['vdigit'] and \
-                    self.toolbars['vdigit'].GetAction() == 'addLine' and \
-                    self.toolbars['vdigit'].GetAction('type') in ('line', 'boundary') and \
-                    len(self.MapWindow.polycoords) > 0:
-                # for linear feature show segment and total length
-                distance_seg = self.MapWindow.Distance(self.MapWindow.polycoords[-1],
-                                                       (e, n), screen=False)[0]
-                distance_tot = distance_seg
-                for idx in range(1, len(self.MapWindow.polycoords)):
-                    distance_tot += self.MapWindow.Distance(self.MapWindow.polycoords[idx-1],
-                                                            self.MapWindow.polycoords[idx],
-                                                            screen=False )[0]
-                self.statusbar.SetStatusText("%.*f, %.*f (seg: %.*f; tot: %.*f)" % \
-                                                 (precision, e, precision, n,
-                                                  precision, distance_seg,
-                                                  precision, distance_tot), 0)
-            else:
-                if self.statusbarWin['projection'].IsChecked():
-                    if not UserSettings.Get(group='projection', key='statusbar', subkey='proj4'):
-                        self.statusbar.SetStatusText(_("Projection not defined (check the settings)"), 0)
-                    else:
-                        proj, coord  = utils.ReprojectCoordinates(coord = (e, n),
-                                                                  projOut = UserSettings.Get(group='projection',
-                                                                                             key='statusbar',
-                                                                                             subkey='proj4'),
-                                                                  flags = 'd')
-                    
-                        if coord:
-                            e, n = coord
-                            if proj in ('ll', 'latlong', 'longlat') and format == 'DMS':
-                                self.statusbar.SetStatusText("%s" % \
-                                                                 utils.Deg2DMS(e, n, precision = precision),
-                                                             0)
-                            else:
-                                self.statusbar.SetStatusText("%.*f; %.*f" % \
-                                                                 (precision, e, precision, n), 0)
-                        else:
-                            self.statusbar.SetStatusText(_("Error in projection (check the settings)"), 0)
-                else:
-                    if self.Map.projinfo['proj'] == 'll' and format == 'DMS':
-                        self.statusbar.SetStatusText("%s" % \
-                                                         utils.Deg2DMS(e, n, precision = precision),
-                                                     0)
-                    else:
-                        self.statusbar.SetStatusText("%.*f; %.*f" % \
-                                                         (precision, e, precision, n), 0)
-                
-        event.Skip()
-
-    def OnDraw(self, event):
-        """
-        Re-display current map composition
-        """
-        self.MapWindow.UpdateMap(render=False)
-        
-    def OnRender(self, event):
-        """
-        Re-render map composition (each map layer)
-        """
-        # delete tmp map layers (queries)
-        qlayer = self.Map.GetListOfLayers(l_name=globalvar.QUERYLAYER)
-        for layer in qlayer:
-            self.Map.DeleteLayer(layer)
-
-        # delete tmp lines
-        if self.MapWindow.mouse["use"] in ("measure",
-                                           "profile"):
-            self.MapWindow.polycoords = []
-            self.MapWindow.ClearLines()
-        
-        # deselect features in vdigit
-        if self.toolbars['vdigit'] and self.digit:
-            self.digit.driver.SetSelected([])
-            self.MapWindow.UpdateMap(render=True, renderVector=True)
-        else:
-            self.MapWindow.UpdateMap(render=True)
-        
-        # update statusbar
-        self.StatusbarUpdate()
-
-    def OnPointer(self, event):
-        """
-        Pointer button clicked
-        """
-        if self.toolbars['map']:
-            if event:
-                self.toolbars['map'].OnTool(event)
-            self.toolbars['map'].action['desc'] = ''
-        
-        self.MapWindow.mouse['use'] = "pointer"
-        self.MapWindow.mouse['box'] = "point"
-
-        # change the cursor
-        if self.toolbars['vdigit']:
-            # digitization tool activated
-            self.MapWindow.SetCursor(self.cursors["cross"])
-
-            # reset mouse['box'] if needed
-            if self.toolbars['vdigit'].GetAction() in ['addLine']:
-                if self.toolbars['vdigit'].GetAction('type') in ['point', 'centroid']:
-                    self.MapWindow.mouse['box'] = 'point'
-                else: # line, boundary
-                    self.MapWindow.mouse['box'] = 'line'
-            elif self.toolbars['vdigit'].GetAction() in ['addVertex', 'removeVertex', 'splitLine',
-                                                         'editLine', 'displayCats', 'displayAttrs',
-                                                         'copyCats']:
-                self.MapWindow.mouse['box'] = 'point'
-            else: # moveLine, deleteLine
-                self.MapWindow.mouse['box'] = 'box'
-        
-        elif self._layerManager and self._layerManager.georectifying:
-            self.MapWindow.SetCursor(self.cursors["cross"])
-        
-        else:
-            self.MapWindow.SetCursor(self.cursors["default"])
-
-    def OnZoomIn(self, event):
-        """
-        Zoom in the map.
-        Set mouse cursor, zoombox attributes, and zoom direction
-        """
-        if self.toolbars['map']:
-            self.toolbars['map'].OnTool(event)
-            self.toolbars['map'].action['desc'] = ''
-        
-        self.MapWindow.mouse['use'] = "zoom"
-        self.MapWindow.mouse['box'] = "box"
-        self.MapWindow.zoomtype = 1
-        self.MapWindow.pen = wx.Pen(colour='Red', width=2, style=wx.SHORT_DASH)
-        
-        # change the cursor
-        self.MapWindow.SetCursor(self.cursors["cross"])
-
-    def OnZoomOut(self, event):
-        """
-        Zoom out the map.
-        Set mouse cursor, zoombox attributes, and zoom direction
-        """
-        if self.toolbars['map']:
-            self.toolbars['map'].OnTool(event)
-            self.toolbars['map'].action['desc'] = ''
-        
-        self.MapWindow.mouse['use'] = "zoom"
-        self.MapWindow.mouse['box'] = "box"
-        self.MapWindow.zoomtype = -1
-        self.MapWindow.pen = wx.Pen(colour='Red', width=2, style=wx.SHORT_DASH)
-        
-        # change the cursor
-        self.MapWindow.SetCursor(self.cursors["cross"])
-
-    def OnZoomBack(self, event):
-        """
-        Zoom last (previously stored position)
-        """
-        self.MapWindow.ZoomBack()
-
-    def OnPan(self, event):
-        """
-        Panning, set mouse to drag
-        """
-        if self.toolbars['map']:
-            self.toolbars['map'].OnTool(event)
-            self.toolbars['map'].action['desc'] = ''
-        
-        self.MapWindow.mouse['use'] = "pan"
-        self.MapWindow.mouse['box'] = "pan"
-        self.MapWindow.zoomtype = 0
-        
-        # change the cursor
-        self.MapWindow.SetCursor(self.cursors["hand"])
-
-    def OnErase(self, event):
-        """
-        Erase the canvas
-        """
-        self.MapWindow.EraseMap()
-
-    def OnZoomRegion(self, event):
-        """
-        Zoom to region
-        """
-        self.Map.getRegion()
-        self.Map.getResolution()
-        self.UpdateMap()
-        # event.Skip()
-
-    def OnAlignRegion(self, event):
-        """
-        Align region
-        """
-        if not self.Map.alignRegion:
-            self.Map.alignRegion = True
-        else:
-            self.Map.alignRegion = False
-        # event.Skip()
-
-    def OnToggleRender(self, event):
-        """
-        Enable/disable auto-rendering
-        """
-        if self.statusbarWin['render'].GetValue():
-            self.OnRender(None)
-
-    def OnToggleShowRegion(self, event):
-        """
-        Show/Hide extent in map canvas
-        """
-        if self.statusbarWin['region'].GetValue():
-            # show extent
-            self.MapWindow.regionCoords = []
-        else:
-            del self.MapWindow.regionCoords
-
-        # redraw map if auto-rendering is enabled
-        if self.statusbarWin['render'].GetValue():
-            self.OnRender(None)
-
-    def OnToggleResolution(self, event):
-        """
-        Use resolution of computation region settings
-        for redering image instead of display resolution
-        """
-        # redraw map if auto-rendering is enabled
-        if self.statusbarWin['render'].GetValue():
-            self.OnRender(None)
-        
-    def OnToggleStatus(self, event):
-        """
-        Toggle status text
-        """
-        self.StatusbarUpdate()
-
-    def OnChangeMapScale(self, event):
-        """
-        Map scale changed by user
-        """
-        scale = event.GetString()
-
-        try:
-            if scale[:2] != '1:':
-                raise ValueError
-            value = int(scale[2:])
-        except ValueError:
-            self.statusbarWin['mapscale'].SetValue('1:%ld' % int(self.mapScaleValue))
-            return
-
-        dEW = value * (self.Map.region['cols'] / self.ppm[0])
-        dNS = value * (self.Map.region['rows'] / self.ppm[1])
-        self.Map.region['n'] = self.Map.region['center_northing'] + dNS / 2.
-        self.Map.region['s'] = self.Map.region['center_northing'] - dNS / 2.
-        self.Map.region['w'] = self.Map.region['center_easting']  - dEW / 2.
-        self.Map.region['e'] = self.Map.region['center_easting']  + dEW / 2.
-        
-        # add to zoom history
-        self.MapWindow.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
-                                   self.Map.region['e'], self.Map.region['w'])
-        
-        # redraw a map
-        self.MapWindow.UpdateMap()
-        self.statusbarWin['mapscale'].SetFocus()
-        
-    def OnGoTo(self, event):
-        """
-        Go to position
-        """
-        try:
-            if self.statusbarWin['projection'].IsChecked():
-                if not UserSettings.Get(group='projection', key='statusbar', subkey='proj4'):
-                    self.statusbar.SetStatusText(_("Projection not defined (check the settings)"), 0)
-                else:
-                    # reproject values
-                    projIn = UserSettings.Get(group='projection',
-                                              key='statusbar',
-                                              subkey='proj4')
-                    projOut = gcmd.RunCommand('g.proj',
-                                              flags = 'jf',
-                                              read = True)
-                    proj = projIn.split(' ')[0].split('=')[1]
-                    if proj in ('ll', 'latlong', 'longlat'):
-                        e, n = self.statusbarWin['goto'].GetValue().split(';')
-                        e, n = utils.DMS2Deg(e, n)
-                        proj, coord1 = utils.ReprojectCoordinates(coord = (e, n),
-                                                                  projIn = projIn,
-                                                                  projOut = projOut, flags = 'd')
-                        e, n = coord1
-                    else:
-                        e, n = map(float, self.statusbarWin['goto'].GetValue().split(';'))
-                        proj, coord1 = utils.ReprojectCoordinates(coord = (e, n),
-                                                                  projIn = projIn,
-                                                                  projOut = projOut, flags = 'd')
-                        e, n = coord1
-            else:
-                if self.Map.projinfo['proj'] == 'll':
-                    e, n = self.statusbarWin['goto'].GetValue().split(';')
-                else:
-                    e, n = map(float, self.statusbarWin['goto'].GetValue().split(';'))
-                    
-            region = self.Map.GetCurrentRegion()
-            if self.statusbarWin['projection'].IsChecked():
-                if not UserSettings.Get(group='projection', key='statusbar', subkey='proj4'):
-                    self.statusbar.SetStatusText(_("Projection not defined (check the settings)"), 0)
-                else:
-                    region['center_easting'], region['center_northing'] = e, n
-            else:
-                if self.Map.projinfo['proj'] == 'll':
-                    region['center_easting'], region['center_northing'] = utils.DMS2Deg(e, n)
-                else:
-                    region['center_easting'], region['center_northing'] = e, n
-        except ValueError:
-            region = self.Map.GetCurrentRegion()
-            precision = int(UserSettings.Get(group = 'projection', key = 'format',
-                                             subkey = 'precision'))
-            format = UserSettings.Get(group = 'projection', key = 'format',
-                                      subkey = 'll')
-            if self.Map.projinfo['proj'] == 'll' and format == 'DMS':
-                    self.statusbarWin['goto'].SetValue("%s" % utils.Deg2DMS(region['center_easting'], 
-                                                                            region['center_northing'],
-                                                                            precision = precision))
-            else:
-                self.statusbarWin['goto'].SetValue("%.*f; %.*f" % \
-                                                       (precision, region['center_easting'],
-                                                        precision, region['center_northing']))
-            return
-        
-        
-        dn = (region['nsres'] * region['rows']) / 2.
-        region['n'] = region['center_northing'] + dn
-        region['s'] = region['center_northing'] - dn
-        de = (region['ewres'] * region['cols']) / 2.
-        region['e'] = region['center_easting'] + de
-        region['w'] = region['center_easting'] - de
-        
-        self.Map.AdjustRegion()
-
-        # add to zoom history
-        self.MapWindow.ZoomHistory(region['n'], region['s'],
-                                   region['e'], region['w'])
-        
-        # redraw a map
-        self.MapWindow.UpdateMap()
-        self.statusbarWin['goto'].SetFocus()
-        
-    def StatusbarUpdate(self):
-        """!Update statusbar content"""
-
-        self.statusbarWin['region'].Hide()
-        self.statusbarWin['resolution'].Hide()
-        self.statusbarWin['mapscale'].Hide()
-        self.statusbarWin['goto'].Hide()
-        self.statusbarWin['projection'].Hide()
-        self.mapScaleValue = self.ppm = None
-
-        if self.statusbarWin['toggle'].GetSelection() == 0: # Coordinates
-            self.statusbar.SetStatusText("", 0)
-            # enable long help
-            self.StatusbarEnableLongHelp()
-
-        elif self.statusbarWin['toggle'].GetSelection() in (1, 2): # Extent
-            sel = self.statusbarWin['toggle'].GetSelection()
-            if sel == 1:
-                region = self.Map.region
-            else:
-                region = self.Map.GetRegion() # computation region
-
-            precision = int(UserSettings.Get(group = 'projection', key = 'format',
-                                             subkey = 'precision'))
-            format = UserSettings.Get(group = 'projection', key = 'format',
-                                      subkey = 'll')
-            
-            if self.statusbarWin['projection'].IsChecked():
-                if not UserSettings.Get(group='projection', key='statusbar', subkey='proj4'):
-                    self.statusbar.SetStatusText(_("Projection not defined (check the settings)"), 0)
-                else:
-                    projOut = UserSettings.Get(group='projection',
-                                               key='statusbar',
-                                               subkey='proj4')
-                    proj, coord1 = utils.ReprojectCoordinates(coord = (region["w"], region["s"]),
-                                                              projOut = projOut, flags = 'd')
-                    proj, coord2 = utils.ReprojectCoordinates(coord = (region["e"], region["n"]),
-                                                          projOut = projOut, flags = 'd')
-                    if sel == 2:
-                        proj, coord3 = utils.ReprojectCoordinates(coord = (0.0, 0.0),
-                                                                  projOut = projOut, flags = 'd')
-                        proj, coord4 = utils.ReprojectCoordinates(coord = (region["ewres"], region["nsres"]),
-                                                                  projOut = projOut, flags = 'd')
-                    if coord1 and coord2:
-                        if proj in ('ll', 'latlong', 'longlat') and format == 'DMS':
-                            w, s = utils.Deg2DMS(coord1[0], coord1[1], string = False,
-                                                 precision = precision)
-                            e, n = utils.Deg2DMS(coord2[0], coord2[1], string = False,
-                                                 precision = precision)
-                            if sel == 1:
-                                self.statusbar.SetStatusText("%s - %s, %s - %s" %
-                                                             (w, e, s, n), 0)
-                            else:
-                                ewres, nsres = utils.Deg2DMS(abs(coord3[0]) - abs(coord4[0]),
-                                                             abs(coord3[1]) - abs(coord4[1]),
-                                                             string = False, hemisphere = False,
-                                                             precision = precision)
-                                self.statusbar.SetStatusText("%s - %s, %s - %s (%s, %s)" %
-                                                             (w, e, s, n, ewres, nsres), 0)
-                        else:
-                            w, s = coord1
-                            e, n = coord2
-                            if sel == 1:
-                                self.statusbar.SetStatusText("%.*f - %.*f, %.*f - %.*f" %
-                                                         (precision, w, precision, e,
-                                                          precision, s, precision, n), 0)
-                            else:
-                                ewres, nsres = coord3
-                                self.statusbar.SetStatusText("%.*f - %.*f, %.*f - %.*f (%.*f, %.*f)" %
-                                                             (precision, w, precision, e,
-                                                              precision, s, precision, n,
-                                                              precision, ewres, precision, nsres), 0)
-                    else:
-                        self.statusbar.SetStatusText(_("Error in projection (check the settings)"), 0)
-            else:
-                if self.Map.projinfo['proj'] == 'll' and format == 'DMS':
-                    w, s = utils.Deg2DMS(region["w"], region["s"],
-                                         string = False, precision = precision)
-                    e, n = utils.Deg2DMS(region["e"], region["n"],
-                                         string = False, precision = precision)
-                    if sel == 1:
-                        self.statusbar.SetStatusText("%s - %s, %s - %s" %
-                                                     (w, e, s, n), 0)
-                    else:
-                        ewres, nsres = utils.Deg2DMS(region['ewres'], region['nsres'],
-                                                     string = False, precision = precision)
-                        self.statusbar.SetStatusText("%s - %s, %s - %s (%s, %s)" %
-                                                     (w, e, s, n, ewres, nsres), 0)
-                else:
-                    w, s = region["w"], region["s"]
-                    e, n = region["e"], region["n"]
-                    if sel == 1:
-                        self.statusbar.SetStatusText("%.*f - %.*f, %.*f - %.*f" %
-                                                     (precision, w, precision, e,
-                                                      precision, s, precision, n), 0)
-                    else:
-                        ewres, nsres = region['ewres'], region['nsres']
-                        self.statusbar.SetStatusText("%.*f - %.*f, %.*f - %.*f (%.*f, %.*f)" %
-                                                     (precision, w, precision, e,
-                                                      precision, s, precision, n,
-                                                      precision, ewres, precision, nsres), 0)
-            # enable long help
-            self.StatusbarEnableLongHelp()
-
-        elif self.statusbarWin['toggle'].GetSelection() == 3: # Show comp. extent
-            self.statusbar.SetStatusText("", 0)
-            self.statusbarWin['region'].Show()
-            # disable long help
-            self.StatusbarEnableLongHelp(False)
-
-        elif self.statusbarWin['toggle'].GetSelection() == 4: # Display mode
-            self.statusbar.SetStatusText("", 0)
-            self.statusbarWin['resolution'].Show()
-            # disable long help
-            self.StatusbarEnableLongHelp(False)
-
-        elif self.statusbarWin['toggle'].GetSelection() == 5: # Display geometry
-            self.statusbar.SetStatusText("rows=%d; cols=%d; nsres=%.2f; ewres=%.2f" %
-                                         (self.Map.region["rows"], self.Map.region["cols"],
-                                          self.Map.region["nsres"], self.Map.region["ewres"]), 0)
-            # enable long help
-            self.StatusbarEnableLongHelp()
-
-        elif self.statusbarWin['toggle'].GetSelection() == 6: # Map scale
-            # TODO: need to be fixed...
-            ### screen X region problem
-            ### user should specify ppm
-            dc = wx.ScreenDC()
-            dpSizePx = wx.DisplaySize()   # display size in pixels
-            dpSizeMM = wx.DisplaySizeMM() # display size in mm (system)
-            dpSizeIn = (dpSizeMM[0] / 25.4, dpSizeMM[1] / 25.4) # inches
-            sysPpi  = dc.GetPPI()
-            comPpi = (dpSizePx[0] / dpSizeIn[0],
-                      dpSizePx[1] / dpSizeIn[1])
-
-            ppi = comPpi                  # pixel per inch
-            self.ppm = ((ppi[0] / 2.54) * 100, # pixel per meter
-                        (ppi[1] / 2.54) * 100)
-
-            Debug.msg(4, "MapFrame.StatusbarUpdate(mapscale): size: px=%d,%d mm=%f,%f "
-                      "in=%f,%f ppi: sys=%d,%d com=%d,%d; ppm=%f,%f" % \
-                          (dpSizePx[0], dpSizePx[1], dpSizeMM[0], dpSizeMM[1],
-                           dpSizeIn[0], dpSizeIn[1],
-                           sysPpi[0], sysPpi[1], comPpi[0], comPpi[1],
-                           self.ppm[0], self.ppm[1]))
-
-            region = self.Map.region
-
-            heightCm = region['rows'] / self.ppm[1] * 100
-            widthCm  = region['cols'] / self.ppm[0] * 100
-
-            Debug.msg(4, "MapFrame.StatusbarUpdate(mapscale): width_cm=%f, height_cm=%f" %
-                      (widthCm, heightCm))
-
-            xscale = (region['e'] - region['w']) / (region['cols'] / self.ppm[0])
-            yscale = (region['n'] - region['s']) / (region['rows'] / self.ppm[1])
-            scale = (xscale + yscale) / 2.
-            
-            Debug.msg(3, "MapFrame.StatusbarUpdate(mapscale): xscale=%f, yscale=%f -> scale=%f" % \
-                          (xscale, yscale, scale))
-
-            self.statusbar.SetStatusText("")
-            try:
-                self.statusbarWin['mapscale'].SetValue("1:%ld" % (scale + 0.5))
-            except TypeError:
-                pass
-            self.mapScaleValue = scale
-            self.statusbarWin['mapscale'].Show()
-
-            # disable long help
-            self.StatusbarEnableLongHelp(False)
-
-        elif self.statusbarWin['toggle'].GetSelection() == 7: # go to
-            self.statusbar.SetStatusText("")
-            region = self.Map.GetCurrentRegion()
-            precision = int(UserSettings.Get(group = 'projection', key = 'format',
-                                             subkey = 'precision'))
-            format = UserSettings.Get(group = 'projection', key = 'format',
-                                      subkey = 'll')
-            
-            if self.statusbarWin['projection'].IsChecked():
-                if not UserSettings.Get(group='projection', key='statusbar', subkey='proj4'):
-                    self.statusbar.SetStatusText(_("Projection not defined (check the settings)"), 0)
-                else:
-                    proj, coord  = utils.ReprojectCoordinates(coord = (region['center_easting'],
-                                                                       region['center_northing']),
-                                                              projOut = UserSettings.Get(group='projection',
-                                                                                         key='statusbar',
-                                                                                         subkey='proj4'),
-                                                              flags = 'd')
-                    if coord:
-                        if proj in ('ll', 'latlong', 'longlat') and format == 'DMS':
-                            self.statusbarWin['goto'].SetValue("%s" % utils.Deg2DMS(coord[0],
-                                                                                    coord[1],
-                                                                                    precision = precision))
-                        else:
-                            self.statusbarWin['goto'].SetValue("%.*f; %.*f" % (precision, coord[0],
-                                                                               precision, coord[1]))
-                    else:
-                        self.statusbar.SetStatusText(_("Error in projection (check the settings)"), 0)
-            else:
-                if self.Map.projinfo['proj'] == 'll' and format == 'DMS':
-                    self.statusbarWin['goto'].SetValue("%s" % utils.Deg2DMS(region['center_easting'], 
-                                                                            region['center_northing'],
-                                                                            precision = precision))
-                else:
-                    self.statusbarWin['goto'].SetValue("%.*f; %.*f" % (precision, region['center_easting'],
-                                                                       precision, region['center_northing']))
-            self.statusbarWin['goto'].Show()
-
-            # disable long help
-            self.StatusbarEnableLongHelp(False)
-        
-        elif self.statusbarWin['toggle'].GetSelection() == 8: # projection
-            self.statusbar.SetStatusText("")
-            epsg = UserSettings.Get(group='projection', key='statusbar', subkey='epsg')
-            if epsg:
-                label = '%s (EPSG: %s)' % (_("Use defined projection"), epsg)
-                self.statusbarWin['projection'].SetLabel(label)
-            else:
-                self.statusbarWin['projection'].SetLabel(_("Use defined projection"))
-            self.statusbarWin['projection'].Show()
-            
-            # disable long help
-            self.StatusbarEnableLongHelp(False)
-            
-        else:
-            self.statusbar.SetStatusText("", 1)
-
-    def StatusbarEnableLongHelp(self, enable=True):
-        """!Enable/disable toolbars long help"""
-        for toolbar in self.toolbars.itervalues():
-            if toolbar:
-                toolbar.EnableLongHelp(enable)
-                
-    def StatusbarReposition(self):
-        """!Reposition checkbox in statusbar"""
-        # reposition checkbox
-        widgets = [(0, self.statusbarWin['region']),
-                   (0, self.statusbarWin['resolution']),
-                   (0, self.statusbarWin['mapscale']),
-                   (0, self.statusbarWin['progress']),
-                   (0, self.statusbarWin['projection']),
-                   (1, self.statusbarWin['toggle']),
-                   (2, self.statusbarWin['mask']),
-                   (3, self.statusbarWin['render'])]
-        for idx, win in widgets:
-            rect = self.statusbar.GetFieldRect(idx)
-            if idx == 0: # show region / mapscale / process bar
-                # -> size
-                wWin, hWin = win.GetBestSize()
-                if win == self.statusbarWin['progress']:
-                    wWin = rect.width - 6
-                # -> position
-                # if win == self.statusbarWin['region']:
-                # x, y = rect.x + rect.width - wWin, rect.y - 1
-                # align left
-                # else:
-                x, y = rect.x + 3, rect.y - 1
-                w, h = wWin, rect.height + 2
-            else: # choice || auto-rendering
-                x, y = rect.x, rect.y - 1
-                w, h = rect.width, rect.height + 2
-                if idx == 2: # mask
-                    x += 5
-                    y += 4
-                elif idx == 3: # render
-                    x += 5
-            win.SetPosition((x, y))
-            win.SetSize((w, h))
-
-    def SaveToFile(self, event):
-        """!Save map to image
-        """
-        if self.toolbars['nviz']:
-            filetype = "PPM file (*.ppm)|*.ppm|TIF file (*.tif)|*.tif"
-            ltype = [{ 'ext' : 'ppm', 'type' : -1 },
-                     { 'ext' : 'tif', 'type' : wx.BITMAP_TYPE_TIF }]
-        else:
-            filetype, ltype = gdialogs.GetImageHandlers(self.MapWindow.img)
-        
-        # get size
-        dlg = gdialogs.ImageSizeDialog(self)
-        dlg.CentreOnParent()
-        if dlg.ShowModal() != wx.ID_OK:
-            dlg.Destroy()
-            return
-        width, height = dlg.GetValues()
-        dlg.Destroy()
-        
-        # get filename
-        dlg = wx.FileDialog(parent = self,
-                            message = _("Choose a file name to save the image "
-                                        "(no need to add extension)"),
-                            wildcard = filetype,
-                            style=wx.SAVE | wx.FD_OVERWRITE_PROMPT)
-        
-        if dlg.ShowModal() == wx.ID_OK:
-            path = dlg.GetPath()
-            if not path:
-                dlg.Destroy()
-                return
-            
-            base, ext = os.path.splitext(path)
-            fileType = ltype[dlg.GetFilterIndex()]['type']
-            extType  = ltype[dlg.GetFilterIndex()]['ext']
-            if ext != extType:
-                path = base + '.' + extType
-            
-            self.MapWindow.SaveToFile(path, fileType,
-                                      width, height)
-            
-        dlg.Destroy()
-
-    def PrintMenu(self, event):
-        """
-        Print options and output menu for map display
-        """
-        point = wx.GetMousePosition()
-        printmenu = wx.Menu()
-        # Add items to the menu
-        setup = wx.MenuItem(printmenu, wx.ID_ANY, _('Page setup'))
-        printmenu.AppendItem(setup)
-        self.Bind(wx.EVT_MENU, self.printopt.OnPageSetup, setup)
-
-        preview = wx.MenuItem(printmenu, wx.ID_ANY, _('Print preview'))
-        printmenu.AppendItem(preview)
-        self.Bind(wx.EVT_MENU, self.printopt.OnPrintPreview, preview)
-
-        doprint = wx.MenuItem(printmenu, wx.ID_ANY, _('Print display'))
-        printmenu.AppendItem(doprint)
-        self.Bind(wx.EVT_MENU, self.printopt.OnDoPrint, doprint)
-
-        # Popup the menu.  If an item is selected then its handler
-        # will be called before PopupMenu returns.
-        self.PopupMenu(printmenu)
-        printmenu.Destroy()
-
-    def OnCloseWindow(self, event):
-        """!Window closed.
-        Also close associated layer tree page
-        """
-        pgnum = None
-        self.Map.Clean()
-        
-        # close edited map and 3D tools properly
-        if self.toolbars['vdigit']:
-            maplayer = self.toolbars['vdigit'].GetLayer()
-            if maplayer:
-                self.toolbars['vdigit'].OnExit()
-                self.imgVectorMap = None
-
-        if self.toolbars['nviz']:
-            self.toolbars['nviz'].OnExit()
-        
-        if not self._layerManager:
-            self.Destroy()
-        elif self.page:
-            pgnum = self.layerbook.GetPageIndex(self.page)
-            if pgnum > -1:
-                self.layerbook.DeletePage(pgnum)
-        
-    def GetRender(self):
-        """!Returns current instance of render.Map()
-        """
-        return self.Map
-
-    def GetWindow(self):
-        """!Get map window"""
-        return self.MapWindow
-    
-    def OnQueryDisplay(self, event):
-        """
-        Query currrent raster/vector map layers (display mode)
-        """
-        if self.toolbars['map'].GetAction() == 'displayAttrb': # select previous action
-            self.toolbars['map'].SelectDefault(event)
-            return
-
-        self.toolbars['map'].action['desc'] = 'displayAttrb'
-        
-        # switch GIS Manager to output console to show query results
-        self._layerManager.notebook.SetSelection(1)
-
-        self.MapWindow.mouse['use'] = "query"
-        self.MapWindow.mouse['box'] = "point"
-        self.MapWindow.zoomtype = 0
-
-        # change the cursor
-        self.MapWindow.SetCursor(self.cursors["cross"])
-
-    def OnQueryModify(self, event):
-        """
-        Query vector map layer (edit mode)
-        """
-        if self.toolbars['map'].GetAction() == 'modifyAttrb': # select previous action
-            self.toolbars['map'].SelectDefault(event)
-            return
-        
-        self.toolbars['map'].action['desc'] = 'modifyAttrb'
-        
-        self.MapWindow.mouse['use'] = "queryVector"
-        self.MapWindow.mouse['box'] = "point"
-        self.MapWindow.pen = wx.Pen(colour='Red', width=2, style=wx.SHORT_DASH)
-        self.MapWindow.zoomtype = 0
-
-        # change the cursor
-        self.MapWindow.SetCursor(self.cursors["cross"])
-        
-    def QueryMap(self, x, y):
-        """!Query map layer features
-
-        Currently only raster and vector map layers are supported.
-        
-        @param x,y coordinates
-        """
-        #set query snap distance for v.what at mapunit equivalent of 10 pixels
-        qdist = 10.0 * ((self.Map.region['e'] - self.Map.region['w']) / self.Map.width)
-        east, north = self.MapWindow.Pixel2Cell((x, y))
-
-        num = 0
-        for layer in self.tree.GetSelections():
-            type = self.tree.GetPyData(layer)[0]['maplayer'].GetType()
-            if type in ('raster', 'rgb', 'his',
-                        'vector', 'thememap', 'themechart'):
-                num += 1
-        
-        if num < 1:
-            dlg = wx.MessageDialog(parent=self,
-                                   message=_('No raster or vector map layer selected for querying.'),
-                                   caption=_('No map layer selected'),
-                                   style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
-            dlg.ShowModal()
-            dlg.Destroy()
-            return
-        
-        mapname = None
-        raststr = ''
-        vectstr = ''
-        rcmd = ['r.what', '--q']
-        vcmd = ['v.what', '--q']
-        for layer in self.tree.GetSelections():
-            type = self.tree.GetPyData(layer)[0]['maplayer'].GetType()
-            dcmd = self.tree.GetPyData(layer)[0]['cmd']
-            name = utils.GetLayerNameFromCmd(dcmd)
-            if name == '':
-                continue
-            if type in ('raster', 'rgb', 'his'):
-                raststr += "%s," % name
-            elif type in ('vector', 'thememap', 'themechart'):
-                vectstr += "%s," % name
-
-        # use display region settings instead of computation region settings
-        self.tmpreg = os.getenv("GRASS_REGION")
-        os.environ["GRASS_REGION"] = self.Map.SetRegion(windres=False)
-        
-        # build query commands for any selected rasters and vectors
-        if raststr != '':
-            rcmd.append('-f')
-            rcmd.append('input=%s' % raststr.rstrip(','))
-            rcmd.append('east_north=%f,%f' % (float(east), float(north)))
-        
-        if vectstr != '':
-            # check for vector maps open to be edited
-            digitToolbar = self.toolbars['vdigit']
-            if digitToolbar:
-                map = digitToolbar.GetLayer().GetName()
-                vect = []
-                for vector in vectstr.split(','):
-                    if map == vector:
-                        self._layerManager.goutput.WriteWarning("Vector map <%s> "
-                                                                "opened for editing - skipped." % map)
-                        continue
-                    vect.append(vector)
-                vectstr = ','.join(vect)
-                
-            if len(vectstr) <= 1:
-                self._layerManager.goutput.WriteCmdLog("Nothing to query.")
-                return
-            
-            vcmd.append('-a')
-            vcmd.append('map=%s' % vectstr.rstrip(','))
-            vcmd.append('east_north=%f,%f' % (float(east), float(north)))
-            vcmd.append('distance=%f' % float(qdist))
-        
-        # parse query command(s)
-        if self._layerManager:
-            if raststr:
-                self._layerManager.goutput.RunCmd(rcmd,
-                                                  compReg=False,
-                                                  onDone = self._QueryMapDone)
-            if vectstr:
-                self._layerManager.goutput.RunCmd(vcmd,
-                                                  onDone = self._QueryMapDone)
-        else:
-            if raststr:
-                gcmd.RunCommand(rcmd)
-            if vectstr:
-                gcmd.RunCommand(vcmd)
-        
-    def _QueryMapDone(self, returncode):
-        """!Restore settings after querying (restore GRASS_REGION)
-
-        @param returncode command return code
-        """
-        if hasattr(self, "tmpreg"):
-            if self.tmpreg:
-                os.environ["GRASS_REGION"] = self.tmpreg
-            elif os.environ.has_key('GRASS_REGION'):
-                del os.environ["GRASS_REGION"]
-        elif os.environ.has_key('GRASS_REGION'):
-            del os.environ["GRASS_REGION"]
-        
-        if hasattr(self, "tmpreg"):
-            del self.tmpreg
-        
-    def QueryVector(self, x, y):
-        """
-        Query vector map layer features
-
-        Attribute data of selected vector object are displayed in GUI dialog.
-        Data can be modified (On Submit)
-        """
-        if not self.tree.layer_selected or \
-                self.tree.GetPyData(self.tree.layer_selected)[0]['type'] != 'vector':
-            wx.MessageBox(parent=self,
-                          message=_("No vector map selected for querying."),
-                          caption=_("Vector querying"),
-                          style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
-            return
-        
-        if self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].GetMapset() != \
-                grass.gisenv()['MAPSET']:
-            wx.MessageBox(parent=self,
-                          message=_("Only vector map from the current mapset can be modified."),
-                          caption=_("Vector querying"),
-                          style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
-            return
-        
-        posWindow = self.ClientToScreen((x + self.MapWindow.dialogOffset,
-                                         y + self.MapWindow.dialogOffset))
-
-        qdist = 10.0 * ((self.Map.region['e'] - self.Map.region['w']) /
-                        self.Map.width)
-        
-        east, north = self.MapWindow.Pixel2Cell((x, y))
-        
-        mapName = self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name
-        
-        if self.dialogs['attributes'] is None:
-            self.dialogs['attributes'] = \
-                dbm_dialogs.DisplayAttributesDialog(parent=self.MapWindow,
-                                                    map=mapName,
-                                                    query=((east, north), qdist),
-                                                    pos=posWindow,
-                                                    action="update")
-        else:
-            # selection changed?
-            if not self.dialogs['attributes'].mapDBInfo or \
-                    self.dialogs['attributes'].mapDBInfo.map != mapName:
-                self.dialogs['attributes'].UpdateDialog(map=mapName, query=((east, north), qdist))
-            else:
-                self.dialogs['attributes'].UpdateDialog(query=((east, north), qdist))
-                
-        cats = self.dialogs['attributes'].GetCats()
-        
-        try:
-            qlayer = self.Map.GetListOfLayers(l_name=globalvar.QUERYLAYER)[0]
-        except IndexError:
-            qlayer = None
-        
-        if self.dialogs['attributes'].mapDBInfo and cats:
-            # highlight feature & re-draw map
-            if qlayer:
-                qlayer.SetCmd(self.AddTmpVectorMapLayer(mapName, cats,
-                                                        useId=False,
-                                                        addLayer=False))
-            else:
-                qlayer = self.AddTmpVectorMapLayer(mapName, cats, useId=False)
-            
-            # set opacity based on queried layer
-            opacity = self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].GetOpacity(float=True)
-            qlayer.SetOpacity(opacity)
-            
-            self.MapWindow.UpdateMap(render=False, renderVector=False)
-            if not self.dialogs['attributes'].IsShown():
-                self.dialogs['attributes'].Show()
-        else:
-            if qlayer:
-                self.Map.DeleteLayer(qlayer)
-                self.MapWindow.UpdateMap(render=False, renderVector=False)
-            if self.dialogs['attributes'].IsShown():
-                self.dialogs['attributes'].Hide()
-        
-    def OnQuery(self, event):
-        """!Query tools menu"""
-        if self.toolbars['map']:
-            self.toolbars['map'].OnTool(event)
-            action = self.toolbars['map'].GetAction()
-        
-        point = wx.GetMousePosition()
-        toolsmenu = wx.Menu()
-        # Add items to the menu
-        display = wx.MenuItem(parentMenu=toolsmenu, id=wx.ID_ANY,
-                              text=_("Query raster/vector map(s) (display mode)"),
-                              kind=wx.ITEM_CHECK)
-        toolsmenu.AppendItem(display)
-        self.Bind(wx.EVT_MENU, self.OnQueryDisplay, display)
-        numLayers = 0
-        for layer in self.tree.GetSelections():
-            type = self.tree.GetPyData(layer)[0]['maplayer'].GetType()
-            if type in ('raster', 'rgb', 'his',
-                        'vector', 'thememap', 'themechart'):
-                numLayers += 1
-        if numLayers < 1:
-            display.Enable(False)
-        
-        if action == "displayAttrb":
-            display.Check(True)
-        
-        modify = wx.MenuItem(parentMenu=toolsmenu, id=wx.ID_ANY,
-                             text=_("Query vector map (edit mode)"),
-                             kind=wx.ITEM_CHECK)
-        toolsmenu.AppendItem(modify)
-        self.Bind(wx.EVT_MENU, self.OnQueryModify, modify)
-        digitToolbar = self.toolbars['vdigit']
-        if self.tree.layer_selected:
-            layer_selected = self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer']
-            if layer_selected.GetType() != 'vector' or \
-                    (digitToolbar and \
-                         digitToolbar.GetLayer() == layer_selected):
-                modify.Enable(False)
-            else:
-                if action == "modifyAttrb":
-                    modify.Check(True)
-        
-        self.PopupMenu(toolsmenu)
-        toolsmenu.Destroy()
-
-    def AddTmpVectorMapLayer(self, name, cats, useId=False, addLayer=True):
-        """
-        Add temporal vector map layer to map composition
-
-        @param name name of map layer
-        @param useId use feature id instead of category 
-        """
-
-        # color settings from ATM
-        color = UserSettings.Get(group='atm', key='highlight', subkey='color')
-        colorStr = str(color[0]) + ":" + \
-            str(color[1]) + ":" + \
-            str(color[2])
-
-        # icon used in vector display and its size
-        icon = ''
-        size = 0
-        vparam = self.tree.GetPyData(self.tree.layer_selected)[0]['cmd']
-        for p in vparam:
-            if '=' in p:
-                parg,pval = p.split('=')
-                if parg == 'icon': icon = pval
-                elif parg == 'size': size = int(pval)
-
-        pattern = ["d.vect",
-                   "map=%s" % name,
-                   "color=%s" % colorStr,
-                   "fcolor=%s" % colorStr,
-                   "width=%d"  % UserSettings.Get(group='atm', key='highlight', subkey='width')]
-        if icon != '':
-            pattern.append('icon=%s' % icon)
-        if size > 0:
-            pattern.append('size=%i' % size)
-        
-        if useId:
-            cmd = pattern
-            cmd.append('-i')
-            cmd.append('cats=%s' % str(cats))
-        else:
-            cmd = []
-            for layer in cats.keys():
-                cmd.append(copy.copy(pattern))
-                lcats = cats[layer]
-                cmd[-1].append("layer=%d" % layer)
-                cmd[-1].append("cats=%s" % utils.ListOfCatsToRange(lcats))
-        
-        #     if self.icon:
-        #         cmd.append("icon=%s" % (self.icon))
-        #     if self.pointsize:
-        #         cmd.append("size=%s" % (self.pointsize))
-
-        if addLayer:
-            if useId:
-                return self.Map.AddLayer(type='vector', name=globalvar.QUERYLAYER, command=cmd,
-                                         l_active=True, l_hidden=True, l_opacity=1.0)
-            else:
-                return self.Map.AddLayer(type='command', name=globalvar.QUERYLAYER, command=cmd,
-                                         l_active=True, l_hidden=True, l_opacity=1.0)
-        else:
-            return cmd
-
-    def OnAnalyze(self, event):
-        """
-        Analysis tools menu
-        """
-        point = wx.GetMousePosition()
-        toolsmenu = wx.Menu()
-        # Add items to the menu
-        measure = wx.MenuItem(toolsmenu, wx.ID_ANY, Icons["measure"].GetLabel())
-        measure.SetBitmap(Icons["measure"].GetBitmap(self.iconsize))
-        toolsmenu.AppendItem(measure)
-        self.Bind(wx.EVT_MENU, self.OnMeasure, measure)
-
-        profile = wx.MenuItem(toolsmenu, wx.ID_ANY, Icons["profile"].GetLabel())
-        profile.SetBitmap(Icons["profile"].GetBitmap(self.iconsize))
-        toolsmenu.AppendItem(profile)
-        self.Bind(wx.EVT_MENU, self.Profile, profile)
-
-        histogram = wx.MenuItem(toolsmenu, wx.ID_ANY, Icons["histogram"].GetLabel())
-        histogram.SetBitmap(Icons["histogram"].GetBitmap(self.iconsize))
-        toolsmenu.AppendItem(histogram)
-        self.Bind(wx.EVT_MENU, self.Histogram, histogram)
-
-        # Popup the menu.  If an item is selected then its handler
-        # will be called before PopupMenu returns.
-        self.PopupMenu(toolsmenu)
-        toolsmenu.Destroy()
-
-    def OnMeasure(self, event):
-        """
-        Init measurement routine that calculates
-        map distance along transect drawn on
-        map display
-        """
-
-        self.totaldist = 0.0 # total measured distance
-
-        # switch GIS Manager to output console to show measure results
-        self._layerManager.notebook.SetSelection(1)
-
-        # change mouse to draw line for measurement
-        self.MapWindow.mouse['use'] = "measure"
-        self.MapWindow.mouse['box'] = "line"
-        self.MapWindow.zoomtype = 0
-        self.MapWindow.pen     = wx.Pen(colour='red', width=2, style=wx.SHORT_DASH)
-        self.MapWindow.polypen = wx.Pen(colour='green', width=2, style=wx.SHORT_DASH)
-
-        # change the cursor
-        self.MapWindow.SetCursor(self.cursors["pencil"])
-
-        # initiating output
-        style = self._layerManager.goutput.cmd_output.StyleWarning
-        self._layerManager.goutput.WriteLog(_('Click and drag with left mouse button '
-                                              'to measure.%s'
-                                              'Double click with left button to clear.') % \
-                                                (os.linesep), style)
-        if self.Map.projinfo['proj'] != 'xy':
-            units = self.Map.projinfo['units']
-            style = self._layerManager.goutput.cmd_output.StyleCommand
-            self._layerManager.goutput.WriteLog(_('Measuring distance') + ' ('
-                                                + units + '):',
-                                                style)
-        else:
-            self._layerManager.goutput.WriteLog(_('Measuring distance:'),
-                                                style)
-
-    def MeasureDist(self, beginpt, endpt):
-        """
-        Calculate map distance from screen distance
-        and print to output window
-        """
-
-        if self._layerManager.notebook.GetSelection() != 1:
-            self._layerManager.notebook.SetSelection(1)
-
-        dist, (north, east) = self.MapWindow.Distance(beginpt, endpt)
-
-        dist = round(dist, 3)
-        d, dunits = self.FormatDist(dist)
-
-        self.totaldist += dist
-        td, tdunits = self.FormatDist(self.totaldist)
-
-        strdist = str(d)
-        strtotdist = str(td)
-
-        if self.Map.projinfo['proj'] == 'xy' or 'degree' not in self.Map.projinfo['unit']:
-            angle = int(math.degrees(math.atan2(north,east)) + 0.5)
-            angle = 180 - angle
-            if angle < 0:
-                angle = 360+angle
-
-            mstring = 'segment = %s %s\ttotal distance = %s %s\tbearing = %d deg' \
-                % (strdist,dunits,strtotdist,tdunits,angle)
-        else:
-            mstring = 'segment = %s %s\ttotal distance = %s %s' \
-                % (strdist,dunits,strtotdist,tdunits)
-
-        self._layerManager.goutput.WriteLog(mstring)
-
-        return dist
-
-    def Profile(self, event):
-        """
-        Init profile canvas and tools
-        """
-        raster = []
-        if self.tree.layer_selected and \
-                self.tree.GetPyData(self.tree.layer_selected)[0]['type'] == 'raster':
-            raster.append(self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name)
-
-        self.profile = profile.ProfileFrame(self,
-                                            id=wx.ID_ANY, pos=wx.DefaultPosition, size=(700,300),
-                                            style=wx.DEFAULT_FRAME_STYLE, rasterList=raster)
-        self.profile.Show()
-        # Open raster select dialog to make sure that a raster (and the desired raster)
-        # is selected to be profiled
-        self.profile.OnSelectRaster(None)
-
-    def FormatDist(self, dist):
-        """!Format length numbers and units in a nice way,
-        as a function of length. From code by Hamish Bowman
-        Grass Development Team 2006"""
-
-        mapunits = self.Map.projinfo['units']
-        if mapunits == 'metres': mapunits = 'meters'
-        outunits = mapunits
-        dist = float(dist)
-        divisor = 1.0
-
-        # figure out which units to use
-        if mapunits == 'meters':
-            if dist > 2500.0:
-                outunits = 'km'
-                divisor = 1000.0
-            else: outunits = 'm'
-        elif mapunits == 'feet':
-            # nano-bug: we match any "feet", but US Survey feet is really
-            #  5279.9894 per statute mile, or 10.6' per 1000 miles. As >1000
-            #  miles the tick markers are rounded to the nearest 10th of a
-            #  mile (528'), the difference in foot flavours is ignored.
-            if dist > 5280.0:
-                outunits = 'miles'
-                divisor = 5280.0
-            else:
-                outunits = 'ft'
-        elif 'degree' in mapunits:
-            if dist < 1:
-                outunits = 'min'
-                divisor = (1/60.0)
-            else:
-                outunits = 'deg'
-
-        # format numbers in a nice way
-        if (dist/divisor) >= 2500.0:
-            outdist = round(dist/divisor)
-        elif (dist/divisor) >= 1000.0:
-            outdist = round(dist/divisor,1)
-        elif (dist/divisor) > 0.0:
-            outdist = round(dist/divisor,int(math.ceil(3-math.log10(dist/divisor))))
-        else:
-            outdist = float(dist/divisor)
-
-        return (outdist, outunits)
-
-
-    def Histogram(self, event):
-        """
-        Init histogram display canvas and tools
-        """
-        self.histogram = histogram.HistFrame(self,
-                                             id=wx.ID_ANY, size=globalvar.HIST_WINDOW_SIZE,
-                                             style=wx.DEFAULT_FRAME_STYLE)
-
-        #show new display
-        self.histogram.Show()
-        self.histogram.Refresh()
-        self.histogram.Update()
-
-
-    def OnDecoration(self, event):
-        """
-        Decorations overlay menu
-        """
-        point = wx.GetMousePosition()
-        decmenu = wx.Menu()
-        # Add items to the menu
-        AddScale = wx.MenuItem(decmenu, wx.ID_ANY, Icons["addbarscale"].GetLabel())
-        AddScale.SetBitmap(Icons["addbarscale"].GetBitmap(self.iconsize))
-        decmenu.AppendItem(AddScale)
-        self.Bind(wx.EVT_MENU, self.OnAddBarscale, AddScale)
-
-        AddLegend = wx.MenuItem(decmenu, wx.ID_ANY, Icons["addlegend"].GetLabel())
-        AddLegend.SetBitmap(Icons["addlegend"].GetBitmap(self.iconsize))
-        decmenu.AppendItem(AddLegend)
-        self.Bind(wx.EVT_MENU, self.OnAddLegend, AddLegend)
-
-        AddText = wx.MenuItem(decmenu, wx.ID_ANY, Icons["addtext"].GetLabel())
-        AddText.SetBitmap(Icons["addtext"].GetBitmap(self.iconsize))
-        decmenu.AppendItem(AddText)
-        self.Bind(wx.EVT_MENU, self.OnAddText, AddText)
-
-        # Popup the menu.  If an item is selected then its handler
-        # will be called before PopupMenu returns.
-        self.PopupMenu(decmenu)
-        decmenu.Destroy()
-
-    def OnAddBarscale(self, event):
-        """
-        Handler for scale/arrow map decoration menu selection.
-        """
-        if self.dialogs['barscale']:
-            return
-
-        id = 0 # unique index for overlay layer
-
-        # If location is latlon, only display north arrow (scale won't work)
-        #        proj = self.Map.projinfo['proj']
-        #        if proj == 'll':
-        #            barcmd = 'd.barscale -n'
-        #        else:
-        #            barcmd = 'd.barscale'
-
-        # decoration overlay control dialog
-        self.dialogs['barscale'] = \
-            gdialogs.DecorationDialog(parent=self, title=_('Scale and North arrow'),
-                                      size=(350, 200),
-                                      style=wx.DEFAULT_DIALOG_STYLE | wx.CENTRE,
-                                      cmd=['d.barscale', 'at=0,5'],
-                                      ovlId=id,
-                                      name='barscale',
-                                      checktxt = _("Show/hide scale and North arrow"),
-                                      ctrltxt = _("scale object"))
-
-        self.dialogs['barscale'].CentreOnParent()
-        ### dialog cannot be show as modal - in the result d.barscale is not selectable
-        ### self.dialogs['barscale'].ShowModal()
-        self.dialogs['barscale'].Show()
-        self.MapWindow.mouse['use'] = 'pointer'        
-
-    def OnAddLegend(self, event):
-        """
-        Handler for legend map decoration menu selection.
-        """
-        if self.dialogs['legend']:
-            return
-        
-        id = 1 # index for overlay layer in render
-
-        cmd = ['d.legend', 'at=5,50,2,5']
-        if self.tree.layer_selected and \
-                self.tree.GetPyData(self.tree.layer_selected)[0]['type'] == 'raster':
-            cmd.append('map=%s' % self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name)
-
-        # Decoration overlay control dialog
-        self.dialogs['legend'] = \
-            gdialogs.DecorationDialog(parent=self, title=('Legend'),
-                                      size=(350, 200),
-                                      style=wx.DEFAULT_DIALOG_STYLE | wx.CENTRE,
-                                      cmd=cmd,
-                                      ovlId=id,
-                                      name='legend',
-                                      checktxt = _("Show/hide legend"),
-                                      ctrltxt = _("legend object")) 
-
-        self.dialogs['legend'].CentreOnParent() 
-        ### dialog cannot be show as modal - in the result d.legend is not selectable
-        ### self.dialogs['legend'].ShowModal()
-        self.dialogs['legend'].Show()
-        self.MapWindow.mouse['use'] = 'pointer'
-
-    def OnAddText(self, event):
-        """
-        Handler for text decoration menu selection.
-        """
-        if self.MapWindow.dragid > -1:
-            id = self.MapWindow.dragid
-        else:
-            # index for overlay layer in render
-            if len(self.MapWindow.textdict.keys()) > 0:
-                id = self.MapWindow.textdict.keys()[-1] + 1
-            else:
-                id = 101
-
-        self.dialogs['text'] = gdialogs.TextLayerDialog(parent=self, ovlId=id, 
-                                                        title=_('Add text layer'),
-                                                        size=(400, 200))
-        self.dialogs['text'].CenterOnParent()
-
-        # If OK button pressed in decoration control dialog
-        if self.dialogs['text'].ShowModal() == wx.ID_OK:
-            text = self.dialogs['text'].GetValues()['text']
-            active = self.dialogs['text'].GetValues()['active']
-            coords, w, h = self.MapWindow.TextBounds(self.dialogs['text'].GetValues())
-        
-            # delete object if it has no text or is not active
-            if text == '' or active == False:
-                try:
-                    self.MapWindow.pdc.ClearId(id)
-                    self.MapWindow.pdc.RemoveId(id)
-                    del self.MapWindow.textdict[id]
-                except:
-                    pass
-                return
-
-            self.MapWindow.pdc.ClearId(id)
-            self.MapWindow.pdc.SetId(id)
-            self.MapWindow.textdict[id] = self.dialogs['text'].GetValues()
-            
-            self.MapWindow.Draw(self.MapWindow.pdcDec, img=self.MapWindow.textdict[id],
-                                drawid=id, pdctype='text', coords=coords)
-            
-            self.MapWindow.UpdateMap(render=False, renderVector=False)
-            
-        self.MapWindow.mouse['use'] = 'pointer'
-
-    def GetOptData(self, dcmd, type, params, propwin):
-        """
-        Callback method for decoration overlay command generated by
-        dialog created in menuform.py
-        """
-        # Reset comand and rendering options in render.Map. Always render decoration.
-        # Showing/hiding handled by PseudoDC
-        self.Map.ChangeOverlay(ovltype=type, type='overlay', name='', command=dcmd,
-                               l_active=True, l_render=False)
-        self.params[type] = params
-        self.propwin[type] = propwin
-
-    def OnZoomToMap(self, event):
-        """!
-        Set display extents to match selected raster (including NULLs)
-        or vector map.
-        """
-        self.MapWindow.ZoomToMap()
-
-    def OnZoomToRaster(self, event):
-        """!
-        Set display extents to match selected raster map (ignore NULLs)
-        """
-        self.MapWindow.ZoomToMap(ignoreNulls = True)
-
-    def OnZoomToWind(self, event):
-        """!Set display geometry to match computational region
-        settings (set with g.region)
-        """
-        self.MapWindow.ZoomToWind()
-        
-    def OnZoomToDefault(self, event):
-        """!Set display geometry to match default region settings
-        """
-        self.MapWindow.ZoomToDefault()
-        
-    def OnZoomToSaved(self, event):
-        """!Set display geometry to match extents in
-        saved region file
-        """
-        self.MapWindow.ZoomToSaved()
-        
-    def OnDisplayToWind(self, event):
-        """!Set computational region (WIND file) to match display
-        extents
-        """
-        self.MapWindow.DisplayToWind()
- 
-    def SaveDisplayRegion(self, event):
-        """!Save display extents to named region file.
-        """
-        self.MapWindow.SaveDisplayRegion()
-        
-    def OnZoomMenu(self, event):
-        """!Popup Zoom menu
-        """
-        point = wx.GetMousePosition()
-        zoommenu = wx.Menu()
-        # Add items to the menu
-
-        zoomwind = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to computational region (set with g.region)'))
-        zoommenu.AppendItem(zoomwind)
-        self.Bind(wx.EVT_MENU, self.OnZoomToWind, zoomwind)
-
-        zoomdefault = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to default region'))
-        zoommenu.AppendItem(zoomdefault)
-        self.Bind(wx.EVT_MENU, self.OnZoomToDefault, zoomdefault)
-
-        zoomsaved = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to saved region'))
-        zoommenu.AppendItem(zoomsaved)
-        self.Bind(wx.EVT_MENU, self.OnZoomToSaved, zoomsaved)
-
-        savewind = wx.MenuItem(zoommenu, wx.ID_ANY, _('Set computational region from display'))
-        zoommenu.AppendItem(savewind)
-        self.Bind(wx.EVT_MENU, self.OnDisplayToWind, savewind)
-
-        savezoom = wx.MenuItem(zoommenu, wx.ID_ANY, _('Save display geometry to named region'))
-        zoommenu.AppendItem(savezoom)
-        self.Bind(wx.EVT_MENU, self.SaveDisplayRegion, savezoom)
-
-        # Popup the menu. If an item is selected then its handler
-        # will be called before PopupMenu returns.
-        self.PopupMenu(zoommenu)
-        zoommenu.Destroy()
-        
-    def SetProperties(self, render=False, mode=0, showCompExtent=False,
-                      constrainRes=False, projection=False):
-        """!Set properies of map display window"""
-        self.statusbarWin['render'].SetValue(render)
-        self.statusbarWin['toggle'].SetSelection(mode)
-        self.StatusbarUpdate()
-        self.statusbarWin['region'].SetValue(showCompExtent)
-        self.statusbarWin['resolution'].SetValue(constrainRes)
-        self.statusbarWin['projection'].SetValue(projection)
-        if showCompExtent:
-            self.MapWindow.regionCoords = []
-        
-    def IsStandalone(self):
-        """!Check if Map display is standalone"""
-        if self._layerManager:
-            return False
-        
-        return True
-    
-    def GetLayerManager(self):
-        """!Get reference to Layer Manager
-
-        @return window reference
-        @return None (if standalone)
-        """
-        return self._layerManager
-    
-# end of class MapFrame
-



More information about the grass-commit mailing list