mapdisp.py 68 KB

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