mapdisp.py 64 KB

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