mapdisp.py 67 KB

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