mapdisp.py 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805
  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.MapWindow3D.overlays = self.MapWindow2D.overlays
  537. self.MapWindow3D.textdict = self.MapWindow2D.textdict
  538. # update overlays needs to be called after because getClientSize
  539. # is called during update and it must give reasonable values
  540. wx.CallAfter(self.MapWindow3D.UpdateOverlays)
  541. self.SetStatusText("", 0)
  542. self._mgr.Update()
  543. def RemoveNviz(self):
  544. """!Restore 2D view"""
  545. self.toolbars['map'].RemoveTool(self.toolbars['map'].rotate)
  546. # update status bar
  547. self.statusbarManager.ShowStatusbarChoiceItemsByClass(self.statusbarItemsHiddenInNviz)
  548. self.statusbarManager.SetMode(UserSettings.Get(group = 'display',
  549. key = 'statusbarMode',
  550. subkey = 'selection'))
  551. self.SetStatusText(_("Please wait, unloading data..."), 0)
  552. self._layerManager.goutput.WriteCmdLog(_("Switching back to 2D view mode..."),
  553. switchPage = False)
  554. self.MapWindow3D.UnloadDataLayers(force = True)
  555. # switch from MapWindowGL to MapWindow
  556. self._mgr.GetPane('2d').Show()
  557. self._mgr.GetPane('3d').Hide()
  558. self.MapWindow = self.MapWindow2D
  559. # remove nviz notebook page
  560. self._layerManager.RemoveNvizTools()
  561. self.MapWindow2D.overlays = self.MapWindow3D.overlays
  562. self.MapWindow2D.textdict = self.MapWindow3D.textdict
  563. self.MapWindow.UpdateMap()
  564. self._mgr.Update()
  565. def AddToolbar(self, name):
  566. """!Add defined toolbar to the window
  567. Currently known toolbars are:
  568. - 'map' - basic map toolbar
  569. - 'vdigit' - vector digitizer
  570. - 'gcpdisp' - GCP Manager Display
  571. """
  572. # default toolbar
  573. if name == "map":
  574. self.toolbars['map'] = toolbars.MapToolbar(self, self.Map)
  575. self._mgr.AddPane(self.toolbars['map'],
  576. wx.aui.AuiPaneInfo().
  577. Name("maptoolbar").Caption(_("Map Toolbar")).
  578. ToolbarPane().Top().Name('mapToolbar').
  579. LeftDockable(False).RightDockable(False).
  580. BottomDockable(False).TopDockable(True).
  581. CloseButton(False).Layer(2).
  582. BestSize((self.toolbars['map'].GetBestSize())))
  583. # vector digitizer
  584. elif name == "vdigit":
  585. self._addToolbarVDigit()
  586. self._mgr.Update()
  587. def RemoveToolbar (self, name):
  588. """!Removes defined toolbar from the window
  589. @todo Only hide, activate by calling AddToolbar()
  590. """
  591. # cannot hide main toolbar
  592. if name == "map":
  593. return
  594. self._mgr.DetachPane(self.toolbars[name])
  595. self.toolbars[name].Destroy()
  596. self.toolbars.pop(name)
  597. if name == 'vdigit':
  598. self._mgr.GetPane('vdigit').Hide()
  599. self._mgr.GetPane('2d').Show()
  600. self.MapWindow = self.MapWindow2D
  601. self.toolbars['map'].combo.SetValue(_("2D view"))
  602. self.toolbars['map'].Enable2D(True)
  603. self._mgr.Update()
  604. def IsPaneShown(self, name):
  605. """!Check if pane (toolbar, mapWindow ...) of given name is currently shown"""
  606. if self._mgr.GetPane(name).IsOk():
  607. return self._mgr.GetPane(name).IsShown()
  608. return False
  609. def OnUpdateProgress(self, event):
  610. """!Update progress bar info
  611. """
  612. self.GetProgressBar().SetValue(event.value)
  613. event.Skip()
  614. def OnFocus(self, event):
  615. """!Change choicebook page to match display.
  616. """
  617. # change bookcontrol page to page associated with display
  618. if self.page:
  619. pgnum = self.layerbook.GetPageIndex(self.page)
  620. if pgnum > -1:
  621. self.layerbook.SetSelection(pgnum)
  622. self._layerManager.curr_page = self.layerbook.GetCurrentPage()
  623. event.Skip()
  624. def OnRender(self, event):
  625. """!Re-render map composition (each map layer)
  626. """
  627. # delete tmp map layers (queries)
  628. qlayer = self.Map.GetListOfLayers(l_name = globalvar.QUERYLAYER)
  629. for layer in qlayer:
  630. self.Map.DeleteLayer(layer)
  631. # delete tmp lines
  632. if self.MapWindow.mouse["use"] in ("measure",
  633. "profile"):
  634. self.MapWindow.polycoords = []
  635. self.MapWindow.ClearLines()
  636. # deselect features in vdigit
  637. if self.GetToolbar('vdigit'):
  638. self.MapWindow.digit.GetDisplay().SetSelected([])
  639. self.MapWindow.UpdateMap(render = True, renderVector = True)
  640. else:
  641. self.MapWindow.UpdateMap(render = True)
  642. # update statusbar
  643. self.StatusbarUpdate()
  644. def OnPointer(self, event):
  645. """!Pointer button clicked
  646. """
  647. if self.GetMapToolbar():
  648. if event:
  649. self.toolbars['map'].OnTool(event)
  650. self.toolbars['map'].action['desc'] = ''
  651. self.MapWindow.mouse['use'] = "pointer"
  652. self.MapWindow.mouse['box'] = "point"
  653. # change the cursor
  654. if self.GetToolbar('vdigit'):
  655. # digitization tool activated
  656. self.MapWindow.SetCursor(self.cursors["cross"])
  657. # reset mouse['box'] if needed
  658. if self.toolbars['vdigit'].GetAction() in ['addLine']:
  659. if self.toolbars['vdigit'].GetAction('type') in ['point', 'centroid']:
  660. self.MapWindow.mouse['box'] = 'point'
  661. else: # line, boundary
  662. self.MapWindow.mouse['box'] = 'line'
  663. elif self.toolbars['vdigit'].GetAction() in ['addVertex', 'removeVertex', 'splitLine',
  664. 'editLine', 'displayCats', 'queryMap',
  665. 'copyCats']:
  666. self.MapWindow.mouse['box'] = 'point'
  667. else: # moveLine, deleteLine
  668. self.MapWindow.mouse['box'] = 'box'
  669. else:
  670. self.MapWindow.SetCursor(self.cursors["default"])
  671. def OnRotate(self, event):
  672. """!Rotate 3D view
  673. """
  674. if self.GetMapToolbar():
  675. self.toolbars['map'].OnTool(event)
  676. self.toolbars['map'].action['desc'] = ''
  677. self.MapWindow.mouse['use'] = "rotate"
  678. # change the cursor
  679. self.MapWindow.SetCursor(self.cursors["hand"])
  680. def OnZoomRegion(self, event):
  681. """!Zoom to region
  682. """
  683. self.Map.getRegion()
  684. self.Map.getResolution()
  685. self.UpdateMap()
  686. # event.Skip()
  687. def OnAlignRegion(self, event):
  688. """!Align region
  689. """
  690. if not self.Map.alignRegion:
  691. self.Map.alignRegion = True
  692. else:
  693. self.Map.alignRegion = False
  694. # event.Skip()
  695. def SaveToFile(self, event):
  696. """!Save map to image
  697. """
  698. if self.IsPaneShown('3d'):
  699. filetype = "PPM file (*.ppm)|*.ppm|TIF file (*.tif)|*.tif"
  700. ltype = [{ 'ext' : 'ppm', 'type' : 'ppm' },
  701. { 'ext' : 'tif', 'type' : 'tif' }]
  702. else:
  703. img = self.MapWindow.img
  704. if not img:
  705. gcmd.GMessage(parent = self,
  706. message = _("Nothing to render (empty map). Operation canceled."))
  707. return
  708. filetype, ltype = gdialogs.GetImageHandlers(img)
  709. # get size
  710. dlg = gdialogs.ImageSizeDialog(self)
  711. dlg.CentreOnParent()
  712. if dlg.ShowModal() != wx.ID_OK:
  713. dlg.Destroy()
  714. return
  715. width, height = dlg.GetValues()
  716. dlg.Destroy()
  717. # get filename
  718. dlg = wx.FileDialog(parent = self,
  719. message = _("Choose a file name to save the image "
  720. "(no need to add extension)"),
  721. wildcard = filetype,
  722. style = wx.SAVE | wx.FD_OVERWRITE_PROMPT)
  723. if dlg.ShowModal() == wx.ID_OK:
  724. path = dlg.GetPath()
  725. if not path:
  726. dlg.Destroy()
  727. return
  728. base, ext = os.path.splitext(path)
  729. fileType = ltype[dlg.GetFilterIndex()]['type']
  730. extType = ltype[dlg.GetFilterIndex()]['ext']
  731. if ext != extType:
  732. path = base + '.' + extType
  733. self.MapWindow.SaveToFile(path, fileType,
  734. width, height)
  735. dlg.Destroy()
  736. def PrintMenu(self, event):
  737. """
  738. Print options and output menu for map display
  739. """
  740. point = wx.GetMousePosition()
  741. printmenu = wx.Menu()
  742. # Add items to the menu
  743. setup = wx.MenuItem(printmenu, wx.ID_ANY, _('Page setup'))
  744. printmenu.AppendItem(setup)
  745. self.Bind(wx.EVT_MENU, self.printopt.OnPageSetup, setup)
  746. preview = wx.MenuItem(printmenu, wx.ID_ANY, _('Print preview'))
  747. printmenu.AppendItem(preview)
  748. self.Bind(wx.EVT_MENU, self.printopt.OnPrintPreview, preview)
  749. doprint = wx.MenuItem(printmenu, wx.ID_ANY, _('Print display'))
  750. printmenu.AppendItem(doprint)
  751. self.Bind(wx.EVT_MENU, self.printopt.OnDoPrint, doprint)
  752. # Popup the menu. If an item is selected then its handler
  753. # will be called before PopupMenu returns.
  754. self.PopupMenu(printmenu)
  755. printmenu.Destroy()
  756. def OnCloseWindow(self, event):
  757. """!Window closed.
  758. Also close associated layer tree page
  759. """
  760. pgnum = None
  761. self.Map.Clean()
  762. # close edited map and 3D tools properly
  763. if self.GetToolbar('vdigit'):
  764. maplayer = self.toolbars['vdigit'].GetLayer()
  765. if maplayer:
  766. self.toolbars['vdigit'].OnExit()
  767. if self.IsPaneShown('3d'):
  768. self.RemoveNviz()
  769. if not self._layerManager:
  770. self.Destroy()
  771. elif self.page:
  772. pgnum = self.layerbook.GetPageIndex(self.page)
  773. if pgnum > -1:
  774. self.layerbook.DeletePage(pgnum)
  775. def QueryMap(self, x, y):
  776. """!Query raster or vector map layers by r/v.what
  777. @param x,y coordinates
  778. """
  779. # set query snap distance for v.what at map unit equivalent of 10 pixels
  780. qdist = 10.0 * ((self.Map.region['e'] - self.Map.region['w']) / self.Map.width)
  781. east, north = self.MapWindow.Pixel2Cell((x, y))
  782. if not self.IsStandalone():
  783. num = 0
  784. for layer in self.tree.GetSelections():
  785. ltype = self.tree.GetPyData(layer)[0]['maplayer'].GetType()
  786. if ltype in ('raster', 'rgb', 'his',
  787. 'vector', 'thememap', 'themechart'):
  788. num += 1
  789. if num < 1:
  790. gcmd.GMessage(parent = self,
  791. message = _('No raster or vector map layer selected for querying.'))
  792. return
  793. rast = list()
  794. vect = list()
  795. rcmd = ['r.what', '--v']
  796. vcmd = ['v.what', '--v']
  797. if self.IsStandalone():
  798. pass
  799. else:
  800. for layer in self.tree.GetSelections():
  801. ltype = self.tree.GetPyData(layer)[0]['maplayer'].GetType()
  802. dcmd = self.tree.GetPyData(layer)[0]['cmd']
  803. name, found = utils.GetLayerNameFromCmd(dcmd)
  804. if not found:
  805. continue
  806. if ltype == 'raster':
  807. rast.append(name)
  808. elif ltype in ('rgb', 'his'):
  809. for iname in name.split('\n'):
  810. rast.append(iname)
  811. elif ltype in ('vector', 'thememap', 'themechart'):
  812. vect.append(name)
  813. # rasters are not queried this way in 3D, we don't want them now
  814. if self.IsPaneShown('3d'):
  815. rast = list()
  816. # use display region settings instead of computation region settings
  817. self.tmpreg = os.getenv("GRASS_REGION")
  818. os.environ["GRASS_REGION"] = self.Map.SetRegion(windres = False)
  819. # build query commands for any selected rasters and vectors
  820. if rast:
  821. rcmd.append('-f')
  822. rcmd.append('-n')
  823. rcmd.append('input=%s' % ','.join(rast))
  824. rcmd.append('east_north=%f,%f' % (float(east), float(north)))
  825. if vect:
  826. # check for vector maps open to be edited
  827. digitToolbar = self.toolbars['vdigit']
  828. if digitToolbar:
  829. lmap = digitToolbar.GetLayer().GetName()
  830. for name in vect:
  831. if lmap == name:
  832. self._layerManager.goutput.WriteWarning(_("Vector map <%s> "
  833. "opened for editing - skipped.") % map)
  834. vect.remove(name)
  835. if len(vect) < 1:
  836. self._layerManager.goutput.WriteCmdLog(_("Nothing to query."))
  837. return
  838. vcmd.append('-a')
  839. vcmd.append('map=%s' % ','.join(vect))
  840. vcmd.append('layer=%s' % ','.join(['-1'] * len(vect)))
  841. vcmd.append('east_north=%f,%f' % (float(east), float(north)))
  842. vcmd.append('distance=%f' % float(qdist))
  843. Debug.msg(1, "QueryMap(): raster=%s vector=%s" % (','.join(rast),
  844. ','.join(vect)))
  845. # parse query command(s)
  846. if not self.IsStandalone():
  847. if rast:
  848. self._layerManager.goutput.RunCmd(rcmd,
  849. compReg = False,
  850. onDone = self._QueryMapDone)
  851. if vect:
  852. self._layerManager.goutput.RunCmd(vcmd,
  853. onDone = self._QueryMapDone)
  854. else:
  855. if rast:
  856. gcmd.RunCommand(rcmd)
  857. if vect:
  858. gcmd.RunCommand(vcmd)
  859. def _QueryMapDone(self, cmd, returncode):
  860. """!Restore settings after querying (restore GRASS_REGION)
  861. @param returncode command return code
  862. """
  863. if hasattr(self, "tmpreg"):
  864. if self.tmpreg:
  865. os.environ["GRASS_REGION"] = self.tmpreg
  866. elif 'GRASS_REGION' in os.environ:
  867. del os.environ["GRASS_REGION"]
  868. elif 'GRASS_REGION' in os.environ:
  869. del os.environ["GRASS_REGION"]
  870. if hasattr(self, "tmpreg"):
  871. del self.tmpreg
  872. def QueryVector(self, x, y):
  873. """!Query vector map layer features
  874. Attribute data of selected vector object are displayed in GUI dialog.
  875. Data can be modified (On Submit)
  876. """
  877. if not self.tree.layer_selected or \
  878. self.tree.GetPyData(self.tree.layer_selected)[0]['type'] != 'vector':
  879. gcmd.GMessage(parent = self,
  880. message = _("No map layer selected for querying."))
  881. return
  882. posWindow = self.ClientToScreen((x + self.MapWindow.dialogOffset,
  883. y + self.MapWindow.dialogOffset))
  884. qdist = 10.0 * ((self.Map.region['e'] - self.Map.region['w']) /
  885. self.Map.width)
  886. east, north = self.MapWindow.Pixel2Cell((x, y))
  887. mapName = self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name
  888. if self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].GetMapset() != \
  889. grass.gisenv()['MAPSET']:
  890. mode = 'display'
  891. else:
  892. mode = 'update'
  893. if self.dialogs['attributes'] is None:
  894. dlg = dbm_dialogs.DisplayAttributesDialog(parent = self.MapWindow,
  895. map = mapName,
  896. query = ((east, north), qdist),
  897. pos = posWindow,
  898. action = mode)
  899. self.dialogs['attributes'] = dlg
  900. else:
  901. # selection changed?
  902. if not self.dialogs['attributes'].mapDBInfo or \
  903. self.dialogs['attributes'].mapDBInfo.map != mapName:
  904. self.dialogs['attributes'].UpdateDialog(map = mapName, query = ((east, north), qdist),
  905. action = mode)
  906. else:
  907. self.dialogs['attributes'].UpdateDialog(query = ((east, north), qdist),
  908. action = mode)
  909. if not self.dialogs['attributes'].IsFound():
  910. self._layerManager.goutput.WriteLog(_('Nothing found.'))
  911. cats = self.dialogs['attributes'].GetCats()
  912. qlayer = None
  913. if not self.IsPaneShown('3d'):
  914. try:
  915. qlayer = self.Map.GetListOfLayers(l_name = globalvar.QUERYLAYER)[0]
  916. except IndexError:
  917. pass
  918. if self.dialogs['attributes'].mapDBInfo and cats:
  919. if not self.IsPaneShown('3d'):
  920. # highlight feature & re-draw map
  921. if qlayer:
  922. qlayer.SetCmd(self.AddTmpVectorMapLayer(mapName, cats,
  923. useId = False,
  924. addLayer = False))
  925. else:
  926. qlayer = self.AddTmpVectorMapLayer(mapName, cats, useId = False)
  927. # set opacity based on queried layer
  928. opacity = self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].GetOpacity(float = True)
  929. qlayer.SetOpacity(opacity)
  930. self.MapWindow.UpdateMap(render = False, renderVector = False)
  931. if not self.dialogs['attributes'].IsShown():
  932. self.dialogs['attributes'].Show()
  933. else:
  934. if qlayer:
  935. self.Map.DeleteLayer(qlayer)
  936. self.MapWindow.UpdateMap(render = False, renderVector = False)
  937. if self.dialogs['attributes'].IsShown():
  938. self.dialogs['attributes'].Hide()
  939. def OnQuery(self, event):
  940. """!Query tools menu"""
  941. if self.GetMapToolbar():
  942. self.toolbars['map'].OnTool(event)
  943. action = self.toolbars['map'].GetAction()
  944. self.toolbars['map'].action['desc'] = 'queryMap'
  945. self.MapWindow.mouse['use'] = "query"
  946. if not self.IsStandalone():
  947. # switch to output console to show query results
  948. self._layerManager.notebook.SetSelectionByName('output')
  949. self.MapWindow.mouse['box'] = "point"
  950. self.MapWindow.zoomtype = 0
  951. # change the cursor
  952. self.MapWindow.SetCursor(self.cursors["cross"])
  953. def AddTmpVectorMapLayer(self, name, cats, useId = False, addLayer = True):
  954. """!Add temporal vector map layer to map composition
  955. @param name name of map layer
  956. @param useId use feature id instead of category
  957. """
  958. # color settings from ATM
  959. color = UserSettings.Get(group = 'atm', key = 'highlight', subkey = 'color')
  960. colorStr = str(color[0]) + ":" + \
  961. str(color[1]) + ":" + \
  962. str(color[2])
  963. # icon used in vector display and its size
  964. icon = ''
  965. size = 0
  966. vparam = self.tree.GetPyData(self.tree.layer_selected)[0]['cmd']
  967. for p in vparam:
  968. if '=' in p:
  969. parg,pval = p.split('=')
  970. if parg == 'icon': icon = pval
  971. elif parg == 'size': size = int(pval)
  972. pattern = ["d.vect",
  973. "map=%s" % name,
  974. "color=%s" % colorStr,
  975. "fcolor=%s" % colorStr,
  976. "width=%d" % UserSettings.Get(group = 'atm', key = 'highlight', subkey = 'width')]
  977. if icon != '':
  978. pattern.append('icon=%s' % icon)
  979. if size > 0:
  980. pattern.append('size=%i' % size)
  981. if useId:
  982. cmd = pattern
  983. cmd.append('-i')
  984. cmd.append('cats=%s' % str(cats))
  985. else:
  986. cmd = []
  987. for layer in cats.keys():
  988. cmd.append(copy.copy(pattern))
  989. lcats = cats[layer]
  990. cmd[-1].append("layer=%d" % layer)
  991. cmd[-1].append("cats=%s" % utils.ListOfCatsToRange(lcats))
  992. if addLayer:
  993. if useId:
  994. return self.Map.AddLayer(type = 'vector', name = globalvar.QUERYLAYER, command = cmd,
  995. l_active = True, l_hidden = True, l_opacity = 1.0)
  996. else:
  997. return self.Map.AddLayer(type = 'command', name = globalvar.QUERYLAYER, command = cmd,
  998. l_active = True, l_hidden = True, l_opacity = 1.0)
  999. else:
  1000. return cmd
  1001. def OnAnalyze(self, event):
  1002. """!Analysis tools menu
  1003. """
  1004. point = wx.GetMousePosition()
  1005. toolsmenu = wx.Menu()
  1006. icons = Icons['displayWindow']
  1007. # Add items to the menu
  1008. measure = wx.MenuItem(toolsmenu, wx.ID_ANY, icons["measure"].GetLabel())
  1009. measure.SetBitmap(icons["measure"].GetBitmap(self.iconsize))
  1010. toolsmenu.AppendItem(measure)
  1011. self.Bind(wx.EVT_MENU, self.OnMeasure, measure)
  1012. profile = wx.MenuItem(toolsmenu, wx.ID_ANY, icons["profile"].GetLabel())
  1013. profile.SetBitmap(icons["profile"].GetBitmap(self.iconsize))
  1014. toolsmenu.AppendItem(profile)
  1015. self.Bind(wx.EVT_MENU, self.OnProfile, profile)
  1016. scatterplot = wx.MenuItem(toolsmenu, wx.ID_ANY, _("Create bivariate scatterplot of raster maps"))
  1017. scatterplot.SetBitmap(icons["profile"].GetBitmap(self.iconsize))
  1018. toolsmenu.AppendItem(scatterplot)
  1019. self.Bind(wx.EVT_MENU, self.OnScatterplot, scatterplot)
  1020. histogram2 = wx.MenuItem(toolsmenu, wx.ID_ANY, icons["histogram"].GetLabel())
  1021. histogram2.SetBitmap(icons["histogram"].GetBitmap(self.iconsize))
  1022. toolsmenu.AppendItem(histogram2)
  1023. self.Bind(wx.EVT_MENU, self.OnHistogramPyPlot, histogram2)
  1024. histogram = wx.MenuItem(toolsmenu, wx.ID_ANY, _("Create histogram with d.histogram"))
  1025. histogram.SetBitmap(icons["histogram"].GetBitmap(self.iconsize))
  1026. toolsmenu.AppendItem(histogram)
  1027. self.Bind(wx.EVT_MENU, self.OnHistogram, histogram)
  1028. # Popup the menu. If an item is selected then its handler
  1029. # will be called before PopupMenu returns.
  1030. self.PopupMenu(toolsmenu)
  1031. toolsmenu.Destroy()
  1032. def OnMeasure(self, event):
  1033. """!Init measurement routine that calculates map distance
  1034. along transect drawn on map display
  1035. """
  1036. self.totaldist = 0.0 # total measured distance
  1037. # switch Layer Manager to output console to show measure results
  1038. self._layerManager.notebook.SetSelectionByName('output')
  1039. # change mouse to draw line for measurement
  1040. self.MapWindow.mouse['use'] = "measure"
  1041. self.MapWindow.mouse['box'] = "line"
  1042. self.MapWindow.zoomtype = 0
  1043. self.MapWindow.pen = wx.Pen(colour = 'red', width = 2, style = wx.SHORT_DASH)
  1044. self.MapWindow.polypen = wx.Pen(colour = 'green', width = 2, style = wx.SHORT_DASH)
  1045. # change the cursor
  1046. self.MapWindow.SetCursor(self.cursors["pencil"])
  1047. # initiating output
  1048. style = self._layerManager.goutput.cmd_output.StyleWarning
  1049. self._layerManager.goutput.WriteLog(_('Click and drag with left mouse button '
  1050. 'to measure.%s'
  1051. 'Double click with left button to clear.') % \
  1052. (os.linesep), style)
  1053. if self.Map.projinfo['proj'] != 'xy':
  1054. units = self.Map.projinfo['units']
  1055. self._layerManager.goutput.WriteCmdLog(_('Measuring distance') + ' ('
  1056. + units + '):')
  1057. else:
  1058. self._layerManager.goutput.WriteCmdLog(_('Measuring distance:'))
  1059. if self.Map.projinfo['proj'] == 'll':
  1060. try:
  1061. import grass.lib.gis as gislib
  1062. global haveCtypes
  1063. haveCtypes = True
  1064. gislib.G_begin_distance_calculations()
  1065. except ImportError, e:
  1066. self._layerManager.goutput.WriteWarning(_('Geodesic distance is not yet '
  1067. 'supported by this tool.\n'
  1068. 'Reason: %s' % e))
  1069. def MeasureDist(self, beginpt, endpt):
  1070. """!Calculate map distance from screen distance
  1071. and print to output window
  1072. """
  1073. self._layerManager.notebook.SetSelectionByName('output')
  1074. dist, (north, east) = self.MapWindow.Distance(beginpt, endpt)
  1075. dist = round(dist, 3)
  1076. d, dunits = self.FormatDist(dist)
  1077. self.totaldist += dist
  1078. td, tdunits = self.FormatDist(self.totaldist)
  1079. strdist = str(d)
  1080. strtotdist = str(td)
  1081. if self.Map.projinfo['proj'] == 'xy' or 'degree' not in self.Map.projinfo['unit']:
  1082. angle = int(math.degrees(math.atan2(north,east)) + 0.5)
  1083. angle = 180 - angle
  1084. if angle < 0:
  1085. angle = 360 + angle
  1086. mstring = '%s = %s %s\n%s = %s %s\n%s = %d %s\n%s' \
  1087. % (_('segment'), strdist, dunits,
  1088. _('total distance'), strtotdist, tdunits,
  1089. _('bearing'), angle, _('deg'),
  1090. '-' * 60)
  1091. else:
  1092. mstring = '%s = %s %s\n%s = %s %s\n%s' \
  1093. % (_('segment'), strdist, dunits,
  1094. _('total distance'), strtotdist, tdunits,
  1095. '-' * 60)
  1096. self._layerManager.goutput.WriteLog(mstring)
  1097. return dist
  1098. def OnProfile(self, event):
  1099. """!Init profile canvas and tools
  1100. """
  1101. raster = []
  1102. if self.tree.layer_selected and \
  1103. self.tree.GetPyData(self.tree.layer_selected)[0]['type'] == 'raster':
  1104. raster.append(self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name)
  1105. self.profile = ProfileFrame(self,
  1106. id = wx.ID_ANY, pos = wx.DefaultPosition, size = (700,300),
  1107. style = wx.DEFAULT_FRAME_STYLE,
  1108. rasterList = raster)
  1109. self.profile.Show()
  1110. # Open raster select dialog to make sure that a raster (and the desired raster)
  1111. # is selected to be profiled
  1112. self.profile.OnSelectRaster(None)
  1113. def FormatDist(self, dist):
  1114. """!Format length numbers and units in a nice way,
  1115. as a function of length. From code by Hamish Bowman
  1116. Grass Development Team 2006"""
  1117. mapunits = self.Map.projinfo['units']
  1118. if mapunits == 'metres':
  1119. mapunits = 'meters'
  1120. outunits = mapunits
  1121. dist = float(dist)
  1122. divisor = 1.0
  1123. # figure out which units to use
  1124. if mapunits == 'meters':
  1125. if dist > 2500.0:
  1126. outunits = 'km'
  1127. divisor = 1000.0
  1128. else: outunits = 'm'
  1129. elif mapunits == 'feet':
  1130. # nano-bug: we match any "feet", but US Survey feet is really
  1131. # 5279.9894 per statute mile, or 10.6' per 1000 miles. As >1000
  1132. # miles the tick markers are rounded to the nearest 10th of a
  1133. # mile (528'), the difference in foot flavours is ignored.
  1134. if dist > 5280.0:
  1135. outunits = 'miles'
  1136. divisor = 5280.0
  1137. else:
  1138. outunits = 'ft'
  1139. elif 'degree' in mapunits and \
  1140. not haveCtypes:
  1141. if dist < 1:
  1142. outunits = 'min'
  1143. divisor = (1/60.0)
  1144. else:
  1145. outunits = 'deg'
  1146. else:
  1147. outunits = 'meters'
  1148. # format numbers in a nice way
  1149. if (dist/divisor) >= 2500.0:
  1150. outdist = round(dist/divisor)
  1151. elif (dist/divisor) >= 1000.0:
  1152. outdist = round(dist/divisor,1)
  1153. elif (dist/divisor) > 0.0:
  1154. outdist = round(dist/divisor,int(math.ceil(3-math.log10(dist/divisor))))
  1155. else:
  1156. outdist = float(dist/divisor)
  1157. return (outdist, outunits)
  1158. def OnHistogramPyPlot(self, event):
  1159. """!Init PyPlot histogram display canvas and tools
  1160. """
  1161. raster = []
  1162. for layer in self.tree.GetSelections():
  1163. if self.tree.GetPyData(layer)[0]['maplayer'].GetType() != 'raster':
  1164. continue
  1165. raster.append(self.tree.GetPyData(layer)[0]['maplayer'].GetName())
  1166. self.histogramPyPlot = HistFramePyPlot(self, id = wx.ID_ANY,
  1167. pos = wx.DefaultPosition, size = (700,300),
  1168. style = wx.DEFAULT_FRAME_STYLE,
  1169. rasterList = raster)
  1170. self.histogramPyPlot.Show()
  1171. # Open raster select dialog to make sure that a raster (and the desired raster)
  1172. # is selected to be histogrammed
  1173. self.histogramPyPlot.OnSelectRaster(None)
  1174. def OnScatterplot(self, event):
  1175. """!Init PyPlot scatterplot display canvas and tools
  1176. """
  1177. raster = []
  1178. for layer in self.tree.GetSelections():
  1179. if self.tree.GetPyData(layer)[0]['maplayer'].GetType() != 'raster':
  1180. continue
  1181. raster.append(self.tree.GetPyData(layer)[0]['maplayer'].GetName())
  1182. self.scatterplot = ScatterFrame(self, id = wx.ID_ANY,
  1183. pos = wx.DefaultPosition, size = (700,300),
  1184. style = wx.DEFAULT_FRAME_STYLE,
  1185. rasterList = raster)
  1186. self.scatterplot.Show()
  1187. # Open raster select dialog to make sure that at least 2 rasters (and the desired rasters)
  1188. # are selected to be plotted
  1189. self.scatterplot.OnSelectRaster(None)
  1190. def OnHistogram(self, event):
  1191. """!Init histogram display canvas and tools
  1192. """
  1193. self.histogram = HistFrame(parent = self, id = wx.ID_ANY, size = globalvar.HIST_WINDOW_SIZE,
  1194. style = wx.DEFAULT_FRAME_STYLE)
  1195. # show new display
  1196. self.histogram.Show()
  1197. self.histogram.Refresh()
  1198. self.histogram.Update()
  1199. def OnDecoration(self, event):
  1200. """!Decorations overlay menu
  1201. """
  1202. point = wx.GetMousePosition()
  1203. decmenu = wx.Menu()
  1204. icons = Icons['displayWindow']
  1205. # Add items to the menu
  1206. AddScale = wx.MenuItem(decmenu, wx.ID_ANY, icons["addBarscale"].GetLabel())
  1207. AddScale.SetBitmap(icons["addBarscale"].GetBitmap(self.iconsize))
  1208. decmenu.AppendItem(AddScale)
  1209. self.Bind(wx.EVT_MENU, self.OnAddBarscale, AddScale)
  1210. # temporary
  1211. if self.IsPaneShown('3d'):
  1212. AddScale.Enable(False)
  1213. AddArrow = wx.MenuItem(decmenu, wx.ID_ANY, _("Add north arrow"))
  1214. AddArrow.SetBitmap(icons["addBarscale"].GetBitmap(self.iconsize))
  1215. decmenu.AppendItem(AddArrow)
  1216. self.Bind(wx.EVT_MENU, self.OnAddArrow, AddArrow)
  1217. AddLegend = wx.MenuItem(decmenu, wx.ID_ANY, icons["addLegend"].GetLabel())
  1218. AddLegend.SetBitmap(icons["addLegend"].GetBitmap(self.iconsize))
  1219. decmenu.AppendItem(AddLegend)
  1220. self.Bind(wx.EVT_MENU, self.OnAddLegend, AddLegend)
  1221. AddText = wx.MenuItem(decmenu, wx.ID_ANY, icons["addText"].GetLabel())
  1222. AddText.SetBitmap(icons["addText"].GetBitmap(self.iconsize))
  1223. decmenu.AppendItem(AddText)
  1224. self.Bind(wx.EVT_MENU, self.OnAddText, AddText)
  1225. # Popup the menu. If an item is selected then its handler
  1226. # will be called before PopupMenu returns.
  1227. self.PopupMenu(decmenu)
  1228. decmenu.Destroy()
  1229. def OnAddBarscale(self, event):
  1230. """!Handler for scale/arrow map decoration menu selection.
  1231. """
  1232. if self.dialogs['barscale']:
  1233. return
  1234. id = 0 # unique index for overlay layer
  1235. # If location is latlon, only display north arrow (scale won't work)
  1236. # proj = self.Map.projinfo['proj']
  1237. # if proj == 'll':
  1238. # barcmd = 'd.barscale -n'
  1239. # else:
  1240. # barcmd = 'd.barscale'
  1241. # decoration overlay control dialog
  1242. self.dialogs['barscale'] = \
  1243. gdialogs.DecorationDialog(parent = self, title = _('Scale and North arrow'),
  1244. size = (350, 200),
  1245. style = wx.DEFAULT_DIALOG_STYLE | wx.CENTRE,
  1246. cmd = ['d.barscale', 'at=0,95'],
  1247. ovlId = id,
  1248. name = 'barscale',
  1249. checktxt = _("Show/hide scale and North arrow"),
  1250. ctrltxt = _("scale object"))
  1251. self.dialogs['barscale'].CentreOnParent()
  1252. ### dialog cannot be show as modal - in the result d.barscale is not selectable
  1253. ### self.dialogs['barscale'].ShowModal()
  1254. self.dialogs['barscale'].Show()
  1255. self.MapWindow.mouse['use'] = 'pointer'
  1256. def OnAddLegend(self, event):
  1257. """!Handler for legend map decoration menu selection.
  1258. """
  1259. if self.dialogs['legend']:
  1260. return
  1261. id = 1 # index for overlay layer in render
  1262. cmd = ['d.legend', 'at=5,50,2,5']
  1263. if self.tree.layer_selected and \
  1264. self.tree.GetPyData(self.tree.layer_selected)[0]['type'] == 'raster':
  1265. cmd.append('map=%s' % self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name)
  1266. # Decoration overlay control dialog
  1267. self.dialogs['legend'] = \
  1268. gdialogs.DecorationDialog(parent = self, title = ('Legend'),
  1269. size = (350, 200),
  1270. style = wx.DEFAULT_DIALOG_STYLE | wx.CENTRE,
  1271. cmd = cmd,
  1272. ovlId = id,
  1273. name = 'legend',
  1274. checktxt = _("Show/hide legend"),
  1275. ctrltxt = _("legend object"))
  1276. self.dialogs['legend'].CentreOnParent()
  1277. ### dialog cannot be show as modal - in the result d.legend is not selectable
  1278. ### self.dialogs['legend'].ShowModal()
  1279. self.dialogs['legend'].Show()
  1280. self.MapWindow.mouse['use'] = 'pointer'
  1281. def OnAddText(self, event):
  1282. """!Handler for text decoration menu selection.
  1283. """
  1284. if self.MapWindow.dragid > -1:
  1285. id = self.MapWindow.dragid
  1286. self.MapWindow.dragid = -1
  1287. else:
  1288. # index for overlay layer in render
  1289. if len(self.MapWindow.textdict.keys()) > 0:
  1290. id = max(self.MapWindow.textdict.keys()) + 1
  1291. else:
  1292. id = 101
  1293. self.dialogs['text'] = gdialogs.TextLayerDialog(parent = self, ovlId = id,
  1294. title = _('Add text layer'),
  1295. size = (400, 200))
  1296. self.dialogs['text'].CenterOnParent()
  1297. # If OK button pressed in decoration control dialog
  1298. if self.dialogs['text'].ShowModal() == wx.ID_OK:
  1299. text = self.dialogs['text'].GetValues()['text']
  1300. active = self.dialogs['text'].GetValues()['active']
  1301. # delete object if it has no text or is not active
  1302. if text == '' or active == False:
  1303. try:
  1304. self.MapWindow2D.pdc.ClearId(id)
  1305. self.MapWindow2D.pdc.RemoveId(id)
  1306. del self.MapWindow.textdict[id]
  1307. if self.IsPaneShown('3d'):
  1308. self.MapWindow3D.UpdateOverlays()
  1309. self.MapWindow.UpdateMap()
  1310. else:
  1311. self.MapWindow2D.UpdateMap(render = False, renderVector = False)
  1312. except:
  1313. pass
  1314. return
  1315. self.MapWindow.textdict[id] = self.dialogs['text'].GetValues()
  1316. if self.IsPaneShown('3d'):
  1317. self.MapWindow3D.UpdateOverlays()
  1318. self.MapWindow3D.UpdateMap()
  1319. else:
  1320. self.MapWindow2D.pdc.ClearId(id)
  1321. self.MapWindow2D.pdc.SetId(id)
  1322. self.MapWindow2D.UpdateMap(render = False, renderVector = False)
  1323. self.MapWindow.mouse['use'] = 'pointer'
  1324. def OnAddArrow(self, event):
  1325. """!Handler for north arrow menu selection.
  1326. Opens Appearance page of nviz notebook.
  1327. """
  1328. self._layerManager.nviz.SetPage('decoration')
  1329. self.MapWindow3D.SetDrawArrow((70, 70))
  1330. def GetOptData(self, dcmd, type, params, propwin):
  1331. """!Callback method for decoration overlay command generated by
  1332. dialog created in menuform.py
  1333. """
  1334. # Reset comand and rendering options in render.Map. Always render decoration.
  1335. # Showing/hiding handled by PseudoDC
  1336. self.Map.ChangeOverlay(ovltype = type, type = 'overlay', name = '', command = dcmd,
  1337. l_active = True, l_render = False)
  1338. self.params[type] = params
  1339. self.propwin[type] = propwin
  1340. def OnZoomToMap(self, event):
  1341. """!Set display extents to match selected raster (including
  1342. NULLs) or vector map.
  1343. """
  1344. self.MapWindow.ZoomToMap()
  1345. def OnZoomToRaster(self, event):
  1346. """!Set display extents to match selected raster map (ignore NULLs)
  1347. """
  1348. self.MapWindow.ZoomToMap(ignoreNulls = True)
  1349. def OnZoomToSaved(self, event):
  1350. """!Set display geometry to match extents in
  1351. saved region file
  1352. """
  1353. self.MapWindow.ZoomToSaved()
  1354. def OnDisplayToWind(self, event):
  1355. """!Set computational region (WIND file) to match display
  1356. extents
  1357. """
  1358. self.MapWindow.DisplayToWind()
  1359. def SaveDisplayRegion(self, event):
  1360. """!Save display extents to named region file.
  1361. """
  1362. self.MapWindow.SaveDisplayRegion()
  1363. def OnZoomMenu(self, event):
  1364. """!Popup Zoom menu
  1365. """
  1366. point = wx.GetMousePosition()
  1367. zoommenu = wx.Menu()
  1368. # Add items to the menu
  1369. zoomwind = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to computational region'))
  1370. zoommenu.AppendItem(zoomwind)
  1371. self.Bind(wx.EVT_MENU, self.OnZoomToWind, zoomwind)
  1372. zoomdefault = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to default region'))
  1373. zoommenu.AppendItem(zoomdefault)
  1374. self.Bind(wx.EVT_MENU, self.OnZoomToDefault, zoomdefault)
  1375. zoomsaved = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to saved region'))
  1376. zoommenu.AppendItem(zoomsaved)
  1377. self.Bind(wx.EVT_MENU, self.OnZoomToSaved, zoomsaved)
  1378. savewind = wx.MenuItem(zoommenu, wx.ID_ANY, _('Set computational region from display extent'))
  1379. zoommenu.AppendItem(savewind)
  1380. self.Bind(wx.EVT_MENU, self.OnDisplayToWind, savewind)
  1381. savezoom = wx.MenuItem(zoommenu, wx.ID_ANY, _('Save display geometry to named region'))
  1382. zoommenu.AppendItem(savezoom)
  1383. self.Bind(wx.EVT_MENU, self.SaveDisplayRegion, savezoom)
  1384. # Popup the menu. If an item is selected then its handler
  1385. # will be called before PopupMenu returns.
  1386. self.PopupMenu(zoommenu)
  1387. zoommenu.Destroy()
  1388. def SetProperties(self, render = False, mode = 0, showCompExtent = False,
  1389. constrainRes = False, projection = False, alignExtent = True):
  1390. """!Set properies of map display window"""
  1391. self.SetProperty('render', render)
  1392. self.statusbarManager.SetMode(mode)
  1393. self.StatusbarUpdate()
  1394. self.SetProperty('region', showCompExtent)
  1395. self.SetProperty('alignExtent', alignExtent)
  1396. self.SetProperty('resolution', constrainRes)
  1397. self.SetProperty('projection', projection)
  1398. def IsStandalone(self):
  1399. """!Check if Map display is standalone"""
  1400. if self._layerManager:
  1401. return False
  1402. return True
  1403. def GetLayerManager(self):
  1404. """!Get reference to Layer Manager
  1405. @return window reference
  1406. @return None (if standalone)
  1407. """
  1408. return self._layerManager
  1409. def GetMapToolbar(self):
  1410. """!Returns toolbar with zooming tools"""
  1411. return self.toolbars['map']
  1412. class MapApp(wx.App):
  1413. def OnInit(self):
  1414. wx.InitAllImageHandlers()
  1415. if __name__ == "__main__":
  1416. self.cmdTimeStamp = os.path.getmtime(monFile['cmd'])
  1417. Map = render.Map(cmdfile = monFile['cmd'], mapfile = monFile['map'],
  1418. envfile = monFile['env'], monitor = monName)
  1419. else:
  1420. Map = None
  1421. self.mapFrm = MapFrame(parent = None, id = wx.ID_ANY, Map = Map,
  1422. size = monSize)
  1423. # self.SetTopWindow(Map)
  1424. self.mapFrm.Show()
  1425. if __name__ == "__main__":
  1426. self.timer = wx.PyTimer(self.watcher)
  1427. #check each 0.5s
  1428. global mtime
  1429. mtime = 500
  1430. self.timer.Start(mtime)
  1431. return True
  1432. def OnExit(self):
  1433. if __name__ == "__main__":
  1434. # stop the timer
  1435. # self.timer.Stop()
  1436. # terminate thread
  1437. for f in monFile.itervalues():
  1438. grass.try_remove(f)
  1439. def watcher(self):
  1440. """!Redraw, if new layer appears (check's timestamp of
  1441. cmdfile)
  1442. """
  1443. # todo: events
  1444. if os.path.getmtime(monFile['cmd']) > self.cmdTimeStamp:
  1445. self.timer.Stop()
  1446. self.cmdTimeStamp = os.path.getmtime(monFile['cmd'])
  1447. self.mapFrm.OnDraw(None)
  1448. self.timer.Start(mtime)
  1449. if __name__ == "__main__":
  1450. # set command variable
  1451. if len(sys.argv) < 5:
  1452. print __doc__
  1453. sys.exit(1)
  1454. monName = sys.argv[1]
  1455. monFile = { 'map' : sys.argv[2],
  1456. 'cmd' : sys.argv[3],
  1457. 'env' : sys.argv[4],
  1458. }
  1459. if len(sys.argv) >= 6:
  1460. try:
  1461. monSize[0] = int(sys.argv[5])
  1462. except ValueError:
  1463. pass
  1464. if len(sys.argv) == 7:
  1465. try:
  1466. monSize[1] = int(sys.argv[6])
  1467. except ValueError:
  1468. pass
  1469. import gettext
  1470. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
  1471. grass.verbose(_("Starting map display <%s>...") % (monName))
  1472. gcmd.RunCommand('g.gisenv',
  1473. set = 'MONITOR_%s_PID=%d' % (monName, os.getpid()))
  1474. gm_map = MapApp(0)
  1475. # set title
  1476. gm_map.mapFrm.SetTitle(_("GRASS GIS Map Display: " +
  1477. monName +
  1478. " - Location: " + grass.gisenv()["LOCATION_NAME"]))
  1479. gm_map.MainLoop()
  1480. grass.verbose(_("Stopping map display <%s>...") % (monName))
  1481. # clean up GRASS env variables
  1482. env = grass.gisenv()
  1483. env_name = 'MONITOR_%s' % monName
  1484. for key in env.keys():
  1485. if key.find(env_name) == 0:
  1486. gcmd.RunCommand('g.gisenv',
  1487. set = '%s=' % key)
  1488. if key == 'MONITOR' and env[key] == monName:
  1489. gcmd.RunCommand('g.gisenv',
  1490. set = '%s=' % key)
  1491. sys.exit(0)