frame.py 13 KB

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