mapdisp.py 66 KB

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