Browse Source

wxGUI: improved system of switching tools in toolbars

git-svn-id: https://svn.osgeo.org/grass/grass/trunk@57436 15284696-431f-4ddb-bdfa-cd5b030d7da7
Anna Petrášová 11 years ago
parent
commit
57ffe8113a

+ 8 - 17
gui/wxpython/gcp/mapdisplay.py

@@ -33,6 +33,7 @@ from gui_core.mapdisp  import SingleMapFrame
 from core.settings     import UserSettings
 from core.settings     import UserSettings
 from mapwin.buffered import BufferedMapWindow
 from mapwin.buffered import BufferedMapWindow
 from mapwin.base import MapWindowProperties
 from mapwin.base import MapWindowProperties
+from gui_core.toolbars import ToolSwitcher
 
 
 import mapdisp.statusbar as sb
 import mapdisp.statusbar as sb
 import gcp.statusbar as sbgcp
 import gcp.statusbar as sbgcp
@@ -141,6 +142,8 @@ class MapFrame(SingleMapFrame):
         #
         #
         self._initMap(Map = self.SrcMap) 
         self._initMap(Map = self.SrcMap) 
         self._initMap(Map = self.TgtMap) 
         self._initMap(Map = self.TgtMap) 
+        
+        self.GetMapToolbar().SelectDefault()
 
 
         #
         #
         # Bind various events
         # Bind various events
@@ -239,7 +242,7 @@ class MapFrame(SingleMapFrame):
         """
         """
         # default toolbar
         # default toolbar
         if name == "map":
         if name == "map":
-            self.toolbars['map'] = MapToolbar(self, self.Map)
+            self.toolbars['map'] = MapToolbar(self, self._toolSwitcher)
 
 
             self._mgr.AddPane(self.toolbars['map'],
             self._mgr.AddPane(self.toolbars['map'],
                               wx.aui.AuiPaneInfo().
                               wx.aui.AuiPaneInfo().
@@ -252,7 +255,7 @@ class MapFrame(SingleMapFrame):
 
 
         # GCP display
         # GCP display
         elif name == "gcpdisp":
         elif name == "gcpdisp":
-            self.toolbars['gcpdisp'] = GCPDisplayToolbar(self)
+            self.toolbars['gcpdisp'] = GCPDisplayToolbar(self, self._toolSwitcher)
 
 
             self._mgr.AddPane(self.toolbars['gcpdisp'],
             self._mgr.AddPane(self.toolbars['gcpdisp'],
                               wx.aui.AuiPaneInfo().
                               wx.aui.AuiPaneInfo().
@@ -322,10 +325,7 @@ class MapFrame(SingleMapFrame):
 
 
     def OnPointer(self, event):
     def OnPointer(self, event):
         """!Pointer button clicked
         """!Pointer button clicked
-        """
-        self.toolbars['gcpdisp'].OnTool(event)
-        self.toolbars['gcpdisp'].action['desc'] = ''
-        
+        """        
         # change the cursor
         # change the cursor
         self.SrcMapWindow.SetNamedCursor('cross')
         self.SrcMapWindow.SetNamedCursor('cross')
         self.SrcMapWindow.mouse['use'] = "pointer"
         self.SrcMapWindow.mouse['use'] = "pointer"
@@ -338,10 +338,7 @@ class MapFrame(SingleMapFrame):
         """
         """
         Zoom in the map.
         Zoom in the map.
         Set mouse cursor, zoombox attributes, and zoom direction
         Set mouse cursor, zoombox attributes, and zoom direction
-        """
-        self.toolbars['gcpdisp'].OnTool(event)
-        self.toolbars['gcpdisp'].action['desc'] = ''
-        
+        """        
         self.MapWindow.mouse['use'] = "zoom"
         self.MapWindow.mouse['use'] = "zoom"
         self.MapWindow.mouse['box'] = "box"
         self.MapWindow.mouse['box'] = "box"
         self.MapWindow.zoomtype = 1
         self.MapWindow.zoomtype = 1
@@ -368,9 +365,6 @@ class MapFrame(SingleMapFrame):
         Zoom out the map.
         Zoom out the map.
         Set mouse cursor, zoombox attributes, and zoom direction
         Set mouse cursor, zoombox attributes, and zoom direction
         """
         """
-        self.toolbars['gcpdisp'].OnTool(event)
-        self.toolbars['gcpdisp'].action['desc'] = ''
-        
         self.MapWindow.mouse['use'] = "zoom"
         self.MapWindow.mouse['use'] = "zoom"
         self.MapWindow.mouse['box'] = "box"
         self.MapWindow.mouse['box'] = "box"
         self.MapWindow.zoomtype = -1
         self.MapWindow.zoomtype = -1
@@ -395,10 +389,7 @@ class MapFrame(SingleMapFrame):
     def OnPan(self, event):
     def OnPan(self, event):
         """
         """
         Panning, set mouse to drag
         Panning, set mouse to drag
-        """
-        self.toolbars['gcpdisp'].OnTool(event)
-        self.toolbars['gcpdisp'].action['desc'] = ''
-        
+        """        
         self.MapWindow.mouse['use'] = "pan"
         self.MapWindow.mouse['use'] = "pan"
         self.MapWindow.mouse['box'] = "pan"
         self.MapWindow.mouse['box'] = "pan"
         self.MapWindow.zoomtype = 0
         self.MapWindow.zoomtype = 0

+ 7 - 10
gui/wxpython/gcp/toolbars.py

@@ -78,12 +78,13 @@ class GCPManToolbar(BaseToolbar):
 class GCPDisplayToolbar(BaseToolbar):
 class GCPDisplayToolbar(BaseToolbar):
     """!GCP Display toolbar
     """!GCP Display toolbar
     """
     """
-    def __init__(self, parent):
+    def __init__(self, parent, toolSwitcher):
         """!GCP Display toolbar constructor
         """!GCP Display toolbar constructor
         """
         """
-        BaseToolbar.__init__(self, parent)
+        BaseToolbar.__init__(self, parent, toolSwitcher)
         
         
         self.InitToolbar(self._toolbarData())
         self.InitToolbar(self._toolbarData())
+        self._default = self.gcpset
         
         
         # add tool to toggle active map window
         # add tool to toggle active map window
         self.togglemapid = wx.NewId()
         self.togglemapid = wx.NewId()
@@ -96,15 +97,12 @@ class GCPDisplayToolbar(BaseToolbar):
                                                               BaseIcons["zoomBack"].GetLabel(),
                                                               BaseIcons["zoomBack"].GetLabel(),
                                                               _(' / Zoom to map')))
                                                               _(' / Zoom to map')))
 
 
+        for tool in (self.gcpset, self.pan, self.zoomin, self.zoomout):
+            self.toolSwitcher.AddToolToGroup(group='mouseUse', toolbar=self, tool=tool)
+
         # realize the toolbar
         # realize the toolbar
         self.Realize()
         self.Realize()
-        
-        self.action = { 'id' : self.gcpset }
-        self.defaultAction = { 'id' : self.gcpset,
-                               'bind' : self.parent.OnPointer }
-        
-        self.OnTool(None)
-        
+
         self.EnableTool(self.zoomback, False)
         self.EnableTool(self.zoomback, False)
         
         
     def _toolbarData(self):
     def _toolbarData(self):
@@ -153,4 +151,3 @@ class GCPDisplayToolbar(BaseToolbar):
                                      ('quit', icons["quit"],
                                      ('quit', icons["quit"],
                                       self.parent.OnQuit))
                                       self.parent.OnQuit))
                                     )
                                     )
-

+ 6 - 1
gui/wxpython/gui_core/forms.py

@@ -394,6 +394,8 @@ class TaskFrame(wx.Frame):
             self.modeler = self.parent
             self.modeler = self.parent
         else:
         else:
             self.modeler = None
             self.modeler = None
+
+        self.dialogClosing = Signal('TaskFrame.dialogClosing')
         
         
         # module name + keywords
         # module name + keywords
         title = self.task.get_name()
         title = self.task.get_name()
@@ -738,7 +740,7 @@ class TaskFrame(wx.Frame):
     def OnCancel(self, event):
     def OnCancel(self, event):
         """!Cancel button pressed"""
         """!Cancel button pressed"""
         self.MakeModal(False)
         self.MakeModal(False)
-        
+        self.dialogClosing.emit()
         if self.get_dcmd and \
         if self.get_dcmd and \
                 self.parent and \
                 self.parent and \
                 self.parent.GetName() in ('LayerTree',
                 self.parent.GetName() in ('LayerTree',
@@ -1516,6 +1518,9 @@ class CmdPanel(wx.Panel):
                                                         param = p)
                                                         param = p)
                         p['wxId'] = [win.GetTextWin().GetId()]
                         p['wxId'] = [win.GetTextWin().GetId()]
                         win.GetTextWin().Bind(wx.EVT_TEXT, self.OnSetValue)
                         win.GetTextWin().Bind(wx.EVT_TEXT, self.OnSetValue)
+                        # bind closing event because destructor is not working properly
+                        if hasattr(self.parent, 'dialogClosing'):
+                            self.parent.dialogClosing.connect(win.OnClose)
                     
                     
                     # normal text field
                     # normal text field
                     else:
                     else:

+ 11 - 8
gui/wxpython/gui_core/gselect.py

@@ -1993,6 +1993,10 @@ class CoordinatesSelect(wx.Panel):
                                                                    size = globalvar.DIALOG_COLOR_SIZE)
                                                                    size = globalvar.DIALOG_COLOR_SIZE)
         self.registered = False
         self.registered = False
         self.buttonInsCoords.Bind(wx.EVT_BUTTON, self._onClick)
         self.buttonInsCoords.Bind(wx.EVT_BUTTON, self._onClick)
+        switcher = self._giface.GetMapDisplay().GetToolSwitcher()
+        switcher.AddCustomToolToGroup(group='mouseUse',
+                                      btnId=self.buttonInsCoords.GetId(), 
+                                      toggleHandler=self.buttonInsCoords.SetValue)
         self._doLayout()
         self._doLayout()
         
         
     def _doLayout(self):
     def _doLayout(self):
@@ -2005,12 +2009,13 @@ class CoordinatesSelect(wx.Panel):
         
         
     def _onClick(self, event):
     def _onClick(self, event):
         """!Button for interacitve inserting of coordinates clicked"""
         """!Button for interacitve inserting of coordinates clicked"""
+        switcher = self._giface.GetMapDisplay().GetToolSwitcher()
+        switcher.ToolChanged(self.buttonInsCoords.GetId())
         self.mapWin = self._giface.GetMapWindow()
         self.mapWin = self._giface.GetMapWindow()
         if self.buttonInsCoords.GetToggle() and self.mapWin:
         if self.buttonInsCoords.GetToggle() and self.mapWin:
             if self.mapWin.RegisterMouseEventHandler(wx.EVT_LEFT_DOWN, 
             if self.mapWin.RegisterMouseEventHandler(wx.EVT_LEFT_DOWN, 
                                                      self._onMapClickHandler,
                                                      self._onMapClickHandler,
                                                      'cross') == False:
                                                      'cross') == False:
-                self.buttonInsCoords.SetToggle(False)
                 return
                 return
             
             
             self.registered = True
             self.registered = True
@@ -2021,14 +2026,10 @@ class CoordinatesSelect(wx.Panel):
                                                             self._onMapClickHandler):
                                                             self._onMapClickHandler):
                 self.registered = False
                 self.registered = False
                 return
                 return
-            
-            self.buttonInsCoords.SetToggle(False)           
-    
+
     def _onMapClickHandler(self, event):
     def _onMapClickHandler(self, event):
         """!Gets coordinates from mapwindow"""
         """!Gets coordinates from mapwindow"""
         if event == "unregistered":
         if event == "unregistered":
-            if self.buttonInsCoords:
-                self.buttonInsCoords.SetToggle(False)
             return
             return
         
         
         e, n = self.mapWin.GetLastEN()
         e, n = self.mapWin.GetLastEN()
@@ -2041,9 +2042,11 @@ class CoordinatesSelect(wx.Panel):
         
         
         value = prevCoords + str(e) + "," + str(n)
         value = prevCoords + str(e) + "," + str(n)
         self.coordsField.SetValue(value)
         self.coordsField.SetValue(value)
-        
-    def __del__(self):
+
+    def OnClose(self):
         """!Unregistrates _onMapClickHandler from mapWin"""
         """!Unregistrates _onMapClickHandler from mapWin"""
+        switcher = self._giface.GetMapDisplay().GetToolSwitcher()
+        switcher.RemoveCustomToolFromGroup(self.buttonInsCoords.GetId())
         if self.mapWin and self.registered:
         if self.mapWin and self.registered:
             self.mapWin.UnregisterMouseEventHandler(wx.EVT_LEFT_DOWN,  
             self.mapWin.UnregisterMouseEventHandler(wx.EVT_LEFT_DOWN,  
                                                     self._onMapClickHandler)
                                                     self._onMapClickHandler)

+ 25 - 37
gui/wxpython/gui_core/mapdisp.py

@@ -28,9 +28,11 @@ import wx.aui
 from core        import globalvar
 from core        import globalvar
 from core.debug  import Debug
 from core.debug  import Debug
 from core.utils import _
 from core.utils import _
+from gui_core.toolbars import ToolSwitcher
 
 
 from grass.script import core as grass
 from grass.script import core as grass
 
 
+
 class MapFrameBase(wx.Frame):
 class MapFrameBase(wx.Frame):
     """!Base class for map display window
     """!Base class for map display window
     
     
@@ -94,6 +96,10 @@ class MapFrameBase(wx.Frame):
         else:
         else:
             self._mgr = auimgr
             self._mgr = auimgr
         
         
+        # handles switching between tools in different toolbars
+        self._toolSwitcher = ToolSwitcher()
+        self._toolSwitcher.toggleToolChanged.connect(self._onToggleTool)
+
     def _initMap(self, Map):
     def _initMap(self, Map):
         """!Initialize map display, set dimensions and map region
         """!Initialize map display, set dimensions and map region
         """
         """
@@ -106,6 +112,9 @@ class MapFrameBase(wx.Frame):
         Map.region = Map.GetRegion() # g.region -upgc
         Map.region = Map.GetRegion() # g.region -upgc
         # self.Map.SetRegion() # adjust region to match display window
         # self.Map.SetRegion() # adjust region to match display window
 
 
+    def _onToggleTool(self):
+        self.GetWindow().UnregisterAllHandlers()
+
     def OnSize(self, event):
     def OnSize(self, event):
         """!Adjust statusbar on changing size"""
         """!Adjust statusbar on changing size"""
         # reposition checkbox in statusbar
         # reposition checkbox in statusbar
@@ -114,6 +123,9 @@ class MapFrameBase(wx.Frame):
         # update statusbar
         # update statusbar
         self.StatusbarUpdate()
         self.StatusbarUpdate()
 
 
+    def GetToolSwitcher(self):
+        return self._toolSwitcher
+
     def SetProperty(self, name, value):
     def SetProperty(self, name, value):
         """!Sets property"""
         """!Sets property"""
         self.statusbarManager.SetProperty(name, value)
         self.statusbarManager.SetProperty(name, value)
@@ -288,20 +300,14 @@ class MapFrameBase(wx.Frame):
     def OnZoomIn(self, event):
     def OnZoomIn(self, event):
         """!Zoom in the map.
         """!Zoom in the map.
         Set mouse cursor, zoombox attributes, and zoom direction
         Set mouse cursor, zoombox attributes, and zoom direction
-        """
-        toolbar = self.GetMapToolbar()
-        self.SwitchTool(toolbar, event)
-        
+        """        
         win = self.GetWindow()
         win = self.GetWindow()
         self._prepareZoom(mapWindow = win, zoomType = 1)
         self._prepareZoom(mapWindow = win, zoomType = 1)
         
         
     def OnZoomOut(self, event):
     def OnZoomOut(self, event):
         """!Zoom out the map.
         """!Zoom out the map.
         Set mouse cursor, zoombox attributes, and zoom direction
         Set mouse cursor, zoombox attributes, and zoom direction
-        """
-        toolbar = self.GetMapToolbar()
-        self.SwitchTool(toolbar, event)
-        
+        """        
         win = self.GetWindow()
         win = self.GetWindow()
         self._prepareZoom(mapWindow = win, zoomType = -1)
         self._prepareZoom(mapWindow = win, zoomType = -1)
 
 
@@ -329,27 +335,15 @@ class MapFrameBase(wx.Frame):
         
         
         # change the cursor
         # change the cursor
         mapWindow.SetNamedCursor('cross')
         mapWindow.SetNamedCursor('cross')
-    
-    def SwitchTool(self, toolbar, event):
-        """!Helper function to switch tools"""
-        # unregistration of all registered mouse event handlers of
-        # Mapwindow
-        self.MapWindow.UnregisterAllHandlers()
-        
-        if toolbar:
-            toolbar.OnTool(event)
-            toolbar.action['desc'] = ''
             
             
     def OnPointer(self, event):
     def OnPointer(self, event):
         """!Sets mouse mode to pointer."""
         """!Sets mouse mode to pointer."""
         self.MapWindow.mouse['use'] = 'pointer'
         self.MapWindow.mouse['use'] = 'pointer'
+        self.MapWindow.mouse['box'] = 'point'
 
 
     def OnPan(self, event):
     def OnPan(self, event):
         """!Panning, set mouse to drag
         """!Panning, set mouse to drag
         """
         """
-        toolbar = self.GetMapToolbar()
-        self.SwitchTool(toolbar, event)
-        
         win = self.GetWindow()
         win = self.GetWindow()
         self._preparePan(mapWindow = win)
         self._preparePan(mapWindow = win)
     
     
@@ -359,7 +353,7 @@ class MapFrameBase(wx.Frame):
         @param mapWindow MapWindow to prepare
         @param mapWindow MapWindow to prepare
         """
         """
         mapWindow.mouse['use'] = "pan"
         mapWindow.mouse['use'] = "pan"
-        mapWindow.mouse['box'] = "pan"
+        mapWindow.mouse['box'] = "box"
         mapWindow.zoomtype = 0
         mapWindow.zoomtype = 0
         
         
         # change the cursor
         # change the cursor
@@ -503,6 +497,10 @@ class DoubleMapFrame(MapFrameBase):
         self.GetFirstWindow().Bind(wx.EVT_ENTER_WINDOW, self.ActivateFirstMap)
         self.GetFirstWindow().Bind(wx.EVT_ENTER_WINDOW, self.ActivateFirstMap)
         self.GetSecondWindow().Bind(wx.EVT_ENTER_WINDOW, self.ActivateSecondMap)
         self.GetSecondWindow().Bind(wx.EVT_ENTER_WINDOW, self.ActivateSecondMap)
     
     
+    def _onToggleTool(self):
+        self.GetFirstWindow().UnregisterAllHandlers()
+        self.GetSecondWindow().UnregisterAllHandlers()
+
     def GetFirstMap(self):
     def GetFirstMap(self):
         """!Returns first Map instance
         """!Returns first Map instance
         """
         """
@@ -606,10 +604,7 @@ class DoubleMapFrame(MapFrameBase):
     def OnZoomIn(self, event):
     def OnZoomIn(self, event):
         """!Zoom in the map.
         """!Zoom in the map.
         Set mouse cursor, zoombox attributes, and zoom direction
         Set mouse cursor, zoombox attributes, and zoom direction
-        """
-        toolbar = self.GetMapToolbar()
-        self.SwitchTool(toolbar, event)
-        
+        """        
         win = self.GetFirstWindow()
         win = self.GetFirstWindow()
         self._prepareZoom(mapWindow = win, zoomType = 1)
         self._prepareZoom(mapWindow = win, zoomType = 1)
         
         
@@ -619,10 +614,7 @@ class DoubleMapFrame(MapFrameBase):
     def OnZoomOut(self, event):
     def OnZoomOut(self, event):
         """!Zoom out the map.
         """!Zoom out the map.
         Set mouse cursor, zoombox attributes, and zoom direction
         Set mouse cursor, zoombox attributes, and zoom direction
-        """
-        toolbar = self.GetMapToolbar()
-        self.SwitchTool(toolbar, event)
-        
+        """        
         win = self.GetFirstWindow()
         win = self.GetFirstWindow()
         self._prepareZoom(mapWindow = win, zoomType = -1)
         self._prepareZoom(mapWindow = win, zoomType = -1)
         
         
@@ -631,10 +623,7 @@ class DoubleMapFrame(MapFrameBase):
         
         
     def OnPan(self, event):
     def OnPan(self, event):
         """!Panning, set mouse to drag
         """!Panning, set mouse to drag
-        """
-        toolbar = self.GetMapToolbar()
-        self.SwitchTool(toolbar, event)
-        
+        """        
         win = self.GetFirstWindow()
         win = self.GetFirstWindow()
         self._preparePan(mapWindow = win)
         self._preparePan(mapWindow = win)
         
         
@@ -643,12 +632,11 @@ class DoubleMapFrame(MapFrameBase):
         
         
     def OnPointer(self, event):
     def OnPointer(self, event):
         """!Set pointer mode (dragging overlays)"""
         """!Set pointer mode (dragging overlays)"""
-        toolbar = self.GetMapToolbar()
-        self.SwitchTool(toolbar, event)
-
         self.GetFirstWindow().mouse['use'] = 'pointer'
         self.GetFirstWindow().mouse['use'] = 'pointer'
+        self.GetFirstWindow().mouse['box'] = 'point'
         self.GetFirstWindow().SetNamedCursor('default')
         self.GetFirstWindow().SetNamedCursor('default')
         self.GetSecondWindow().mouse['use'] = 'pointer'
         self.GetSecondWindow().mouse['use'] = 'pointer'
+        self.GetSecondWindow().mouse['box'] = 'point'
         self.GetSecondWindow().SetNamedCursor('default')
         self.GetSecondWindow().SetNamedCursor('default')
 
 
     def OnRender(self, event):
     def OnRender(self, event):

+ 107 - 36
gui/wxpython/gui_core/toolbars.py

@@ -20,10 +20,14 @@ import platform
 
 
 import wx
 import wx
 
 
-from core               import globalvar
-from core.debug         import Debug
+from core import globalvar
+from core.debug import Debug
 from core.utils import _
 from core.utils import _
-from icons.icon         import MetaIcon
+from icons.icon import MetaIcon
+from collections import defaultdict
+
+from grass.pydispatch.signal import Signal
+
 
 
 BaseIcons = {
 BaseIcons = {
     'display'    : MetaIcon(img = 'show',
     'display'    : MetaIcon(img = 'show',
@@ -94,17 +98,18 @@ class BaseToolbar(wx.ToolBar):
                                               ))
                                               ))
     @endcode
     @endcode
     """
     """
-    def __init__(self, parent, style=wx.NO_BORDER|wx.TB_HORIZONTAL):
+    def __init__(self, parent, toolSwitcher=None, style=wx.NO_BORDER|wx.TB_HORIZONTAL):
         self.parent = parent
         self.parent = parent
         wx.ToolBar.__init__(self, parent=self.parent, id=wx.ID_ANY,
         wx.ToolBar.__init__(self, parent=self.parent, id=wx.ID_ANY,
                             style=style)
                             style=style)
         
         
-        self.action = dict()
-        
-        self.Bind(wx.EVT_TOOL, self.OnTool)
-        
+
+        self._default = None
         self.SetToolBitmapSize(globalvar.toolbarSize)
         self.SetToolBitmapSize(globalvar.toolbarSize)
         
         
+        self.toolSwitcher = toolSwitcher
+        self.handlers = {}
+        
     def InitToolbar(self, toolData):
     def InitToolbar(self, toolData):
         """!Initialize toolbar, add tools to the toolbar
         """!Initialize toolbar, add tools to the toolbar
         """
         """
@@ -138,12 +143,14 @@ class BaseToolbar(wx.ToolBar):
                 toolWin = self.InsertLabelTool(pos, tool, label, bitmap,
                 toolWin = self.InsertLabelTool(pos, tool, label, bitmap,
                                             bmpDisabled, kind,
                                             bmpDisabled, kind,
                                             shortHelp, longHelp)
                                             shortHelp, longHelp)
+            self.handlers[tool] = handler
             self.Bind(wx.EVT_TOOL, handler, toolWin)
             self.Bind(wx.EVT_TOOL, handler, toolWin)
+            self.Bind(wx.EVT_TOOL, self.OnTool, toolWin)
         else: # separator
         else: # separator
             self.AddSeparator()
             self.AddSeparator()
-        
+
         return tool
         return tool
-    
+
     def EnableLongHelp(self, enable = True):
     def EnableLongHelp(self, enable = True):
         """!Enable/disable long help
         """!Enable/disable long help
         
         
@@ -152,7 +159,7 @@ class BaseToolbar(wx.ToolBar):
         for tool in self._data:
         for tool in self._data:
             if tool[0] == '': # separator
             if tool[0] == '': # separator
                 continue
                 continue
-            
+
             if enable:
             if enable:
                 self.SetToolLongHelp(vars(self)[tool[0]], tool[4])
                 self.SetToolLongHelp(vars(self)[tool[0]], tool[4])
             else:
             else:
@@ -161,33 +168,20 @@ class BaseToolbar(wx.ToolBar):
     def OnTool(self, event):
     def OnTool(self, event):
         """!Tool selected
         """!Tool selected
         """
         """
+        if self.toolSwitcher:
+            Debug.msg(3, "BaseToolbar.OnTool(): id = %s" % event.GetId())
+            self.toolSwitcher.ToolChanged(event.GetId())
+        event.Skip()
+
+    def SelectTool(self, id):
+        self.ToggleTool(id, True)
+        self.toolSwitcher.ToolChanged(id)
         
         
-        id = self.action.get('id', -1)
-        
-        if event:
-            # deselect previously selected tool
-            if id != -1 and id != event.GetId() :
-                self.ToggleTool(self.action['id'], False)
-            elif id != -1:
-                self.ToggleTool(self.action['id'], True)
-            
-            self.action['id'] = event.GetId()
-            
-            event.Skip()
-        elif id != -1:
-            # initialize toolbar
-            self.ToggleTool(self.action['id'], True)
-        
-    def GetAction(self, type = 'desc'):
-        """!Get current action info"""
-        return self.action.get(type, '')
-    
-    def SelectDefault(self, event):
+        self.handlers[id](event=None)
+
+    def SelectDefault(self):
         """!Select default tool"""
         """!Select default tool"""
-        self.ToggleTool(self.defaultAction['id'], True)
-        self.defaultAction['bind'](event)
-        self.action = { 'id' : self.defaultAction['id'],
-                        'desc' : self.defaultAction.get('desc', '') }
+        self.SelectTool(self._default)
         
         
     def FixSize(self, width):
     def FixSize(self, width):
         """!Fix toolbar width on Windows
         """!Fix toolbar width on Windows
@@ -253,3 +247,80 @@ class BaseToolbar(wx.ToolBar):
         
         
         self.PopupMenu(menu)
         self.PopupMenu(menu)
         menu.Destroy()
         menu.Destroy()
+
+
+class ToolSwitcher:
+    """!Class handling switching tools in toolbar and custom toggle buttons."""
+    def __init__(self):
+        self._groups = defaultdict(lambda: defaultdict(list))
+        self._toolsGroups = defaultdict(list)
+        
+        # emitted when tool is changed
+        self.toggleToolChanged = Signal('ToolSwitcher.toggleToolChanged')
+
+    def AddToolToGroup(self, group, toolbar, tool):
+        """!Adds tool from toolbar to group of exclusive tools.
+        
+        @param group name of group (e.g. 'mouseUse')
+        @param toolbar instance of toolbar
+        @param tool id of a tool from the toolbar
+        """
+        self._groups[group][toolbar].append(tool)
+        self._toolsGroups[tool].append(group)
+        
+    def AddCustomToolToGroup(self, group, btnId, toggleHandler):
+        """!Adds custom tool from to group of exclusive tools (some toggle button).
+        
+        @param group name of group (e.g. 'mouseUse')
+        @param btnId id of a tool (typically button)
+        @param toggleHandler handler to be called to switch the button
+        """
+        self._groups[group]['custom'].append((btnId, toggleHandler))
+        self._toolsGroups[btnId].append(group)
+       
+    def RemoveCustomToolFromGroup(self, tool):
+        """!Removes custom tool from group.
+
+        @param tool id of the button
+        """
+        if not tool in self._toolsGroups:
+            return
+        for group in self._toolsGroups[tool]:
+            self._groups[group]['custom'] = \
+                [(bid, hdlr) for (bid, hdlr)
+                in self._groups[group]['custom'] if bid != tool]
+        
+    def RemoveToolbarFromGroup(self, group, toolbar):
+        """!Removes toolbar from group.
+        
+        Before toolbar is destroyed, it must be removed from group, too.
+        Otherwise we can expect some DeadObject errors.
+        
+        @param group name of group (e.g. 'mouseUse')
+        @param toolbar instance of toolbar
+        """
+        for tb in self._groups[group]:
+            if tb == toolbar:
+                del self._groups[group][tb]
+                break
+
+    def ToolChanged(self, tool):
+        """!When any tool/button is pressed, other tools from group must be unchecked.
+        
+        @param tool id of a tool/button
+        """
+        for group in self._toolsGroups[tool]:
+            for tb in self._groups[group]:
+                if tb == 'custom':
+                    for btnId, handler in self._groups[group][tb]:
+                        if btnId != tool:
+                            handler(False)
+                else:
+                    for tl in self._groups[group][tb]:
+                        if tb.FindById(tl):  # check if still exists
+                            if tl != tool:
+                                tb.ToggleTool(tl, False)
+                            else:
+                                tb.ToggleTool(tool, True)
+
+        self.toggleToolChanged.emit(id=tool)

+ 6 - 23
gui/wxpython/iclass/frame.py

@@ -53,6 +53,7 @@ from core.gcmd          import RunCommand, GMessage, GError, GWarning
 from gui_core.dialogs   import SetOpacityDialog
 from gui_core.dialogs   import SetOpacityDialog
 from mapwin.base import MapWindowProperties
 from mapwin.base import MapWindowProperties
 from dbmgr.vinfo        import VectorDBInfo
 from dbmgr.vinfo        import VectorDBInfo
+from gui_core.toolbars import ToolSwitcher
 import grass.script as grass
 import grass.script as grass
 
 
 from iclass.digit       import IClassVDigitWindow, IClassVDigit
 from iclass.digit       import IClassVDigitWindow, IClassVDigit
@@ -186,7 +187,7 @@ class IClassMapFrame(DoubleMapFrame):
         self.previewMapManager.SetToolbar(self.toolbars['iClassPreviewMapManager'])
         self.previewMapManager.SetToolbar(self.toolbars['iClassPreviewMapManager'])
         
         
         # default action
         # default action
-        self.OnPan(event = None)
+        self.GetMapToolbar().SelectDefault()
         
         
         wx.CallAfter(self.AddTrainingAreaMap)
         wx.CallAfter(self.AddTrainingAreaMap)
         
         
@@ -263,7 +264,7 @@ class IClassMapFrame(DoubleMapFrame):
          Toolbars 'iClassPreviewMapManager' are added in _addPanes().
          Toolbars 'iClassPreviewMapManager' are added in _addPanes().
         """
         """
         if name == "iClassMap":
         if name == "iClassMap":
-            self.toolbars[name] = IClassMapToolbar(self)
+            self.toolbars[name] = IClassMapToolbar(self, self._toolSwitcher)
             
             
             self._mgr.AddPane(self.toolbars[name],
             self._mgr.AddPane(self.toolbars[name],
                               wx.aui.AuiPaneInfo().
                               wx.aui.AuiPaneInfo().
@@ -299,13 +300,13 @@ class IClassMapFrame(DoubleMapFrame):
                               BestSize((self.toolbars[name].GetBestSize())))
                               BestSize((self.toolbars[name].GetBestSize())))
 
 
         if name == "vdigit":
         if name == "vdigit":
-            self.toolbars[name] = VDigitToolbar(parent = self, MapWindow = self.GetFirstWindow(),
-                                                digitClass = IClassVDigit, giface = self._giface,
+            self.toolbars[name] = VDigitToolbar(parent=self, toolSwitcher=self._toolSwitcher,
+                                                MapWindow=self.GetFirstWindow(),
+                                                digitClass=IClassVDigit, giface=self._giface,
                                                 tools = ['addArea', 'moveVertex', 'addVertex',
                                                 tools = ['addArea', 'moveVertex', 'addVertex',
                                                          'removeVertex', 'editLine', 'moveLine',
                                                          'removeVertex', 'editLine', 'moveLine',
                                                          'deleteLine', 'deleteArea',
                                                          'deleteLine', 'deleteArea',
                                                          'undo', 'redo'])
                                                          'undo', 'redo'])
-            
             self._mgr.AddPane(self.toolbars[name],
             self._mgr.AddPane(self.toolbars[name],
                               wx.aui.AuiPaneInfo().
                               wx.aui.AuiPaneInfo().
                               Name(name).Caption(_("Digitization Toolbar")).
                               Name(name).Caption(_("Digitization Toolbar")).
@@ -1119,24 +1120,6 @@ class IClassMapFrame(DoubleMapFrame):
 
 
         self.GetFirstWindow().mouse['use'] = 'pointer'
         self.GetFirstWindow().mouse['use'] = 'pointer'
 
 
-    def SwitchTool(self, toolbar, event):
-        """!Calls UpdateTools to manage connected toolbars"""
-        self.UpdateTools(event)
-        super(IClassMapFrame, self).SwitchTool(toolbar, event)
-
-    def UpdateTools(self, event):
-        """!Method deals with relations of toolbars and other
-        elements"""
-        # untoggles button in other toolbars
-        for toolbar in self.toolbars.itervalues():
-            if hasattr(event, 'GetEventObject') == True:
-                if event.GetEventObject() == toolbar:
-                    continue
-                if toolbar.action:
-                    toolbar.ToggleTool(toolbar.action['id'], False)
-                    toolbar.action['id'] = -1
-                    toolbar.OnTool(None)
-
     def OnScatterplot(self, event):
     def OnScatterplot(self, event):
         """!Init interactive scatterplot tools
         """!Init interactive scatterplot tools
         """
         """

+ 5 - 8
gui/wxpython/iclass/toolbars.py

@@ -54,12 +54,13 @@ iClassIcons = {
 class IClassMapToolbar(BaseToolbar):
 class IClassMapToolbar(BaseToolbar):
     """!IClass Map toolbar
     """!IClass Map toolbar
     """
     """
-    def __init__(self, parent):
+    def __init__(self, parent, toolSwitcher):
         """!IClass Map toolbar constructor
         """!IClass Map toolbar constructor
         """
         """
-        BaseToolbar.__init__(self, parent)
+        BaseToolbar.__init__(self, parent, toolSwitcher)
         
         
         self.InitToolbar(self._toolbarData())
         self.InitToolbar(self._toolbarData())
+        self._default = self.pan
         
         
         # add tool to toggle active map window
         # add tool to toggle active map window
         self.togglemapid = wx.NewId()
         self.togglemapid = wx.NewId()
@@ -72,15 +73,11 @@ class IClassMapToolbar(BaseToolbar):
                                                               BaseIcons["zoomBack"].GetLabel(),
                                                               BaseIcons["zoomBack"].GetLabel(),
                                                               _('/ Zoom to map')))
                                                               _('/ Zoom to map')))
 
 
+        for tool in (self.pan, self.zoomIn, self.zoomOut):
+            self.toolSwitcher.AddToolToGroup(group='mouseUse', toolbar=self, tool=tool)
         # realize the toolbar
         # realize the toolbar
         self.Realize()
         self.Realize()
         
         
-        self.action = { 'id' : self.pan }
-        self.defaultAction = { 'id' : self.pan,
-                               'bind' : self.parent.OnPan }
-        
-        self.OnTool(None)
-        
         self.EnableTool(self.zoomBack, False)
         self.EnableTool(self.zoomBack, False)
         
         
     def GetActiveMapTool(self):
     def GetActiveMapTool(self):

+ 20 - 82
gui/wxpython/mapdisp/frame.py

@@ -49,6 +49,7 @@ from core.settings      import UserSettings
 from gui_core.mapdisp   import SingleMapFrame
 from gui_core.mapdisp   import SingleMapFrame
 from mapwin.base import MapWindowProperties
 from mapwin.base import MapWindowProperties
 from gui_core.query     import QueryDialog, PrepareQueryResults
 from gui_core.query     import QueryDialog, PrepareQueryResults
+from gui_core.toolbars import ToolSwitcher
 from mapwin.buffered import BufferedMapWindow
 from mapwin.buffered import BufferedMapWindow
 from mapwin.decorations import DecorationDialog, TextLayerDialog, \
 from mapwin.decorations import DecorationDialog, TextLayerDialog, \
     LegendController, BarscaleController, \
     LegendController, BarscaleController, \
@@ -119,7 +120,7 @@ class MapFrame(SingleMapFrame):
         #
         #
         for toolb in toolbars:
         for toolb in toolbars:
             self.AddToolbar(toolb)
             self.AddToolbar(toolb)
-        
+
         #
         #
         # Add statusbar
         # Add statusbar
         #
         #
@@ -179,10 +180,7 @@ class MapFrame(SingleMapFrame):
         self.MapWindow2D.mapQueried.connect(self.Query)
         self.MapWindow2D.mapQueried.connect(self.Query)
         self.MapWindow2D.overlayActivated.connect(self._activateOverlay)
         self.MapWindow2D.overlayActivated.connect(self._activateOverlay)
         self._setUpMapWindow(self.MapWindow2D)
         self._setUpMapWindow(self.MapWindow2D)
-        # manage the state of toolbars connected to mouse cursor
-        self.MapWindow2D.mouseHandlerRegistered.connect(
-            lambda:
-            self.UpdateTools(None))
+
         self.MapWindow2D.mouseHandlerUnregistered.connect(self.ResetPointer)
         self.MapWindow2D.mouseHandlerUnregistered.connect(self.ResetPointer)
 
 
         self.MapWindow2D.InitZoomHistory()
         self.MapWindow2D.InitZoomHistory()
@@ -202,6 +200,7 @@ class MapFrame(SingleMapFrame):
         #
         #
         self._initMap(Map = self.Map) 
         self._initMap(Map = self.Map) 
 
 
+        self.toolbars['map'].SelectDefault()
         #
         #
         # Bind various events
         # Bind various events
         #
         #
@@ -281,7 +280,8 @@ class MapFrame(SingleMapFrame):
         elif self._mgr.GetPane('3d').IsShown():
         elif self._mgr.GetPane('3d').IsShown():
             self._mgr.GetPane('3d').Hide()
             self._mgr.GetPane('3d').Hide()
         self._mgr.GetPane('vdigit').Show()
         self._mgr.GetPane('vdigit').Show()
-        self.toolbars['vdigit'] = VDigitToolbar(parent = self, MapWindow = self.MapWindow,
+        self.toolbars['vdigit'] = VDigitToolbar(parent=self, toolSwitcher=self._toolSwitcher,
+                                                MapWindow = self.MapWindow,
                                                 digitClass=VDigit, giface=self._giface,
                                                 digitClass=VDigit, giface=self._giface,
                                                 layerTree=self.tree)
                                                 layerTree=self.tree)
         self.MapWindowVDigit.SetToolbar(self.toolbars['vdigit'])
         self.MapWindowVDigit.SetToolbar(self.toolbars['vdigit'])
@@ -320,8 +320,12 @@ class MapFrame(SingleMapFrame):
         # add rotate tool to map toolbar
         # add rotate tool to map toolbar
         self.toolbars['map'].InsertTool((('rotate', NvizIcons['rotate'],
         self.toolbars['map'].InsertTool((('rotate', NvizIcons['rotate'],
                                           self.OnRotate, wx.ITEM_CHECK, 7),)) # 7 is position
                                           self.OnRotate, wx.ITEM_CHECK, 7),)) # 7 is position
+        self._toolSwitcher.AddToolToGroup(group='mouseUse', toolbar=self.toolbars['map'],
+                                          tool=self.toolbars['map'].rotate)
         self.toolbars['map'].InsertTool((('flyThrough', NvizIcons['flyThrough'],
         self.toolbars['map'].InsertTool((('flyThrough', NvizIcons['flyThrough'],
-                                          self.OnFlyThrough, wx.ITEM_CHECK, 8),)) 
+                                          self.OnFlyThrough, wx.ITEM_CHECK, 8),))
+        self._toolSwitcher.AddToolToGroup(group='mouseUse', toolbar=self.toolbars['map'],
+                                          tool=self.toolbars['map'].flyThrough)
         self.toolbars['map'].ChangeToolsDesc(mode2d = False)
         self.toolbars['map'].ChangeToolsDesc(mode2d = False)
         # update status bar
         # update status bar
         
         
@@ -424,6 +428,7 @@ class MapFrame(SingleMapFrame):
 
 
         self.MapWindow.UpdateMap()
         self.MapWindow.UpdateMap()
         self._mgr.Update()
         self._mgr.Update()
+        self.GetMapToolbar().SelectDefault()
         
         
     def AddToolbar(self, name, fixed = False):
     def AddToolbar(self, name, fixed = False):
         """!Add defined toolbar to the window
         """!Add defined toolbar to the window
@@ -437,7 +442,7 @@ class MapFrame(SingleMapFrame):
         """
         """
         # default toolbar
         # default toolbar
         if name == "map":
         if name == "map":
-            self.toolbars['map'] = MapToolbar(self, self.Map)
+            self.toolbars['map'] = MapToolbar(self, toolSwitcher=self._toolSwitcher)
             
             
             self._mgr.AddPane(self.toolbars['map'],
             self._mgr.AddPane(self.toolbars['map'],
                               wx.aui.AuiPaneInfo().
                               wx.aui.AuiPaneInfo().
@@ -468,6 +473,7 @@ class MapFrame(SingleMapFrame):
             return
             return
         
         
         self._mgr.DetachPane(self.toolbars[name])
         self._mgr.DetachPane(self.toolbars[name])
+        self._toolSwitcher.RemoveToolbarFromGroup('mouseUse', self.toolbars[name])
         self.toolbars[name].Destroy()
         self.toolbars[name].Destroy()
         self.toolbars.pop(name)
         self.toolbars.pop(name)
         
         
@@ -511,43 +517,20 @@ class MapFrame(SingleMapFrame):
 
 
     def OnPointer(self, event):
     def OnPointer(self, event):
         """!Pointer button clicked
         """!Pointer button clicked
-        """
-        if self.GetMapToolbar():
-            if event:
-                self.SwitchTool(self.toolbars['map'], event)
-            self.toolbars['map'].action['desc'] = ''
-        
+        """        
         self.MapWindow.mouse['use'] = "pointer"
         self.MapWindow.mouse['use'] = "pointer"
         self.MapWindow.mouse['box'] = "point"
         self.MapWindow.mouse['box'] = "point"
 
 
         # change the cursor
         # change the cursor
         if self.GetToolbar('vdigit'):
         if self.GetToolbar('vdigit'):
-            # digitization tool activated
-            self.MapWindow.SetNamedCursor('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', 'queryMap',
-                                                         'copyCats']:
-                self.MapWindow.mouse['box'] = 'point'
-            else: # moveLine, deleteLine
-                self.MapWindow.mouse['box'] = 'box'
-        
-        else:
-            self.MapWindow.SetNamedCursor('default')
+            self.toolbars['vdigit'].action['id'] = -1
+            self.toolbars['vdigit'].action['desc']=''
+
+        self.MapWindow.SetNamedCursor('default')
 
 
     def OnRotate(self, event):
     def OnRotate(self, event):
         """!Rotate 3D view
         """!Rotate 3D view
         """
         """
-        if self.GetMapToolbar():
-            self.SwitchTool(self.toolbars['map'], event)
-            self.toolbars['map'].action['desc'] = ''
-        
         self.MapWindow.mouse['use'] = "rotate"
         self.MapWindow.mouse['use'] = "rotate"
         
         
         # change the cursor
         # change the cursor
@@ -556,10 +539,6 @@ class MapFrame(SingleMapFrame):
     def OnFlyThrough(self, event):
     def OnFlyThrough(self, event):
         """!Fly-through mode
         """!Fly-through mode
         """
         """
-        if self.GetMapToolbar():
-            self.SwitchTool(self.toolbars['map'], event)
-            self.toolbars['map'].action['desc'] = ''
-        
         self.MapWindow.mouse['use'] = "fly"
         self.MapWindow.mouse['use'] = "fly"
         
         
         # change the cursor
         # change the cursor
@@ -803,10 +782,6 @@ class MapFrame(SingleMapFrame):
         
         
     def OnQuery(self, event):
     def OnQuery(self, event):
         """!Query tools menu"""
         """!Query tools menu"""
-        if self.GetMapToolbar():
-            self.SwitchTool(self.toolbars['map'], event)
-        
-        self.toolbars['map'].action['desc'] = 'queryMap'
         self.MapWindow.mouse['use'] = "query"
         self.MapWindow.mouse['use'] = "query"
         self.MapWindow.mouse['box'] = "point"
         self.MapWindow.mouse['box'] = "point"
         self.MapWindow.zoomtype = 0
         self.MapWindow.zoomtype = 0
@@ -1030,7 +1005,6 @@ class MapFrame(SingleMapFrame):
     def OnAddText(self, event):
     def OnAddText(self, event):
         """!Handler for text decoration menu selection.
         """!Handler for text decoration menu selection.
         """
         """
-        self.SwitchTool(self.toolbars['map'], event)
         if self.MapWindow.dragid > -1:
         if self.MapWindow.dragid > -1:
             id = self.MapWindow.dragid
             id = self.MapWindow.dragid
             self.MapWindow.dragid = -1
             self.MapWindow.dragid = -1
@@ -1210,47 +1184,11 @@ class MapFrame(SingleMapFrame):
         self.dialogs['vnet'] = VNETDialog(parent=self, giface=self._giface)
         self.dialogs['vnet'] = VNETDialog(parent=self, giface=self._giface)
         self.dialogs['vnet'].CenterOnScreen()
         self.dialogs['vnet'].CenterOnScreen()
         self.dialogs['vnet'].Show()
         self.dialogs['vnet'].Show()
-            
-    def SwitchTool(self, toolbar, event):
-        """!Calls UpdateTools to manage connected toolbars"""
-        self.UpdateTools(event)
-        SingleMapFrame.SwitchTool(self, toolbar, event)
-
-    def UpdateTools(self, event):
-        """!Method deals with relations of toolbars and other
-        elements""" 
-        # untoggles button in other toolbars
-        for toolbar in self.toolbars.itervalues():
-            if hasattr(event, 'GetEventObject') == True:
-                if event.GetEventObject() == toolbar:
-                    continue
-            toolbar.ToggleTool(toolbar.action['id'], False)
-            toolbar.action['id'] = -1
-            toolbar.OnTool(None)
-        
-        # mouse settings
-        self.MapWindow.mouse['box'] = 'point' 
-        self.MapWindow.mouse['use'] = 'pointer'
-        
-        # untoggles button in add legend dialog
-        # FIXME: remove this mess
-        if self.dialogs['legend']:
-            btn = self.dialogs['legend'].resizeBtn
-            if btn.GetValue():
-                btn.SetValue(0)
-                self.dialogs['legend'].DisconnectResizing()
-        if self.measureDistController and self.measureDistController.IsActive():
-            self.measureDistController.Stop(restore=False)
 
 
     def ResetPointer(self):
     def ResetPointer(self):
         """Sets pointer mode.
         """Sets pointer mode.
 
 
         Sets pointer and toggles it (e.g. after unregistration of mouse
         Sets pointer and toggles it (e.g. after unregistration of mouse
         handler).
         handler).
-        Somehow related to UpdateTools.
         """
         """
-        # sets pointer mode
-        toolbar = self.toolbars['map']
-        toolbar.action['id'] = vars(toolbar)["pointer"]
-        toolbar.OnTool(None)
-        self.OnPointer(event=None)
+        self.GetMapToolbar().SelectDefault()

+ 5 - 9
gui/wxpython/mapdisp/toolbars.py

@@ -66,16 +66,15 @@ NvizIcons = {
 class MapToolbar(BaseToolbar):
 class MapToolbar(BaseToolbar):
     """!Map Display toolbar
     """!Map Display toolbar
     """
     """
-    def __init__(self, parent, mapcontent):
+    def __init__(self, parent, toolSwitcher):
         """!Map Display constructor
         """!Map Display constructor
 
 
         @param parent reference to MapFrame
         @param parent reference to MapFrame
-        @param mapcontent reference to render.Map (registred by MapFrame)
         """
         """
-        self.mapcontent = mapcontent # render.Map
-        BaseToolbar.__init__(self, parent = parent) # MapFrame
+        BaseToolbar.__init__(self, parent=parent, toolSwitcher=toolSwitcher) # MapFrame
         
         
         self.InitToolbar(self._toolbarData())
         self.InitToolbar(self._toolbarData())
+        self._default = self.pointer
         
         
         # optional tools
         # optional tools
         choices = [ _('2D view'), ]
         choices = [ _('2D view'), ]
@@ -127,11 +126,8 @@ class MapToolbar(BaseToolbar):
         self.combo.Hide()
         self.combo.Hide()
         self.combo.Show()
         self.combo.Show()
         
         
-        self.action = { 'id' : self.pointer }
-        self.defaultAction = { 'id' : self.pointer,
-                               'bind' : self.parent.OnPointer }
-        
-        self.OnTool(None)
+        for tool in (self.pointer, self.query, self.pan, self.zoomIn, self.zoomOut):
+            self.toolSwitcher.AddToolToGroup(group='mouseUse', toolbar=self, tool=tool)
         
         
         self.EnableTool(self.zoomBack, False)
         self.EnableTool(self.zoomBack, False)
         
         

+ 3 - 2
gui/wxpython/mapswipe/frame.py

@@ -23,6 +23,7 @@ import grass.script as grass
 
 
 from gui_core.mapdisp   import DoubleMapFrame
 from gui_core.mapdisp   import DoubleMapFrame
 from gui_core.dialogs   import GetImageHandlers
 from gui_core.dialogs   import GetImageHandlers
+from gui_core.toolbars import ToolSwitcher
 from mapwin.base import MapWindowProperties
 from mapwin.base import MapWindowProperties
 from core.render        import Map
 from core.render        import Map
 from mapdisp            import statusbar as sb
 from mapdisp            import statusbar as sb
@@ -98,7 +99,7 @@ class SwipeMapFrame(DoubleMapFrame):
         self.rasters = {'first': None, 'second': None}
         self.rasters = {'first': None, 'second': None}
 
 
         # default action in map toolbar
         # default action in map toolbar
-        self.OnPan(event = None)
+        self.GetMapToolbar().SelectDefault()
 
 
         self.resize = False
         self.resize = False
 
 
@@ -256,7 +257,7 @@ class SwipeMapFrame(DoubleMapFrame):
          - 'swipeMain'         - swipe functionality
          - 'swipeMain'         - swipe functionality
         """
         """
         if name == "swipeMap":
         if name == "swipeMap":
-            self.toolbars[name] = SwipeMapToolbar(self)
+            self.toolbars[name] = SwipeMapToolbar(self, self._toolSwitcher)
             self._mgr.AddPane(self.toolbars[name],
             self._mgr.AddPane(self.toolbars[name],
                       wx.aui.AuiPaneInfo().
                       wx.aui.AuiPaneInfo().
                       Name(name).Caption(_("Map Toolbar")).
                       Name(name).Caption(_("Map Toolbar")).

+ 5 - 5
gui/wxpython/mapswipe/toolbars.py

@@ -32,19 +32,19 @@ swipeIcons = {
 class SwipeMapToolbar(BaseToolbar):
 class SwipeMapToolbar(BaseToolbar):
     """!Map toolbar (to control map zoom and rendering)
     """!Map toolbar (to control map zoom and rendering)
     """
     """
-    def __init__(self, parent):
+    def __init__(self, parent, toolSwitcher):
         """!Map toolbar constructor
         """!Map toolbar constructor
         """
         """
-        BaseToolbar.__init__(self, parent)
+        BaseToolbar.__init__(self, parent, toolSwitcher)
         
         
         self.InitToolbar(self._toolbarData())
         self.InitToolbar(self._toolbarData())
+        self._default = self.pan
 
 
         # realize the toolbar
         # realize the toolbar
         self.Realize()
         self.Realize()
         
         
-        self.action = { 'id' : self.pan }
-        self.defaultAction = { 'id' : self.pan,
-                               'bind' : self.parent.OnPan }
+        for tool in (self.pointer, self.pan, self.zoomIn, self.zoomOut):
+            self.toolSwitcher.AddToolToGroup(group='mouseUse', toolbar=self, tool=tool)
         
         
         self.EnableTool(self.zoomBack, False)
         self.EnableTool(self.zoomBack, False)
         
         

+ 30 - 29
gui/wxpython/mapwin/decorations.py

@@ -22,6 +22,8 @@ import wx
 from core.utils import GetLayerNameFromCmd, _
 from core.utils import GetLayerNameFromCmd, _
 from gui_core.forms import GUI
 from gui_core.forms import GUI
 
 
+from grass.pydispatch.errors import DispatcherKeyError
+
 
 
 class OverlayController(object):
 class OverlayController(object):
 
 
@@ -187,9 +189,6 @@ class DecorationDialog(wx.Dialog):
         self._ddstyle = ddstyle
         self._ddstyle = ddstyle
         self._giface = giface
         self._giface = giface
 
 
-        self._oldMouseUse = None
-        self._oldCursor = None
-
         sizer = wx.BoxSizer(wx.VERTICAL)
         sizer = wx.BoxSizer(wx.VERTICAL)
 
 
         box = wx.BoxSizer(wx.HORIZONTAL)
         box = wx.BoxSizer(wx.HORIZONTAL)
@@ -218,7 +217,12 @@ class DecorationDialog(wx.Dialog):
             self.resizeBtn.SetToolTipString(_("Click and drag on the map display to set legend "
             self.resizeBtn.SetToolTipString(_("Click and drag on the map display to set legend "
                                               "size and position and then press OK"))
                                               "size and position and then press OK"))
             self.resizeBtn.Disable()
             self.resizeBtn.Disable()
-            self.resizeBtn.Bind(wx.EVT_TOGGLEBUTTON, self.OnResize)
+            toolSwitcher = self._giface.GetMapDisplay().GetToolSwitcher()
+            toolSwitcher.AddCustomToolToGroup(group='mouseUse', btnId=self.resizeBtn.GetId(),
+                                              toggleHandler=self.resizeBtn.SetValue)
+            toolSwitcher.toggleToolChanged.connect(self._toolChanged)
+            self.resizeBtn.Bind(wx.EVT_TOGGLEBUTTON, lambda evt: toolSwitcher.ToolChanged(evt.GetId()))
+
             box.Add(item=self.resizeBtn, proportion=0,
             box.Add(item=self.resizeBtn, proportion=0,
                     flag=wx.ALIGN_CENTRE | wx.ALL, border=5)
                     flag=wx.ALIGN_CENTRE | wx.ALL, border=5)
             sizer.Add(item=box, proportion=0,
             sizer.Add(item=box, proportion=0,
@@ -294,38 +298,37 @@ class DecorationDialog(wx.Dialog):
             else:
             else:
                 self._overlay.propwin.Show()
                 self._overlay.propwin.Show()
 
 
-    def OnResize(self, event):
-        window = self._giface.GetMapWindow()
-        if event.GetInt():
-            self._oldMouseUse = window.mouse['use']
-            self._oldCursor = window.GetNamedCursor()
-            window.SetNamedCursor('cross')
-            window.mouse['use'] = None
-            window.mouse['box'] = 'box'
-            window.pen = wx.Pen(colour='Black', width=2, style=wx.SHORT_DASH)
-            window.mouseLeftUp.connect(self._resizeLegend)
+    def _toolChanged(self, id):
+        """!Tool in toolbar or button itself were pressed"""
+        if id == self.resizeBtn.GetId():
+            if self.resizeBtn.GetValue():
+                # prepare for resizing
+                window = self._giface.GetMapWindow()
+                window.SetNamedCursor('cross')
+                window.mouse['use'] = None
+                window.mouse['box'] = 'box'
+                window.pen = wx.Pen(colour='Black', width=2, style=wx.SHORT_DASH)
+                window.mouseLeftUp.connect(self._resizeLegend)
+            else:
+                # stop resizing mode
+                self.DisconnectResizing()
+                self._giface.GetMapDisplay().GetMapToolbar().SelectDefault()
         else:
         else:
-            self.Restore()
+            # any other tool was pressed -> stop resizing mode
             self.DisconnectResizing()
             self.DisconnectResizing()
 
 
-    def Restore(self):
-        """!Restore conditions before resizing"""
-        window = self._giface.GetMapWindow()
-        if self._oldCursor:
-            window.SetNamedCursor(self._oldCursor)
-        if self._oldMouseUse:
-            window.mouse['use'] = self._oldMouseUse
-
     def DisconnectResizing(self):
     def DisconnectResizing(self):
-        self._giface.GetMapWindow().mouseLeftUp.disconnect(self._resizeLegend)
+        try:
+            self._giface.GetMapWindow().mouseLeftUp.disconnect(self._resizeLegend)
+        except DispatcherKeyError:
+            pass
 
 
     def _resizeLegend(self, x, y):
     def _resizeLegend(self, x, y):
         """!Update legend after drawing new legend size (moved from BufferedWindow)"""
         """!Update legend after drawing new legend size (moved from BufferedWindow)"""
-        self.resizeBtn.SetValue(False)
-        window = self._giface.GetMapWindow()
+        self._giface.GetMapDisplay().GetMapToolbar().SelectDefault()
         self.DisconnectResizing()
         self.DisconnectResizing()
-        self.Restore()
         # resize legend
         # resize legend
+        window = self._giface.GetMapWindow()
         screenSize = window.GetClientSizeTuple()
         screenSize = window.GetClientSizeTuple()
         self._overlay.ResizeLegend(window.mouse["begin"], window.mouse["end"], screenSize)
         self._overlay.ResizeLegend(window.mouse["begin"], window.mouse["end"], screenSize)
         # redraw
         # redraw
@@ -334,8 +337,6 @@ class DecorationDialog(wx.Dialog):
     def CloseDialog(self):
     def CloseDialog(self):
         """!Hide dialog"""
         """!Hide dialog"""
         if self._ddstyle == DECOR_DIALOG_LEGEND and self.resizeBtn.GetValue():
         if self._ddstyle == DECOR_DIALOG_LEGEND and self.resizeBtn.GetValue():
-            self.Restore()
-            self.resizeBtn.SetValue(False)
             self.DisconnectResizing()
             self.DisconnectResizing()
 
 
         self.Hide()
         self.Hide()

+ 11 - 34
gui/wxpython/psmap/frame.py

@@ -40,6 +40,7 @@ from gui_core.forms     import GUI
 from gui_core.dialogs   import HyperlinkDialog
 from gui_core.dialogs   import HyperlinkDialog
 from gui_core.ghelp     import ShowAboutDialog
 from gui_core.ghelp     import ShowAboutDialog
 from psmap.menudata     import PsMapMenuData
 from psmap.menudata     import PsMapMenuData
+from gui_core.toolbars import ToolSwitcher
 
 
 from psmap.dialogs      import *
 from psmap.dialogs      import *
 from psmap.instructions import *
 from psmap.instructions import *
@@ -65,10 +66,10 @@ class PsMapFrame(wx.Frame):
         self.SetMenuBar(self.menubar)
         self.SetMenuBar(self.menubar)
         #toolbar
         #toolbar
 
 
-        self.toolbar = PsMapToolbar(parent = self)
+        self._toolSwitcher = ToolSwitcher()
+        self.toolbar = PsMapToolbar(parent=self, toolSwitcher=self._toolSwitcher)
         self.SetToolBar(self.toolbar)
         self.SetToolBar(self.toolbar)
         
         
-        self.actionOld = self.toolbar.action['id']
         self.iconsize = (16, 16)
         self.iconsize = (16, 16)
         #satusbar
         #satusbar
         self.statusbar = self.CreateStatusBar(number = 1)
         self.statusbar = self.CreateStatusBar(number = 1)
@@ -154,7 +155,9 @@ class PsMapFrame(wx.Frame):
         
         
         # set WIND_OVERRIDE
         # set WIND_OVERRIDE
         grass.use_temp_region()
         grass.use_temp_region()
-        
+
+        self.toolbar.SelectDefault()
+
         # create queues
         # create queues
         self.requestQ = Queue.Queue()
         self.requestQ = Queue.Queue()
         self.resultQ = Queue.Queue()
         self.resultQ = Queue.Queue()
@@ -457,25 +460,21 @@ class PsMapFrame(wx.Frame):
         dlg.Destroy()
         dlg.Destroy()
         
         
     def OnPointer(self, event):
     def OnPointer(self, event):
-        self.toolbar.OnTool(event)
         self.mouse["use"] = "pointer"
         self.mouse["use"] = "pointer"
         self.canvas.SetCursor(self.cursors["default"])
         self.canvas.SetCursor(self.cursors["default"])
         self.previewCanvas.SetCursor(self.cursors["default"])
         self.previewCanvas.SetCursor(self.cursors["default"])
         
         
     def OnPan(self, event):
     def OnPan(self, event):
-        self.toolbar.OnTool(event)
         self.mouse["use"] = "pan"
         self.mouse["use"] = "pan"
         self.canvas.SetCursor(self.cursors["hand"])
         self.canvas.SetCursor(self.cursors["hand"])
         self.previewCanvas.SetCursor(self.cursors["hand"])
         self.previewCanvas.SetCursor(self.cursors["hand"])
         
         
     def OnZoomIn(self, event):
     def OnZoomIn(self, event):
-        self.toolbar.OnTool(event)
         self.mouse["use"] = "zoomin"
         self.mouse["use"] = "zoomin"
         self.canvas.SetCursor(self.cursors["cross"])
         self.canvas.SetCursor(self.cursors["cross"])
         self.previewCanvas.SetCursor(self.cursors["cross"])
         self.previewCanvas.SetCursor(self.cursors["cross"])
         
         
     def OnZoomOut(self, event):
     def OnZoomOut(self, event):
-        self.toolbar.OnTool(event)
         self.mouse["use"] = "zoomout"
         self.mouse["use"] = "zoomout"
         self.canvas.SetCursor(self.cursors["cross"])
         self.canvas.SetCursor(self.cursors["cross"])
         self.previewCanvas.SetCursor(self.cursors["cross"])
         self.previewCanvas.SetCursor(self.cursors["cross"])
@@ -500,14 +499,7 @@ class PsMapFrame(wx.Frame):
         
         
         
         
     def OnAddMap(self, event, notebook = False):
     def OnAddMap(self, event, notebook = False):
-        """!Add or edit map frame"""
-        if event is not None:
-            if event.GetId() != self.toolbar.action['id']:
-                self.actionOld = self.toolbar.action['id']
-                self.mouseOld = self.mouse['use']
-                self.cursorOld = self.canvas.GetCursor()
-            self.toolbar.OnTool(event)
-        
+        """!Add or edit map frame"""        
         if self.instruction.FindInstructionByType('map'):
         if self.instruction.FindInstructionByType('map'):
             mapId = self.instruction.FindInstructionByType('map').id
             mapId = self.instruction.FindInstructionByType('map').id
         else: mapId = None
         else: mapId = None
@@ -524,19 +516,9 @@ class PsMapFrame(wx.Frame):
             id[2] = vectorId
             id[2] = vectorId
         
         
         
         
-        if mapId: # map exists
-            
-            self.toolbar.ToggleTool(self.actionOld, True)
-            self.toolbar.ToggleTool(self.toolbar.action['id'], False)
-            self.toolbar.action['id'] = self.actionOld
-            try:
-                self.canvas.SetCursor(self.cursorOld) 
-            except AttributeError:
-                pass
-            
-##            dlg = MapDialog(parent = self, id  = id, settings = self.instruction,
-##                            notebook = notebook)
-##            dlg.ShowModal()  
+        if mapId: # map exists        
+            self.toolbar.SelectDefault()
+
             if notebook:
             if notebook:
                 #check map, raster, vector and save, destroy them
                 #check map, raster, vector and save, destroy them
                 if 'map' in self.openDialogs:
                 if 'map' in self.openDialogs:
@@ -1450,12 +1432,7 @@ class PsMapBufferedWindow(wx.Window):
             self.openDialogs['map'] = dlg
             self.openDialogs['map'] = dlg
             self.openDialogs['map'].Show()
             self.openDialogs['map'].Show()
             
             
-            self.mouse['use'] = self.parent.mouseOld
-
-            self.SetCursor(self.parent.cursorOld)
-            self.parent.toolbar.ToggleTool(self.parent.actionOld, True)
-            self.parent.toolbar.ToggleTool(self.parent.toolbar.action['id'], False)
-            self.parent.toolbar.action['id'] = self.parent.actionOld
+            self.parent.toolbar.SelectDefault()
             return
             return
 
 
         # resize resizable objects (map, line, rectangle)
         # resize resizable objects (map, line, rectangle)

+ 7 - 8
gui/wxpython/psmap/toolbars.py

@@ -26,14 +26,19 @@ from icons.icon        import MetaIcon
 from core.globalvar    import ETCIMGDIR
 from core.globalvar    import ETCIMGDIR
 
 
 class PsMapToolbar(BaseToolbar):
 class PsMapToolbar(BaseToolbar):
-    def __init__(self, parent):
+    def __init__(self, parent, toolSwitcher):
         """!Toolbar Cartographic Composer (psmap.py)
         """!Toolbar Cartographic Composer (psmap.py)
         
         
         @param parent parent window
         @param parent parent window
         """
         """
-        BaseToolbar.__init__(self, parent)
+        BaseToolbar.__init__(self, parent, toolSwitcher)
         
         
         self.InitToolbar(self._toolbarData())
         self.InitToolbar(self._toolbarData())
+        self._default = self.pointer
+        
+        for tool in (self.pointer, self.pan, self.zoomin, self.zoomout,
+                     self.drawGraphics, self.addMap):
+            self.toolSwitcher.AddToolToGroup(group='mouseUse', toolbar=self, tool=tool)
 
 
         # custom button for graphics mode selection
         # custom button for graphics mode selection
         # TODO: could this be somehow generalized?
         # TODO: could this be somehow generalized?
@@ -46,11 +51,6 @@ class PsMapToolbar(BaseToolbar):
 
 
         self.Realize()
         self.Realize()
 
 
-        self.action = { 'id' : self.pointer }
-        self.defaultAction = { 'id' : self.pointer,
-                               'bind' : self.parent.OnPointer }
-        self.OnTool(None)
-        
         from psmap.frame import havePILImage
         from psmap.frame import havePILImage
         if not havePILImage:
         if not havePILImage:
             self.EnableTool(self.preview, False)
             self.EnableTool(self.preview, False)
@@ -169,7 +169,6 @@ class PsMapToolbar(BaseToolbar):
 
 
     def OnDrawGraphics(self, event):
     def OnDrawGraphics(self, event):
         """!Graphics tool activated."""
         """!Graphics tool activated."""
-        self.OnTool(event)
         # we need the previous id
         # we need the previous id
         if self.drawGraphicsAction == 'pointAdd':
         if self.drawGraphicsAction == 'pointAdd':
             self.parent.OnAddPoint(event)
             self.parent.OnAddPoint(event)

+ 14 - 21
gui/wxpython/rlisetup/sampling_frame.py

@@ -33,7 +33,7 @@ from core.giface import StandaloneGrassInterface
 from mapwin.base import MapWindowProperties
 from mapwin.base import MapWindowProperties
 from mapwin.buffered import BufferedMapWindow
 from mapwin.buffered import BufferedMapWindow
 from core.render import Map
 from core.render import Map
-from gui_core.toolbars import BaseToolbar, BaseIcons
+from gui_core.toolbars import BaseToolbar, BaseIcons, ToolSwitcher
 from icons.icon import MetaIcon
 from icons.icon import MetaIcon
 
 
 from grass.pydispatch.signal import Signal
 from grass.pydispatch.signal import Signal
@@ -65,7 +65,9 @@ class RLiSetupMapPanel(wx.Panel):
                           Dockable(True).BestSize((-1, -1)).Name('mapwindow').
                           Dockable(True).BestSize((-1, -1)).Name('mapwindow').
                           CloseButton(False).DestroyOnClose(True).
                           CloseButton(False).DestroyOnClose(True).
                           Layer(0))
                           Layer(0))
-        self.toolbar = RLiSetupToolbar(self)
+        self._toolSwitcher = ToolSwitcher()
+        self._toolSwitcher.toggleToolChanged.connect(self._onToolChanged)
+        self.toolbar = RLiSetupToolbar(self, self._toolSwitcher)
 
 
         self._mgr.AddPane(self.toolbar,
         self._mgr.AddPane(self.toolbar,
                           wx.aui.AuiPaneInfo().
                           wx.aui.AuiPaneInfo().
@@ -75,18 +77,12 @@ class RLiSetupMapPanel(wx.Panel):
                           BestSize((self.toolbar.GetBestSize())))
                           BestSize((self.toolbar.GetBestSize())))
         self._mgr.Update()
         self._mgr.Update()
 
 
-        self._initTool()
+        self.toolbar.SelectDefault()
 
 
         self._registeredGraphics = self.mapWindow.RegisterGraphicsToDraw(graphicsType='rectangle')
         self._registeredGraphics = self.mapWindow.RegisterGraphicsToDraw(graphicsType='rectangle')
         self._registeredGraphics.AddPen('rlisetup', wx.Pen(wx.GREEN, width=3, style=wx.SOLID))
         self._registeredGraphics.AddPen('rlisetup', wx.Pen(wx.GREEN, width=3, style=wx.SOLID))
         self._registeredGraphics.AddItem(coords=[[0, 0], [0, 0]], penName='rlisetup', hide=True)
         self._registeredGraphics.AddItem(coords=[[0, 0], [0, 0]], penName='rlisetup', hide=True)
 
 
-    def _initTool(self):
-        """!Initialize draw mode"""
-        self.toolbar.ToggleTool(self.toolbar.draw, True)
-        self.toolbar.action['id'] = self.toolbar.draw
-        self.OnDraw(None)
-
     def GetMap(self):
     def GetMap(self):
         return self.map_
         return self.map_
 
 
@@ -97,13 +93,11 @@ class RLiSetupMapPanel(wx.Panel):
     def OnZoomIn(self, event):
     def OnZoomIn(self, event):
         """!Zoom in the map.
         """!Zoom in the map.
         """
         """
-        self.SwitchTool(event)
         self._prepareZoom(mapWindow=self.mapWindow, zoomType=1)
         self._prepareZoom(mapWindow=self.mapWindow, zoomType=1)
 
 
     def OnZoomOut(self, event):
     def OnZoomOut(self, event):
         """!Zoom out the map.
         """!Zoom out the map.
         """
         """
-        self.SwitchTool(event)
         self._prepareZoom(mapWindow=self.mapWindow, zoomType=-1)
         self._prepareZoom(mapWindow=self.mapWindow, zoomType=-1)
 
 
     def _prepareZoom(self, mapWindow, zoomType):
     def _prepareZoom(self, mapWindow, zoomType):
@@ -120,10 +114,8 @@ class RLiSetupMapPanel(wx.Panel):
         # change the cursor
         # change the cursor
         mapWindow.SetNamedCursor('cross')
         mapWindow.SetNamedCursor('cross')
 
 
-    def SwitchTool(self, event):
-        """!Helper function to switch tools"""
-        self.toolbar.OnTool(event)
-        self.toolbar.action['desc'] = ''
+    def _onToolChanged(self):
+        """!Helper function to disconnect drawing"""
         try:
         try:
             self.mapWindow.mouseLeftUp.disconnect(self._rectangleDrawn)
             self.mapWindow.mouseLeftUp.disconnect(self._rectangleDrawn)
         except DispatcherKeyError:
         except DispatcherKeyError:
@@ -132,8 +124,6 @@ class RLiSetupMapPanel(wx.Panel):
     def OnPan(self, event):
     def OnPan(self, event):
         """!Panning, set mouse to drag
         """!Panning, set mouse to drag
         """
         """
-        self.SwitchTool(event)
-
         self.mapWindow.mouse['use'] = "pan"
         self.mapWindow.mouse['use'] = "pan"
         self.mapWindow.mouse['box'] = "pan"
         self.mapWindow.mouse['box'] = "pan"
         self.mapWindow.zoomtype = 0
         self.mapWindow.zoomtype = 0
@@ -147,8 +137,6 @@ class RLiSetupMapPanel(wx.Panel):
 
 
     def OnDraw(self, event):
     def OnDraw(self, event):
         """!Start draw mode"""
         """!Start draw mode"""
-        self.SwitchTool(event)
-
         self.mapWindow.mouse['use'] = None
         self.mapWindow.mouse['use'] = None
         self.mapWindow.mouse['box'] = "box"
         self.mapWindow.mouse['box'] = "box"
         self.mapWindow.pen = wx.Pen(colour=wx.RED, width=2, style=wx.SHORT_DASH)
         self.mapWindow.pen = wx.Pen(colour=wx.RED, width=2, style=wx.SHORT_DASH)
@@ -182,12 +170,17 @@ icons = {'draw': MetaIcon(img='edit',
 class RLiSetupToolbar(BaseToolbar):
 class RLiSetupToolbar(BaseToolbar):
     """!IClass toolbar
     """!IClass toolbar
     """
     """
-    def __init__(self, parent):
+    def __init__(self, parent, toolSwitcher):
         """!RLiSetup toolbar constructor
         """!RLiSetup toolbar constructor
         """
         """
-        BaseToolbar.__init__(self, parent, style=wx.NO_BORDER | wx.TB_VERTICAL)
+        BaseToolbar.__init__(self, parent, toolSwitcher, style=wx.NO_BORDER | wx.TB_VERTICAL)
 
 
         self.InitToolbar(self._toolbarData())
         self.InitToolbar(self._toolbarData())
+        self._default = self.draw
+
+        for tool in (self.draw, self.pan, self.zoomIn, self.zoomOut):
+            self.toolSwitcher.AddToolToGroup(group='mouseUse', toolbar=self, tool=tool)
+
         # realize the toolbar
         # realize the toolbar
         self.Realize()
         self.Realize()
 
 

+ 23 - 28
gui/wxpython/vdigit/toolbars.py

@@ -31,14 +31,14 @@ from iclass.digit       import IClassVDigit
 class VDigitToolbar(BaseToolbar):
 class VDigitToolbar(BaseToolbar):
     """!Toolbar for digitization
     """!Toolbar for digitization
     """
     """
-    def __init__(self, parent, MapWindow, digitClass, giface,
+    def __init__(self, parent, toolSwitcher, MapWindow, digitClass, giface,
                  tools=[], layerTree=None):
                  tools=[], layerTree=None):
         self.MapWindow     = MapWindow
         self.MapWindow     = MapWindow
         self.Map           = MapWindow.GetMap() # Map class instance
         self.Map           = MapWindow.GetMap() # Map class instance
         self.layerTree     = layerTree  # reference to layer tree associated to map display
         self.layerTree     = layerTree  # reference to layer tree associated to map display
         self.tools         = tools
         self.tools         = tools
         self.digitClass    = digitClass
         self.digitClass    = digitClass
-        BaseToolbar.__init__(self, parent)
+        BaseToolbar.__init__(self, parent, toolSwitcher)
         self.digit         = None
         self.digit         = None
         self._giface       = giface
         self._giface       = giface
         
         
@@ -53,11 +53,11 @@ class VDigitToolbar(BaseToolbar):
         
         
         # only one dialog can be open
         # only one dialog can be open
         self.settingsDialog   = None
         self.settingsDialog   = None
-        
+
         # create toolbars (two rows optionally)
         # create toolbars (two rows optionally)
         self.InitToolbar(self._toolbarData())
         self.InitToolbar(self._toolbarData())
-        self.Bind(wx.EVT_TOOL, self._toolChosen)
         
         
+        self._default = -1
         # default action (digitize new point, line, etc.)
         # default action (digitize new point, line, etc.)
         self.action = { 'desc' : '',
         self.action = { 'desc' : '',
                         'type' : '',
                         'type' : '',
@@ -66,6 +66,13 @@ class VDigitToolbar(BaseToolbar):
         # list of available vector maps
         # list of available vector maps
         self.UpdateListOfLayers(updateTool = True)
         self.UpdateListOfLayers(updateTool = True)
         
         
+        for tool in ('addPoint', 'addLine', 'addBoundary', 'addCentroid', 'addArea',
+                     'addVertex', 'deleteLine', 'deleteArea', 'displayAttr', 'displayCats',
+                     'editLine', 'moveLine', 'moveVertex', 'removeVertex', 'additionalTools'):
+            if hasattr(self, tool):
+                tool = getattr(self, tool)
+                self.toolSwitcher.AddToolToGroup(group='mouseUse', toolbar=self, tool=tool)
+        
         # realize toolbar
         # realize toolbar
         self.Realize()
         self.Realize()
         # workaround for Mac bug. May be fixed by 2.8.8, but not before then.
         # workaround for Mac bug. May be fixed by 2.8.8, but not before then.
@@ -78,12 +85,9 @@ class VDigitToolbar(BaseToolbar):
             self.EnableTool(self.undo, False)
             self.EnableTool(self.undo, False)
         if self.redo > 0:
         if self.redo > 0:
             self.EnableTool(self.redo, False)
             self.EnableTool(self.redo, False)
-        
-        # toogle to pointer by default
-        self.OnTool(None)
-        
+
         self.FixSize(width = 105)
         self.FixSize(width = 105)
-                
+
     def _toolbarData(self):
     def _toolbarData(self):
         """!Toolbar data
         """!Toolbar data
         """
         """
@@ -235,27 +239,15 @@ class VDigitToolbar(BaseToolbar):
                          self.OnExit))
                          self.OnExit))
         
         
         return self._getToolbarData(data)
         return self._getToolbarData(data)
-    
-    def _toolChosen(self, event):
-        """!Tool selected -> untoggles selected tools in other
-        toolbars
 
 
-        @todo implement iclass front-end
-        """
-        self.parent.MapWindow.UnregisterAllHandlers()
-        
-        if hasattr(self.parent, "UpdateTools"):
-            self.parent.UpdateTools(event)
-        self.OnTool(event)
-        
     def OnTool(self, event):
     def OnTool(self, event):
         """!Tool selected -> untoggles previusly selected tool in
         """!Tool selected -> untoggles previusly selected tool in
         toolbar"""
         toolbar"""
+        Debug.msg(3, "VDigitToolbar.OnTool(): id = %s" % event.GetId())
         # set cursor
         # set cursor
         self.MapWindow.SetNamedCursor('cross')
         self.MapWindow.SetNamedCursor('cross')
-        
-        # pointer
-        self.parent.OnPointer(None)
+        self.MapWindow.mouse['box'] = 'point' 
+        self.MapWindow.mouse['use'] = 'pointer'
          
          
         aId = self.action.get('id', -1)       
         aId = self.action.get('id', -1)       
         BaseToolbar.OnTool(self, event)
         BaseToolbar.OnTool(self, event)
@@ -316,7 +308,7 @@ class VDigitToolbar(BaseToolbar):
 
 
     def OnAddArea(self, event):
     def OnAddArea(self, event):
         """!Add area to the vector map layer"""
         """!Add area to the vector map layer"""
-        Debug.msg (2, "VDigitToolbar.OnAddCentroid()")
+        Debug.msg (2, "VDigitToolbar.OnAddArea()")
         self.action = { 'desc' : "addLine",
         self.action = { 'desc' : "addLine",
                         'type' : "area",
                         'type' : "area",
                         'id'   : self.addArea }
                         'id'   : self.addArea }
@@ -333,8 +325,7 @@ class VDigitToolbar(BaseToolbar):
             self.settingsDialog.OnCancel(None)
             self.settingsDialog.OnCancel(None)
         
         
         # set default mouse settings
         # set default mouse settings
-        self.MapWindow.mouse['use'] = "pointer"
-        self.MapWindow.mouse['box'] = "point"
+        self.parent.GetMapToolbar().SelectDefault()
         self.MapWindow.polycoords = []
         self.MapWindow.polycoords = []
 
 
         # TODO: replace this by binding wx event in parent (or use signals...)
         # TODO: replace this by binding wx event in parent (or use signals...)
@@ -443,7 +434,11 @@ class VDigitToolbar(BaseToolbar):
         else:
         else:
             if self.GetToolEnabled(tool) is True:
             if self.GetToolEnabled(tool) is True:
                 self.EnableTool(tool, False)
                 self.EnableTool(tool, False)
-        
+
+    def GetAction(self, type = 'desc'):
+        """!Get current action info"""
+        return self.action.get(type, '')
+
     def OnSettings(self, event):
     def OnSettings(self, event):
         """!Show settings dialog"""
         """!Show settings dialog"""
         if self.digit is None:
         if self.digit is None:

+ 5 - 3
gui/wxpython/vnet/dialogs.py

@@ -207,9 +207,11 @@ class VNETDialog(wx.Dialog):
                               name = 'points')
                               name = 'points')
 
 
         self.list = PtsList(parent = pointsPanel, vnet_mgr = self.vnet_mgr)
         self.list = PtsList(parent = pointsPanel, vnet_mgr = self.vnet_mgr)
-        self.toolbars['pointsList'] = PointListToolbar(parent = pointsPanel, 
-                                                       dialog = self, 
-                                                       vnet_mgr = self.vnet_mgr)
+        toolSwitcher=self.giface.GetMapDisplay().GetToolSwitcher()
+        self.toolbars['pointsList'] = PointListToolbar(parent=pointsPanel,
+                                                       toolSwitcher=toolSwitcher,
+                                                       dialog=self, 
+                                                       vnet_mgr=self.vnet_mgr)
 
 
         anSettingsPanel = wx.Panel(parent = pointsPanel)
         anSettingsPanel = wx.Panel(parent = pointsPanel)
 
 

+ 3 - 2
gui/wxpython/vnet/toolbars.py

@@ -29,14 +29,15 @@ class PointListToolbar(BaseToolbar):
 
 
     @param parent reference to VNETDialog
     @param parent reference to VNETDialog
     """
     """
-    def __init__(self, parent, dialog, vnet_mgr):
-        BaseToolbar.__init__(self, parent)
+    def __init__(self, parent, toolSwitcher, dialog, vnet_mgr):
+        BaseToolbar.__init__(self, parent, toolSwitcher)
         self.vnet_mgr = vnet_mgr
         self.vnet_mgr = vnet_mgr
         self.vnet_pts_mgr = self.vnet_mgr.GetPointsManager()
         self.vnet_pts_mgr = self.vnet_mgr.GetPointsManager()
 
 
         self.dialog = dialog
         self.dialog = dialog
 
 
         self.InitToolbar(self._toolbarData())
         self.InitToolbar(self._toolbarData())
+        self.toolSwitcher.AddToolToGroup('mouseUse', self, self.insertPoint)
         
         
         # realize the toolbar
         # realize the toolbar
         self.Realize()
         self.Realize()