mapdisp.py 66 KB

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