mapdisp.py 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824
  1. """
  2. @package mapdisp.py
  3. @brief GIS map display canvas, with toolbar for various display
  4. management functions, and additional toolbars (vector digitizer, 3d
  5. view).
  6. Can be used either from Layer Manager or as p.mon backend.
  7. Classes:
  8. - MapFrame
  9. - MapApp
  10. Usage:
  11. python mapdisp.py monitor-identifier /path/to/command/file
  12. (C) 2006-2009 by the GRASS Development Team
  13. This program is free software under the GNU General Public
  14. License (>=v2). Read the file COPYING that comes with GRASS
  15. for details.
  16. @author Michael Barton
  17. @author Jachym Cepicky
  18. @author Martin Landa <landa.martin gmail.com>
  19. """
  20. import os
  21. import sys
  22. import glob
  23. import math
  24. import tempfile
  25. import copy
  26. import globalvar
  27. if not os.getenv("GRASS_WXBUNDLED"):
  28. globalvar.CheckForWx()
  29. import wx
  30. import wx.aui
  31. try:
  32. import subprocess
  33. except:
  34. CompatPath = os.path.join(globalvar.ETCWXDIR)
  35. sys.path.append(CompatPath)
  36. from compat import subprocess
  37. gmpath = os.path.join(globalvar.ETCWXDIR, "icons")
  38. sys.path.append(gmpath)
  39. grassPath = os.path.join(globalvar.ETCDIR, "python")
  40. sys.path.append(grassPath)
  41. import render
  42. import toolbars
  43. import menuform
  44. import gselect
  45. import disp_print
  46. import gcmd
  47. import dbm
  48. import dbm_dialogs
  49. import histogram
  50. import profile
  51. import globalvar
  52. import utils
  53. import gdialogs
  54. from grass.script import core as grass
  55. from debug import Debug
  56. from icon import Icons
  57. from preferences import globalSettings as UserSettings
  58. from mapdisp_command import Command
  59. from mapdisp_window import BufferedWindow
  60. import images
  61. imagepath = images.__path__[0]
  62. sys.path.append(imagepath)
  63. ###
  64. ### global variables
  65. ###
  66. # for standalone app
  67. cmdfilename = None
  68. class MapFrame(wx.Frame):
  69. """
  70. Main frame for map display window. Drawing takes place in child double buffered
  71. drawing window.
  72. """
  73. def __init__(self, parent=None, id=wx.ID_ANY, title=_("GRASS GIS - Map display"),
  74. pos=wx.DefaultPosition, size=wx.DefaultSize,
  75. style=wx.DEFAULT_FRAME_STYLE, toolbars=["map"],
  76. tree=None, notebook=None, lmgr=None, page=None,
  77. Map=None, auimgr=None):
  78. """
  79. Main map display window with toolbars, statusbar and
  80. DrawWindow
  81. @param toolbars array of activated toolbars, e.g. ['map', 'digit']
  82. @param tree reference to layer tree
  83. @param notebook control book ID in Layer Manager
  84. @param mgr Layer Manager
  85. @param page notebook page with layer tree
  86. @param Map instance of render.Map
  87. """
  88. self._layerManager = lmgr # Layer Manager object
  89. self.Map = Map # instance of render.Map
  90. self.tree = tree # Layer Manager layer tree object
  91. self.page = page # Notebook page holding the layer tree
  92. self.layerbook = notebook # Layer Manager layer tree notebook
  93. self.parent = parent
  94. self.title = title
  95. #
  96. # available cursors
  97. #
  98. self.cursors = {
  99. # default: cross
  100. # "default" : wx.StockCursor(wx.CURSOR_DEFAULT),
  101. "default" : wx.StockCursor(wx.CURSOR_ARROW),
  102. "cross" : wx.StockCursor(wx.CURSOR_CROSS),
  103. "hand" : wx.StockCursor(wx.CURSOR_HAND),
  104. "pencil" : wx.StockCursor(wx.CURSOR_PENCIL),
  105. "sizenwse": wx.StockCursor(wx.CURSOR_SIZENWSE)
  106. }
  107. wx.Frame.__init__(self, parent, id, title, pos, size, style)
  108. self.SetName("MapWindow")
  109. #
  110. # set the size & system icon
  111. #
  112. self.SetClientSize(size)
  113. self.iconsize = (16, 16)
  114. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass_map.ico'), wx.BITMAP_TYPE_ICO))
  115. #
  116. # Fancy gui
  117. #
  118. # self._mgr = auimgr
  119. self._mgr = wx.aui.AuiManager(self)
  120. #
  121. # Add toolbars
  122. #
  123. self.toolbars = { 'map' : None,
  124. 'vdigit' : None,
  125. 'georect' : None,
  126. 'nviz' : None }
  127. for toolb in toolbars:
  128. self.AddToolbar(toolb)
  129. #
  130. # Add statusbar
  131. #
  132. self.statusbar = self.CreateStatusBar(number=3, style=0)
  133. self.statusbar.SetStatusWidths([-5, -2, -1])
  134. self.toggleStatus = wx.Choice(self.statusbar, wx.ID_ANY,
  135. choices = globalvar.MAP_DISPLAY_STATUSBAR_MODE)
  136. self.toggleStatus.SetSelection(UserSettings.Get(group='display', key='statusbarMode', subkey='selection'))
  137. self.statusbar.Bind(wx.EVT_CHOICE, self.OnToggleStatus, self.toggleStatus)
  138. # auto-rendering checkbox
  139. self.autoRender = wx.CheckBox(parent=self.statusbar, id=wx.ID_ANY,
  140. label=_("Render"))
  141. self.statusbar.Bind(wx.EVT_CHECKBOX, self.OnToggleRender, self.autoRender)
  142. self.autoRender.SetValue(UserSettings.Get(group='display', key='autoRendering', subkey='enabled'))
  143. self.autoRender.SetToolTip(wx.ToolTip (_("Enable/disable auto-rendering")))
  144. # show region
  145. self.showRegion = wx.CheckBox(parent=self.statusbar, id=wx.ID_ANY,
  146. label=_("Show computational extent"))
  147. self.statusbar.Bind(wx.EVT_CHECKBOX, self.OnToggleShowRegion, self.showRegion)
  148. self.showRegion.SetValue(False)
  149. self.showRegion.Hide()
  150. self.showRegion.SetToolTip(wx.ToolTip (_("Show/hide computational "
  151. "region extent (set with g.region). "
  152. "Display region drawn as a blue box inside the "
  153. "computational region, "
  154. "computational region inside a display region "
  155. "as a red box).")))
  156. # set resolution
  157. self.compResolution = wx.CheckBox(parent=self.statusbar, id=wx.ID_ANY,
  158. label=_("Constrain display resolution to computational settings"))
  159. self.statusbar.Bind(wx.EVT_CHECKBOX, self.OnToggleResolution, self.compResolution)
  160. self.compResolution.SetValue(UserSettings.Get(group='display', key='compResolution', subkey='enabled'))
  161. self.compResolution.Hide()
  162. self.compResolution.SetToolTip(wx.ToolTip (_("Constrain display resolution "
  163. "to computational region settings. "
  164. "Default value for new map displays can "
  165. "be set up in 'User GUI settings' dialog.")))
  166. # map scale
  167. self.mapScale = wx.TextCtrl(parent=self.statusbar, id=wx.ID_ANY,
  168. value="", style=wx.TE_PROCESS_ENTER,
  169. size=(150, -1))
  170. self.mapScale.Hide()
  171. self.statusbar.Bind(wx.EVT_TEXT_ENTER, self.OnChangeMapScale, self.mapScale)
  172. # go to
  173. self.goTo = wx.TextCtrl(parent=self.statusbar, id=wx.ID_ANY,
  174. value="", style=wx.TE_PROCESS_ENTER,
  175. size=(200, -1))
  176. self.goTo.Hide()
  177. self.statusbar.Bind(wx.EVT_TEXT_ENTER, self.OnGoTo, self.goTo)
  178. # on-render gauge
  179. self.onRenderGauge = wx.Gauge(parent=self.statusbar, id=wx.ID_ANY,
  180. range=0, style=wx.GA_HORIZONTAL)
  181. self.onRenderGauge.Hide()
  182. self.StatusbarReposition() # reposition statusbar
  183. #
  184. # Init map display (buffered DC & set default cursor)
  185. #
  186. self.MapWindow2D = BufferedWindow(self, id=wx.ID_ANY,
  187. Map=self.Map, tree=self.tree, lmgr=self._layerManager)
  188. # default is 2D display mode
  189. self.MapWindow = self.MapWindow2D
  190. self.MapWindow.Bind(wx.EVT_MOTION, self.OnMotion)
  191. self.MapWindow.SetCursor(self.cursors["default"])
  192. # used by Nviz (3D display mode)
  193. self.MapWindow3D = None
  194. #
  195. # initialize region values
  196. #
  197. self.__InitDisplay()
  198. #
  199. # Bind various events
  200. #
  201. self.Bind(wx.EVT_ACTIVATE, self.OnFocus)
  202. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  203. self.Bind(render.EVT_UPDATE_PRGBAR, self.OnUpdateProgress)
  204. #
  205. # Update fancy gui style
  206. #
  207. self._mgr.AddPane(self.MapWindow, wx.aui.AuiPaneInfo().CentrePane().
  208. Dockable(False).BestSize((-1,-1)).
  209. CloseButton(False).DestroyOnClose(True).
  210. Layer(0))
  211. self._mgr.Update()
  212. #
  213. # Init print module and classes
  214. #
  215. self.printopt = disp_print.PrintOptions(self, self.MapWindow)
  216. #
  217. # Initialization of digitization tool
  218. #
  219. self.digit = None
  220. #
  221. # Init zoom history
  222. #
  223. self.MapWindow.ZoomHistory(self.Map.region['n'],
  224. self.Map.region['s'],
  225. self.Map.region['e'],
  226. self.Map.region['w'])
  227. #
  228. # Re-use dialogs
  229. #
  230. self.dialogs = {}
  231. self.dialogs['attributes'] = None
  232. self.dialogs['category'] = None
  233. self.dialogs['barscale'] = None
  234. self.dialogs['legend'] = None
  235. self.decorationDialog = None # decoration/overlays
  236. def AddToolbar(self, name):
  237. """
  238. Add defined toolbar to the window
  239. Currently known toolbars are:
  240. - map basic map toolbar
  241. - digit vector digitizer
  242. - georect georectifier
  243. """
  244. # default toolbar
  245. if name == "map":
  246. self.toolbars['map'] = toolbars.MapToolbar(self, self.Map)
  247. self._mgr.AddPane(self.toolbars['map'].toolbar,
  248. wx.aui.AuiPaneInfo().
  249. Name("maptoolbar").Caption(_("Map Toolbar")).
  250. ToolbarPane().Top().
  251. LeftDockable(False).RightDockable(False).
  252. BottomDockable(False).TopDockable(True).
  253. CloseButton(False).Layer(2).
  254. BestSize((self.toolbars['map'].GetToolbar().GetSize())))
  255. # vector digitizer
  256. elif name == "vdigit":
  257. from vdigit import haveVDigit
  258. if not haveVDigit:
  259. from vdigit import errorMsg
  260. msg = _("Unable to start vector digitizer.\nThe VDigit python extension "
  261. "was not found or loaded properly.\n"
  262. "Switching back to 2D display mode.\n\nDetails: %s" % errorMsg)
  263. self.toolbars['map'].combo.SetValue (_("2D view"))
  264. wx.MessageBox(parent=self,
  265. message=msg,
  266. caption=_("Error"),
  267. style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  268. return
  269. if self._layerManager:
  270. log = self._layerManager.goutput
  271. else:
  272. log = None
  273. self.toolbars['vdigit'] = toolbars.VDigitToolbar(parent=self, map=self.Map,
  274. layerTree=self.tree,
  275. log=log)
  276. for toolRow in range(0, self.toolbars['vdigit'].numOfRows):
  277. self._mgr.AddPane(self.toolbars['vdigit'].toolbar[toolRow],
  278. wx.aui.AuiPaneInfo().
  279. Name("vdigittoolbar" + str(toolRow)).Caption(_("Vector digitizer toolbar")).
  280. ToolbarPane().Top().Row(toolRow + 1).
  281. LeftDockable(False).RightDockable(False).
  282. BottomDockable(False).TopDockable(True).
  283. CloseButton(False).Layer(2).
  284. BestSize((self.toolbars['vdigit'].GetToolbar().GetSize())))
  285. # change mouse to draw digitized line
  286. self.MapWindow.mouse['box'] = "point"
  287. self.MapWindow.zoomtype = 0
  288. self.MapWindow.pen = wx.Pen(colour='red', width=2, style=wx.SOLID)
  289. self.MapWindow.polypen = wx.Pen(colour='green', width=2, style=wx.SOLID)
  290. # georectifier
  291. elif name == "georect":
  292. self.toolbars['georect'] = toolbars.GRToolbar(self, self.Map)
  293. self._mgr.AddPane(self.toolbars['georect'].toolbar,
  294. wx.aui.AuiPaneInfo().
  295. Name("georecttoolbar").Caption(_("Georectification toolbar")).
  296. ToolbarPane().Top().
  297. LeftDockable(False).RightDockable(False).
  298. BottomDockable(False).TopDockable(True).
  299. CloseButton(False).Layer(2))
  300. # nviz
  301. elif name == "nviz":
  302. import nviz
  303. # check for GLCanvas and OpenGL
  304. msg = None
  305. if not nviz.haveGLCanvas:
  306. msg = _("Unable to switch to 3D display mode.\nThe GLCanvas class has not been "
  307. "included with this build "
  308. "of wxPython!\nSwitching back to "
  309. "2D display mode.\n\nDetails: %s" % nviz.errorMsg)
  310. if not nviz.haveNviz:
  311. msg = _("Unable to switch to 3D display mode.\nThe Nviz python extension "
  312. "was not found or loaded properly.\n"
  313. "Switching back to 2D display mode.\n\nDetails: %s" % nviz.errorMsg)
  314. if msg:
  315. self.toolbars['map'].combo.SetValue (_("2D view"))
  316. wx.MessageBox(parent=self,
  317. message=msg,
  318. caption=_("Error"),
  319. style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  320. return
  321. #
  322. # add Nviz toolbar and disable 2D display mode tools
  323. #
  324. self.toolbars['nviz'] = toolbars.NvizToolbar(self, self.Map)
  325. self.toolbars['map'].Enable2D(False)
  326. #
  327. # update layer tree (-> enable 3d-rasters)
  328. #
  329. if self.tree:
  330. self.tree.EnableItemType(type='3d-raster', enable=True)
  331. #
  332. # update status bar
  333. #
  334. self.toggleStatus.Enable(False)
  335. #
  336. # erase map window
  337. #
  338. self.MapWindow.EraseMap()
  339. self.statusbar.SetStatusText(_("Please wait, loading data..."), 0)
  340. #
  341. # create GL window & NVIZ toolbar
  342. #
  343. if not self.MapWindow3D:
  344. self.MapWindow3D = nviz.GLWindow(self, id=wx.ID_ANY,
  345. Map=self.Map, tree=self.tree, lmgr=self._layerManager)
  346. # -> show after paint
  347. self.nvizToolWin = nviz.NvizToolWindow(self, id=wx.ID_ANY,
  348. mapWindow=self.MapWindow3D)
  349. self.MapWindow3D.OnPaint(None) # -> LoadData
  350. self.MapWindow3D.Show()
  351. self.MapWindow3D.UpdateView(None)
  352. self.nvizToolWin.Show()
  353. #
  354. # switch from MapWindow to MapWindowGL
  355. # add nviz toolbar
  356. #
  357. self._mgr.DetachPane(self.MapWindow2D)
  358. self.MapWindow2D.Hide()
  359. self._mgr.AddPane(self.MapWindow3D, wx.aui.AuiPaneInfo().CentrePane().
  360. Dockable(False).BestSize((-1,-1)).
  361. CloseButton(False).DestroyOnClose(True).
  362. Layer(0))
  363. self._mgr.AddPane(self.toolbars['nviz'].toolbar,
  364. wx.aui.AuiPaneInfo().
  365. Name("nviztoolbar").Caption(_("Nviz toolbar")).
  366. ToolbarPane().Top().Row(1).
  367. LeftDockable(False).RightDockable(False).
  368. BottomDockable(False).TopDockable(True).
  369. CloseButton(False).Layer(2))
  370. self.MapWindow = self.MapWindow3D
  371. self.SetStatusText("", 0)
  372. self._mgr.Update()
  373. def RemoveToolbar (self, name):
  374. """
  375. Removes toolbar from the window
  376. TODO: Only hide, activate by calling AddToolbar()
  377. """
  378. # cannot hide main toolbar
  379. if name == "map":
  380. return
  381. elif name == "vdigit":
  382. # TODO: not destroy only hide
  383. for toolRow in range(0, self.toolbars['vdigit'].numOfRows):
  384. self._mgr.DetachPane (self.toolbars['vdigit'].toolbar[toolRow])
  385. self.toolbars['vdigit'].toolbar[toolRow].Destroy()
  386. else:
  387. self._mgr.DetachPane (self.toolbars[name].toolbar)
  388. self.toolbars[name].toolbar.Destroy()
  389. self.toolbars[name] = None
  390. if name == 'nviz':
  391. # hide nviz tools
  392. self.nvizToolWin.Hide()
  393. # unload data
  394. # self.MapWindow3D.Reset()
  395. # switch from MapWindowGL to MapWindow
  396. self._mgr.DetachPane(self.MapWindow3D)
  397. self.MapWindow3D.Hide()
  398. self.MapWindow2D.Show()
  399. self._mgr.AddPane(self.MapWindow2D, wx.aui.AuiPaneInfo().CentrePane().
  400. Dockable(False).BestSize((-1,-1)).
  401. CloseButton(False).DestroyOnClose(True).
  402. Layer(0))
  403. self.MapWindow = self.MapWindow2D
  404. #
  405. # update layer tree (-> disable 3d-rasters)
  406. #
  407. if self.tree:
  408. self.tree.EnableItemType(type='3d-raster', enable=False)
  409. self.MapWindow.UpdateMap()
  410. self.toolbars['map'].combo.SetValue (_("2D view"))
  411. self.toolbars['map'].Enable2D(True)
  412. self.toggleStatus.Enable(True)
  413. self._mgr.Update()
  414. def __InitDisplay(self):
  415. """
  416. Initialize map display, set dimensions and map region
  417. """
  418. self.width, self.height = self.GetClientSize()
  419. Debug.msg(2, "MapFrame.__InitDisplay():")
  420. self.Map.ChangeMapSize(self.GetClientSize())
  421. self.Map.region = self.Map.GetRegion() # g.region -upgc
  422. # self.Map.SetRegion() # adjust region to match display window
  423. def OnUpdateProgress(self, event):
  424. """
  425. Update progress bar info
  426. """
  427. self.onRenderGauge.SetValue(event.value)
  428. event.Skip()
  429. def OnFocus(self, event):
  430. """
  431. Change choicebook page to match display.
  432. Or set display for georectifying
  433. """
  434. if self._layerManager and \
  435. self._layerManager.georectifying:
  436. # in georectifying session; display used to get get geographic
  437. # coordinates for GCPs
  438. self.OnPointer(event)
  439. else:
  440. # change bookcontrol page to page associated with display
  441. if self.page:
  442. pgnum = self.layerbook.GetPageIndex(self.page)
  443. if pgnum > -1:
  444. self.layerbook.SetSelection(pgnum)
  445. event.Skip()
  446. def OnMotion(self, event):
  447. """
  448. Mouse moved
  449. Track mouse motion and update status bar
  450. """
  451. # update statusbar if required
  452. if self.toggleStatus.GetSelection() == 0: # Coordinates
  453. e, n = self.MapWindow.Pixel2Cell(event.GetPositionTuple())
  454. if self.toolbars['vdigit'] and \
  455. self.toolbars['vdigit'].GetAction() == 'addLine' and \
  456. self.toolbars['vdigit'].GetAction('type') in ('line', 'boundary') and \
  457. len(self.MapWindow.polycoords) > 0:
  458. # for linear feature show segment and total length
  459. distance_seg = self.MapWindow.Distance(self.MapWindow.polycoords[-1],
  460. (e, n), screen=False)[0]
  461. distance_tot = distance_seg
  462. for idx in range(1, len(self.MapWindow.polycoords)):
  463. distance_tot += self.MapWindow.Distance(self.MapWindow.polycoords[idx-1],
  464. self.MapWindow.polycoords[idx],
  465. screen=False )[0]
  466. self.statusbar.SetStatusText("%.2f, %.2f (seg: %.2f; tot: %.2f)" % \
  467. (e, n, distance_seg, distance_tot), 0)
  468. else:
  469. if self.Map.projinfo['proj'] == 'll':
  470. self.statusbar.SetStatusText("%s" % utils.Deg2DMS(e, n), 0)
  471. else:
  472. self.statusbar.SetStatusText("%.2f, %.2f" % (e, n), 0)
  473. event.Skip()
  474. def OnDraw(self, event):
  475. """
  476. Re-display current map composition
  477. """
  478. self.MapWindow.UpdateMap(render=False)
  479. def OnRender(self, event):
  480. """
  481. Re-render map composition (each map layer)
  482. """
  483. # delete tmp map layers (queries)
  484. qlayer = self.Map.GetListOfLayers(l_name=globalvar.QUERYLAYER)
  485. for layer in qlayer:
  486. self.Map.DeleteLayer(layer)
  487. # delete tmp lines
  488. if self.MapWindow.mouse["use"] in ("measure",
  489. "profile"):
  490. self.MapWindow.polycoords = []
  491. self.MapWindow.ClearLines()
  492. # deselect features in vdigit
  493. if self.toolbars['vdigit'] and self.digit:
  494. self.digit.driver.SetSelected([])
  495. self.MapWindow.UpdateMap(render=True, renderVector=True)
  496. else:
  497. self.MapWindow.UpdateMap(render=True)
  498. # update statusbar
  499. self.StatusbarUpdate()
  500. def OnPointer(self, event):
  501. """
  502. Pointer button clicked
  503. """
  504. if self.toolbars['map']:
  505. if event:
  506. self.toolbars['map'].OnTool(event)
  507. self.toolbars['map'].action['desc'] = ''
  508. self.MapWindow.mouse['use'] = "pointer"
  509. self.MapWindow.mouse['box'] = "point"
  510. # change the cursor
  511. if self.toolbars['vdigit']:
  512. # digitization tool activated
  513. self.MapWindow.SetCursor(self.cursors["cross"])
  514. # reset mouse['box'] if needed
  515. if self.toolbars['vdigit'].GetAction() in ['addLine']:
  516. if self.toolbars['vdigit'].GetAction('type') in ['point', 'centroid']:
  517. self.MapWindow.mouse['box'] = 'point'
  518. else: # line, boundary
  519. self.MapWindow.mouse['box'] = 'line'
  520. elif self.toolbars['vdigit'].GetAction() in ['addVertex', 'removeVertex', 'splitLine',
  521. 'editLine', 'displayCats', 'displayAttrs',
  522. 'copyCats']:
  523. self.MapWindow.mouse['box'] = 'point'
  524. else: # moveLine, deleteLine
  525. self.MapWindow.mouse['box'] = 'box'
  526. elif self._layerManager and self._layerManager.georectifying:
  527. self.MapWindow.SetCursor(self.cursors["cross"])
  528. else:
  529. self.MapWindow.SetCursor(self.cursors["default"])
  530. def OnZoomIn(self, event):
  531. """
  532. Zoom in the map.
  533. Set mouse cursor, zoombox attributes, and zoom direction
  534. """
  535. if self.toolbars['map']:
  536. self.toolbars['map'].OnTool(event)
  537. self.toolbars['map'].action['desc'] = ''
  538. self.MapWindow.mouse['use'] = "zoom"
  539. self.MapWindow.mouse['box'] = "box"
  540. self.MapWindow.zoomtype = 1
  541. self.MapWindow.pen = wx.Pen(colour='Red', width=2, style=wx.SHORT_DASH)
  542. # change the cursor
  543. self.MapWindow.SetCursor(self.cursors["cross"])
  544. def OnZoomOut(self, event):
  545. """
  546. Zoom out the map.
  547. Set mouse cursor, zoombox attributes, and zoom direction
  548. """
  549. if self.toolbars['map']:
  550. self.toolbars['map'].OnTool(event)
  551. self.toolbars['map'].action['desc'] = ''
  552. self.MapWindow.mouse['use'] = "zoom"
  553. self.MapWindow.mouse['box'] = "box"
  554. self.MapWindow.zoomtype = -1
  555. self.MapWindow.pen = wx.Pen(colour='Red', width=2, style=wx.SHORT_DASH)
  556. # change the cursor
  557. self.MapWindow.SetCursor(self.cursors["cross"])
  558. def OnZoomBack(self, event):
  559. """
  560. Zoom last (previously stored position)
  561. """
  562. self.MapWindow.ZoomBack()
  563. def OnPan(self, event):
  564. """
  565. Panning, set mouse to drag
  566. """
  567. if self.toolbars['map']:
  568. self.toolbars['map'].OnTool(event)
  569. self.toolbars['map'].action['desc'] = ''
  570. self.MapWindow.mouse['use'] = "pan"
  571. self.MapWindow.mouse['box'] = "pan"
  572. self.MapWindow.zoomtype = 0
  573. # change the cursor
  574. self.MapWindow.SetCursor(self.cursors["hand"])
  575. def OnErase(self, event):
  576. """
  577. Erase the canvas
  578. """
  579. self.MapWindow.EraseMap()
  580. def OnZoomRegion(self, event):
  581. """
  582. Zoom to region
  583. """
  584. self.Map.getRegion()
  585. self.Map.getResolution()
  586. self.UpdateMap()
  587. # event.Skip()
  588. def OnAlignRegion(self, event):
  589. """
  590. Align region
  591. """
  592. if not self.Map.alignRegion:
  593. self.Map.alignRegion = True
  594. else:
  595. self.Map.alignRegion = False
  596. # event.Skip()
  597. def OnToggleRender(self, event):
  598. """
  599. Enable/disable auto-rendering
  600. """
  601. if self.autoRender.GetValue():
  602. self.OnRender(None)
  603. def OnToggleShowRegion(self, event):
  604. """
  605. Show/Hide extent in map canvas
  606. """
  607. if self.showRegion.GetValue():
  608. # show extent
  609. self.MapWindow.regionCoords = []
  610. else:
  611. del self.MapWindow.regionCoords
  612. # redraw map if auto-rendering is enabled
  613. if self.autoRender.GetValue():
  614. self.OnRender(None)
  615. def OnToggleResolution(self, event):
  616. """
  617. Use resolution of computation region settings
  618. for redering image instead of display resolution
  619. """
  620. # redraw map if auto-rendering is enabled
  621. if self.autoRender.GetValue():
  622. self.OnRender(None)
  623. def OnToggleStatus(self, event):
  624. """
  625. Toggle status text
  626. """
  627. self.StatusbarUpdate()
  628. def OnChangeMapScale(self, event):
  629. """
  630. Map scale changed by user
  631. """
  632. scale = event.GetString()
  633. try:
  634. if scale[:2] != '1:':
  635. raise ValueError
  636. value = int(scale[2:])
  637. except ValueError:
  638. self.mapScale.SetValue('1:%ld' % int(self.mapScaleValue))
  639. return
  640. dEW = value * (self.Map.region['cols'] / self.ppm[0])
  641. dNS = value * (self.Map.region['rows'] / self.ppm[1])
  642. self.Map.region['n'] = self.Map.region['center_northing'] + dNS / 2.
  643. self.Map.region['s'] = self.Map.region['center_northing'] - dNS / 2.
  644. self.Map.region['w'] = self.Map.region['center_easting'] - dEW / 2.
  645. self.Map.region['e'] = self.Map.region['center_easting'] + dEW / 2.
  646. # add to zoom history
  647. self.MapWindow.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  648. self.Map.region['e'], self.Map.region['w'])
  649. # redraw a map
  650. self.MapWindow.UpdateMap()
  651. self.mapScale.SetFocus()
  652. def OnGoTo(self, event):
  653. """
  654. Go to position
  655. """
  656. try:
  657. e, n = map(float, self.goTo.GetValue().split(','))
  658. except ValueError:
  659. region = self.Map.GetCurrentRegion()
  660. self.goTo.SetValue("%.2f, %.2f" % (region['center_easting'],
  661. region['center_northing']))
  662. return
  663. region = self.Map.GetCurrentRegion()
  664. region['center_northing'] = n
  665. region['center_easting'] = e
  666. dn = (region['nsres'] * region['rows']) / 2.
  667. region['n'] = region['center_northing'] + dn
  668. region['s'] = region['center_northing'] - dn
  669. de = (region['ewres'] * region['cols']) / 2.
  670. region['e'] = region['center_easting'] + de
  671. region['w'] = region['center_easting'] - de
  672. self.Map.AdjustRegion()
  673. # add to zoom history
  674. self.MapWindow.ZoomHistory(region['n'], region['s'],
  675. region['e'], region['w'])
  676. # redraw a map
  677. self.MapWindow.UpdateMap()
  678. self.goTo.SetFocus()
  679. def StatusbarUpdate(self):
  680. """!Update statusbar content"""
  681. self.showRegion.Hide()
  682. self.compResolution.Hide()
  683. self.mapScale.Hide()
  684. self.goTo.Hide()
  685. self.mapScaleValue = self.ppm = None
  686. if self.toggleStatus.GetSelection() == 0: # Coordinates
  687. self.statusbar.SetStatusText("", 0)
  688. # enable long help
  689. self.StatusbarEnableLongHelp()
  690. elif self.toggleStatus.GetSelection() == 1: # Extent
  691. self.statusbar.SetStatusText("%.2f - %.2f, %.2f - %.2f" %
  692. (self.Map.region["w"], self.Map.region["e"],
  693. self.Map.region["s"], self.Map.region["n"]), 0)
  694. # enable long help
  695. self.StatusbarEnableLongHelp()
  696. elif self.toggleStatus.GetSelection() == 2: # Comp. region
  697. compregion = self.Map.GetRegion()
  698. self.statusbar.SetStatusText("%.2f - %.2f, %.2f - %.2f (%.2f, %.2f)" %
  699. (compregion["w"], compregion["e"],
  700. compregion["s"], compregion["n"],
  701. compregion["ewres"], compregion["nsres"]), 0)
  702. # enable long help
  703. self.StatusbarEnableLongHelp()
  704. elif self.toggleStatus.GetSelection() == 3: # Show comp. extent
  705. self.statusbar.SetStatusText("", 0)
  706. self.showRegion.Show()
  707. # disable long help
  708. self.StatusbarEnableLongHelp(False)
  709. elif self.toggleStatus.GetSelection() == 4: # Display mode
  710. self.statusbar.SetStatusText("", 0)
  711. self.compResolution.Show()
  712. # disable long help
  713. self.StatusbarEnableLongHelp(False)
  714. elif self.toggleStatus.GetSelection() == 5: # Display geometry
  715. self.statusbar.SetStatusText("rows=%d; cols=%d; nsres=%.2f; ewres=%.2f" %
  716. (self.Map.region["rows"], self.Map.region["cols"],
  717. self.Map.region["nsres"], self.Map.region["ewres"]), 0)
  718. # enable long help
  719. self.StatusbarEnableLongHelp()
  720. elif self.toggleStatus.GetSelection() == 6: # Map scale
  721. # TODO: need to be fixed...
  722. ### screen X region problem
  723. ### user should specify ppm
  724. dc = wx.ScreenDC()
  725. dpSizePx = wx.DisplaySize() # display size in pixels
  726. dpSizeMM = wx.DisplaySizeMM() # display size in mm (system)
  727. dpSizeIn = (dpSizeMM[0] / 25.4, dpSizeMM[1] / 25.4) # inches
  728. sysPpi = dc.GetPPI()
  729. comPpi = (dpSizePx[0] / dpSizeIn[0],
  730. dpSizePx[1] / dpSizeIn[1])
  731. ppi = comPpi # pixel per inch
  732. self.ppm = ((ppi[0] / 2.54) * 100, # pixel per meter
  733. (ppi[1] / 2.54) * 100)
  734. Debug.msg(4, "MapFrame.StatusbarUpdate(mapscale): size: px=%d,%d mm=%f,%f "
  735. "in=%f,%f ppi: sys=%d,%d com=%d,%d; ppm=%f,%f" % \
  736. (dpSizePx[0], dpSizePx[1], dpSizeMM[0], dpSizeMM[1],
  737. dpSizeIn[0], dpSizeIn[1],
  738. sysPpi[0], sysPpi[1], comPpi[0], comPpi[1],
  739. self.ppm[0], self.ppm[1]))
  740. region = self.Map.region
  741. heightCm = region['rows'] / self.ppm[1] * 100
  742. widthCm = region['cols'] / self.ppm[0] * 100
  743. Debug.msg(4, "MapFrame.StatusbarUpdate(mapscale): width_cm=%f, height_cm=%f" %
  744. (widthCm, heightCm))
  745. xscale = (region['e'] - region['w']) / (region['cols'] / self.ppm[0])
  746. yscale = (region['n'] - region['s']) / (region['rows'] / self.ppm[1])
  747. scale = (xscale + yscale) / 2.
  748. Debug.msg(3, "MapFrame.StatusbarUpdate(mapscale): xscale=%f, yscale=%f -> scale=%f" % \
  749. (xscale, yscale, scale))
  750. self.statusbar.SetStatusText("")
  751. try:
  752. self.mapScale.SetValue("1:%ld" % (scale + 0.5))
  753. except TypeError:
  754. pass
  755. self.mapScaleValue = scale
  756. self.mapScale.Show()
  757. # disable long help
  758. self.StatusbarEnableLongHelp(False)
  759. elif self.toggleStatus.GetSelection() == 7: # go to
  760. self.statusbar.SetStatusText("")
  761. region = self.Map.GetCurrentRegion()
  762. self.goTo.SetValue("%.2f, %.2f" % (region['center_easting'],
  763. region['center_northing']))
  764. self.goTo.Show()
  765. # disable long help
  766. self.StatusbarEnableLongHelp(False)
  767. else:
  768. self.statusbar.SetStatusText("", 1)
  769. def StatusbarEnableLongHelp(self, enable=True):
  770. """!Enable/disable toolbars long help"""
  771. for toolbar in self.toolbars.itervalues():
  772. if toolbar:
  773. toolbar.EnableLongHelp(enable)
  774. def StatusbarReposition(self):
  775. """!Reposition checkbox in statusbar"""
  776. # reposition checkbox
  777. widgets = [(0, self.showRegion),
  778. (0, self.compResolution),
  779. (0, self.mapScale),
  780. (0, self.onRenderGauge),
  781. (1, self.toggleStatus),
  782. (2, self.autoRender)]
  783. for idx, win in widgets:
  784. rect = self.statusbar.GetFieldRect(idx)
  785. if idx == 0: # show region / mapscale / process bar
  786. # -> size
  787. wWin, hWin = win.GetBestSize()
  788. if win == self.onRenderGauge:
  789. wWin = rect.width - 6
  790. # -> position
  791. # if win == self.showRegion:
  792. # x, y = rect.x + rect.width - wWin, rect.y - 1
  793. # align left
  794. # else:
  795. x, y = rect.x + 3, rect.y - 1
  796. w, h = wWin, rect.height + 2
  797. else: # choice || auto-rendering
  798. x, y = rect.x, rect.y - 1
  799. w, h = rect.width, rect.height + 2
  800. if idx == 2:
  801. x += 5
  802. win.SetPosition((x, y))
  803. win.SetSize((w, h))
  804. def SaveToFile(self, event):
  805. """
  806. Save image to file
  807. """
  808. lext = []
  809. for h in self.MapWindow.img.GetHandlers():
  810. lext.append(h.GetExtension())
  811. filetype = "BMP file (*.bmp)|*.bmp|"
  812. if 'gif' in lext:
  813. filetype += "GIF file (*.gif)|*.gif|"
  814. if 'jpg' in lext:
  815. filetype += "JPG file (*.jpg)|*.jpg|"
  816. if 'pcx' in lext:
  817. filetype += "PCX file (*.pcx)|*.pcx|"
  818. if 'png' in lext:
  819. filetype += "PNG file (*.png)|*.png|"
  820. if 'pnm' in lext:
  821. filetype += "PNM file (*.pnm)|*.pnm|"
  822. if 'tif' in lext:
  823. filetype += "TIF file (*.tif)|*.tif|"
  824. if 'xpm' in lext:
  825. filetype += "XPM file (*.xpm)|*.xpm"
  826. dlg = wx.FileDialog(self, _("Choose a file name to save the image (no need to add extension)"),
  827. defaultDir = "",
  828. defaultFile = "",
  829. wildcard = filetype,
  830. style=wx.SAVE|wx.FD_OVERWRITE_PROMPT)
  831. if dlg.ShowModal() == wx.ID_OK:
  832. path = dlg.GetPath()
  833. if path == None: return
  834. base = os.path.splitext(dlg.GetPath())[0]
  835. ext = os.path.splitext(dlg.GetPath())[1]
  836. if dlg.GetFilterIndex() == 0:
  837. type = wx.BITMAP_TYPE_BMP
  838. if ext != '.bmp': path = base+'.bmp'
  839. if dlg.GetFilterIndex() == 1:
  840. type = wx.BITMAP_TYPE_GIF
  841. if ext != '.gif': path = base+'.gif'
  842. elif dlg.GetFilterIndex() == 2:
  843. type = wx.BITMAP_TYPE_JPEG
  844. if ext != '.jpg': path = base+'.jpg'
  845. elif dlg.GetFilterIndex() == 3:
  846. type = wx.BITMAP_TYPE_GIF
  847. if ext != '.pcx': path = base+'.pcx'
  848. elif dlg.GetFilterIndex() == 4:
  849. type = wx.BITMAP_TYPE_PNG
  850. if ext != '.png': path = base+'.png'
  851. elif dlg.GetFilterIndex() == 5:
  852. type = wx.BITMAP_TYPE_PNM
  853. if ext != '.pnm': path = base+'.pnm'
  854. elif dlg.GetFilterIndex() == 6:
  855. type = wx.BITMAP_TYPE_TIF
  856. if ext != '.tif': path = base+'.tif'
  857. elif dlg.GetFilterIndex() == 7:
  858. type = wx.BITMAP_TYPE_XPM
  859. if ext != '.xpm': path = base+'.xpm'
  860. self.MapWindow.SaveToFile(path, type)
  861. dlg.Destroy()
  862. def PrintMenu(self, event):
  863. """
  864. Print options and output menu for map display
  865. """
  866. point = wx.GetMousePosition()
  867. printmenu = wx.Menu()
  868. # Add items to the menu
  869. setup = wx.MenuItem(printmenu, wx.ID_ANY, _('Page setup'))
  870. printmenu.AppendItem(setup)
  871. self.Bind(wx.EVT_MENU, self.printopt.OnPageSetup, setup)
  872. preview = wx.MenuItem(printmenu, wx.ID_ANY, _('Print preview'))
  873. printmenu.AppendItem(preview)
  874. self.Bind(wx.EVT_MENU, self.printopt.OnPrintPreview, preview)
  875. doprint = wx.MenuItem(printmenu, wx.ID_ANY, _('Print display'))
  876. printmenu.AppendItem(doprint)
  877. self.Bind(wx.EVT_MENU, self.printopt.OnDoPrint, doprint)
  878. # Popup the menu. If an item is selected then its handler
  879. # will be called before PopupMenu returns.
  880. self.PopupMenu(printmenu)
  881. printmenu.Destroy()
  882. def OnCloseWindow(self, event):
  883. """
  884. Window closed.
  885. Also close associated layer tree page
  886. """
  887. pgnum = None
  888. self.Map.Clean()
  889. # close edited map and 3D tools properly
  890. if self.toolbars['vdigit']:
  891. maplayer = self.toolbars['vdigit'].GetLayer()
  892. if maplayer:
  893. self.toolbars['vdigit'].OnExit()
  894. self.imgVectorMap = None
  895. if self.toolbars['nviz']:
  896. self.toolbars['nviz'].OnExit()
  897. if not self._layerManager:
  898. self.Destroy()
  899. elif self.page:
  900. pgnum = self.layerbook.GetPageIndex(self.page)
  901. if pgnum > -1:
  902. self.layerbook.DeletePage(pgnum)
  903. def GetRender(self):
  904. """
  905. Returns the current instance of render.Map()
  906. """
  907. return self.Map
  908. def OnQueryDisplay(self, event):
  909. """
  910. Query currrent raster/vector map layers (display mode)
  911. """
  912. if self.toolbars['map'].GetAction() == 'displayAttrb': # select previous action
  913. self.toolbars['map'].SelectDefault(event)
  914. return
  915. self.toolbars['map'].action['desc'] = 'displayAttrb'
  916. # switch GIS Manager to output console to show query results
  917. self._layerManager.notebook.SetSelection(1)
  918. self.MapWindow.mouse['use'] = "query"
  919. self.MapWindow.mouse['box'] = "point"
  920. self.MapWindow.zoomtype = 0
  921. # change the cursor
  922. self.MapWindow.SetCursor(self.cursors["cross"])
  923. def OnQueryModify(self, event):
  924. """
  925. Query vector map layer (edit mode)
  926. """
  927. if self.toolbars['map'].GetAction() == 'modifyAttrb': # select previous action
  928. self.toolbars['map'].SelectDefault(event)
  929. return
  930. self.toolbars['map'].action['desc'] = 'modifyAttrb'
  931. self.MapWindow.mouse['use'] = "queryVector"
  932. self.MapWindow.mouse['box'] = "point"
  933. self.MapWindow.pen = wx.Pen(colour='Red', width=2, style=wx.SHORT_DASH)
  934. self.MapWindow.zoomtype = 0
  935. # change the cursor
  936. self.MapWindow.SetCursor(self.cursors["cross"])
  937. def QueryMap(self, x, y):
  938. """!Query map layer features
  939. Currently only raster and vector map layers are supported.
  940. @param x,y coordinates
  941. """
  942. #set query snap distance for v.what at mapunit equivalent of 10 pixels
  943. qdist = 10.0 * ((self.Map.region['e'] - self.Map.region['w']) / self.Map.width)
  944. east, north = self.MapWindow.Pixel2Cell((x, y))
  945. num = 0
  946. for layer in self.tree.GetSelections():
  947. type = self.tree.GetPyData(layer)[0]['maplayer'].GetType()
  948. if type in ('raster', 'rgb', 'his',
  949. 'vector', 'thememap', 'themechart'):
  950. num += 1
  951. if num < 1:
  952. dlg = wx.MessageDialog(parent=self,
  953. message=_('No raster or vector map layer selected for querying.'),
  954. caption=_('No map layer selected'),
  955. style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  956. dlg.ShowModal()
  957. dlg.Destroy()
  958. return
  959. mapname = None
  960. raststr = ''
  961. vectstr = ''
  962. rcmd = ['r.what', '--q']
  963. vcmd = ['v.what', '--q']
  964. for layer in self.tree.GetSelections():
  965. type = self.tree.GetPyData(layer)[0]['maplayer'].GetType()
  966. dcmd = self.tree.GetPyData(layer)[0]['cmd']
  967. name = utils.GetLayerNameFromCmd(dcmd)
  968. if name == '':
  969. continue
  970. if type in ('raster', 'rgb', 'his'):
  971. raststr += "%s," % name
  972. elif type in ('vector', 'thememap', 'themechart'):
  973. vectstr += "%s," % name
  974. # use display region settings instead of computation region settings
  975. tmpreg = os.getenv("GRASS_REGION")
  976. os.environ["GRASS_REGION"] = self.Map.SetRegion(windres=False)
  977. # build query commands for any selected rasters and vectors
  978. if raststr != '':
  979. rcmd.append('-f')
  980. rcmd.append('input=%s' % raststr.rstrip(','))
  981. rcmd.append('east_north=%f,%f' % (float(east), float(north)))
  982. if vectstr != '':
  983. # check for vector maps open to be edited
  984. digitToolbar = self.toolbars['vdigit']
  985. if digitToolbar:
  986. map = digitToolbar.GetLayer().GetName()
  987. vect = []
  988. for vector in vectstr.split(','):
  989. if map == vector:
  990. self._layerManager.goutput.WriteWarning("Vector map <%s> "
  991. "opened for editing - skipped." % map)
  992. continue
  993. vect.append(vector)
  994. vectstr = ','.join(vect)
  995. if len(vectstr) <= 1:
  996. self._layerManager.goutput.WriteCmdLog("Nothing to query.")
  997. return
  998. vcmd.append('-a')
  999. vcmd.append('map=%s' % vectstr.rstrip(','))
  1000. vcmd.append('east_north=%f,%f' % (float(east), float(north)))
  1001. vcmd.append('distance=%f' % float(qdist))
  1002. # parse query command(s)
  1003. if self._layerManager:
  1004. if raststr:
  1005. self._layerManager.goutput.RunCmd(rcmd,
  1006. compReg=False)
  1007. if vectstr:
  1008. self._layerManager.goutput.RunCmd(vcmd)
  1009. else:
  1010. if raststr:
  1011. gcmd.RunCommand(rcmd)
  1012. if vectstr:
  1013. gcmd.RunCommand(vcmd)
  1014. # restore GRASS_REGION
  1015. if tmpreg:
  1016. os.environ["GRASS_REGION"] = tmpreg
  1017. def QueryVector(self, x, y):
  1018. """
  1019. Query vector map layer features
  1020. Attribute data of selected vector object are displayed in GUI dialog.
  1021. Data can be modified (On Submit)
  1022. """
  1023. if not self.tree.layer_selected or \
  1024. self.tree.GetPyData(self.tree.layer_selected)[0]['type'] != 'vector':
  1025. wx.MessageBox(parent=self,
  1026. message=_("No vector map selected for querying."),
  1027. caption=_("Vector querying"),
  1028. style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  1029. return
  1030. if self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].GetMapset() != \
  1031. grass.gisenv()['MAPSET']:
  1032. wx.MessageBox(parent=self,
  1033. message=_("Only vector map from the current mapset can be modified."),
  1034. caption=_("Vector querying"),
  1035. style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  1036. return
  1037. posWindow = self.ClientToScreen((x + self.MapWindow.dialogOffset,
  1038. y + self.MapWindow.dialogOffset))
  1039. qdist = 10.0 * ((self.Map.region['e'] - self.Map.region['w']) /
  1040. self.Map.width)
  1041. east, north = self.MapWindow.Pixel2Cell((x, y))
  1042. mapName = self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name
  1043. if self.dialogs['attributes'] is None:
  1044. self.dialogs['attributes'] = \
  1045. dbm_dialogs.DisplayAttributesDialog(parent=self.MapWindow,
  1046. map=mapName,
  1047. query=((east, north), qdist),
  1048. pos=posWindow,
  1049. action="update")
  1050. else:
  1051. # selection changed?
  1052. if not self.dialogs['attributes'].mapDBInfo or \
  1053. self.dialogs['attributes'].mapDBInfo.map != mapName:
  1054. self.dialogs['attributes'].UpdateDialog(map=mapName, query=((east, north), qdist))
  1055. else:
  1056. self.dialogs['attributes'].UpdateDialog(query=((east, north), qdist))
  1057. cats = self.dialogs['attributes'].GetCats()
  1058. try:
  1059. qlayer = self.Map.GetListOfLayers(l_name=globalvar.QUERYLAYER)[0]
  1060. except IndexError:
  1061. qlayer = None
  1062. if self.dialogs['attributes'].mapDBInfo and cats:
  1063. # highlight feature & re-draw map
  1064. if qlayer:
  1065. qlayer.SetCmd(self.AddTmpVectorMapLayer(mapName, cats,
  1066. useId=False,
  1067. addLayer=False))
  1068. else:
  1069. qlayer = self.AddTmpVectorMapLayer(mapName, cats, useId=False)
  1070. # set opacity based on queried layer
  1071. opacity = self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].GetOpacity(float=True)
  1072. qlayer.SetOpacity(opacity)
  1073. self.MapWindow.UpdateMap(render=False, renderVector=False)
  1074. if not self.dialogs['attributes'].IsShown():
  1075. self.dialogs['attributes'].Show()
  1076. else:
  1077. if qlayer:
  1078. self.Map.DeleteLayer(qlayer)
  1079. self.MapWindow.UpdateMap(render=False, renderVector=False)
  1080. if self.dialogs['attributes'].IsShown():
  1081. self.dialogs['attributes'].Hide()
  1082. def OnQuery(self, event):
  1083. """!Query tools menu"""
  1084. if self.toolbars['map']:
  1085. self.toolbars['map'].OnTool(event)
  1086. action = self.toolbars['map'].GetAction()
  1087. point = wx.GetMousePosition()
  1088. toolsmenu = wx.Menu()
  1089. # Add items to the menu
  1090. display = wx.MenuItem(parentMenu=toolsmenu, id=wx.ID_ANY,
  1091. text=_("Query raster/vector map(s) (display mode)"),
  1092. kind=wx.ITEM_CHECK)
  1093. toolsmenu.AppendItem(display)
  1094. self.Bind(wx.EVT_MENU, self.OnQueryDisplay, display)
  1095. numLayers = 0
  1096. for layer in self.tree.GetSelections():
  1097. type = self.tree.GetPyData(layer)[0]['maplayer'].GetType()
  1098. if type in ('raster', 'rgb', 'his',
  1099. 'vector', 'thememap', 'themechart'):
  1100. numLayers += 1
  1101. if numLayers < 1:
  1102. display.Enable(False)
  1103. if action == "displayAttrb":
  1104. display.Check(True)
  1105. modify = wx.MenuItem(parentMenu=toolsmenu, id=wx.ID_ANY,
  1106. text=_("Query vector map (edit mode)"),
  1107. kind=wx.ITEM_CHECK)
  1108. toolsmenu.AppendItem(modify)
  1109. self.Bind(wx.EVT_MENU, self.OnQueryModify, modify)
  1110. digitToolbar = self.toolbars['vdigit']
  1111. if self.tree.layer_selected:
  1112. layer_selected = self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer']
  1113. if layer_selected.GetType() != 'vector' or \
  1114. (digitToolbar and \
  1115. digitToolbar.GetLayer() == layer_selected):
  1116. modify.Enable(False)
  1117. else:
  1118. if action == "modifyAttrb":
  1119. modify.Check(True)
  1120. self.PopupMenu(toolsmenu)
  1121. toolsmenu.Destroy()
  1122. def AddTmpVectorMapLayer(self, name, cats, useId=False, addLayer=True):
  1123. """
  1124. Add temporal vector map layer to map composition
  1125. @param name name of map layer
  1126. @param useId use feature id instead of category
  1127. """
  1128. # color settings from ATM
  1129. color = UserSettings.Get(group='atm', key='highlight', subkey='color')
  1130. colorStr = str(color[0]) + ":" + \
  1131. str(color[1]) + ":" + \
  1132. str(color[2])
  1133. pattern = ["d.vect",
  1134. "map=%s" % name,
  1135. "color=%s" % colorStr,
  1136. "fcolor=%s" % colorStr,
  1137. "width=%d" % UserSettings.Get(group='atm', key='highlight', subkey='width')]
  1138. if useId:
  1139. cmd = pattern
  1140. cmd.append('-i')
  1141. cmd.append('cats=%s' % str(cats))
  1142. else:
  1143. cmd = []
  1144. for layer in cats.keys():
  1145. cmd.append(copy.copy(pattern))
  1146. lcats = cats[layer]
  1147. cmd[-1].append("layer=%d" % layer)
  1148. cmd[-1].append("cats=%s" % utils.ListOfCatsToRange(lcats))
  1149. # if self.icon:
  1150. # cmd.append("icon=%s" % (self.icon))
  1151. # if self.pointsize:
  1152. # cmd.append("size=%s" % (self.pointsize))
  1153. if addLayer:
  1154. if useId:
  1155. return self.Map.AddLayer(type='vector', name=globalvar.QUERYLAYER, command=cmd,
  1156. l_active=True, l_hidden=True, l_opacity=1.0)
  1157. else:
  1158. return self.Map.AddLayer(type='command', name=globalvar.QUERYLAYER, command=cmd,
  1159. l_active=True, l_hidden=True, l_opacity=1.0)
  1160. else:
  1161. return cmd
  1162. def OnAnalyze(self, event):
  1163. """
  1164. Analysis tools menu
  1165. """
  1166. point = wx.GetMousePosition()
  1167. toolsmenu = wx.Menu()
  1168. # Add items to the menu
  1169. measure = wx.MenuItem(toolsmenu, wx.ID_ANY, Icons["measure"].GetLabel())
  1170. measure.SetBitmap(Icons["measure"].GetBitmap(self.iconsize))
  1171. toolsmenu.AppendItem(measure)
  1172. self.Bind(wx.EVT_MENU, self.OnMeasure, measure)
  1173. profile = wx.MenuItem(toolsmenu, wx.ID_ANY, Icons["profile"].GetLabel())
  1174. profile.SetBitmap(Icons["profile"].GetBitmap(self.iconsize))
  1175. toolsmenu.AppendItem(profile)
  1176. self.Bind(wx.EVT_MENU, self.Profile, profile)
  1177. histogram = wx.MenuItem(toolsmenu, wx.ID_ANY, Icons["histogram"].GetLabel())
  1178. histogram.SetBitmap(Icons["histogram"].GetBitmap(self.iconsize))
  1179. toolsmenu.AppendItem(histogram)
  1180. self.Bind(wx.EVT_MENU, self.Histogram, histogram)
  1181. # Popup the menu. If an item is selected then its handler
  1182. # will be called before PopupMenu returns.
  1183. self.PopupMenu(toolsmenu)
  1184. toolsmenu.Destroy()
  1185. def OnMeasure(self, event):
  1186. """
  1187. Init measurement routine that calculates
  1188. map distance along transect drawn on
  1189. map display
  1190. """
  1191. self.totaldist = 0.0 # total measured distance
  1192. # switch GIS Manager to output console to show measure results
  1193. self._layerManager.notebook.SetSelection(1)
  1194. # change mouse to draw line for measurement
  1195. self.MapWindow.mouse['use'] = "measure"
  1196. self.MapWindow.mouse['box'] = "line"
  1197. self.MapWindow.zoomtype = 0
  1198. self.MapWindow.pen = wx.Pen(colour='red', width=2, style=wx.SHORT_DASH)
  1199. self.MapWindow.polypen = wx.Pen(colour='green', width=2, style=wx.SHORT_DASH)
  1200. # change the cursor
  1201. self.MapWindow.SetCursor(self.cursors["pencil"])
  1202. # initiating output
  1203. style = self._layerManager.goutput.cmd_output.StyleWarning
  1204. self._layerManager.goutput.WriteLog(_('Click and drag with left mouse button '
  1205. 'to measure.%s'
  1206. 'Double click with left button to clear.') % \
  1207. (os.linesep), style)
  1208. if self.Map.projinfo['proj'] != 'xy':
  1209. units = self.Map.projinfo['units']
  1210. style = self._layerManager.goutput.cmd_output.StyleCommand
  1211. self._layerManager.goutput.WriteLog(_('Measuring distance') + ' ('
  1212. + units + '):',
  1213. style)
  1214. else:
  1215. self._layerManager.goutput.WriteLog(_('Measuring distance:'),
  1216. style)
  1217. def MeasureDist(self, beginpt, endpt):
  1218. """
  1219. Calculate map distance from screen distance
  1220. and print to output window
  1221. """
  1222. if self._layerManager.notebook.GetSelection() != 1:
  1223. self._layerManager.notebook.SetSelection(1)
  1224. dist, (north, east) = self.MapWindow.Distance(beginpt, endpt)
  1225. dist = round(dist, 3)
  1226. d, dunits = self.FormatDist(dist)
  1227. self.totaldist += dist
  1228. td, tdunits = self.FormatDist(self.totaldist)
  1229. strdist = str(d)
  1230. strtotdist = str(td)
  1231. if self.Map.projinfo['proj'] == 'xy' or 'degree' not in self.Map.projinfo['unit']:
  1232. angle = int(math.degrees(math.atan2(north,east)) + 0.5)
  1233. angle = 180 - angle
  1234. if angle < 0:
  1235. angle = 360+angle
  1236. mstring = 'segment = %s %s\ttotal distance = %s %s\tbearing = %d deg' \
  1237. % (strdist,dunits,strtotdist,tdunits,angle)
  1238. else:
  1239. mstring = 'segment = %s %s\ttotal distance = %s %s' \
  1240. % (strdist,dunits,strtotdist,tdunits)
  1241. self._layerManager.goutput.WriteLog(mstring)
  1242. return dist
  1243. def Profile(self, event):
  1244. """
  1245. Init profile canvas and tools
  1246. """
  1247. raster = []
  1248. if self.tree.layer_selected and \
  1249. self.tree.GetPyData(self.tree.layer_selected)[0]['type'] == 'raster':
  1250. raster.append(self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name)
  1251. self.profile = profile.ProfileFrame(self,
  1252. id=wx.ID_ANY, pos=wx.DefaultPosition, size=(700,300),
  1253. style=wx.DEFAULT_FRAME_STYLE, rasterList=raster)
  1254. self.profile.Show()
  1255. # Open raster select dialog to make sure that a raster (and the desired raster)
  1256. # is selected to be profiled
  1257. self.profile.OnSelectRaster(None)
  1258. def FormatDist(self, dist):
  1259. """!Format length numbers and units in a nice way,
  1260. as a function of length. From code by Hamish Bowman
  1261. Grass Development Team 2006"""
  1262. mapunits = self.Map.projinfo['units']
  1263. if mapunits == 'metres': mapunits = 'meters'
  1264. outunits = mapunits
  1265. dist = float(dist)
  1266. divisor = 1.0
  1267. # figure out which units to use
  1268. if mapunits == 'meters':
  1269. if dist > 2500.0:
  1270. outunits = 'km'
  1271. divisor = 1000.0
  1272. else: outunits = 'm'
  1273. elif mapunits == 'feet':
  1274. # nano-bug: we match any "feet", but US Survey feet is really
  1275. # 5279.9894 per statute mile, or 10.6' per 1000 miles. As >1000
  1276. # miles the tick markers are rounded to the nearest 10th of a
  1277. # mile (528'), the difference in foot flavours is ignored.
  1278. if dist > 5280.0:
  1279. outunits = 'miles'
  1280. divisor = 5280.0
  1281. else:
  1282. outunits = 'ft'
  1283. elif 'degree' in mapunits:
  1284. if dist < 1:
  1285. outunits = 'min'
  1286. divisor = (1/60.0)
  1287. else:
  1288. outunits = 'deg'
  1289. # format numbers in a nice way
  1290. if (dist/divisor) >= 2500.0:
  1291. outdist = round(dist/divisor)
  1292. elif (dist/divisor) >= 1000.0:
  1293. outdist = round(dist/divisor,1)
  1294. elif (dist/divisor) > 0.0:
  1295. outdist = round(dist/divisor,int(math.ceil(3-math.log10(dist/divisor))))
  1296. else:
  1297. outdist = float(dist/divisor)
  1298. return (outdist, outunits)
  1299. def Histogram(self, event):
  1300. """
  1301. Init histogram display canvas and tools
  1302. """
  1303. self.histogram = histogram.HistFrame(self,
  1304. id=wx.ID_ANY, size=globalvar.HIST_WINDOW_SIZE,
  1305. style=wx.DEFAULT_FRAME_STYLE)
  1306. #show new display
  1307. self.histogram.Show()
  1308. self.histogram.Refresh()
  1309. self.histogram.Update()
  1310. def OnDecoration(self, event):
  1311. """
  1312. Decorations overlay menu
  1313. """
  1314. point = wx.GetMousePosition()
  1315. decmenu = wx.Menu()
  1316. # Add items to the menu
  1317. AddScale = wx.MenuItem(decmenu, wx.ID_ANY, Icons["addbarscale"].GetLabel())
  1318. AddScale.SetBitmap(Icons["addbarscale"].GetBitmap(self.iconsize))
  1319. decmenu.AppendItem(AddScale)
  1320. self.Bind(wx.EVT_MENU, self.OnAddBarscale, AddScale)
  1321. AddLegend = wx.MenuItem(decmenu, wx.ID_ANY, Icons["addlegend"].GetLabel())
  1322. AddLegend.SetBitmap(Icons["addlegend"].GetBitmap(self.iconsize))
  1323. decmenu.AppendItem(AddLegend)
  1324. self.Bind(wx.EVT_MENU, self.OnAddLegend, AddLegend)
  1325. AddText = wx.MenuItem(decmenu, wx.ID_ANY, Icons["addtext"].GetLabel())
  1326. AddText.SetBitmap(Icons["addtext"].GetBitmap(self.iconsize))
  1327. decmenu.AppendItem(AddText)
  1328. self.Bind(wx.EVT_MENU, self.OnAddText, AddText)
  1329. # Popup the menu. If an item is selected then its handler
  1330. # will be called before PopupMenu returns.
  1331. self.PopupMenu(decmenu)
  1332. decmenu.Destroy()
  1333. def OnAddBarscale(self, event):
  1334. """
  1335. Handler for scale/arrow map decoration menu selection.
  1336. """
  1337. if self.dialogs['barscale']:
  1338. return
  1339. id = 0 # unique index for overlay layer
  1340. # If location is latlon, only display north arrow (scale won't work)
  1341. # proj = self.Map.projinfo['proj']
  1342. # if proj == 'll':
  1343. # barcmd = 'd.barscale -n'
  1344. # else:
  1345. # barcmd = 'd.barscale'
  1346. # decoration overlay control dialog
  1347. self.dialogs['barscale'] = \
  1348. gdialogs.DecorationDialog(parent=self, title=_('Scale and North arrow'),
  1349. size=(350, 200),
  1350. style=wx.DEFAULT_DIALOG_STYLE | wx.CENTRE,
  1351. cmd=['d.barscale', 'at=0,5'],
  1352. ovlId=id,
  1353. name='barscale',
  1354. checktxt = _("Show/hide scale and North arrow"),
  1355. ctrltxt = _("scale object"))
  1356. self.dialogs['barscale'].CentreOnParent()
  1357. ### dialog cannot be show as modal - in the result d.barscale is not selectable
  1358. ### self.dialogs['barscale'].ShowModal()
  1359. self.dialogs['barscale'].Show()
  1360. self.MapWindow.mouse['use'] = 'pointer'
  1361. def OnAddLegend(self, event):
  1362. """
  1363. Handler for legend map decoration menu selection.
  1364. """
  1365. if self.dialogs['legend']:
  1366. return
  1367. id = 1 # index for overlay layer in render
  1368. cmd = ['d.legend']
  1369. if self.tree.layer_selected and \
  1370. self.tree.GetPyData(self.tree.layer_selected)[0]['type'] == 'raster':
  1371. cmd.append('map=%s' % self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name)
  1372. # Decoration overlay control dialog
  1373. self.dialogs['legend'] = \
  1374. gdialogs.DecorationDialog(parent=self, title=('Legend'),
  1375. size=(350, 200),
  1376. style=wx.DEFAULT_DIALOG_STYLE | wx.CENTRE,
  1377. cmd=cmd,
  1378. ovlId=id,
  1379. name='legend',
  1380. checktxt = _("Show/hide legend"),
  1381. ctrltxt = _("legend object"))
  1382. self.dialogs['legend'].CentreOnParent()
  1383. ### dialog cannot be show as modal - in the result d.legend is not selectable
  1384. ### self.dialogs['legend'].ShowModal()
  1385. self.dialogs['legend'].Show()
  1386. self.MapWindow.mouse['use'] = 'pointer'
  1387. def OnAddText(self, event):
  1388. """
  1389. Handler for text decoration menu selection.
  1390. """
  1391. if self.MapWindow.dragid > -1:
  1392. id = self.MapWindow.dragid
  1393. else:
  1394. # index for overlay layer in render
  1395. if len(self.MapWindow.textdict.keys()) > 0:
  1396. id = self.MapWindow.textdict.keys()[-1] + 1
  1397. else:
  1398. id = 101
  1399. self.dialogs['text'] = gdialogs.TextLayerDialog(parent=self, ovlId=id,
  1400. title=_('Add text layer'),
  1401. size=(400, 200))
  1402. self.dialogs['text'].CenterOnParent()
  1403. # If OK button pressed in decoration control dialog
  1404. if self.dialogs['text'].ShowModal() == wx.ID_OK:
  1405. text = self.dialogs['text'].GetValues()['text']
  1406. active = self.dialogs['text'].GetValues()['active']
  1407. coords, w, h = self.MapWindow.TextBounds(self.dialogs['text'].GetValues())
  1408. # delete object if it has no text or is not active
  1409. if text == '' or active == False:
  1410. try:
  1411. self.MapWindow.pdc.ClearId(id)
  1412. self.MapWindow.pdc.RemoveId(id)
  1413. del self.MapWindow.textdict[id]
  1414. except:
  1415. pass
  1416. return
  1417. self.MapWindow.pdc.ClearId(id)
  1418. self.MapWindow.pdc.SetId(id)
  1419. self.MapWindow.textdict[id] = self.dialogs['text'].GetValues()
  1420. self.MapWindow.Draw(self.MapWindow.pdcDec, img=self.MapWindow.textdict[id],
  1421. drawid=id, pdctype='text', coords=coords)
  1422. self.MapWindow.UpdateMap(render=False, renderVector=False)
  1423. self.MapWindow.mouse['use'] = 'pointer'
  1424. def GetOptData(self, dcmd, type, params, propwin):
  1425. """
  1426. Callback method for decoration overlay command generated by
  1427. dialog created in menuform.py
  1428. """
  1429. # Reset comand and rendering options in render.Map. Always render decoration.
  1430. # Showing/hiding handled by PseudoDC
  1431. self.Map.ChangeOverlay(ovltype=type, type='overlay', name='', command=dcmd,
  1432. l_active=True, l_render=False)
  1433. self.params[type] = params
  1434. self.propwin[type] = propwin
  1435. def OnZoomMenu(self, event):
  1436. """
  1437. Zoom menu
  1438. """
  1439. point = wx.GetMousePosition()
  1440. zoommenu = wx.Menu()
  1441. # Add items to the menu
  1442. zoommap = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to selected map(s)'))
  1443. zoommenu.AppendItem(zoommap)
  1444. self.Bind(wx.EVT_MENU, self.MapWindow.OnZoomToMap, zoommap)
  1445. zoomwind = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to computational region (set with g.region)'))
  1446. zoommenu.AppendItem(zoomwind)
  1447. self.Bind(wx.EVT_MENU, self.MapWindow.ZoomToWind, zoomwind)
  1448. zoomdefault = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to default region'))
  1449. zoommenu.AppendItem(zoomdefault)
  1450. self.Bind(wx.EVT_MENU, self.MapWindow.ZoomToDefault, zoomdefault)
  1451. zoomsaved = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to saved region'))
  1452. zoommenu.AppendItem(zoomsaved)
  1453. self.Bind(wx.EVT_MENU, self.MapWindow.ZoomToSaved, zoomsaved)
  1454. savewind = wx.MenuItem(zoommenu, wx.ID_ANY, _('Set computational region from display'))
  1455. zoommenu.AppendItem(savewind)
  1456. self.Bind(wx.EVT_MENU, self.MapWindow.DisplayToWind, savewind)
  1457. savezoom = wx.MenuItem(zoommenu, wx.ID_ANY, _('Save display geometry to named region'))
  1458. zoommenu.AppendItem(savezoom)
  1459. self.Bind(wx.EVT_MENU, self.MapWindow.SaveDisplayRegion, savezoom)
  1460. # Popup the menu. If an item is selected then its handler
  1461. # will be called before PopupMenu returns.
  1462. self.PopupMenu(zoommenu)
  1463. zoommenu.Destroy()
  1464. def SetProperties(self, render=False, mode=0, showCompExtent=False,
  1465. constrainRes=False):
  1466. """!Set properies of map display window"""
  1467. self.autoRender.SetValue(render)
  1468. self.toggleStatus.SetSelection(mode)
  1469. self.StatusbarUpdate()
  1470. self.showRegion.SetValue(showCompExtent)
  1471. self.compResolution.SetValue(constrainRes)
  1472. if showCompExtent:
  1473. self.MapWindow.regionCoords = []
  1474. def IsStandalone(self):
  1475. """!Check if Map display is standalone"""
  1476. if self._layerManager:
  1477. return False
  1478. return True
  1479. def GetLayerManager(self):
  1480. """!Get reference to Layer Manager
  1481. @return window reference
  1482. @return None (if standalone)
  1483. """
  1484. return self._layerManager
  1485. # end of class MapFrame
  1486. class MapApp(wx.App):
  1487. """
  1488. MapApp class
  1489. """
  1490. def OnInit(self):
  1491. wx.InitAllImageHandlers()
  1492. if __name__ == "__main__":
  1493. Map = render.Map() # instance of Map class to render GRASS display output to PPM file
  1494. else:
  1495. Map = None
  1496. self.mapFrm = MapFrame(parent=None, id=wx.ID_ANY, Map=Map,
  1497. size=globalvar.MAP_WINDOW_SIZE)
  1498. #self.SetTopWindow(Map)
  1499. self.mapFrm.Show()
  1500. if __name__ == "__main__":
  1501. # redraw map, if new command appears
  1502. self.redraw = False
  1503. status = Command(self, Map, cmdfilename)
  1504. status.start()
  1505. self.timer = wx.PyTimer(self.watcher)
  1506. # check each 0.1s
  1507. self.timer.Start(100)
  1508. return 1
  1509. def OnExit(self):
  1510. if __name__ == "__main__":
  1511. # stop the timer
  1512. self.timer.Stop()
  1513. # terminate thread (a bit ugly)
  1514. os.system("""!echo "quit" >> %s""" % (cmdfilename))
  1515. def watcher(self):
  1516. """!Redraw, if new layer appears"""
  1517. if self.redraw:
  1518. self.mapFrm.OnDraw(None)
  1519. self.redraw = False
  1520. return
  1521. # end of class MapApp
  1522. if __name__ == "__main__":
  1523. ###### SET command variable
  1524. if len(sys.argv) != 3:
  1525. print __doc__
  1526. sys.exit()
  1527. title = sys.argv[1]
  1528. cmdfilename = sys.argv[2]
  1529. import gettext
  1530. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode=True)
  1531. print >> sys.stderr, "\nStarting monitor <%s>...\n" % (title)
  1532. gm_map = MapApp(0)
  1533. # set title
  1534. gm_map.mapFrm.SetTitle(_("GRASS GIS Map Display: " +
  1535. title +
  1536. " - Location: " + grass.gisenv()["LOCATION_NAME"]))
  1537. gm_map.MainLoop()
  1538. os.remove(cmdfilename)
  1539. os.system("""!g.gisenv set="GRASS_PYCMDFILE" """)
  1540. print >> sys.stderr, "\nStopping monitor <%s>...\n" % (title)
  1541. sys.exit(0)