Browse Source

wxGUI example application update to work with current gui

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

+ 5 - 0
doc/gui/wxpython/example/Makefile

@@ -0,0 +1,5 @@
+MODULE_TOPDIR = ../../..
+
+include $(MODULE_TOPDIR)/include/Make/GuiScript.make
+
+default: guiscript

+ 14 - 20
doc/gui/wxpython/example/README

@@ -22,16 +22,7 @@ or it can be launched from the console.
 
 
 2. Copy directory ./doc/gui/wxpython/example to ./gui/wxpython/example
 2. Copy directory ./doc/gui/wxpython/example to ./gui/wxpython/example
 
 
-3. Now you should be able to run Example Tool as a standalone 
-application in GRASS environment. Start GRASS GIS and start application:
-
-    > python ./gui/wxpython/example/frame.py
-
-If you want to add Example Tool in the compilation.
-
-4. Move file ./gui/wxpython/example/wxGUI.Example.html to ./gui/wxpython/docs/
-
-5. Edit ./gui/wxpython/Makefile:
+3. Edit ./gui/wxpython/Makefile:
 
 
  SRCFILES := $(wildcard icons/*.* scripts/* xml/*) \
  SRCFILES := $(wildcard icons/*.* scripts/* xml/*) \
 -	$(wildcard core/* dbmgr/* gcp/* gmodeler/* ... \
 -	$(wildcard core/* dbmgr/* gcp/* gmodeler/* ... \
@@ -40,12 +31,18 @@ If you want to add Example Tool in the compilation.
 -PYDSTDIRS := $(patsubst %,$(ETCDIR)/%,core dbmgr gcp gmodeler ... \
 -PYDSTDIRS := $(patsubst %,$(ETCDIR)/%,core dbmgr gcp gmodeler ... \
 +PYDSTDIRS := $(patsubst %,$(ETCDIR)/%,core dbmgr example gcp gmodeler ... \
 +PYDSTDIRS := $(patsubst %,$(ETCDIR)/%,core dbmgr example gcp gmodeler ... \
 
 
-6. Run make (in ./gui/wxpython)
-    
+4. Run make (in ./gui/wxpython)
+
+Now you can start the application by running
+
+$ g.gui.example
+
+from terminal or wxGUI command console. Try also g.gui.example --help.
+
 If you want to access Example Tool from Layer Manager menu, there are
 If you want to access Example Tool from Layer Manager menu, there are
 a few more things to be done.
 a few more things to be done.
 
 
-7. Edit ./gui/wxpython/xml/menudata.xml. Add following code to appropriate place:
+5. Edit ./gui/wxpython/xml/menudata.xml. Add following code to appropriate place:
 
 
     <menuitem>
     <menuitem>
       <label>Example</label>
       <label>Example</label>
@@ -54,20 +51,17 @@ a few more things to be done.
       <handler>OnExample</handler>
       <handler>OnExample</handler>
     </menuitem>
     </menuitem>
     
     
-8. Add folowing event handler to class GMFrame in ./gui/wxpython/lmgr/frame.py:
+6. Add folowing event handler to class GMFrame in ./gui/wxpython/lmgr/frame.py:
 
 
     def OnExample(self, event):
     def OnExample(self, event):
         """!Launch ExampleTool"""
         """!Launch ExampleTool"""
-        win = ExampleMapFrame(parent = self)
+        from example.frame import ExampleMapFrame
+        win = ExampleMapFrame(parent=self, giface=self._giface)
         win.CentreOnScreen()
         win.CentreOnScreen()
         
         
         win.Show()
         win.Show()
-        
-and don't forget to insert following line at the beginning of the file:
-
-    from example.frame import ExampleMapFrame
 
 
-9. Run make again.
+7. Run make again.
 
 
 
 
 Note
 Note

+ 20 - 19
doc/gui/wxpython/example/dialogs.py

@@ -6,53 +6,54 @@
 Classes:
 Classes:
  - dialogs::ExampleMapDialog
  - dialogs::ExampleMapDialog
 
 
-(C) 2006-2011 by the GRASS Development Team
+(C) 2011-2014 by the GRASS Development Team
 This program is free software under the GNU General Public
 This program is free software under the GNU General Public
 License (>=v2). Read the file COPYING that comes with GRASS
 License (>=v2). Read the file COPYING that comes with GRASS
 for details.
 for details.
 
 
-@author Anna Kratochvilova <kratochanna gmail.com>
+@author Anna Petrasova <kratochanna gmail.com>
 """
 """
 
 
 import wx
 import wx
 
 
-from core               import globalvar
-from gui_core.dialogs   import SimpleDialog, GroupDialog
-from gui_core           import gselect
+from core import globalvar
+from gui_core.dialogs import SimpleDialog
+from gui_core import gselect
+from core.utils import _
+
 
 
 class ExampleMapDialog(SimpleDialog):
 class ExampleMapDialog(SimpleDialog):
     """!Dialog for adding raster map.
     """!Dialog for adding raster map.
-    
+
     Dialog can be easily changed to enable to choose vector, imagery groups or other elements.
     Dialog can be easily changed to enable to choose vector, imagery groups or other elements.
     """
     """
-    def __init__(self, parent, title = _("Choose raster map"), id = wx.ID_ANY):
+    def __init__(self, parent, title=_("Choose raster map")):
         """!Calls super class constructor.
         """!Calls super class constructor.
-        
+
         @param parent gui parent
         @param parent gui parent
         @param title dialog window title
         @param title dialog window title
         @param id id
         @param id id
         """
         """
         SimpleDialog.__init__(self, parent, title)
         SimpleDialog.__init__(self, parent, title)
-        
+
         # here is the place to determine element type
         # here is the place to determine element type
-        self.element = gselect.Select(parent = self.panel, type = 'raster',
-                                      size = globalvar.DIALOG_GSELECT_SIZE)
-        
+        self.element = gselect.Select(parent=self.panel, type='raster',
+                                      size=globalvar.DIALOG_GSELECT_SIZE)
+
         self._layout()
         self._layout()
 
 
         self.SetMinSize(self.GetSize())
         self.SetMinSize(self.GetSize())
 
 
     def _layout(self):
     def _layout(self):
         """!Do layout"""
         """!Do layout"""
-        self.dataSizer.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
-                                                label = _("Name of raster map:")),
-                           proportion = 0, flag = wx.ALL, border = 1)
-        self.dataSizer.Add(self.element, proportion = 0,
-                           flag = wx.EXPAND | wx.ALL, border = 1)
+        self.dataSizer.Add(item=wx.StaticText(parent=self.panel,
+                                              label=_("Name of raster map:")),
+                           proportion=0, flag=wx.ALL, border=1)
+        self.dataSizer.Add(self.element, proportion=0,
+                           flag=wx.EXPAND | wx.ALL, border=1)
         self.panel.SetSizer(self.sizer)
         self.panel.SetSizer(self.sizer)
         self.sizer.Fit(self)
         self.sizer.Fit(self)
-        
+
     def GetRasterMap(self):
     def GetRasterMap(self):
         """!Returns selected raster map"""
         """!Returns selected raster map"""
         return self.element.GetValue()
         return self.element.GetValue()
-

+ 126 - 137
doc/gui/wxpython/example/frame.py

@@ -7,12 +7,12 @@ Classes:
  - frame::ExampleMapFrame
  - frame::ExampleMapFrame
  - frame::ExampleInfoTextManager
  - frame::ExampleInfoTextManager
 
 
-(C) 2006-2011 by the GRASS Development Team
+(C) 2011-2014 by the GRASS Development Team
 This program is free software under the GNU General Public
 This program is free software under the GNU General Public
 License (>=v2). Read the file COPYING that comes with GRASS
 License (>=v2). Read the file COPYING that comes with GRASS
 for details.
 for details.
 
 
-@author Anna Kratochvilova <kratochanna gmail.com>
+@author Anna Petrasova <kratochanna gmail.com>
 """
 """
 
 
 import os
 import os
@@ -24,16 +24,18 @@ if __name__ == "__main__":
     sys.path.append(os.path.join(os.environ['GISBASE'], "etc", "gui", "wxpython"))
     sys.path.append(os.path.join(os.environ['GISBASE'], "etc", "gui", "wxpython"))
 
 
 from gui_core.mapdisp import SingleMapFrame
 from gui_core.mapdisp import SingleMapFrame
-from mapdisp.mapwindow import BufferedWindow
+from mapwin.buffered import BufferedMapWindow
+from mapwin.base import MapWindowProperties
 from mapdisp import statusbar as sb
 from mapdisp import statusbar as sb
 from core.render import Map
 from core.render import Map
 from core.debug import Debug
 from core.debug import Debug
-from core.gcmd import RunCommand
+from core.gcmd import RunCommand, GError
+from core.utils import _
 
 
-import grass.script as grass
+from grass.script import core as gcore
 
 
 from toolbars import ExampleMapToolbar, ExampleMiscToolbar, ExampleMainToolbar
 from toolbars import ExampleMapToolbar, ExampleMiscToolbar, ExampleMainToolbar
-from dialogs  import ExampleMapDialog
+from dialogs import ExampleMapDialog
 
 
 # It is possible to call grass library functions (in C) directly via ctypes
 # It is possible to call grass library functions (in C) directly via ctypes
 # however this is less stable. Example is available in trunk/doc/python/, ctypes
 # however this is less stable. Example is available in trunk/doc/python/, ctypes
@@ -48,33 +50,34 @@ from dialogs  import ExampleMapDialog
 #     haveExample = False
 #     haveExample = False
 #     errMsg = _("Loading raster lib failed.\n%s") % e
 #     errMsg = _("Loading raster lib failed.\n%s") % e
 
 
+
 class ExampleMapFrame(SingleMapFrame):
 class ExampleMapFrame(SingleMapFrame):
     """! Main frame of example tool.
     """! Main frame of example tool.
-    
+
     Inherits from SingleMapFrame, so map is displayed in one map widow.
     Inherits from SingleMapFrame, so map is displayed in one map widow.
     In case two map windows are needed, use DoubleMapFrame from (gui_core.mapdisp).
     In case two map windows are needed, use DoubleMapFrame from (gui_core.mapdisp).
-    
+
     @see IClassMapFrame in iclass.frame
     @see IClassMapFrame in iclass.frame
     """
     """
-    def __init__(self, parent = None, title = _("Example Tool"),
-                 toolbars = ["MiscToolbar", "MapToolbar", "MainToolbar"],
-                 size = (800, 600), name = 'exampleWindow', **kwargs):
+    def __init__(self, parent, giface, title=_("Example Tool"),
+                 toolbars=["MiscToolbar", "MapToolbar", "MainToolbar"],
+                 size=(800, 600), name='exampleWindow', **kwargs):
         """!Map Frame constructor
         """!Map Frame constructor
-        
+
         @param parent (no parent is expected)
         @param parent (no parent is expected)
         @param title window title
         @param title window title
         @param toolbars list of active toolbars (default value represents all toolbars)
         @param toolbars list of active toolbars (default value represents all toolbars)
         @param size default size
         @param size default size
         """
         """
-        SingleMapFrame.__init__(self, parent = parent, title = title,
-                                name = name, Map = Map(), **kwargs)
-        
+        SingleMapFrame.__init__(self, parent=parent, title=title,
+                                name=name, Map=Map(), **kwargs)
+
         # Place debug message where appropriate
         # Place debug message where appropriate
         # and set debug level from 1 to 5 (higher to lower level functions).
         # and set debug level from 1 to 5 (higher to lower level functions).
         # To enable debug mode write:
         # To enable debug mode write:
         # > g.gisenv set=WX_DEBUG=5
         # > g.gisenv set=WX_DEBUG=5
         Debug.msg(1, "ExampleMapFrame.__init__()")
         Debug.msg(1, "ExampleMapFrame.__init__()")
-        
+
         #
         #
         # Add toolbars to aui manager
         # Add toolbars to aui manager
         #
         #
@@ -82,14 +85,18 @@ class ExampleMapFrame(SingleMapFrame):
         # workaround to have the same toolbar order on all platforms
         # workaround to have the same toolbar order on all platforms
         if sys.platform == 'win32':
         if sys.platform == 'win32':
             toolbarsCopy.reverse()
             toolbarsCopy.reverse()
-            
+
         for toolbar in toolbarsCopy:
         for toolbar in toolbarsCopy:
             self.AddToolbar(toolbar)
             self.AddToolbar(toolbar)
-        
+
+        self.mapWindowProperties = MapWindowProperties()
+        self.mapWindowProperties.setValuesFromUserSettings()
+        self.mapWindowProperties.autoRenderChanged.connect(
+            lambda value: self.OnRender(None) if value else None)
         #
         #
         # Add statusbar
         # Add statusbar
         #
         #
-        
+
         # choose items in statusbar choice, which makes sense for your application
         # choose items in statusbar choice, which makes sense for your application
         self.statusbarItems = [sb.SbCoordinates,
         self.statusbarItems = [sb.SbCoordinates,
                                sb.SbRegionExtent,
                                sb.SbRegionExtent,
@@ -101,94 +108,90 @@ class ExampleMapFrame(SingleMapFrame):
                                sb.SbMapScale,
                                sb.SbMapScale,
                                sb.SbGoTo,
                                sb.SbGoTo,
                                sb.SbProjection]
                                sb.SbProjection]
-        
+
         # create statusbar and its manager
         # create statusbar and its manager
-        statusbar = self.CreateStatusBar(number = 4, style = 0)
+        statusbar = self.CreateStatusBar(number=4, style=0)
         statusbar.SetStatusWidths([-5, -2, -1, -1])
         statusbar.SetStatusWidths([-5, -2, -1, -1])
-        self.statusbarManager = sb.SbManager(mapframe = self, statusbar = statusbar)
-        
+        self.statusbarManager = sb.SbManager(mapframe=self, statusbar=statusbar)
+
         # fill statusbar manager
         # fill statusbar manager
-        self.statusbarManager.AddStatusbarItemsByClass(self.statusbarItems, mapframe = self, statusbar = statusbar)
-        self.statusbarManager.AddStatusbarItem(sb.SbMask(self, statusbar = statusbar, position = 2))
-        self.statusbarManager.AddStatusbarItem(sb.SbRender(self, statusbar = statusbar, position = 3))
-        
+        self.statusbarManager.AddStatusbarItemsByClass(self.statusbarItems,
+                                                       mapframe=self, statusbar=statusbar)
+        self.statusbarManager.AddStatusbarItem(sb.SbMask(self, statusbar=statusbar, position=2))
+        self.statusbarManager.AddStatusbarItem(sb.SbRender(self, statusbar=statusbar, position=3))
+
         self.statusbarManager.Update()
         self.statusbarManager.Update()
-        
-        
+
         # create map window
         # create map window
-        self.MapWindow = BufferedWindow(self, Map = self.GetMap(), frame = self, giface = self)
-        
+        self.MapWindow = BufferedMapWindow(parent=self, Map=self.GetMap(),
+                                           properties=self.mapWindowProperties, giface=self)
+        self._setUpMapWindow(self.MapWindow)
+        self.MapWindow.InitZoomHistory()
+
         # create whatever you want, here it is a widget for displaying raster info
         # create whatever you want, here it is a widget for displaying raster info
         self.info = ExampleInfoTextManager(self)
         self.info = ExampleInfoTextManager(self)
-        
+
         # add map window (and other widgets) to aui manager
         # add map window (and other widgets) to aui manager
         self._addPanes()
         self._addPanes()
         self._mgr.Update()
         self._mgr.Update()
-        
-        # default action in map toolbar
-        self.OnPan(event = None)
-        
+
         # initialize variables related to your application functionality
         # initialize variables related to your application functionality
         self.InitVariables()
         self.InitVariables()
-        
+
+        # default action
+        self.GetMapToolbar().SelectDefault()
+
+        self.Bind(wx.EVT_SIZE, self.OnSize)
         self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
         self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
-        
+
         self.SetSize(size)
         self.SetSize(size)
-        
+
     def __del__(self):
     def __del__(self):
         """!Destructor deletes temporary region"""
         """!Destructor deletes temporary region"""
-        grass.del_temp_region()
-        
+        gcore.del_temp_region()
+
     def OnCloseWindow(self, event):
     def OnCloseWindow(self, event):
         """!Destroy frame"""
         """!Destroy frame"""
         self.Destroy()
         self.Destroy()
-        
+
     def IsStandalone(self):
     def IsStandalone(self):
         """!Check if application is standalone.
         """!Check if application is standalone.
-        
+
         Standalone application can work without parent.
         Standalone application can work without parent.
         Parent can be e.g. Layer Manager.
         Parent can be e.g. Layer Manager.
         """
         """
         if self.parent:
         if self.parent:
             return False
             return False
-            
+
         return True
         return True
-        
-    def GetLayerManager(self):
-        """!Returns frame parent.
-        
-        If IsStandalone() is True, returns None,
-        otherwise retuns frame parent (Layer Manager)
-        """
-        return self.parent
-            
+
     def InitVariables(self):
     def InitVariables(self):
         """!Initialize any variables nneded by application"""
         """!Initialize any variables nneded by application"""
         self.currentRaster = None
         self.currentRaster = None
         self.statitistics = dict()
         self.statitistics = dict()
-        
+
         # use WIND_OVERRIDE region not to affect current region
         # use WIND_OVERRIDE region not to affect current region
-        grass.use_temp_region()
-        
+        gcore.use_temp_region()
+
     def _addPanes(self):
     def _addPanes(self):
         """!Add mapwindow (and other widgets) to aui manager"""
         """!Add mapwindow (and other widgets) to aui manager"""
         window = self.GetWindow()
         window = self.GetWindow()
         name = "mainWindow"
         name = "mainWindow"
         self._mgr.AddPane(window, wx.aui.AuiPaneInfo().
         self._mgr.AddPane(window, wx.aui.AuiPaneInfo().
-                  Name(name).CentrePane().
-                  Dockable(False).CloseButton(False).DestroyOnClose(True).
-                  Layer(0))
-                  
+                          Name(name).CentrePane().
+                          Dockable(False).CloseButton(False).DestroyOnClose(True).
+                          Layer(0))
+
         window = self.info.GetControl()
         window = self.info.GetControl()
         name = "infoText"
         name = "infoText"
         self._mgr.AddPane(window, wx.aui.AuiPaneInfo().
         self._mgr.AddPane(window, wx.aui.AuiPaneInfo().
-                  Name(name).Caption(_("Raster Info")).MinSize((250, -1)).
-                  Dockable(True).CloseButton(False).
-                  Layer(0).Left())
-                  
+                          Name(name).Caption(_("Raster Info")).MinSize((250, -1)).
+                          Dockable(True).CloseButton(False).
+                          Layer(0).Left())
+
     def AddToolbar(self, name):
     def AddToolbar(self, name):
         """!Add defined toolbar to the window
         """!Add defined toolbar to the window
-        
+
         Currently known toolbars are:
         Currently known toolbars are:
          - 'ExampleMapToolbar'        - basic map toolbar
          - 'ExampleMapToolbar'        - basic map toolbar
          - 'ExampleMainToolbar'       - toolbar with application specific tools
          - 'ExampleMainToolbar'       - toolbar with application specific tools
@@ -196,8 +199,8 @@ class ExampleMapFrame(SingleMapFrame):
         """
         """
         # see wx.aui.AuiPaneInfo documentation for understanding all options
         # see wx.aui.AuiPaneInfo documentation for understanding all options
         if name == "MapToolbar":
         if name == "MapToolbar":
-            self.toolbars[name] = ExampleMapToolbar(self)
-            
+            self.toolbars[name] = ExampleMapToolbar(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")).
@@ -206,10 +209,10 @@ class ExampleMapFrame(SingleMapFrame):
                               BottomDockable(False).TopDockable(True).
                               BottomDockable(False).TopDockable(True).
                               CloseButton(False).Layer(1).Row(1).
                               CloseButton(False).Layer(1).Row(1).
                               BestSize((self.toolbars[name].GetBestSize())))
                               BestSize((self.toolbars[name].GetBestSize())))
-                              
+
         if name == "MiscToolbar":
         if name == "MiscToolbar":
             self.toolbars[name] = ExampleMiscToolbar(self)
             self.toolbars[name] = ExampleMiscToolbar(self)
-            
+
             self._mgr.AddPane(self.toolbars[name],
             self._mgr.AddPane(self.toolbars[name],
                               wx.aui.AuiPaneInfo().
                               wx.aui.AuiPaneInfo().
                               Name(name).Caption(_("Misc Toolbar")).
                               Name(name).Caption(_("Misc Toolbar")).
@@ -218,10 +221,10 @@ class ExampleMapFrame(SingleMapFrame):
                               BottomDockable(False).TopDockable(True).
                               BottomDockable(False).TopDockable(True).
                               CloseButton(False).Layer(1).Row(1).
                               CloseButton(False).Layer(1).Row(1).
                               BestSize((self.toolbars[name].GetBestSize())))
                               BestSize((self.toolbars[name].GetBestSize())))
-                              
+
         if name == "MainToolbar":
         if name == "MainToolbar":
             self.toolbars[name] = ExampleMainToolbar(self)
             self.toolbars[name] = ExampleMainToolbar(self)
-            
+
             self._mgr.AddPane(self.toolbars[name],
             self._mgr.AddPane(self.toolbars[name],
                               wx.aui.AuiPaneInfo().
                               wx.aui.AuiPaneInfo().
                               Name(name).Caption(_("Main Toolbar")).
                               Name(name).Caption(_("Main Toolbar")).
@@ -230,95 +233,97 @@ class ExampleMapFrame(SingleMapFrame):
                               BottomDockable(False).TopDockable(True).
                               BottomDockable(False).TopDockable(True).
                               CloseButton(False).Layer(1).Row(1).
                               CloseButton(False).Layer(1).Row(1).
                               BestSize((self.toolbars[name].GetBestSize())))
                               BestSize((self.toolbars[name].GetBestSize())))
-                              
+
     def GetMapToolbar(self):
     def GetMapToolbar(self):
         """!Returns toolbar with zooming tools"""
         """!Returns toolbar with zooming tools"""
         return self.toolbars['MapToolbar']
         return self.toolbars['MapToolbar']
-        
+
     def OnHelp(self, event):
     def OnHelp(self, event):
         """!Show help page"""
         """!Show help page"""
-        RunCommand('g.manual', entry = 'wxGUI.Example')
-        
+        RunCommand('g.manual', entry='wxGUI.Example')
+
     def OnSelectRaster(self, event):
     def OnSelectRaster(self, event):
         """!Opens dialog to select raster map"""
         """!Opens dialog to select raster map"""
         dlg = ExampleMapDialog(self)
         dlg = ExampleMapDialog(self)
-        
+
         if dlg.ShowModal() == wx.ID_OK:
         if dlg.ShowModal() == wx.ID_OK:
-            raster = grass.find_file(name = dlg.GetRasterMap(), element = 'cell')
+            raster = gcore.find_file(name=dlg.GetRasterMap(), element='cell')
             if raster['fullname']:
             if raster['fullname']:
-                self.SetLayer(name = raster['fullname'])
-                
+                self.SetLayer(name=raster['fullname'])
+            else:
+                # show user that the map name is incorrect
+                GError(parent=self,
+                       message=_("Raster map <{raster}> not found").format(raster=dlg.GetRasterMap()))
+
         dlg.Destroy()
         dlg.Destroy()
-        
+
     def SetLayer(self, name):
     def SetLayer(self, name):
         """!Sets layer in Map and updates statistics.
         """!Sets layer in Map and updates statistics.
-        
+
         @param name layer (raster) name
         @param name layer (raster) name
         """
         """
         Debug.msg (3, "ExampleMapFrame.SetLayer(): name=%s" % name)
         Debug.msg (3, "ExampleMapFrame.SetLayer(): name=%s" % name)
-        
+
         # this simple application enables to keep only one raster
         # this simple application enables to keep only one raster
         self.GetMap().DeleteAllLayers()
         self.GetMap().DeleteAllLayers()
         cmdlist = ['d.rast', 'map=%s' % name]
         cmdlist = ['d.rast', 'map=%s' % name]
         # add layer to Map instance (core.render)
         # add layer to Map instance (core.render)
-        newLayer = self.GetMap().AddLayer(ltype = 'raster', command = cmdlist, active = True,
-                                          name = name, hidden = False, opacity = 1.0,
-                                          render = True)
-        self.GetWindow().ZoomToMap(layers = [newLayer,], render = True)
+        newLayer = self.GetMap().AddLayer(ltype='raster', command=cmdlist, active=True,
+                                          name=name, hidden=False, opacity=1.0,
+                                          render=True)
+        self.GetWindow().ZoomToMap(layers=[newLayer, ], render=True)
         self.currentRaster = name
         self.currentRaster = name
-        
+
         # change comp. region to match new raster, so that the statistics
         # change comp. region to match new raster, so that the statistics
         # are computed for the entire raster
         # are computed for the entire raster
         RunCommand('g.region',
         RunCommand('g.region',
-                   rast = self.currentRaster,
-                   parent = self)
-        
+                   rast=self.currentRaster,
+                   parent=self)
+
         self.UpdateStatistics()
         self.UpdateStatistics()
-        
+
     def ComputeStatitistics(self):
     def ComputeStatitistics(self):
         """!Computes statistics for raster map using 'r.univar' module.
         """!Computes statistics for raster map using 'r.univar' module.
-        
-        @return statistic in form of dictionary 
+
+        @return statistic in form of dictionary
         """
         """
         # RunCommand enables to run GRASS module
         # RunCommand enables to run GRASS module
-        res = RunCommand('r.univar', # module name
-                         flags = 'g', # command flags
-                         map = self.currentRaster, # module parameters
-                         read = True) # get command output
-                              
-        return grass.parse_key_val(res, val_type = float)
-        
+        res = RunCommand('r.univar',  # module name
+                         flags='g',  # command flags
+                         map=self.currentRaster,  # module parameters
+                         read=True)  # get command output
+
+        return gcore.parse_key_val(res, val_type=float)
+
     def UpdateStatistics(self):
     def UpdateStatistics(self):
         """!Upadate statistic information.
         """!Upadate statistic information.
-        
+
         Called after changing raster map.
         Called after changing raster map.
         """
         """
         stats = self.ComputeStatitistics()
         stats = self.ComputeStatitistics()
-        self.info.WriteStatistics(name = self.currentRaster, statDict = stats)
-        
-        
+        self.info.WriteStatistics(name=self.currentRaster, statDict=stats)
+
+
 class ExampleInfoTextManager:
 class ExampleInfoTextManager:
     """!Class for displaying information.
     """!Class for displaying information.
-    
-    Wrraper for wx.TextCtrl. 
+
+    Wrraper for wx.TextCtrl.
     """
     """
     def __init__(self, parent):
     def __init__(self, parent):
         """!Creates wx.TextCtrl for displaying information.
         """!Creates wx.TextCtrl for displaying information.
         """
         """
-        self.textCtrl = wx.TextCtrl(parent, id = wx.ID_ANY,
-                                    style = wx.TE_MULTILINE | wx.TE_RICH2 | wx.TE_READONLY)
+        self.textCtrl = wx.TextCtrl(parent, id=wx.ID_ANY,
+                                    style=wx.TE_MULTILINE | wx.TE_RICH2 | wx.TE_READONLY)
         self.textCtrl.SetInsertionPoint(0)
         self.textCtrl.SetInsertionPoint(0)
-        self.textCtrl.Disable()
         self.font = self.textCtrl.GetFont()
         self.font = self.textCtrl.GetFont()
-        self.bgColor = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BACKGROUND)
-        
+
     def GetControl(self):
     def GetControl(self):
         """!Returns control itself."""
         """!Returns control itself."""
         return self.textCtrl
         return self.textCtrl
-        
+
     def _setStyle(self, style):
     def _setStyle(self, style):
         """!Sets default style of textCtrl.
         """!Sets default style of textCtrl.
-        
+
         @param style "title"/"value"
         @param style "title"/"value"
         """
         """
         if style == "title":
         if style == "title":
@@ -327,44 +332,28 @@ class ExampleInfoTextManager:
             self.font.SetWeight(wx.FONTWEIGHT_NORMAL)
             self.font.SetWeight(wx.FONTWEIGHT_NORMAL)
         else:
         else:
             return
             return
-            
-        self.textCtrl.SetDefaultStyle(wx.TextAttr(colBack = self.bgColor, font = self.font))
-    
+
+        self.textCtrl.SetDefaultStyle(wx.TextAttr(font=self.font))
+
     def _writeLine(self, title, value):
     def _writeLine(self, title, value):
         """!Formats text (key, value pair) with styles."""
         """!Formats text (key, value pair) with styles."""
         self._setStyle("title")
         self._setStyle("title")
         self.textCtrl.AppendText("%s: " % title)
         self.textCtrl.AppendText("%s: " % title)
         self._setStyle("value")
         self._setStyle("value")
         self.textCtrl.AppendText("%.2f\n" % value)
         self.textCtrl.AppendText("%.2f\n" % value)
-        
+
     def _writeRasterTitle(self, name):
     def _writeRasterTitle(self, name):
         """!Writes title."""
         """!Writes title."""
         self._setStyle("title")
         self._setStyle("title")
         self.textCtrl.AppendText("%s\n\n" % name)
         self.textCtrl.AppendText("%s\n\n" % name)
-        
+
     def WriteStatistics(self, name, statDict):
     def WriteStatistics(self, name, statDict):
         """!Write and format information about raster map
         """!Write and format information about raster map
-        
+
         @param name raster map name
         @param name raster map name
         @param statDict dictionary containing information
         @param statDict dictionary containing information
         """
         """
         self.GetControl().Clear()
         self.GetControl().Clear()
-        self._writeRasterTitle(name = name)
+        self._writeRasterTitle(name=name)
         for key, value in statDict.iteritems():
         for key, value in statDict.iteritems():
-            self._writeLine(title = key, value = value)
-    
-
-def main():
-    import gettext
-    
-    gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
-    
-    app = wx.PySimpleApp()
-    wx.InitAllImageHandlers()
-    
-    frame = ExampleMapFrame()
-    frame.Show()
-    app.MainLoop()
-
-if __name__ == "__main__":
-    main()
+            self._writeLine(title=key, value=value)

doc/gui/wxpython/example/wxGUI.example.html → doc/gui/wxpython/example/g.gui.example.html


+ 80 - 0
doc/gui/wxpython/example/g.gui.example.py

@@ -0,0 +1,80 @@
+#!/usr/bin/env python
+############################################################################
+#
+# MODULE:    g.gui.iclass
+# AUTHOR(S): Anna Petrasova
+# PURPOSE:   Example GUI application
+# COPYRIGHT: (C) 2012-2014 by the GRASS Development Team
+#
+#  This program is free software; you can redistribute it and/or modify
+#  it under the terms of the GNU General Public License as published by
+#  the Free Software Foundation; either version 2 of the License, or
+#  (at your option) any later version.
+#
+#  This program is distributed in the hope that it will be useful,
+#  but WITHOUT ANY WARRANTY; without even the implied warranty of
+#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+#  GNU General Public License for more details.
+#
+############################################################################
+
+#%module
+#% description: Example GUI application which displays raster map and further information
+#% keywords: example
+#% keywords: GUI
+#% keywords: raster
+#%end
+#%option G_OPT_R_INPUT
+#% description: Name of raster map to load
+#% required: no
+#%end
+
+import os
+import sys
+import wx
+
+import grass.script.core as gcore
+
+if __name__ == '__main__':
+    wxbase = os.path.join(os.getenv('GISBASE'), 'etc', 'gui', 'wxpython')
+    if wxbase not in sys.path:
+        sys.path.append(wxbase)
+
+from core.globalvar import CheckWxVersion
+from core.giface import StandaloneGrassInterface
+from core.utils import _, GuiModuleMain
+from core.settings import UserSettings
+from example.frame import ExampleMapFrame
+
+
+def main():
+    options, flags = gcore.parser()
+    if options['input']:
+        map_name = gcore.find_file(name=options['input'], element='cell')['fullname']
+        if not map_name:
+            gcore.fatal(_("Raster map <{raster}> not found").format(raster=options['input']))
+
+    # define display driver (avoid 'no graphics device selected' error at start up)
+    driver = UserSettings.Get(group='display', key='driver', subkey='type')
+    if driver == 'png':
+        os.environ['GRASS_RENDER_IMMEDIATE'] = 'png'
+    else:
+        os.environ['GRASS_RENDER_IMMEDIATE'] = 'cairo'
+
+    # launch application
+    app = wx.App()
+    if not CheckWxVersion([2, 9]):
+        wx.InitAllImageHandlers()
+
+    # show main frame
+    giface = StandaloneGrassInterface()
+    frame = ExampleMapFrame(parent=None, giface=giface)
+    if options['input']:
+        giface.WriteLog(_("Loading raster map <{raster}>...").format(raster=map_name))
+        frame.SetLayer(map_name)
+
+    frame.Show()
+    app.MainLoop()
+
+if __name__ == '__main__':
+    GuiModuleMain(main)

+ 25 - 22
doc/gui/wxpython/example/toolbars.py

@@ -8,12 +8,12 @@ Classes:
  - toolbars::ExampleMainToolbar
  - toolbars::ExampleMainToolbar
  - toolbars::ExampleMiscToolbar
  - toolbars::ExampleMiscToolbar
 
 
-(C) 2006-2011 by the GRASS Development Team
+(C) 2011-2014 by the GRASS Development Team
 This program is free software under the GNU General Public
 This program is free software under the GNU General Public
 License (>=v2). Read the file COPYING that comes with GRASS
 License (>=v2). Read the file COPYING that comes with GRASS
 for details.
 for details.
 
 
-@author Anna Kratochvilova <kratochanna gmail.com>
+@author Anna Petrasova <kratochanna gmail.com>
 """
 """
 
 
 import wx
 import wx
@@ -25,22 +25,23 @@ from icons.icon import MetaIcon
 class ExampleMapToolbar(BaseToolbar):
 class ExampleMapToolbar(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())
 
 
         # 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._default = self.pan
+
+        for tool in (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)
-        
+
     def _toolbarData(self):
     def _toolbarData(self):
         """!Returns toolbar data (name, icon, handler)"""
         """!Returns toolbar data (name, icon, handler)"""
         # BaseIcons are a set of often used icons. It is possible
         # BaseIcons are a set of often used icons. It is possible
@@ -52,10 +53,10 @@ class ExampleMapToolbar(BaseToolbar):
                                       self.parent.OnRender),
                                       self.parent.OnRender),
                                      ("erase", icons["erase"],
                                      ("erase", icons["erase"],
                                       self.parent.OnErase),
                                       self.parent.OnErase),
-                                     (None, ), # creates separator
+                                     (None, ),  # creates separator
                                      ("pan", icons["pan"],
                                      ("pan", icons["pan"],
                                       self.parent.OnPan,
                                       self.parent.OnPan,
-                                      wx.ITEM_CHECK), # toggle tool
+                                      wx.ITEM_CHECK),  # toggle tool
                                      ("zoomIn", icons["zoomIn"],
                                      ("zoomIn", icons["zoomIn"],
                                       self.parent.OnZoomIn,
                                       self.parent.OnZoomIn,
                                       wx.ITEM_CHECK),
                                       wx.ITEM_CHECK),
@@ -67,8 +68,9 @@ class ExampleMapToolbar(BaseToolbar):
                                       self.parent.OnZoomBack),
                                       self.parent.OnZoomBack),
                                      ("zoomToMap", icons["zoomExtent"],
                                      ("zoomToMap", icons["zoomExtent"],
                                       self.parent.OnZoomToMap),
                                       self.parent.OnZoomToMap),
-                                    ))
-                                    
+                                     ))
+
+
 class ExampleMainToolbar(BaseToolbar):
 class ExampleMainToolbar(BaseToolbar):
     """!Toolbar with tools related to application functionality
     """!Toolbar with tools related to application functionality
     """
     """
@@ -76,18 +78,19 @@ class ExampleMainToolbar(BaseToolbar):
         """!Toolbar constructor
         """!Toolbar constructor
         """
         """
         BaseToolbar.__init__(self, parent)
         BaseToolbar.__init__(self, parent)
-        
+
         self.InitToolbar(self._toolbarData())
         self.InitToolbar(self._toolbarData())
-        
+
         # realize the toolbar
         # realize the toolbar
         self.Realize()
         self.Realize()
-        
+
     def _toolbarData(self):
     def _toolbarData(self):
         """!Toolbar data"""
         """!Toolbar data"""
         return self._getToolbarData((("addRaster", BaseIcons['addRast'],
         return self._getToolbarData((("addRaster", BaseIcons['addRast'],
                                       self.parent.OnSelectRaster),
                                       self.parent.OnSelectRaster),
-                                    ))
-        
+                                     ))
+
+
 class ExampleMiscToolbar(BaseToolbar):
 class ExampleMiscToolbar(BaseToolbar):
     """!Toolbar with miscellaneous tools related to app
     """!Toolbar with miscellaneous tools related to app
     """
     """
@@ -95,11 +98,11 @@ class ExampleMiscToolbar(BaseToolbar):
         """!Toolbar constructor
         """!Toolbar constructor
         """
         """
         BaseToolbar.__init__(self, parent)
         BaseToolbar.__init__(self, parent)
-        
+
         self.InitToolbar(self._toolbarData())
         self.InitToolbar(self._toolbarData())
         # realize the toolbar
         # realize the toolbar
         self.Realize()
         self.Realize()
-        
+
     def _toolbarData(self):
     def _toolbarData(self):
         """!Toolbar data"""
         """!Toolbar data"""
         icons = BaseIcons
         icons = BaseIcons