mapdisp.py 62 KB

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