mapdisp.py 66 KB

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