mapdisp.py 68 KB

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