frame.py 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445
  1. """
  2. @package mapdisp.frame
  3. @brief Map display with toolbar for various display management
  4. functions, and additional toolbars (vector digitizer, 3d view).
  5. Can be used either from Layer Manager or as d.mon backend.
  6. Classes:
  7. - mapdisp::MapFrame
  8. (C) 2006-2014 by the GRASS Development Team
  9. This program is free software under the GNU General Public License
  10. (>=v2). Read the file COPYING that comes with GRASS for details.
  11. @author Michael Barton
  12. @author Jachym Cepicky
  13. @author Martin Landa <landa.martin gmail.com>
  14. @author Vaclav Petras <wenzeslaus gmail.com> (SingleMapFrame, handlers support)
  15. @author Anna Kratochvilova <kratochanna gmail.com> (SingleMapFrame)
  16. @author Stepan Turek <stepan.turek seznam.cz> (handlers support)
  17. """
  18. import os
  19. import sys
  20. import copy
  21. from core import globalvar
  22. import wx
  23. import wx.aui
  24. from core.render import Map
  25. from vdigit.toolbars import VDigitToolbar
  26. from mapdisp.toolbars import MapToolbar, NvizIcons
  27. from mapdisp.gprint import PrintOptions
  28. from core.gcmd import GError, GMessage, RunCommand
  29. from dbmgr.dialogs import DisplayAttributesDialog
  30. from core.utils import ListOfCatsToRange, GetLayerNameFromCmd, _
  31. from gui_core.dialogs import GetImageHandlers, ImageSizeDialog
  32. from core.debug import Debug
  33. from core.settings import UserSettings
  34. from gui_core.mapdisp import SingleMapFrame
  35. from mapwin.base import MapWindowProperties
  36. from gui_core.query import QueryDialog, PrepareQueryResults
  37. from mapwin.buffered import BufferedMapWindow
  38. from mapwin.decorations import TextLayerDialog, \
  39. LegendController, BarscaleController, ArrowController
  40. from modules.histogram import HistogramFrame
  41. from wxplot.histogram import HistogramPlotFrame
  42. from wxplot.profile import ProfileFrame
  43. from wxplot.scatter import ScatterFrame
  44. from mapwin.analysis import ProfileController, MeasureDistanceController, \
  45. MeasureAreaController
  46. from gui_core.forms import GUI
  47. from core.giface import Notification
  48. from mapdisp import statusbar as sb
  49. import grass.script as grass
  50. from grass.pydispatch.signal import Signal
  51. class MapFrame(SingleMapFrame):
  52. """Main frame for map display window. Drawing takes place in
  53. child double buffered drawing window.
  54. """
  55. def __init__(self, parent, giface, title = _("GRASS GIS - Map display"),
  56. toolbars = ["map"], tree = None, notebook = None, lmgr = None,
  57. page = None, Map = Map(), auimgr = None, name = 'MapWindow', **kwargs):
  58. """Main map display window with toolbars, statusbar and
  59. 2D map window, 3D map window and digitizer.
  60. :param toolbars: array of activated toolbars, e.g. ['map', 'digit']
  61. :param tree: reference to layer tree
  62. :param notebook: control book ID in Layer Manager
  63. :param lmgr: Layer Manager
  64. :param page: notebook page with layer tree
  65. :param map: instance of render.Map
  66. :param auimgs: AUI manager
  67. :param name: frame name
  68. :param kwargs: wx.Frame attributes
  69. """
  70. SingleMapFrame.__init__(self, parent = parent, title = title,
  71. Map = Map, auimgr = auimgr, name = name, **kwargs)
  72. self._giface = giface
  73. # Layer Manager object
  74. # need by GLWindow (a lot), VDigitWindow (a little bit)
  75. self._layerManager = lmgr
  76. # Layer Manager layer tree object
  77. # used for VDigit toolbar and window and GLWindow
  78. self.tree = tree
  79. # Notebook page holding the layer tree
  80. # used only in OnCloseWindow
  81. self.page = page
  82. # Layer Manager layer tree notebook
  83. # used only in OnCloseWindow
  84. self.layerbook = notebook
  85. # Emitted when starting (switching to) 3D mode.
  86. # Parameter firstTime specifies if 3D was already actived.
  87. self.starting3dMode = Signal("MapFrame.starting3dMode")
  88. # Emitted when ending (switching from) 3D mode.
  89. self.ending3dMode = Signal("MapFrame.ending3dMode")
  90. # properties are shared in other objects, so defining here
  91. self.mapWindowProperties = MapWindowProperties()
  92. self.mapWindowProperties.setValuesFromUserSettings()
  93. #
  94. # Add toolbars
  95. #
  96. for toolb in toolbars:
  97. self.AddToolbar(toolb)
  98. #
  99. # Add statusbar
  100. #
  101. # items for choice
  102. self.statusbarItems = [sb.SbCoordinates,
  103. sb.SbRegionExtent,
  104. sb.SbCompRegionExtent,
  105. sb.SbShowRegion,
  106. sb.SbAlignExtent,
  107. sb.SbResolution,
  108. sb.SbDisplayGeometry,
  109. sb.SbMapScale,
  110. sb.SbGoTo,
  111. sb.SbProjection]
  112. self.statusbarItemsHiddenInNviz = (sb.SbAlignExtent,
  113. sb.SbDisplayGeometry,
  114. sb.SbShowRegion,
  115. sb.SbResolution,
  116. sb.SbMapScale)
  117. # create statusbar and its manager
  118. statusbar = self.CreateStatusBar(number = 4, style = 0)
  119. if globalvar.wxPython3:
  120. statusbar.SetMinHeight(24)
  121. statusbar.SetStatusWidths([-5, -2, -1, -1])
  122. self.statusbarManager = sb.SbManager(mapframe = self, statusbar = statusbar)
  123. # fill statusbar manager
  124. self.statusbarManager.AddStatusbarItemsByClass(self.statusbarItems, mapframe = self, statusbar = statusbar)
  125. self.statusbarManager.AddStatusbarItem(sb.SbMask(self, statusbar = statusbar, position = 2))
  126. sbRender = sb.SbRender(self, statusbar = statusbar, position = 3)
  127. self.statusbarManager.AddStatusbarItem(sbRender)
  128. self.statusbarManager.Update()
  129. #
  130. self.Map.updateProgress.connect(self.statusbarManager.SetProgress)
  131. # init decoration objects
  132. self.decorations = {}
  133. self.legend = LegendController(self.Map, self._giface)
  134. self.barscale = BarscaleController(self.Map, self._giface)
  135. self.arrow = ArrowController(self.Map, self._giface)
  136. self.decorations[self.legend.id] = self.legend
  137. self.decorations[self.barscale.id] = self.barscale
  138. self.decorations[self.arrow.id] = self.arrow
  139. self.mapWindowProperties.autoRenderChanged.connect(
  140. lambda value:
  141. self.OnRender(None) if value else None)
  142. #
  143. # Init map display (buffered DC & set default cursor)
  144. #
  145. self.MapWindow2D = BufferedMapWindow(self, giface = self._giface,
  146. Map=self.Map,
  147. properties=self.mapWindowProperties,
  148. overlays=self.decorations)
  149. self.MapWindow2D.mapQueried.connect(self.Query)
  150. self.MapWindow2D.overlayActivated.connect(self._activateOverlay)
  151. self.MapWindow2D.overlayHidden.connect(self._hideOverlay)
  152. self.MapWindow2D.overlayHidden.connect(self._hideOverlay)
  153. for overlay in (self.legend, self.barscale, self.arrow):
  154. overlay.overlayChanged.connect(lambda: self.MapWindow2D.UpdateMap(render=False, renderVector=False))
  155. self._setUpMapWindow(self.MapWindow2D)
  156. self.MapWindow2D.mouseHandlerUnregistered.connect(self.ResetPointer)
  157. self.MapWindow2D.InitZoomHistory()
  158. self.MapWindow2D.zoomChanged.connect(self.StatusbarUpdate)
  159. self._giface.updateMap.connect(self.MapWindow2D.UpdateMap)
  160. # default is 2D display mode
  161. self.MapWindow = self.MapWindow2D
  162. self.MapWindow.SetNamedCursor('default')
  163. # used by vector digitizer
  164. self.MapWindowVDigit = None
  165. # used by Nviz (3D display mode)
  166. self.MapWindow3D = None
  167. #
  168. # initialize region values
  169. #
  170. self._initMap(Map = self.Map)
  171. self.toolbars['map'].SelectDefault()
  172. #
  173. # Bind various events
  174. #
  175. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  176. self.Bind(wx.EVT_SIZE, self.OnSize)
  177. #
  178. # Update fancy gui style
  179. #
  180. self._mgr.AddPane(self.MapWindow, wx.aui.AuiPaneInfo().CentrePane().
  181. Dockable(False).BestSize((-1,-1)).Name('2d').
  182. CloseButton(False).DestroyOnClose(True).
  183. Layer(0))
  184. self._mgr.Update()
  185. #
  186. # Init print module and classes
  187. #
  188. self.printopt = PrintOptions(self, self.MapWindow)
  189. #
  190. # Re-use dialogs
  191. #
  192. self.dialogs = {}
  193. self.dialogs['attributes'] = None
  194. self.dialogs['category'] = None
  195. self.dialogs['vnet'] = None
  196. self.dialogs['query'] = None
  197. # initialize layers to query (d.what.vect/rast)
  198. self._vectQueryLayers = []
  199. self._rastQueryLayers = []
  200. self.measureController = None
  201. def GetMapWindow(self):
  202. return self.MapWindow
  203. def SetTitleNumber(self, displayId=1):
  204. """Set map display title"""
  205. try:
  206. grassVersion = grass.version()['version']
  207. except KeyError:
  208. sys.stderr.write(_("Unable to get GRASS version\n"))
  209. grassVersion = "?"
  210. gisenv = grass.gisenv()
  211. title = _("GRASS GIS %(version)s Map Display: %(id)s - Location: %(loc)s@%(mapset)s") % \
  212. {'version': grassVersion,
  213. 'id': str(displayId),
  214. 'loc': gisenv["LOCATION_NAME"],
  215. 'mapset': gisenv["MAPSET"]}
  216. self.SetTitle(title)
  217. def _addToolbarVDigit(self):
  218. """Add vector digitizer toolbar
  219. """
  220. from vdigit.main import haveVDigit, VDigit
  221. if not haveVDigit:
  222. from vdigit import errorMsg
  223. self.toolbars['map'].combo.SetValue(_("2D view"))
  224. GError(_("Unable to start wxGUI vector digitizer.\n"
  225. "Details: %s") % errorMsg, parent = self)
  226. return
  227. if not self.MapWindowVDigit:
  228. from vdigit.mapwindow import VDigitWindow
  229. self.MapWindowVDigit = VDigitWindow(parent=self, giface=self._giface,
  230. properties=self.mapWindowProperties,
  231. Map=self.Map, tree=self.tree,
  232. lmgr=self._layerManager,
  233. overlays=self.decorations)
  234. self._setUpMapWindow(self.MapWindowVDigit)
  235. self.MapWindowVDigit.digitizingInfo.connect(
  236. lambda text:
  237. self.statusbarManager.statusbarItems['coordinates'].SetAdditionalInfo(text))
  238. self.MapWindowVDigit.digitizingInfoUnavailable.connect(
  239. lambda:
  240. self.statusbarManager.statusbarItems['coordinates'].SetAdditionalInfo(None))
  241. self.MapWindowVDigit.Show()
  242. self._mgr.AddPane(self.MapWindowVDigit, wx.aui.AuiPaneInfo().CentrePane().
  243. Dockable(False).BestSize((-1,-1)).Name('vdigit').
  244. CloseButton(False).DestroyOnClose(True).
  245. Layer(0))
  246. self._switchMapWindow(self.MapWindowVDigit)
  247. if self._mgr.GetPane('2d').IsShown():
  248. self._mgr.GetPane('2d').Hide()
  249. elif self._mgr.GetPane('3d').IsShown():
  250. self._mgr.GetPane('3d').Hide()
  251. self._mgr.GetPane('vdigit').Show()
  252. self.toolbars['vdigit'] = VDigitToolbar(parent=self, toolSwitcher=self._toolSwitcher,
  253. MapWindow = self.MapWindow,
  254. digitClass=VDigit, giface=self._giface)
  255. self.MapWindowVDigit.SetToolbar(self.toolbars['vdigit'])
  256. self._mgr.AddPane(self.toolbars['vdigit'],
  257. wx.aui.AuiPaneInfo().
  258. Name("vdigittoolbar").Caption(_("Vector Digitizer Toolbar")).
  259. ToolbarPane().Top().Row(1).
  260. LeftDockable(False).RightDockable(False).
  261. BottomDockable(False).TopDockable(True).
  262. CloseButton(False).Layer(2).
  263. BestSize((self.toolbars['vdigit'].GetBestSize())))
  264. # change mouse to draw digitized line
  265. self.MapWindow.mouse['box'] = "point"
  266. self.MapWindow.zoomtype = 0
  267. self.MapWindow.pen = wx.Pen(colour = 'red', width = 2, style = wx.SOLID)
  268. self.MapWindow.polypen = wx.Pen(colour = 'green', width = 2, style = wx.SOLID)
  269. def AddNviz(self):
  270. """Add 3D view mode window
  271. """
  272. from nviz.main import haveNviz, GLWindow, errorMsg
  273. # check for GLCanvas and OpenGL
  274. if not haveNviz:
  275. self.toolbars['map'].combo.SetValue(_("2D view"))
  276. GError(parent = self,
  277. message = _("Unable to switch to 3D display mode.\nThe Nviz python extension "
  278. "was not found or loaded properly.\n"
  279. "Switching back to 2D display mode.\n\nDetails: %s" % errorMsg))
  280. return
  281. # here was disabling 3D for other displays, now done on starting3dMode
  282. self.toolbars['map'].Enable2D(False)
  283. # add rotate tool to map toolbar
  284. self.toolbars['map'].InsertTool((('rotate', NvizIcons['rotate'],
  285. self.OnRotate, wx.ITEM_CHECK, 7),)) # 7 is position
  286. self._toolSwitcher.AddToolToGroup(group='mouseUse', toolbar=self.toolbars['map'],
  287. tool=self.toolbars['map'].rotate)
  288. self.toolbars['map'].InsertTool((('flyThrough', NvizIcons['flyThrough'],
  289. self.OnFlyThrough, wx.ITEM_CHECK, 8),))
  290. self._toolSwitcher.AddToolToGroup(group='mouseUse', toolbar=self.toolbars['map'],
  291. tool=self.toolbars['map'].flyThrough)
  292. self.toolbars['map'].ChangeToolsDesc(mode2d = False)
  293. # update status bar
  294. self.statusbarManager.HideStatusbarChoiceItemsByClass(self.statusbarItemsHiddenInNviz)
  295. self.statusbarManager.SetMode(0)
  296. # erase map window
  297. self.MapWindow.EraseMap()
  298. self._giface.WriteCmdLog(_("Starting 3D view mode..."), notification=Notification.HIGHLIGHT)
  299. self.SetStatusText(_("Please wait, loading data..."), 0)
  300. # create GL window
  301. if not self.MapWindow3D:
  302. self.MapWindow3D = GLWindow(self, giface = self._giface, id = wx.ID_ANY, frame = self,
  303. Map = self.Map, tree = self.tree, lmgr = self._layerManager)
  304. self._setUpMapWindow(self.MapWindow3D)
  305. self.MapWindow3D.mapQueried.connect(self.Query)
  306. self._switchMapWindow(self.MapWindow3D)
  307. self.MapWindow.SetNamedCursor('default')
  308. # here was AddNvizTools in lmgr
  309. self.starting3dMode.emit(firstTime=True)
  310. # switch from MapWindow to MapWindowGL
  311. self._mgr.GetPane('2d').Hide()
  312. self._mgr.AddPane(self.MapWindow3D, wx.aui.AuiPaneInfo().CentrePane().
  313. Dockable(False).BestSize((-1,-1)).Name('3d').
  314. CloseButton(False).DestroyOnClose(True).
  315. Layer(0))
  316. self.MapWindow3D.Show()
  317. self.MapWindow3D.ResetViewHistory()
  318. self.MapWindow3D.UpdateView(None)
  319. self.MapWindow3D.overlayActivated.connect(self._activateOverlay)
  320. self.MapWindow3D.overlayHidden.connect(self._hideOverlay)
  321. self.legend.overlayChanged.connect(self.MapWindow3D.UpdateOverlays)
  322. else:
  323. self._switchMapWindow(self.MapWindow3D)
  324. os.environ['GRASS_REGION'] = self.Map.SetRegion(windres = True, windres3 = True)
  325. self.MapWindow3D.GetDisplay().Init()
  326. del os.environ['GRASS_REGION']
  327. # switch from MapWindow to MapWindowGL
  328. self._mgr.GetPane('2d').Hide()
  329. self._mgr.GetPane('3d').Show()
  330. # here was AddNvizTools in lmgr and updating of pages
  331. self.starting3dMode.emit(firstTime=False)
  332. self.MapWindow3D.ResetViewHistory()
  333. self._giface.updateMap.disconnect(self.MapWindow2D.UpdateMap)
  334. self._giface.updateMap.connect(self.MapWindow3D.UpdateMap)
  335. self.MapWindow3D.overlays = self.MapWindow2D.overlays
  336. self.MapWindow3D.textdict = self.MapWindow2D.textdict
  337. # update overlays needs to be called after because getClientSize
  338. # is called during update and it must give reasonable values
  339. wx.CallAfter(self.MapWindow3D.UpdateOverlays)
  340. self.SetStatusText("", 0)
  341. self._mgr.Update()
  342. def Disable3dMode(self):
  343. """Disables 3D mode (NVIZ) in user interface."""
  344. # TODO: this is broken since item is removed but switch is drived by index
  345. if '3D' in self.toolbars['map'].combo.GetString(1):
  346. self.toolbars['map'].combo.Delete(1)
  347. def RemoveNviz(self):
  348. """Restore 2D view"""
  349. try:
  350. self.toolbars['map'].RemoveTool(self.toolbars['map'].rotate)
  351. self.toolbars['map'].RemoveTool(self.toolbars['map'].flyThrough)
  352. except AttributeError:
  353. pass
  354. # update status bar
  355. self.statusbarManager.ShowStatusbarChoiceItemsByClass(self.statusbarItemsHiddenInNviz)
  356. self.statusbarManager.SetMode(UserSettings.Get(group = 'display',
  357. key = 'statusbarMode',
  358. subkey = 'selection'))
  359. self.SetStatusText(_("Please wait, unloading data..."), 0)
  360. # unloading messages from library cause highlight anyway
  361. self._giface.WriteCmdLog(_("Switching back to 2D view mode..."),
  362. notification=Notification.NO_NOTIFICATION)
  363. if self.MapWindow3D:
  364. self.MapWindow3D.OnClose(event = None)
  365. # switch from MapWindowGL to MapWindow
  366. self._mgr.GetPane('2d').Show()
  367. self._mgr.GetPane('3d').Hide()
  368. self._switchMapWindow(self.MapWindow2D)
  369. # here was RemoveNvizTools form lmgr
  370. self.ending3dMode.emit()
  371. try:
  372. self.MapWindow2D.overlays = self.MapWindow3D.overlays
  373. self.MapWindow2D.textdict = self.MapWindow3D.textdict
  374. except AttributeError:
  375. pass
  376. # TODO: here we end because self.MapWindow3D is None for a while
  377. self._giface.updateMap.disconnect(self.MapWindow3D.UpdateMap)
  378. self._giface.updateMap.connect(self.MapWindow2D.UpdateMap)
  379. self.legend.overlayChanged.disconnect(self.MapWindow3D.UpdateOverlays)
  380. self.MapWindow.UpdateMap()
  381. self._mgr.Update()
  382. self.GetMapToolbar().SelectDefault()
  383. def AddToolbar(self, name, fixed = False):
  384. """Add defined toolbar to the window
  385. Currently recognized toolbars are:
  386. - 'map' - basic map toolbar
  387. - 'vdigit' - vector digitizer
  388. :param name: toolbar to add
  389. :param fixed: fixed toolbar
  390. """
  391. # default toolbar
  392. if name == "map":
  393. self.toolbars['map'] = MapToolbar(self, toolSwitcher=self._toolSwitcher)
  394. self._mgr.AddPane(self.toolbars['map'],
  395. wx.aui.AuiPaneInfo().
  396. Name("maptoolbar").Caption(_("Map Toolbar")).
  397. ToolbarPane().Top().Name('mapToolbar').
  398. LeftDockable(False).RightDockable(False).
  399. BottomDockable(False).TopDockable(True).
  400. CloseButton(False).Layer(2).
  401. BestSize((self.toolbars['map'].GetBestSize())))
  402. # vector digitizer
  403. elif name == "vdigit":
  404. self.toolbars['map'].combo.SetValue(_("Digitize"))
  405. self._addToolbarVDigit()
  406. if fixed:
  407. self.toolbars['map'].combo.Disable()
  408. self._mgr.Update()
  409. def RemoveToolbar (self, name):
  410. """Removes defined toolbar from the window
  411. .. todo::
  412. Only hide, activate by calling AddToolbar()
  413. """
  414. # cannot hide main toolbar
  415. if name == "map":
  416. return
  417. self._mgr.DetachPane(self.toolbars[name])
  418. self._toolSwitcher.RemoveToolbarFromGroup('mouseUse', self.toolbars[name])
  419. self.toolbars[name].Destroy()
  420. self.toolbars.pop(name)
  421. if name == 'vdigit':
  422. self._mgr.GetPane('vdigit').Hide()
  423. self._mgr.GetPane('2d').Show()
  424. self._switchMapWindow(self.MapWindow2D)
  425. self.toolbars['map'].combo.SetValue(_("2D view"))
  426. self.toolbars['map'].Enable2D(True)
  427. self._mgr.Update()
  428. def IsPaneShown(self, name):
  429. """Check if pane (toolbar, mapWindow ...) of given name is currently shown"""
  430. if self._mgr.GetPane(name).IsOk():
  431. return self._mgr.GetPane(name).IsShown()
  432. return False
  433. def RemoveQueryLayer(self):
  434. """Removes temporary map layers (queries)"""
  435. qlayer = self.GetMap().GetListOfLayers(name = globalvar.QUERYLAYER)
  436. for layer in qlayer:
  437. self.GetMap().DeleteLayer(layer)
  438. def OnRender(self, event):
  439. """Re-render map composition (each map layer)
  440. """
  441. self.RemoveQueryLayer()
  442. # deselect features in vdigit
  443. if self.GetToolbar('vdigit'):
  444. if self.MapWindow.digit:
  445. self.MapWindow.digit.GetDisplay().SetSelected([])
  446. self.MapWindow.UpdateMap(render = True, renderVector = True)
  447. else:
  448. self.MapWindow.UpdateMap(render = True)
  449. # update statusbar
  450. self.StatusbarUpdate()
  451. def OnPointer(self, event):
  452. """Pointer button clicked
  453. """
  454. self.MapWindow.SetModePointer()
  455. if self.GetToolbar('vdigit'):
  456. self.toolbars['vdigit'].action['id'] = -1
  457. self.toolbars['vdigit'].action['desc']=''
  458. def OnRotate(self, event):
  459. """Rotate 3D view
  460. """
  461. self.MapWindow.mouse['use'] = "rotate"
  462. # change the cursor
  463. self.MapWindow.SetNamedCursor('hand')
  464. def OnFlyThrough(self, event):
  465. """Fly-through mode
  466. """
  467. self.MapWindow.mouse['use'] = "fly"
  468. # change the cursor
  469. self.MapWindow.SetNamedCursor('hand')
  470. self.MapWindow.SetFocus()
  471. def SaveToFile(self, event):
  472. """Save map to image
  473. """
  474. filetype, ltype = self._prepareSaveToFile()
  475. if not ltype:
  476. return
  477. # get size
  478. dlg = ImageSizeDialog(self)
  479. dlg.CentreOnParent()
  480. if dlg.ShowModal() != wx.ID_OK:
  481. dlg.Destroy()
  482. return
  483. width, height = dlg.GetValues()
  484. dlg.Destroy()
  485. # get filename
  486. dlg = wx.FileDialog(parent = self,
  487. message = _("Choose a file name to save the image "
  488. "(no need to add extension)"),
  489. wildcard = filetype,
  490. style = wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
  491. if dlg.ShowModal() == wx.ID_OK:
  492. path = dlg.GetPath()
  493. if not path:
  494. dlg.Destroy()
  495. return
  496. base, ext = os.path.splitext(path)
  497. fileType = ltype[dlg.GetFilterIndex()]['type']
  498. extType = ltype[dlg.GetFilterIndex()]['ext']
  499. if ext != extType:
  500. path = base + '.' + extType
  501. self.MapWindow.SaveToFile(path, fileType,
  502. width, height)
  503. dlg.Destroy()
  504. def DOutFile(self, command):
  505. """Saves map to image by running d.out.file from gui or d.mon.
  506. Command is expected to be validated by parser.
  507. """
  508. filetype, ltype = self._prepareSaveToFile()
  509. if not ltype:
  510. return
  511. width, height = self.MapWindow.GetClientSize()
  512. for param in command[1:]:
  513. p, val = param.split('=')
  514. if p == 'format': # must be there
  515. if self.IsPaneShown('3d'):
  516. extType = 'ppm'
  517. else:
  518. extType = val
  519. if p == 'output': # must be there
  520. name = val
  521. elif p == 'size':
  522. width, height = val.split(',')
  523. base, ext = os.path.splitext(name)
  524. if not ext:
  525. name = base + '.' + extType
  526. elif ext[1:] != extType:
  527. extType = ext[1:]
  528. if self.IsPaneShown('3d'):
  529. bitmapType = 'ppm'
  530. else:
  531. bitmapType = wx.BITMAP_TYPE_PNG # default type
  532. for each in ltype:
  533. if each['ext'] == extType:
  534. bitmapType = each['type']
  535. break
  536. self.MapWindow.SaveToFile(name, bitmapType, int(width), int(height))
  537. def DOutFileOptData(self, dcmd, layer, params, propwin):
  538. """Dummy function which is called when d.out.file is called
  539. and returns parsed and validated command which is then passed
  540. to DOutFile method."""
  541. if not dcmd:
  542. return
  543. self.DOutFile(dcmd)
  544. def DToRast(self, command):
  545. """Saves currently loaded composition of layers as a raster map.
  546. """
  547. if self.IsPaneShown('3d'):
  548. self._giface.WriteError(_('d.to.rast can be used only in 2D mode.'))
  549. return
  550. outputRaster = None
  551. overwrite = False
  552. for param in command[1:]:
  553. try:
  554. p, val = param.split('=')
  555. if p == 'output':
  556. outputRaster = val
  557. except ValueError:
  558. if param.startswith('--overwrite'):
  559. overwrite = True
  560. if not outputRaster:
  561. return
  562. # output file as PNG
  563. tmpName = 'd_to_rast_tmp'
  564. pngFile = grass.tempfile(create=False) + '.png'
  565. dOutFileCmd = ['d.out.file', 'output=' + pngFile, 'format=png']
  566. self.DOutFile(dOutFileCmd)
  567. # import back as red, green, blue rasters
  568. returncode, messages = RunCommand('r.in.gdal', flags='o', input=pngFile, output=tmpName,
  569. quiet=True, overwrite=overwrite, getErrorMsg=True)
  570. if not returncode == 0:
  571. self._giface.WriteError(_('Failed to run d.to.rast:\n') + messages)
  572. return
  573. # set region for composite
  574. grass.use_temp_region()
  575. returncode, messages = RunCommand('g.region', raster=tmpName + '.red',
  576. quiet=True, getErrorMsg=True)
  577. if not returncode == 0:
  578. grass.del_temp_region()
  579. self._giface.WriteError(_('Failed to run d.to.rast:\n') + messages)
  580. return
  581. # composite
  582. returncode, messages = RunCommand('r.composite', red=tmpName + '.red',
  583. green=tmpName + '.green', blue=tmpName + '.blue',
  584. output=outputRaster, quiet=True,
  585. overwrite=overwrite, getErrorMsg=True)
  586. grass.del_temp_region()
  587. RunCommand('g.remove', type='raster', flags='f', quiet=True,
  588. name=[tmpName + '.red', tmpName + '.green', tmpName + '.blue'])
  589. if not returncode == 0:
  590. self._giface.WriteError(_('Failed to run d.to.rast:\n') + messages)
  591. grass.try_remove(pngFile)
  592. return
  593. # alignExtent changes only region variable
  594. oldRegion = self.GetMap().GetCurrentRegion().copy()
  595. self.GetMap().AlignExtentFromDisplay()
  596. region = self.GetMap().GetCurrentRegion().copy()
  597. self.GetMap().region.update(oldRegion)
  598. RunCommand('r.region', map=outputRaster, n=region['n'], s=region['s'],
  599. e=region['e'], w=region['w'], quiet=True)
  600. grass.try_remove(pngFile)
  601. def DToRastOptData(self, dcmd, layer, params, propwin):
  602. """Dummy function which is called when d.to.rast is called
  603. and returns parsed and validated command which is then passed
  604. to DToRast method."""
  605. if not dcmd:
  606. return
  607. self.DToRast(dcmd)
  608. def _prepareSaveToFile(self):
  609. """Get wildcards and format extensions."""
  610. if self.IsPaneShown('3d'):
  611. filetype = "TIF file (*.tif)|*.tif|PPM file (*.ppm)|*.ppm"
  612. ltype = [{ 'ext' : 'tif', 'type' : 'tif' },
  613. { 'ext' : 'ppm', 'type' : 'ppm' }]
  614. else:
  615. img = self.MapWindow.img
  616. if not img:
  617. GMessage(parent = self,
  618. message = _("Nothing to render (empty map). Operation canceled."))
  619. return None, None
  620. filetype, ltype = GetImageHandlers(img)
  621. return filetype, ltype
  622. def PrintMenu(self, event):
  623. """
  624. Print options and output menu for map display
  625. """
  626. printmenu = wx.Menu()
  627. # Add items to the menu
  628. setup = wx.MenuItem(printmenu, wx.ID_ANY, _('Page setup'))
  629. printmenu.AppendItem(setup)
  630. self.Bind(wx.EVT_MENU, self.printopt.OnPageSetup, setup)
  631. preview = wx.MenuItem(printmenu, wx.ID_ANY, _('Print preview'))
  632. printmenu.AppendItem(preview)
  633. self.Bind(wx.EVT_MENU, self.printopt.OnPrintPreview, preview)
  634. doprint = wx.MenuItem(printmenu, wx.ID_ANY, _('Print display'))
  635. printmenu.AppendItem(doprint)
  636. self.Bind(wx.EVT_MENU, self.printopt.OnDoPrint, doprint)
  637. # Popup the menu. If an item is selected then its handler
  638. # will be called before PopupMenu returns.
  639. self.PopupMenu(printmenu)
  640. printmenu.Destroy()
  641. def OnCloseWindow(self, event):
  642. """Window closed.
  643. Also close associated layer tree page
  644. """
  645. Debug.msg(2, "MapFrame.OnCloseWindow(): function starts")
  646. pgnum = None
  647. self.Map.Clean()
  648. # close edited map and 3D tools properly
  649. if self.GetToolbar('vdigit'):
  650. maplayer = self.toolbars['vdigit'].GetLayer()
  651. if maplayer:
  652. self.toolbars['vdigit'].OnExit()
  653. if self.IsPaneShown('3d'):
  654. self.RemoveNviz()
  655. if not self._layerManager:
  656. self.Destroy()
  657. elif self.page:
  658. pgnum = self.layerbook.GetPageIndex(self.page)
  659. if pgnum > -1:
  660. self.layerbook.DeletePage(pgnum)
  661. Debug.msg(2, "MapFrame.OnCloseWindow(): function ends")
  662. def Query(self, x, y):
  663. """Query selected layers.
  664. :param x,y: coordinates
  665. """
  666. if self._vectQueryLayers or self._rastQueryLayers:
  667. rast = self._rastQueryLayers
  668. vect = self._vectQueryLayers
  669. else:
  670. layers = self._giface.GetLayerList().GetSelectedLayers(checkedOnly=False)
  671. rast = []
  672. vect = []
  673. for layer in layers:
  674. name, found = GetLayerNameFromCmd(layer.cmd)
  675. if not found:
  676. continue
  677. ltype = layer.maplayer.GetType()
  678. if ltype == 'raster':
  679. rast.append(name)
  680. elif ltype in ('rgb', 'his'):
  681. for iname in name.split('\n'):
  682. rast.append(iname)
  683. elif ltype in ('vector', 'thememap', 'themechart'):
  684. vect.append(name)
  685. if vect:
  686. # check for vector maps open to be edited
  687. digitToolbar = self.GetToolbar('vdigit')
  688. if digitToolbar:
  689. lmap = digitToolbar.GetLayer().GetName()
  690. for name in vect:
  691. if lmap == name:
  692. self._giface.WriteWarning(_("Vector map <%s> "
  693. "opened for editing - skipped.") % lmap)
  694. vect.remove(name)
  695. if not (rast + vect):
  696. GMessage(parent = self,
  697. message = _('No raster or vector map layer selected for querying.'))
  698. return
  699. # set query snap distance for v.what at map unit equivalent of 10 pixels
  700. qdist = 10.0 * ((self.Map.region['e'] - self.Map.region['w']) / self.Map.width)
  701. # TODO: replace returning None by exception or so
  702. try:
  703. east, north = self.MapWindow.Pixel2Cell((x, y))
  704. except TypeError:
  705. return
  706. if not self.IsPaneShown('3d'):
  707. self.QueryMap(east, north, qdist, rast, vect)
  708. else:
  709. if rast:
  710. self.MapWindow.QuerySurface(x, y)
  711. if vect:
  712. self.QueryMap(east, north, qdist, rast = [], vect = vect)
  713. def SetQueryLayersAndActivate(self, ltype, maps):
  714. """Activate query mode and set layers to query.
  715. This method is used for querying in d.mon using d.what.rast/vect"""
  716. self.toolbars['map'].SelectTool(self.toolbars['map'].query)
  717. if ltype == 'vector':
  718. self._vectQueryLayers = maps
  719. elif ltype == 'raster':
  720. self._rastQueryLayers = maps
  721. def QueryMap(self, east, north, qdist, rast, vect):
  722. """Query raster or vector map layers by r/v.what
  723. :param east,north: coordinates
  724. :param qdist: query distance
  725. :param rast: raster map names
  726. :param vect: vector map names
  727. """
  728. Debug.msg(1, "QueryMap(): raster=%s vector=%s" % (','.join(rast),
  729. ','.join(vect)))
  730. # use display region settings instead of computation region settings
  731. self.tmpreg = os.getenv("GRASS_REGION")
  732. os.environ["GRASS_REGION"] = self.Map.SetRegion(windres = False)
  733. rastQuery = []
  734. vectQuery = []
  735. if rast:
  736. rastQuery = grass.raster_what(map=rast, coord=(east, north))
  737. if vect:
  738. encoding = UserSettings.Get(group='atm', key='encoding', subkey='value')
  739. try:
  740. vectQuery = grass.vector_what(map=vect, coord=(east, north), distance=qdist,
  741. encoding=encoding)
  742. except grass.ScriptError:
  743. GError(parent=self,
  744. message=_("Failed to query vector map(s) <{maps}>. "
  745. "Check database settings and topology.").format(maps=','.join(vect)))
  746. self._QueryMapDone()
  747. if 'Id' in vectQuery:
  748. self._queryHighlight(vectQuery)
  749. result = rastQuery + vectQuery
  750. result = PrepareQueryResults(coordinates = (east, north), result = result)
  751. if self.dialogs['query']:
  752. self.dialogs['query'].Raise()
  753. self.dialogs['query'].SetData(result)
  754. else:
  755. self.dialogs['query'] = QueryDialog(parent = self, data = result)
  756. self.dialogs['query'].Bind(wx.EVT_CLOSE, self._oncloseQueryDialog)
  757. self.dialogs['query'].redirectOutput.connect(self._onRedirectQueryOutput)
  758. self.dialogs['query'].Show()
  759. def _oncloseQueryDialog(self, event):
  760. self.dialogs['query'] = None
  761. self._vectQueryLayers = []
  762. self._rastQueryLayers = []
  763. event.Skip()
  764. def _onRedirectQueryOutput(self, output, style='log'):
  765. """Writes query output into console"""
  766. if style == 'log':
  767. self._giface.WriteLog(output, notification=Notification.MAKE_VISIBLE)
  768. elif style == 'cmd':
  769. self._giface.WriteCmdLog(output)
  770. def _queryHighlight(self, vectQuery):
  771. """Highlight category from query."""
  772. cats = name = None
  773. for res in vectQuery:
  774. cats = {res['Layer']: [res['Category']]}
  775. name = res['Map']
  776. try:
  777. qlayer = self.Map.GetListOfLayers(name = globalvar.QUERYLAYER)[0]
  778. except IndexError:
  779. qlayer = None
  780. if not (cats and name):
  781. if qlayer:
  782. self.Map.DeleteLayer(qlayer)
  783. self.MapWindow.UpdateMap(render = False, renderVector = False)
  784. return
  785. if not self.IsPaneShown('3d') and self.IsAutoRendered():
  786. # highlight feature & re-draw map
  787. if qlayer:
  788. qlayer.SetCmd(self.AddTmpVectorMapLayer(name, cats,
  789. useId = False,
  790. addLayer = False))
  791. else:
  792. qlayer = self.AddTmpVectorMapLayer(name, cats, useId = False)
  793. # set opacity based on queried layer
  794. # TODO fix
  795. # opacity = layer.maplayer.GetOpacity(float = True)
  796. # qlayer.SetOpacity(opacity)
  797. self.MapWindow.UpdateMap(render = False, renderVector = False)
  798. def _QueryMapDone(self):
  799. """Restore settings after querying (restore GRASS_REGION)
  800. """
  801. if hasattr(self, "tmpreg"):
  802. if self.tmpreg:
  803. os.environ["GRASS_REGION"] = self.tmpreg
  804. elif 'GRASS_REGION' in os.environ:
  805. del os.environ["GRASS_REGION"]
  806. elif 'GRASS_REGION' in os.environ:
  807. del os.environ["GRASS_REGION"]
  808. if hasattr(self, "tmpreg"):
  809. del self.tmpreg
  810. def OnQuery(self, event):
  811. """Query tools menu"""
  812. self.MapWindow.mouse['use'] = "query"
  813. self.MapWindow.mouse['box'] = "point"
  814. self.MapWindow.zoomtype = 0
  815. # change the cursor
  816. self.MapWindow.SetNamedCursor('cross')
  817. def AddTmpVectorMapLayer(self, name, cats, useId = False, addLayer = True):
  818. """Add temporal vector map layer to map composition
  819. :param name: name of map layer
  820. :param useId: use feature id instead of category
  821. """
  822. # color settings from ATM
  823. color = UserSettings.Get(group = 'atm', key = 'highlight', subkey = 'color')
  824. colorStr = str(color[0]) + ":" + \
  825. str(color[1]) + ":" + \
  826. str(color[2])
  827. # icon used in vector display and its size
  828. icon = ''
  829. size = 0
  830. # here we know that there is one selected layer and it is vector
  831. vparam = self._giface.GetLayerList().GetSelectedLayers()[0].cmd
  832. for p in vparam:
  833. if '=' in p:
  834. parg,pval = p.split('=', 1)
  835. if parg == 'icon': icon = pval
  836. elif parg == 'size': size = float(pval)
  837. pattern = ["d.vect",
  838. "map=%s" % name,
  839. "color=%s" % colorStr,
  840. "fill_color=%s" % colorStr,
  841. "width=%d" % UserSettings.Get(group = 'atm', key = 'highlight', subkey = 'width')]
  842. if icon != '':
  843. pattern.append('icon=%s' % icon)
  844. if size > 0:
  845. pattern.append('size=%i' % size)
  846. if useId:
  847. cmd = pattern
  848. cmd.append('-i')
  849. cmd.append('cats=%s' % str(cats))
  850. else:
  851. cmd = []
  852. for layer in cats.keys():
  853. cmd.append(copy.copy(pattern))
  854. lcats = cats[layer]
  855. cmd[-1].append("layer=%d" % layer)
  856. cmd[-1].append("cats=%s" % ListOfCatsToRange(lcats))
  857. if addLayer:
  858. if useId:
  859. return self.Map.AddLayer(ltype = 'vector', name = globalvar.QUERYLAYER, command = cmd,
  860. active = True, hidden = True, opacity = 1.0)
  861. else:
  862. return self.Map.AddLayer(ltype = 'command', name = globalvar.QUERYLAYER, command = cmd,
  863. active = True, hidden = True, opacity = 1.0)
  864. else:
  865. return cmd
  866. def OnMeasureDistance(self, event):
  867. self._onMeasure(MeasureDistanceController)
  868. def OnMeasureArea(self, event):
  869. self._onMeasure(MeasureAreaController)
  870. def _onMeasure(self, controller):
  871. """Starts measurement mode.
  872. :param controller: measurement class (MeasureDistanceController, MeasureAreaController)
  873. """
  874. self.measureController = controller(self._giface, mapWindow=self.GetMapWindow())
  875. # assure that the mode is ended and lines are cleared whenever other tool is selected
  876. self._toolSwitcher.toggleToolChanged.connect(lambda: self.measureController.Stop())
  877. self.measureController.Start()
  878. def OnProfile(self, event):
  879. """Launch profile tool
  880. """
  881. rasters = []
  882. layers = self._giface.GetLayerList().GetSelectedLayers()
  883. for layer in layers:
  884. if layer.type == 'raster':
  885. rasters.append(layer.maplayer.name)
  886. self.Profile(rasters=rasters)
  887. def Profile(self, rasters=None):
  888. """Launch profile tool"""
  889. self.profileController = ProfileController(self._giface,
  890. mapWindow=self.GetMapWindow())
  891. win = ProfileFrame(parent=self, rasterList=rasters,
  892. units=self.Map.projinfo['units'],
  893. controller=self.profileController)
  894. win.Show()
  895. # Open raster select dialog to make sure that a raster (and
  896. # the desired raster) is selected to be profiled
  897. win.OnSelectRaster(None)
  898. def OnHistogramPyPlot(self, event):
  899. """Init PyPlot histogram display canvas and tools
  900. """
  901. raster = []
  902. for layer in self._giface.GetLayerList().GetSelectedLayers():
  903. if layer.maplayer.GetType() == 'raster':
  904. raster.append(layer.maplayer.GetName())
  905. win = HistogramPlotFrame(parent = self, rasterList = raster)
  906. win.CentreOnParent()
  907. win.Show()
  908. def OnScatterplot(self, event):
  909. """Init PyPlot scatterplot display canvas and tools
  910. """
  911. raster = []
  912. for layer in self._giface.GetLayerList().GetSelectedLayers():
  913. if layer.maplayer.GetType() == 'raster':
  914. raster.append(layer.maplayer.GetName())
  915. win = ScatterFrame(parent = self, rasterList = raster)
  916. win.CentreOnParent()
  917. win.Show()
  918. # Open raster select dialog to make sure that at least 2 rasters (and the desired rasters)
  919. # are selected to be plotted
  920. win.OnSelectRaster(None)
  921. def OnHistogram(self, event):
  922. """Init histogram display canvas and tools
  923. """
  924. win = HistogramFrame(self, giface=self._giface)
  925. win.CentreOnParent()
  926. win.Show()
  927. win.Refresh()
  928. win.Update()
  929. def _activateOverlay(self, overlayId):
  930. """Launch decoration dialog according to overlay id.
  931. :param overlayId: id of overlay
  932. """
  933. if overlayId > 100:
  934. self.OnAddText(None)
  935. elif overlayId == 0:
  936. self.AddLegend(cmd=self.legend.cmd, showDialog=True)
  937. elif overlayId == 1:
  938. self.AddBarscale(showDialog=True)
  939. elif overlayId == 2:
  940. self.AddArrow(showDialog=True)
  941. def _hideOverlay(self, overlayId):
  942. """Hide overlay.
  943. :param overlayId: id of overlay
  944. """
  945. self.decorations[overlayId].Hide()
  946. def AddBarscale(self, cmd=None, showDialog=None):
  947. """Handler for scale bar map decoration menu selection."""
  948. if self.IsPaneShown('3d'):
  949. self.MapWindow3D.SetDrawScalebar((70, 70))
  950. return
  951. if self.barscale.IsShown() and showDialog is None:
  952. self.barscale.Hide()
  953. return
  954. if cmd:
  955. self.barscale.cmd = cmd
  956. if not showDialog:
  957. self.barscale.Show()
  958. return
  959. # Decoration overlay control dialog
  960. if self.barscale.dialog:
  961. if self.barscale.dialog.IsShown():
  962. self.barscale.dialog.SetFocus()
  963. self.barscale.dialog.Raise()
  964. else:
  965. self.barscale.dialog.Show()
  966. else:
  967. # If location is latlon, only display north arrow (scale won't work)
  968. # proj = self.Map.projinfo['proj']
  969. # if proj == 'll':
  970. # barcmd = 'd.barscale -n'
  971. # else:
  972. # barcmd = 'd.barscale'
  973. # decoration overlay control dialog
  974. GUI(parent=self, giface=self._giface, show=True,
  975. modal=False).ParseCommand(self.barscale.cmd,
  976. completed=(self.barscale.GetOptData, None, None))
  977. self.MapWindow.mouse['use'] = 'pointer'
  978. def AddLegend(self, cmd=None, showDialog=None):
  979. """Handler for legend map decoration menu selection."""
  980. if self.legend.IsShown() and showDialog is None:
  981. self.legend.Hide()
  982. return
  983. if cmd:
  984. self.legend.cmd = cmd
  985. else:
  986. layers = self._giface.GetLayerList().GetSelectedLayers()
  987. for layer in layers:
  988. if layer.type == 'raster':
  989. isMap = False
  990. # replace map
  991. for i, legendParam in enumerate(self.legend.cmd[1:]):
  992. idx = i + 1
  993. param_val = legendParam.split('=')
  994. if len(param_val) != 2:
  995. continue
  996. param, val = param_val
  997. if param == 'raster':
  998. self.legend.cmd[idx] = 'raster={rast}'.format(rast=layer.maplayer.name)
  999. isMap = True
  1000. elif param in ('use', 'range'):
  1001. # clear range or use to avoid problems
  1002. del self.legend.cmd[idx]
  1003. if not isMap: # for the first time
  1004. self.legend.cmd.append('raster=%s' % layer.maplayer.name)
  1005. break
  1006. if not showDialog and self.legend.CmdIsValid():
  1007. self.legend.Show()
  1008. return
  1009. # Decoration overlay control dialog
  1010. # always create new one to avoid problem when switching between maps
  1011. if self.legend.dialog:
  1012. if self.legend.dialog.IsShown():
  1013. self.legend.dialog.SetFocus()
  1014. self.legend.dialog.Raise()
  1015. else:
  1016. self.legend.dialog.Destroy()
  1017. self.legend.dialog = None
  1018. if not self.legend.dialog:
  1019. GUI(parent=self, giface=self._giface, show=True,
  1020. modal=False).ParseCommand(self.legend.cmd,
  1021. completed=(self.legend.GetOptData, None, None))
  1022. self.MapWindow.mouse['use'] = 'pointer'
  1023. def AddArrow(self, cmd=None, showDialog=None):
  1024. """Handler for north arrow menu selection."""
  1025. if self.IsPaneShown('3d'):
  1026. # here was opening of appearance page of nviz notebook
  1027. # but now moved to MapWindow3D where are other problematic nviz calls
  1028. self.MapWindow3D.SetDrawArrow((70, 70))
  1029. return
  1030. if self.arrow.IsShown() and showDialog is None:
  1031. self.arrow.Hide()
  1032. return
  1033. if cmd:
  1034. self.arrow.cmd = cmd
  1035. if not showDialog:
  1036. self.arrow.Show()
  1037. return
  1038. # Decoration overlay control dialog
  1039. if self.arrow.dialog:
  1040. if self.arrow.dialog.IsShown():
  1041. self.arrow.dialog.SetFocus()
  1042. self.arrow.dialog.Raise()
  1043. else:
  1044. self.arrow.dialog.Show()
  1045. else:
  1046. GUI(parent=self, giface=self._giface, show=True,
  1047. modal=False).ParseCommand(self.arrow.cmd,
  1048. completed=(self.arrow.GetOptData, None, None))
  1049. self.MapWindow.mouse['use'] = 'pointer'
  1050. def OnAddText(self, event):
  1051. """Handler for text decoration menu selection.
  1052. """
  1053. if self.MapWindow.dragid > -1:
  1054. id = self.MapWindow.dragid
  1055. self.MapWindow.dragid = -1
  1056. else:
  1057. # index for overlay layer in render
  1058. if len(self.MapWindow.textdict.keys()) > 0:
  1059. id = max(self.MapWindow.textdict.keys()) + 1
  1060. else:
  1061. id = 101
  1062. self.dialogs['text'] = TextLayerDialog(parent = self, ovlId = id,
  1063. title = _('Add text layer'),
  1064. size = (400, 200))
  1065. self.dialogs['text'].CenterOnParent()
  1066. # If OK button pressed in decoration control dialog
  1067. if self.dialogs['text'].ShowModal() == wx.ID_OK:
  1068. text = self.dialogs['text'].GetValues()['text']
  1069. active = self.dialogs['text'].GetValues()['active']
  1070. # delete object if it has no text or is not active
  1071. if text == '' or active == False:
  1072. try:
  1073. self.MapWindow2D.pdc.ClearId(id)
  1074. self.MapWindow2D.pdc.RemoveId(id)
  1075. del self.MapWindow.textdict[id]
  1076. if self.IsPaneShown('3d'):
  1077. self.MapWindow3D.UpdateOverlays()
  1078. self.MapWindow.UpdateMap()
  1079. else:
  1080. self.MapWindow2D.UpdateMap(render = False, renderVector = False)
  1081. except:
  1082. pass
  1083. return
  1084. self.MapWindow.textdict[id] = self.dialogs['text'].GetValues()
  1085. if self.IsPaneShown('3d'):
  1086. self.MapWindow3D.UpdateOverlays()
  1087. self.MapWindow3D.UpdateMap()
  1088. else:
  1089. self.MapWindow2D.pdc.ClearId(id)
  1090. self.MapWindow2D.pdc.SetId(id)
  1091. self.MapWindow2D.UpdateMap(render = False, renderVector = False)
  1092. self.MapWindow.mouse['use'] = 'pointer'
  1093. def GetOptData(self, dcmd, type, params, propwin):
  1094. """Callback method for decoration overlay command generated by
  1095. dialog created in menuform.py
  1096. """
  1097. # Reset comand and rendering options in render.Map. Always render decoration.
  1098. # Showing/hiding handled by PseudoDC
  1099. self.Map.ChangeOverlay(ovltype = type, type = 'overlay', name = '', command = dcmd,
  1100. active = True, render = False)
  1101. self.params[type] = params
  1102. self.propwin[type] = propwin
  1103. def OnZoomToMap(self, event):
  1104. """Set display extents to match selected raster (including
  1105. NULLs) or vector map.
  1106. """
  1107. Debug.msg(3, "MapFrame.OnZoomToMap()")
  1108. layers = None
  1109. if self.IsStandalone():
  1110. layers = self.MapWindow.GetMap().GetListOfLayers(active = False)
  1111. self.MapWindow.ZoomToMap(layers = layers)
  1112. def OnZoomToRaster(self, event):
  1113. """Set display extents to match selected raster map (ignore NULLs)
  1114. """
  1115. self.MapWindow.ZoomToMap(ignoreNulls = True)
  1116. def OnZoomToSaved(self, event):
  1117. """Set display geometry to match extents in
  1118. saved region file
  1119. """
  1120. self.MapWindow.SetRegion(zoomOnly=True)
  1121. def OnSetDisplayToWind(self, event):
  1122. """Set computational region (WIND file) to match display
  1123. extents
  1124. """
  1125. self.MapWindow.DisplayToWind()
  1126. def OnSetWindToRegion(self, event):
  1127. """Set computational region (WIND file) from named region
  1128. file
  1129. """
  1130. self.MapWindow.SetRegion(zoomOnly=False)
  1131. def OnSetExtentToWind(self, event):
  1132. """Set compulational region extent interactively"""
  1133. self.MapWindow.SetModeDrawRegion()
  1134. def OnSaveDisplayRegion(self, event):
  1135. """Save display extents to named region file.
  1136. """
  1137. self.MapWindow.SaveRegion(display = True)
  1138. def OnSaveWindRegion(self, event):
  1139. """Save computational region to named region file.
  1140. """
  1141. self.MapWindow.SaveRegion(display = False)
  1142. def OnZoomMenu(self, event):
  1143. """Popup Zoom menu
  1144. """
  1145. zoommenu = wx.Menu()
  1146. for label, handler in ((_('Zoom to default region'), self.OnZoomToDefault),
  1147. (_('Zoom to saved region'), self.OnZoomToSaved),
  1148. (None, None),
  1149. (_('Set computational region extent from display'), self.OnSetDisplayToWind),
  1150. (_('Set computational region extent interactively'), self.OnSetExtentToWind),
  1151. (_('Set computational region from named region'), self.OnSetWindToRegion),
  1152. (None, None),
  1153. (_('Save display geometry to named region'), self.OnSaveDisplayRegion),
  1154. (_('Save computational region to named region'), self.OnSaveWindRegion)):
  1155. if label:
  1156. mid = wx.MenuItem(zoommenu, wx.ID_ANY, label)
  1157. zoommenu.AppendItem(mid)
  1158. self.Bind(wx.EVT_MENU, handler, mid)
  1159. else:
  1160. zoommenu.AppendSeparator()
  1161. # Popup the menu. If an item is selected then its handler will
  1162. # be called before PopupMenu returns.
  1163. self.PopupMenu(zoommenu)
  1164. zoommenu.Destroy()
  1165. def SetProperties(self, render = False, mode = 0, showCompExtent = False,
  1166. constrainRes = False, projection = False, alignExtent = True):
  1167. """Set properies of map display window"""
  1168. self.mapWindowProperties.autoRender = render
  1169. self.statusbarManager.SetMode(mode)
  1170. self.StatusbarUpdate()
  1171. self.mapWindowProperties.showRegion = showCompExtent
  1172. self.mapWindowProperties.alignExtent = alignExtent
  1173. self.mapWindowProperties.resolution = constrainRes
  1174. self.SetProperty('projection', projection)
  1175. def IsStandalone(self):
  1176. """Check if Map display is standalone
  1177. .. deprecated:: 7.0
  1178. """
  1179. # TODO: once it is removed from 2 places in vdigit it can be deleted
  1180. # here and also in base class and other classes in the tree (hopefully)
  1181. # and one place here still uses IsStandalone
  1182. Debug.msg(1, "MapFrame.IsStandalone(): Method IsStandalone is"
  1183. "depreciated, use some general approach instead such as"
  1184. " Signals or giface")
  1185. if self._layerManager:
  1186. return False
  1187. return True
  1188. def GetLayerManager(self):
  1189. """Get reference to Layer Manager
  1190. :return: window reference
  1191. :return: None (if standalone)
  1192. .. deprecated:: 7.0
  1193. """
  1194. Debug.msg(1, "MapFrame.GetLayerManager(): Method GetLayerManager is"
  1195. "depreciated, use some general approach instead such as"
  1196. " Signals or giface")
  1197. return self._layerManager
  1198. def GetMapToolbar(self):
  1199. """Returns toolbar with zooming tools"""
  1200. return self.toolbars['map']
  1201. def OnVNet(self, event):
  1202. """Dialog for v.net* modules
  1203. """
  1204. if self.dialogs['vnet']:
  1205. self.dialogs['vnet'].Raise()
  1206. return
  1207. from vnet.dialogs import VNETDialog
  1208. self.dialogs['vnet'] = VNETDialog(parent=self, giface=self._giface)
  1209. self.dialogs['vnet'].CenterOnScreen()
  1210. self.dialogs['vnet'].Show()
  1211. def ResetPointer(self):
  1212. """Sets pointer mode.
  1213. Sets pointer and toggles it (e.g. after unregistration of mouse
  1214. handler).
  1215. """
  1216. self.GetMapToolbar().SelectDefault()
  1217. def _switchMapWindow(self, map_win):
  1218. """Notifies activated and disactivated map_wins."""
  1219. self.MapWindow.DisactivateWin()
  1220. map_win.ActivateWin()
  1221. self.MapWindow = map_win