mapdisp.py 69 KB

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