mapdisp.py 67 KB

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