mapdisp.py 66 KB

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