frame.py 13 KB

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