frame.py 14 KB

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