frame.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. """!
  2. @package example.frame
  3. @brief Example tool for displaying raster map and related information
  4. Classes:
  5. - frame::ExampleMapFrame
  6. - frame::ExampleInfoTextManager
  7. (C) 2011-2014 by the GRASS Development Team
  8. This program is free software under the GNU General Public
  9. License (>=v2). Read the file COPYING that comes with GRASS
  10. for details.
  11. @author Anna Petrasova <kratochanna gmail.com>
  12. """
  13. import os
  14. import sys
  15. import wx
  16. # this enables to run application standalone (> python example/frame.py )
  17. if __name__ == "__main__":
  18. sys.path.append(os.path.join(os.environ['GISBASE'], "etc", "gui", "wxpython"))
  19. # i18n is taken care of in the grass library code.
  20. # So we need to import it before any of the GUI code.
  21. from grass.script import core as gcore
  22. from gui_core.mapdisp import SingleMapFrame
  23. from mapwin.buffered import BufferedMapWindow
  24. from mapwin.base import MapWindowProperties
  25. from mapdisp import statusbar as sb
  26. from core.render import Map
  27. from core.debug import Debug
  28. from core.gcmd import RunCommand, GError
  29. from toolbars import ExampleMapToolbar, ExampleMiscToolbar, ExampleMainToolbar
  30. from dialogs import ExampleMapDialog
  31. # It is possible to call grass library functions (in C) directly via ctypes
  32. # however this is less stable. Example is available in trunk/doc/python/, ctypes
  33. # are used in nviz, vdigit, iclass gui modules.
  34. # from ctypes import *
  35. # try:
  36. # from grass.lib.raster import *
  37. # haveExample = True
  38. # errMsg = ''
  39. # except ImportError as e:
  40. # haveExample = False
  41. # errMsg = _("Loading raster lib failed.\n%s") % e
  42. class ExampleMapFrame(SingleMapFrame):
  43. """! Main frame of example tool.
  44. Inherits from SingleMapFrame, so map is displayed in one map widow.
  45. In case two map windows are needed, use DoubleMapFrame from (gui_core.mapdisp).
  46. @see IClassMapFrame in iclass.frame
  47. """
  48. def __init__(self, parent, giface, title=_("Example Tool"),
  49. toolbars=["MiscToolbar", "MapToolbar", "MainToolbar"],
  50. size=(800, 600), name='exampleWindow', **kwargs):
  51. """!Map Frame constructor
  52. @param parent (no parent is expected)
  53. @param title window title
  54. @param toolbars list of active toolbars (default value represents all toolbars)
  55. @param size default size
  56. """
  57. SingleMapFrame.__init__(self, parent=parent, title=title,
  58. name=name, Map=Map(), **kwargs)
  59. # Place debug message where appropriate
  60. # and set debug level from 1 to 5 (higher to lower level functions).
  61. # To enable debug mode write:
  62. # > g.gisenv set=WX_DEBUG=5
  63. Debug.msg(1, "ExampleMapFrame.__init__()")
  64. #
  65. # Add toolbars to aui manager
  66. #
  67. toolbarsCopy = toolbars[:]
  68. # workaround to have the same toolbar order on all platforms
  69. if sys.platform == 'win32':
  70. toolbarsCopy.reverse()
  71. for toolbar in toolbarsCopy:
  72. self.AddToolbar(toolbar)
  73. self.mapWindowProperties = MapWindowProperties()
  74. self.mapWindowProperties.setValuesFromUserSettings()
  75. self.mapWindowProperties.autoRenderChanged.connect(
  76. lambda value: self.OnRender(None) if value else None)
  77. #
  78. # Add statusbar
  79. #
  80. # choose items in statusbar choice, which makes sense for your application
  81. self.statusbarItems = [sb.SbCoordinates,
  82. sb.SbRegionExtent,
  83. sb.SbCompRegionExtent,
  84. sb.SbShowRegion,
  85. sb.SbAlignExtent,
  86. sb.SbResolution,
  87. sb.SbDisplayGeometry,
  88. sb.SbMapScale,
  89. sb.SbGoTo,
  90. sb.SbProjection]
  91. # create statusbar and its manager
  92. statusbar = self.CreateStatusBar(number=4, style=0)
  93. statusbar.SetStatusWidths([-5, -2, -1, -1])
  94. self.statusbarManager = sb.SbManager(mapframe=self, statusbar=statusbar)
  95. # fill statusbar manager
  96. self.statusbarManager.AddStatusbarItemsByClass(self.statusbarItems,
  97. mapframe=self, statusbar=statusbar)
  98. self.statusbarManager.AddStatusbarItem(sb.SbMask(self, statusbar=statusbar, position=2))
  99. self.statusbarManager.AddStatusbarItem(sb.SbRender(self, statusbar=statusbar, position=3))
  100. self.statusbarManager.Update()
  101. # create map window
  102. self.MapWindow = BufferedMapWindow(parent=self, Map=self.GetMap(),
  103. properties=self.mapWindowProperties, giface=self)
  104. self._setUpMapWindow(self.MapWindow)
  105. self.MapWindow.InitZoomHistory()
  106. # create whatever you want, here it is a widget for displaying raster info
  107. self.info = ExampleInfoTextManager(self)
  108. # add map window (and other widgets) to aui manager
  109. self._addPanes()
  110. self._mgr.Update()
  111. # initialize variables related to your application functionality
  112. self.InitVariables()
  113. # default action
  114. self.GetMapToolbar().SelectDefault()
  115. self.Bind(wx.EVT_SIZE, self.OnSize)
  116. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  117. self.SetSize(size)
  118. def __del__(self):
  119. """!Destructor deletes temporary region"""
  120. gcore.del_temp_region()
  121. def OnCloseWindow(self, event):
  122. """!Destroy frame"""
  123. self.Destroy()
  124. def IsStandalone(self):
  125. """!Check if application is standalone.
  126. Standalone application can work without parent.
  127. Parent can be e.g. Layer Manager.
  128. """
  129. if self.parent:
  130. return False
  131. return True
  132. def InitVariables(self):
  133. """!Initialize any variables nneded by application"""
  134. self.currentRaster = None
  135. self.statitistics = dict()
  136. # use WIND_OVERRIDE region not to affect current region
  137. gcore.use_temp_region()
  138. def _addPanes(self):
  139. """!Add mapwindow (and other widgets) to aui manager"""
  140. window = self.GetWindow()
  141. name = "mainWindow"
  142. self._mgr.AddPane(window, wx.aui.AuiPaneInfo().
  143. Name(name).CentrePane().
  144. Dockable(False).CloseButton(False).DestroyOnClose(True).
  145. Layer(0))
  146. window = self.info.GetControl()
  147. name = "infoText"
  148. self._mgr.AddPane(window, wx.aui.AuiPaneInfo().
  149. Name(name).Caption(_("Raster Info")).MinSize((250, -1)).
  150. Dockable(True).CloseButton(False).
  151. Layer(0).Left())
  152. def AddToolbar(self, name):
  153. """!Add defined toolbar to the window
  154. Currently known toolbars are:
  155. - 'ExampleMapToolbar' - basic map toolbar
  156. - 'ExampleMainToolbar' - toolbar with application specific tools
  157. - 'ExampleMiscToolbar' - toolbar with common tools (help, quit, ...)
  158. """
  159. # see wx.aui.AuiPaneInfo documentation for understanding all options
  160. if name == "MapToolbar":
  161. self.toolbars[name] = ExampleMapToolbar(self, self._toolSwitcher)
  162. self._mgr.AddPane(self.toolbars[name],
  163. wx.aui.AuiPaneInfo().
  164. Name(name).Caption(_("Map Toolbar")).
  165. ToolbarPane().Top().
  166. LeftDockable(False).RightDockable(False).
  167. BottomDockable(False).TopDockable(True).
  168. CloseButton(False).Layer(1).Row(1).
  169. BestSize((self.toolbars[name].GetBestSize())))
  170. if name == "MiscToolbar":
  171. self.toolbars[name] = ExampleMiscToolbar(self)
  172. self._mgr.AddPane(self.toolbars[name],
  173. wx.aui.AuiPaneInfo().
  174. Name(name).Caption(_("Misc Toolbar")).
  175. ToolbarPane().Top().
  176. LeftDockable(False).RightDockable(False).
  177. BottomDockable(False).TopDockable(True).
  178. CloseButton(False).Layer(1).Row(1).
  179. BestSize((self.toolbars[name].GetBestSize())))
  180. if name == "MainToolbar":
  181. self.toolbars[name] = ExampleMainToolbar(self)
  182. self._mgr.AddPane(self.toolbars[name],
  183. wx.aui.AuiPaneInfo().
  184. Name(name).Caption(_("Main Toolbar")).
  185. ToolbarPane().Top().
  186. LeftDockable(False).RightDockable(False).
  187. BottomDockable(False).TopDockable(True).
  188. CloseButton(False).Layer(1).Row(1).
  189. BestSize((self.toolbars[name].GetBestSize())))
  190. def GetMapToolbar(self):
  191. """!Returns toolbar with zooming tools"""
  192. return self.toolbars['MapToolbar']
  193. def OnHelp(self, event):
  194. """!Show help page"""
  195. RunCommand('g.manual', entry='wxGUI.Example')
  196. def OnSelectRaster(self, event):
  197. """!Opens dialog to select raster map"""
  198. dlg = ExampleMapDialog(self)
  199. if dlg.ShowModal() == wx.ID_OK:
  200. raster = gcore.find_file(name=dlg.GetRasterMap(), element='cell')
  201. if raster['fullname']:
  202. self.SetLayer(name=raster['fullname'])
  203. else:
  204. # show user that the map name is incorrect
  205. GError(parent=self,
  206. message=_("Raster map <{raster}> not found").format(raster=dlg.GetRasterMap()))
  207. dlg.Destroy()
  208. def SetLayer(self, name):
  209. """!Sets layer in Map and updates statistics.
  210. @param name layer (raster) name
  211. """
  212. Debug.msg (3, "ExampleMapFrame.SetLayer(): name=%s" % name)
  213. # this simple application enables to keep only one raster
  214. self.GetMap().DeleteAllLayers()
  215. cmdlist = ['d.rast', 'map=%s' % name]
  216. # add layer to Map instance (core.render)
  217. newLayer = self.GetMap().AddLayer(ltype='raster', command=cmdlist, active=True,
  218. name=name, hidden=False, opacity=1.0,
  219. render=True)
  220. self.GetWindow().ZoomToMap(layers=[newLayer, ], render=True)
  221. self.currentRaster = name
  222. # change comp. region to match new raster, so that the statistics
  223. # are computed for the entire raster
  224. RunCommand('g.region',
  225. rast=self.currentRaster,
  226. parent=self)
  227. self.UpdateStatistics()
  228. def ComputeStatitistics(self):
  229. """!Computes statistics for raster map using 'r.univar' module.
  230. @return statistic in form of dictionary
  231. """
  232. # RunCommand enables to run GRASS module
  233. res = RunCommand('r.univar', # module name
  234. flags='g', # command flags
  235. map=self.currentRaster, # module parameters
  236. read=True) # get command output
  237. return gcore.parse_key_val(res, val_type=float)
  238. def UpdateStatistics(self):
  239. """!Upadate statistic information.
  240. Called after changing raster map.
  241. """
  242. stats = self.ComputeStatitistics()
  243. self.info.WriteStatistics(name=self.currentRaster, statDict=stats)
  244. class ExampleInfoTextManager:
  245. """!Class for displaying information.
  246. Wrraper for wx.TextCtrl.
  247. """
  248. def __init__(self, parent):
  249. """!Creates wx.TextCtrl for displaying information.
  250. """
  251. self.textCtrl = wx.TextCtrl(parent, id=wx.ID_ANY,
  252. style=wx.TE_MULTILINE | wx.TE_RICH2 | wx.TE_READONLY)
  253. self.textCtrl.SetInsertionPoint(0)
  254. self.font = self.textCtrl.GetFont()
  255. def GetControl(self):
  256. """!Returns control itself."""
  257. return self.textCtrl
  258. def _setStyle(self, style):
  259. """!Sets default style of textCtrl.
  260. @param style "title"/"value"
  261. """
  262. if style == "title":
  263. self.font.SetWeight(wx.FONTWEIGHT_BOLD)
  264. elif style == "value":
  265. self.font.SetWeight(wx.FONTWEIGHT_NORMAL)
  266. else:
  267. return
  268. self.textCtrl.SetDefaultStyle(wx.TextAttr(font=self.font))
  269. def _writeLine(self, title, value):
  270. """!Formats text (key, value pair) with styles."""
  271. self._setStyle("title")
  272. self.textCtrl.AppendText("%s: " % title)
  273. self._setStyle("value")
  274. self.textCtrl.AppendText("%.2f\n" % value)
  275. def _writeRasterTitle(self, name):
  276. """!Writes title."""
  277. self._setStyle("title")
  278. self.textCtrl.AppendText("%s\n\n" % name)
  279. def WriteStatistics(self, name, statDict):
  280. """!Write and format information about raster map
  281. @param name raster map name
  282. @param statDict dictionary containing information
  283. """
  284. self.GetControl().Clear()
  285. self._writeRasterTitle(name=name)
  286. for key, value in statDict.iteritems():
  287. self._writeLine(title=key, value=value)