frame.py 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742
  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::MapPanel
  8. (C) 2006-2016 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> (SingleMapPanel, handlers support)
  15. @author Anna Kratochvilova <kratochanna gmail.com> (SingleMapPanel)
  16. @author Stepan Turek <stepan.turek seznam.cz> (handlers support)
  17. """
  18. import os
  19. import copy
  20. from core import globalvar
  21. import wx
  22. import wx.aui
  23. from mapdisp.toolbars import MapToolbar, NvizIcons
  24. from mapdisp.gprint import PrintOptions
  25. from core.gcmd import GError, GMessage, RunCommand
  26. from core.utils import ListOfCatsToRange, GetLayerNameFromCmd
  27. from gui_core.dialogs import GetImageHandlers, ImageSizeDialog
  28. from core.debug import Debug
  29. from core.settings import UserSettings
  30. from gui_core.mapdisp import SingleMapPanel, FrameMixin
  31. from gui_core.query import QueryDialog, PrepareQueryResults
  32. from mapwin.buffered import BufferedMapWindow
  33. from mapwin.decorations import (
  34. LegendController,
  35. BarscaleController,
  36. ArrowController,
  37. DtextController,
  38. LegendVectController,
  39. )
  40. from mapwin.analysis import (
  41. ProfileController,
  42. MeasureDistanceController,
  43. MeasureAreaController,
  44. )
  45. from gui_core.forms import GUI
  46. from core.giface import Notification
  47. from gui_core.vselect import VectorSelectBase, VectorSelectHighlighter
  48. from gui_core.wrap import Menu
  49. from mapdisp import statusbar as sb
  50. import grass.script as grass
  51. from grass.pydispatch.signal import Signal
  52. class MapPanel(SingleMapPanel):
  53. """Main panel for map display window. Drawing takes place in
  54. child double buffered drawing window.
  55. """
  56. def __init__(
  57. self,
  58. parent,
  59. giface,
  60. title=_("Map Display"),
  61. toolbars=["map"],
  62. statusbar=True,
  63. tree=None,
  64. lmgr=None,
  65. Map=None,
  66. auimgr=None,
  67. name="MapWindow",
  68. **kwargs,
  69. ):
  70. """Main map display window with toolbars, statusbar and
  71. 2D map window, 3D map window and digitizer.
  72. :param toolbars: array of activated toolbars, e.g. ['map', 'digit']
  73. :param statusbar: True to add statusbar
  74. :param tree: reference to layer tree
  75. :param lmgr: Layer Manager
  76. :param map: instance of render.Map
  77. :param auimgr: AUI manager
  78. :param name: panel name
  79. :param kwargs: wx.Panel attributes
  80. """
  81. SingleMapPanel.__init__(
  82. self,
  83. parent=parent,
  84. title=title,
  85. Map=Map,
  86. auimgr=auimgr,
  87. name=name,
  88. **kwargs,
  89. )
  90. self._giface = giface
  91. # Layer Manager object
  92. # need by GLWindow (a lot), VDigitWindow (a little bit)
  93. self._layerManager = lmgr
  94. # Layer Manager layer tree object
  95. # used for VDigit toolbar and window and GLWindow
  96. self.tree = tree
  97. # checks for saving workspace
  98. self.canCloseDisplayCallback = None
  99. # Emitted when switching map notebook tabs (Single-Window)
  100. self.onFocus = Signal("MapPanel.onFocus")
  101. # Emitted when starting (switching to) 3D mode.
  102. # Parameter firstTime specifies if 3D was already actived.
  103. self.starting3dMode = Signal("MapPanel.starting3dMode")
  104. # Emitted when ending (switching from) 3D mode.
  105. self.ending3dMode = Signal("MapPanel.ending3dMode")
  106. # Emitted when closing display by closing its window.
  107. self.closingDisplay = Signal("MapPanel.closingDisplay")
  108. # Emitted when closing display by closing its window.
  109. self.closingVNETDialog = Signal("MapPanel.closingVNETDialog")
  110. #
  111. # Add toolbars
  112. #
  113. for toolb in toolbars:
  114. self.AddToolbar(toolb)
  115. #
  116. # Add statusbar
  117. #
  118. self.statusbar = None
  119. self.statusbarManager = None
  120. if statusbar:
  121. # items for choice
  122. statusbarItems = [
  123. sb.SbCoordinates,
  124. sb.SbRegionExtent,
  125. sb.SbCompRegionExtent,
  126. sb.SbDisplayGeometry,
  127. sb.SbMapScale,
  128. sb.SbGoTo,
  129. ]
  130. self.statusbarItemsHiddenInNviz = (
  131. sb.SbDisplayGeometry,
  132. sb.SbMapScale,
  133. )
  134. self.statusbar = self.CreateStatusbar(statusbarItems)
  135. self.Map.GetRenderMgr().updateProgress.connect(
  136. self.statusbarManager.SetProgress
  137. )
  138. self.Map.GetRenderMgr().renderingFailed.connect(
  139. lambda cmd, error: self._giface.WriteError(
  140. _("Failed to run command '%(command)s'. Details:\n%(error)s")
  141. % dict(command=" ".join(cmd), error=error)
  142. )
  143. )
  144. # init decoration objects
  145. self.decorations = {}
  146. self._decorationWindows = {}
  147. self.mapWindowProperties.autoRenderChanged.connect(
  148. lambda value: self.OnRender(None) if value else None
  149. )
  150. #
  151. # Init map display (buffered DC & set default cursor)
  152. #
  153. self.MapWindow2D = BufferedMapWindow(
  154. self,
  155. giface=self._giface,
  156. Map=self.Map,
  157. properties=self.mapWindowProperties,
  158. overlays=self.decorations,
  159. )
  160. self.MapWindow2D.mapQueried.connect(self.Query)
  161. self.MapWindow2D.overlayActivated.connect(self._activateOverlay)
  162. self.MapWindow2D.overlayRemoved.connect(self.RemoveOverlay)
  163. self._setUpMapWindow(self.MapWindow2D)
  164. self.MapWindow2D.mouseHandlerUnregistered.connect(self.ResetPointer)
  165. self.MapWindow2D.InitZoomHistory()
  166. self.MapWindow2D.zoomChanged.connect(self.StatusbarUpdate)
  167. # register context menu actions
  168. if self.statusbar:
  169. self._registerContextMenuActions()
  170. self._giface.updateMap.connect(self.MapWindow2D.UpdateMap)
  171. # default is 2D display mode
  172. self.MapWindow = self.MapWindow2D
  173. self.MapWindow.SetNamedCursor("default")
  174. # used by vector digitizer
  175. self.MapWindowVDigit = None
  176. # used by Nviz (3D display mode)
  177. self.MapWindow3D = None
  178. if "map" in self.toolbars:
  179. self.toolbars["map"].SelectDefault()
  180. #
  181. # Bind various events
  182. #
  183. self.Bind(wx.EVT_SIZE, self.OnSize)
  184. #
  185. # Update fancy gui style
  186. #
  187. self._mgr.AddPane(
  188. self.MapWindow,
  189. wx.aui.AuiPaneInfo()
  190. .CentrePane()
  191. .Dockable(False)
  192. .BestSize((-1, -1))
  193. .Name("2d")
  194. .CloseButton(False)
  195. .DestroyOnClose(True)
  196. .Layer(0),
  197. )
  198. # statusbar
  199. if self.statusbar:
  200. self.AddStatusbarPane()
  201. self._mgr.Update()
  202. #
  203. # Init print module and classes
  204. #
  205. self.printopt = PrintOptions(self, self.MapWindow)
  206. #
  207. # Re-use dialogs
  208. #
  209. self.dialogs = {}
  210. self.dialogs["attributes"] = None
  211. self.dialogs["category"] = None
  212. self.dialogs["vnet"] = None
  213. self.dialogs["query"] = None
  214. self.dialogs["vselect"] = None
  215. # initialize layers to query (d.what.vect/rast)
  216. self._vectQueryLayers = []
  217. self._rastQueryLayers = []
  218. # initialize highlighter for vector features
  219. self._highlighter_layer = None
  220. self.measureController = None
  221. self._resize()
  222. def _registerContextMenuActions(self):
  223. """Register show/hide toolbars and statusbar context menu actions"""
  224. def show_hide_toolbar_label():
  225. return (
  226. _("Hide toolbars") if self.AreAllToolbarsShown() else _("Show toolbars")
  227. )
  228. def on_show_hide_toolbar(event):
  229. self.ShowAllToolbars(not self.AreAllToolbarsShown())
  230. self.MapWindow2D.RegisterContextAction(
  231. name="showAllToolbars",
  232. label=show_hide_toolbar_label,
  233. action=on_show_hide_toolbar,
  234. )
  235. def show_hide_statusbar_label():
  236. return (
  237. _("Hide statusbar") if self.IsStatusbarShown() else _("Show statusbar")
  238. )
  239. def on_show_hide_statusbar(event):
  240. self.ShowStatusbar(not self.IsStatusbarShown())
  241. self.MapWindow2D.RegisterContextAction(
  242. name="showStatusbar",
  243. label=show_hide_statusbar_label,
  244. action=on_show_hide_statusbar,
  245. )
  246. def GetMapWindow(self):
  247. return self.MapWindow
  248. def _addToolbarVDigit(self):
  249. """Add vector digitizer toolbar"""
  250. from vdigit.main import haveVDigit, VDigit
  251. from vdigit.toolbars import VDigitToolbar
  252. if not haveVDigit:
  253. from vdigit import errorMsg
  254. self.toolbars["map"].combo.SetValue(_("2D view"))
  255. GError(
  256. _("Unable to start wxGUI vector digitizer.\n" "Details: %s") % errorMsg,
  257. parent=self,
  258. )
  259. return
  260. if not self.MapWindowVDigit:
  261. from vdigit.mapwindow import VDigitWindow
  262. self.MapWindowVDigit = VDigitWindow(
  263. parent=self,
  264. giface=self._giface,
  265. properties=self.mapWindowProperties,
  266. Map=self.Map,
  267. tree=self.tree,
  268. lmgr=self._layerManager,
  269. overlays=self.decorations,
  270. )
  271. self._setUpMapWindow(self.MapWindowVDigit)
  272. self.MapWindowVDigit.digitizingInfo.connect(
  273. lambda text: self.statusbarManager.statusbarItems[
  274. "coordinates"
  275. ].SetAdditionalInfo(text)
  276. )
  277. self.MapWindowVDigit.digitizingInfoUnavailable.connect(
  278. lambda: self.statusbarManager.statusbarItems[
  279. "coordinates"
  280. ].SetAdditionalInfo(None)
  281. )
  282. self.MapWindowVDigit.Show()
  283. self._mgr.AddPane(
  284. self.MapWindowVDigit,
  285. wx.aui.AuiPaneInfo()
  286. .CentrePane()
  287. .Dockable(False)
  288. .BestSize((-1, -1))
  289. .Name("vdigit")
  290. .CloseButton(False)
  291. .DestroyOnClose(True)
  292. .Layer(0),
  293. )
  294. self._switchMapWindow(self.MapWindowVDigit)
  295. if self._mgr.GetPane("2d").IsShown():
  296. self._mgr.GetPane("2d").Hide()
  297. elif self._mgr.GetPane("3d").IsShown():
  298. self._mgr.GetPane("3d").Hide()
  299. self._mgr.GetPane("vdigit").Show()
  300. if "vdigit" not in self.toolbars:
  301. self.toolbars["vdigit"] = VDigitToolbar(
  302. parent=self,
  303. toolSwitcher=self._toolSwitcher,
  304. MapWindow=self.MapWindow,
  305. digitClass=VDigit,
  306. giface=self._giface,
  307. )
  308. self.toolbars["vdigit"].quitDigitizer.connect(self.QuitVDigit)
  309. def openATM(selection):
  310. self._layerManager.OnShowAttributeTable(None, selection=selection)
  311. self.toolbars["vdigit"].openATM.connect(
  312. lambda selection: openATM(selection)
  313. )
  314. self.Map.layerAdded.connect(self._updateVDigitLayers)
  315. self.MapWindowVDigit.SetToolbar(self.toolbars["vdigit"])
  316. self._mgr.AddPane(
  317. self.toolbars["vdigit"],
  318. wx.aui.AuiPaneInfo()
  319. .Name("vdigittoolbar")
  320. .Caption(_("Vector Digitizer Toolbar"))
  321. .ToolbarPane()
  322. .Top()
  323. .Row(1)
  324. .LeftDockable(False)
  325. .RightDockable(False)
  326. .BottomDockable(False)
  327. .TopDockable(True)
  328. .CloseButton(False)
  329. .Layer(2)
  330. .BestSize((self.toolbars["vdigit"].GetBestSize())),
  331. )
  332. # change mouse to draw digitized line
  333. self.MapWindow.mouse["box"] = "point"
  334. self.MapWindow.zoomtype = 0
  335. self.MapWindow.pen = wx.Pen(colour="red", width=2, style=wx.SOLID)
  336. self.MapWindow.polypen = wx.Pen(colour="green", width=2, style=wx.SOLID)
  337. def _updateVDigitLayers(self, layer):
  338. """Update vdigit layers"""
  339. if "vdigit" in self.toolbars:
  340. self.toolbars["vdigit"].UpdateListOfLayers(updateTool=True)
  341. def AddNviz(self):
  342. """Add 3D view mode window"""
  343. from nviz.main import haveNviz, GLWindow, errorMsg
  344. # check for GLCanvas and OpenGL
  345. if not haveNviz:
  346. self.toolbars["map"].combo.SetValue(_("2D view"))
  347. GError(
  348. parent=self,
  349. message=_(
  350. "Unable to switch to 3D display mode.\nThe Nviz python extension "
  351. "was not found or loaded properly.\n"
  352. "Switching back to 2D display mode.\n\nDetails: %s" % errorMsg
  353. ),
  354. )
  355. return
  356. # here was disabling 3D for other displays, now done on starting3dMode
  357. self.toolbars["map"].Enable2D(False)
  358. # add rotate tool to map toolbar
  359. self.toolbars["map"].InsertTool(
  360. (("rotate", NvizIcons["rotate"], self.OnRotate, wx.ITEM_CHECK, 7),)
  361. ) # 7 is position
  362. self._toolSwitcher.AddToolToGroup(
  363. group="mouseUse",
  364. toolbar=self.toolbars["map"],
  365. tool=self.toolbars["map"].rotate,
  366. )
  367. self.toolbars["map"].InsertTool(
  368. (
  369. (
  370. "flyThrough",
  371. NvizIcons["flyThrough"],
  372. self.OnFlyThrough,
  373. wx.ITEM_CHECK,
  374. 8,
  375. ),
  376. )
  377. )
  378. self._toolSwitcher.AddToolToGroup(
  379. group="mouseUse",
  380. toolbar=self.toolbars["map"],
  381. tool=self.toolbars["map"].flyThrough,
  382. )
  383. # update status bar
  384. self.statusbarManager.HideStatusbarChoiceItemsByClass(
  385. self.statusbarItemsHiddenInNviz
  386. )
  387. self.statusbarManager.SetMode(0)
  388. # erase map window
  389. self.MapWindow.EraseMap()
  390. self._giface.WriteCmdLog(
  391. _("Starting 3D view mode..."), notification=Notification.HIGHLIGHT
  392. )
  393. self.SetStatusText(_("Please wait, loading data..."), 0)
  394. # create GL window
  395. if not self.MapWindow3D:
  396. self.MapWindow3D = GLWindow(
  397. self,
  398. giface=self._giface,
  399. id=wx.ID_ANY,
  400. frame=self,
  401. Map=self.Map,
  402. tree=self.tree,
  403. lmgr=self._layerManager,
  404. )
  405. self._setUpMapWindow(self.MapWindow3D)
  406. self.MapWindow3D.mapQueried.connect(self.Query)
  407. self._switchMapWindow(self.MapWindow3D)
  408. self.MapWindow.SetNamedCursor("default")
  409. # here was AddNvizTools in lmgr
  410. self.starting3dMode.emit(firstTime=True)
  411. # switch from MapWindow to MapWindowGL
  412. self._mgr.GetPane("2d").Hide()
  413. self._mgr.AddPane(
  414. self.MapWindow3D,
  415. wx.aui.AuiPaneInfo()
  416. .CentrePane()
  417. .Dockable(False)
  418. .BestSize((-1, -1))
  419. .Name("3d")
  420. .CloseButton(False)
  421. .DestroyOnClose(True)
  422. .Layer(0),
  423. )
  424. self.MapWindow3D.Show()
  425. self.MapWindow3D.ResetViewHistory()
  426. self.MapWindow3D.UpdateView(None)
  427. self.MapWindow3D.overlayActivated.connect(self._activateOverlay)
  428. self.MapWindow3D.overlayRemoved.connect(self.RemoveOverlay)
  429. else:
  430. self._switchMapWindow(self.MapWindow3D)
  431. os.environ["GRASS_REGION"] = self.Map.SetRegion(windres=True, windres3=True)
  432. self.MapWindow3D.GetDisplay().Init()
  433. self.MapWindow3D.LoadDataLayers()
  434. del os.environ["GRASS_REGION"]
  435. # switch from MapWindow to MapWindowGL
  436. self._mgr.GetPane("2d").Hide()
  437. self._mgr.GetPane("3d").Show()
  438. # here was AddNvizTools in lmgr and updating of pages
  439. self.starting3dMode.emit(firstTime=False)
  440. self.MapWindow3D.ResetViewHistory()
  441. # connect signals for updating overlays
  442. for overlay in self.decorations.values():
  443. overlay.overlayChanged.connect(self.MapWindow3D.UpdateOverlays)
  444. self.Map.GetRenderMgr().renderDone.connect(self.MapWindow3D._onUpdateOverlays)
  445. self._giface.updateMap.disconnect(self.MapWindow2D.UpdateMap)
  446. self._giface.updateMap.connect(self.MapWindow3D.UpdateMap)
  447. self.MapWindow3D.overlays = self.MapWindow2D.overlays
  448. # update overlays needs to be called after because getClientSize
  449. # is called during update and it must give reasonable values
  450. wx.CallAfter(self.MapWindow3D.UpdateOverlays)
  451. self.SetStatusText("", 0)
  452. self._mgr.Update()
  453. def Disable3dMode(self):
  454. """Disables 3D mode (NVIZ) in user interface."""
  455. # TODO: this is broken since item is removed but switch is drived by
  456. # index
  457. if "3D" in self.toolbars["map"].combo.GetString(1):
  458. self.toolbars["map"].combo.Delete(1)
  459. def RemoveNviz(self):
  460. """Restore 2D view. Can be called even if 3D is not active."""
  461. if not self.IsPaneShown("3d"):
  462. return
  463. try:
  464. self.toolbars["map"].RemoveTool(self.toolbars["map"].rotate)
  465. self.toolbars["map"].RemoveTool(self.toolbars["map"].flyThrough)
  466. except AttributeError:
  467. pass
  468. # update status bar
  469. self.statusbarManager.ShowStatusbarChoiceItemsByClass(
  470. self.statusbarItemsHiddenInNviz
  471. )
  472. self.statusbarManager.SetMode(
  473. UserSettings.Get(group="display", key="statusbarMode", subkey="selection")
  474. )
  475. self.SetStatusText(_("Please wait, unloading data..."), 0)
  476. # unloading messages from library cause highlight anyway
  477. self._giface.WriteCmdLog(
  478. _("Switching back to 2D view mode..."),
  479. notification=Notification.NO_NOTIFICATION,
  480. )
  481. if self.MapWindow3D:
  482. self.MapWindow3D.OnClose(event=None)
  483. # switch from MapWindowGL to MapWindow
  484. self._mgr.GetPane("2d").Show()
  485. self._mgr.GetPane("3d").Hide()
  486. self._switchMapWindow(self.MapWindow2D)
  487. # here was RemoveNvizTools form lmgr
  488. self.ending3dMode.emit()
  489. try:
  490. self.MapWindow2D.overlays = self.MapWindow3D.overlays
  491. except AttributeError:
  492. pass
  493. # TODO: here we end because self.MapWindow3D is None for a while
  494. self._giface.updateMap.disconnect(self.MapWindow3D.UpdateMap)
  495. self._giface.updateMap.connect(self.MapWindow2D.UpdateMap)
  496. # disconnect overlays
  497. for overlay in self.decorations.values():
  498. overlay.overlayChanged.disconnect(self.MapWindow3D.UpdateOverlays)
  499. self.Map.GetRenderMgr().renderDone.disconnect(
  500. self.MapWindow3D._onUpdateOverlays
  501. )
  502. self.MapWindow3D.ClearTextures()
  503. self.MapWindow.UpdateMap()
  504. self._mgr.Update()
  505. self.GetMapToolbar().SelectDefault()
  506. def AddToolbar(self, name, fixed=False):
  507. """Add defined toolbar to the window
  508. Currently recognized toolbars are:
  509. - 'map' - basic map toolbar
  510. - 'vdigit' - vector digitizer
  511. :param name: toolbar to add
  512. :param fixed: fixed toolbar
  513. """
  514. # default toolbar
  515. if name == "map":
  516. if "map" not in self.toolbars:
  517. self.toolbars["map"] = MapToolbar(
  518. self, toolSwitcher=self._toolSwitcher, giface=self._giface
  519. )
  520. self._mgr.AddPane(
  521. self.toolbars["map"],
  522. wx.aui.AuiPaneInfo()
  523. .Name("maptoolbar")
  524. .Caption(_("Map Toolbar"))
  525. .ToolbarPane()
  526. .Top()
  527. .Name("mapToolbar")
  528. .LeftDockable(False)
  529. .RightDockable(False)
  530. .BottomDockable(False)
  531. .TopDockable(True)
  532. .CloseButton(False)
  533. .Layer(2)
  534. .BestSize((self.toolbars["map"].GetBestSize())),
  535. )
  536. # vector digitizer
  537. elif name == "vdigit":
  538. self.toolbars["map"].combo.SetValue(_("Vector digitizer"))
  539. self._addToolbarVDigit()
  540. # raster digitizer
  541. elif name == "rdigit":
  542. self.toolbars["map"].combo.SetValue(_("Raster digitizer"))
  543. self.AddRDigit()
  544. if fixed:
  545. self.toolbars["map"].combo.Disable()
  546. self._mgr.Update()
  547. def RemoveToolbar(self, name, destroy=False):
  548. """Removes defined toolbar from the window
  549. :param name toolbar to remove
  550. :param destroy True to destroy otherwise toolbar is only hidden
  551. """
  552. super().RemoveToolbar(name, destroy)
  553. if name == "vdigit":
  554. self._mgr.GetPane("vdigit").Hide()
  555. self._mgr.GetPane("2d").Show()
  556. self._switchMapWindow(self.MapWindow2D)
  557. self.toolbars["map"].Enable2D(True)
  558. self._mgr.Update()
  559. def RemoveQueryLayer(self):
  560. """Removes temporary map layers (queries)"""
  561. qlayer = self.GetMap().GetListOfLayers(name=globalvar.QUERYLAYER)
  562. for layer in qlayer:
  563. self.GetMap().DeleteLayer(layer)
  564. def OnRender(self, event):
  565. """Re-render map composition (each map layer)"""
  566. self.RemoveQueryLayer()
  567. # deselect features in vdigit
  568. if self.GetToolbar("vdigit"):
  569. if self.MapWindow.digit:
  570. self.MapWindow.digit.GetDisplay().SetSelected([])
  571. self.MapWindow.UpdateMap(render=True, renderVector=True)
  572. else:
  573. self.MapWindow.UpdateMap(render=True)
  574. # reset dialog with selected features
  575. if self.dialogs["vselect"]:
  576. self.dialogs["vselect"].Reset()
  577. # update statusbar
  578. self.StatusbarUpdate()
  579. def OnPointer(self, event):
  580. """Pointer button clicked"""
  581. self.MapWindow.SetModePointer()
  582. if self.GetToolbar("vdigit"):
  583. self.toolbars["vdigit"].action["id"] = -1
  584. self.toolbars["vdigit"].action["desc"] = ""
  585. def OnSelect(self, event):
  586. """Vector feature selection button clicked"""
  587. layerList = self._giface.GetLayerList()
  588. layerSelected = layerList.GetSelectedLayer()
  589. if not self.dialogs["vselect"]:
  590. if layerSelected is None:
  591. GMessage(_("No map layer selected. Operation canceled."))
  592. return
  593. self.dialogs["vselect"] = VectorSelectBase(self.parent, self._giface)
  594. self.dialogs["vselect"].CreateDialog(createButton=True)
  595. self.dialogs["vselect"].onCloseDialog.connect(
  596. self._onCloseVectorSelectDialog
  597. )
  598. def _onCloseVectorSelectDialog(self):
  599. self.dialogs["vselect"] = None
  600. def OnRotate(self, event):
  601. """Rotate 3D view"""
  602. self.MapWindow.mouse["use"] = "rotate"
  603. # change the cursor
  604. self.MapWindow.SetNamedCursor("hand")
  605. def OnFlyThrough(self, event):
  606. """Fly-through mode"""
  607. self.MapWindow.mouse["use"] = "fly"
  608. # change the cursor
  609. self.MapWindow.SetNamedCursor("hand")
  610. self.MapWindow.SetFocus()
  611. def SaveToFile(self, event):
  612. """Save map to image"""
  613. filetype, ltype = self._prepareSaveToFile()
  614. if not ltype:
  615. return
  616. # get size
  617. dlg = ImageSizeDialog(self)
  618. dlg.CentreOnParent()
  619. if dlg.ShowModal() != wx.ID_OK:
  620. dlg.Destroy()
  621. return
  622. width, height = dlg.GetValues()
  623. dlg.Destroy()
  624. # get filename
  625. dlg = wx.FileDialog(
  626. parent=self,
  627. message=_(
  628. "Choose a file name to save the image " "(no need to add extension)"
  629. ),
  630. wildcard=filetype,
  631. style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT,
  632. )
  633. if dlg.ShowModal() == wx.ID_OK:
  634. path = dlg.GetPath()
  635. if not path:
  636. dlg.Destroy()
  637. return
  638. base, ext = os.path.splitext(path)
  639. fileType = ltype[dlg.GetFilterIndex()]["type"]
  640. extType = ltype[dlg.GetFilterIndex()]["ext"]
  641. if ext != extType:
  642. path = base + "." + extType
  643. self.MapWindow.SaveToFile(path, fileType, width, height)
  644. dlg.Destroy()
  645. def DOutFile(self, command, callback=None):
  646. """Saves map to image by running d.out.file from gui or d.mon.
  647. Command is expected to be validated by parser.
  648. """
  649. filetype, ltype = self._prepareSaveToFile()
  650. if not ltype:
  651. return
  652. width, height = self.MapWindow.GetClientSize()
  653. for param in command[1:]:
  654. try:
  655. p, val = param.split("=")
  656. except ValueError:
  657. # --overwrite
  658. continue
  659. if p == "format": # must be there
  660. if self.IsPaneShown("3d"):
  661. extType = "ppm"
  662. else:
  663. extType = val
  664. if p == "output": # must be there
  665. name = val
  666. elif p == "size":
  667. width, height = val.split(",")
  668. base, ext = os.path.splitext(name)
  669. if not ext:
  670. name = base + "." + extType
  671. elif ext[1:] != extType:
  672. extType = ext[1:]
  673. if self.IsPaneShown("3d"):
  674. bitmapType = "ppm"
  675. else:
  676. bitmapType = wx.BITMAP_TYPE_PNG # default type
  677. for each in ltype:
  678. if each["ext"] == extType:
  679. bitmapType = each["type"]
  680. break
  681. self.MapWindow.SaveToFile(name, bitmapType, int(width), int(height), callback)
  682. def DOutFileOptData(self, dcmd, layer, params, propwin):
  683. """Dummy function which is called when d.out.file is called
  684. and returns parsed and validated command which is then passed
  685. to DOutFile method."""
  686. if not dcmd:
  687. return
  688. self.DOutFile(dcmd)
  689. def DToRast(self, command):
  690. """Saves currently loaded composition of layers as a raster map."""
  691. def _DToRastDone():
  692. # import back as red, green, blue rasters
  693. returncode, messages = RunCommand(
  694. "r.in.gdal",
  695. flags="o",
  696. input=pngFile,
  697. output=tmpName,
  698. quiet=True,
  699. overwrite=overwrite,
  700. getErrorMsg=True,
  701. )
  702. if not returncode == 0:
  703. self._giface.WriteError(_("Failed to run d.to.rast:\n") + messages)
  704. return
  705. # set region for composite
  706. grass.use_temp_region()
  707. returncode, messages = RunCommand(
  708. "g.region", raster=tmpName + ".red", quiet=True, getErrorMsg=True
  709. )
  710. if not returncode == 0:
  711. grass.del_temp_region()
  712. self._giface.WriteError(_("Failed to run d.to.rast:\n") + messages)
  713. return
  714. # composite
  715. returncode, messages = RunCommand(
  716. "r.composite",
  717. red=tmpName + ".red",
  718. green=tmpName + ".green",
  719. blue=tmpName + ".blue",
  720. output=outputRaster,
  721. quiet=True,
  722. overwrite=overwrite,
  723. getErrorMsg=True,
  724. )
  725. grass.del_temp_region()
  726. RunCommand(
  727. "g.remove",
  728. type="raster",
  729. flags="f",
  730. quiet=True,
  731. name=[tmpName + ".red", tmpName + ".green", tmpName + ".blue"],
  732. )
  733. if not returncode == 0:
  734. self._giface.WriteError(_("Failed to run d.to.rast:\n") + messages)
  735. grass.try_remove(pngFile)
  736. return
  737. # alignExtent changes only region variable
  738. oldRegion = self.GetMap().GetCurrentRegion().copy()
  739. self.GetMap().AlignExtentFromDisplay()
  740. region = self.GetMap().GetCurrentRegion().copy()
  741. self.GetMap().region.update(oldRegion)
  742. RunCommand(
  743. "r.region",
  744. map=outputRaster,
  745. n=region["n"],
  746. s=region["s"],
  747. e=region["e"],
  748. w=region["w"],
  749. quiet=True,
  750. )
  751. grass.try_remove(pngFile)
  752. if self.IsPaneShown("3d"):
  753. self._giface.WriteError(_("d.to.rast can be used only in 2D mode."))
  754. return
  755. outputRaster = None
  756. overwrite = False
  757. for param in command[1:]:
  758. try:
  759. p, val = param.split("=")
  760. if p == "output":
  761. outputRaster = val
  762. except ValueError:
  763. if param.startswith("--overwrite"):
  764. overwrite = True
  765. if not outputRaster:
  766. return
  767. # output file as PNG
  768. tmpName = "d_to_rast_tmp"
  769. pngFile = grass.tempfile(create=False) + ".png"
  770. dOutFileCmd = ["d.out.file", "output=" + pngFile, "format=png"]
  771. self.DOutFile(dOutFileCmd, callback=_DToRastDone)
  772. def DToRastOptData(self, dcmd, layer, params, propwin):
  773. """Dummy function which is called when d.to.rast is called
  774. and returns parsed and validated command which is then passed
  775. to DToRast method."""
  776. if not dcmd:
  777. return
  778. self.DToRast(dcmd)
  779. def _prepareSaveToFile(self):
  780. """Get wildcards and format extensions."""
  781. if self.IsPaneShown("3d"):
  782. filetype = "TIF file (*.tif)|*.tif|PPM file (*.ppm)|*.ppm"
  783. ltype = [{"ext": "tif", "type": "tif"}, {"ext": "ppm", "type": "ppm"}]
  784. else:
  785. img = self.MapWindow.img
  786. if not img:
  787. GMessage(
  788. parent=self,
  789. message=_("Nothing to render (empty map). Operation canceled."),
  790. )
  791. return None, None
  792. filetype, ltype = GetImageHandlers(img)
  793. return filetype, ltype
  794. def PrintMenu(self, event):
  795. """
  796. Print options and output menu for map display
  797. """
  798. printmenu = Menu()
  799. # Add items to the menu
  800. setup = wx.MenuItem(printmenu, wx.ID_ANY, _("Page setup"))
  801. printmenu.AppendItem(setup)
  802. self.Bind(wx.EVT_MENU, self.printopt.OnPageSetup, setup)
  803. preview = wx.MenuItem(printmenu, wx.ID_ANY, _("Print preview"))
  804. printmenu.AppendItem(preview)
  805. self.Bind(wx.EVT_MENU, self.printopt.OnPrintPreview, preview)
  806. doprint = wx.MenuItem(printmenu, wx.ID_ANY, _("Print display"))
  807. printmenu.AppendItem(doprint)
  808. self.Bind(wx.EVT_MENU, self.printopt.OnDoPrint, doprint)
  809. # Popup the menu. If an item is selected then its handler
  810. # will be called before PopupMenu returns.
  811. self.PopupMenu(printmenu)
  812. printmenu.Destroy()
  813. def CleanUp(self):
  814. """Clean up before closing map display.
  815. End digitizer/nviz."""
  816. Debug.msg(2, "MapPanel.CleanUp()")
  817. self.Map.Clean()
  818. # close edited map and 3D tools properly
  819. if self.GetToolbar("vdigit"):
  820. maplayer = self.toolbars["vdigit"].GetLayer()
  821. if maplayer:
  822. self.toolbars["vdigit"].OnExit()
  823. self.RemoveNviz()
  824. if hasattr(self, "rdigit") and self.rdigit:
  825. self.rdigit.CleanUp()
  826. if self.dialogs["vnet"]:
  827. self.closingVNETDialog.emit()
  828. self._mgr.UnInit()
  829. def OnCloseWindow(self, event, askIfSaveWorkspace=True):
  830. """Window closed.
  831. Also close associated layer tree page
  832. """
  833. Debug.msg(2, "MapPanel.OnCloseWindow()")
  834. if self.canCloseDisplayCallback:
  835. pgnum_dict = self.canCloseDisplayCallback(
  836. askIfSaveWorkspace=askIfSaveWorkspace
  837. )
  838. if pgnum_dict is not None:
  839. self.CleanUp()
  840. if pgnum_dict["layers"] > -1:
  841. self.closingDisplay.emit(pgnum_dict=pgnum_dict)
  842. # Destroy is called when notebook page is deleted
  843. else:
  844. self.CleanUp()
  845. self.Destroy()
  846. def Query(self, x, y):
  847. """Query selected layers.
  848. :param x,y: coordinates
  849. """
  850. if self._vectQueryLayers or self._rastQueryLayers:
  851. rast = self._rastQueryLayers
  852. vect = self._vectQueryLayers
  853. else:
  854. layers = self._giface.GetLayerList().GetSelectedLayers(checkedOnly=False)
  855. rast = []
  856. vect = []
  857. for layer in layers:
  858. if layer.type == "command":
  859. continue
  860. name, found = GetLayerNameFromCmd(layer.cmd)
  861. if not found:
  862. continue
  863. ltype = layer.maplayer.GetType()
  864. if ltype == "raster":
  865. rast.append(name)
  866. elif ltype in ("rgb", "his"):
  867. for iname in name.split("\n"):
  868. rast.append(iname)
  869. elif ltype in ("vector", "thememap", "themechart"):
  870. vect.append(name)
  871. if vect:
  872. # check for vector maps open to be edited
  873. digitToolbar = self.GetToolbar("vdigit")
  874. if digitToolbar:
  875. lmap = digitToolbar.GetLayer().GetName()
  876. for name in vect:
  877. if lmap == name:
  878. self._giface.WriteWarning(
  879. _("Vector map <%s> " "opened for editing - skipped.")
  880. % lmap
  881. )
  882. vect.remove(name)
  883. if not (rast + vect):
  884. GMessage(
  885. parent=self,
  886. message=_("No raster or vector map layer selected for querying."),
  887. )
  888. return
  889. # set query snap distance for v.what at map unit equivalent of 10
  890. # pixels
  891. qdist = 10.0 * ((self.Map.region["e"] - self.Map.region["w"]) / self.Map.width)
  892. # TODO: replace returning None by exception or so
  893. try:
  894. east, north = self.MapWindow.Pixel2Cell((x, y))
  895. except TypeError:
  896. return
  897. if not self.IsPaneShown("3d"):
  898. self.QueryMap(east, north, qdist, rast, vect)
  899. else:
  900. if rast:
  901. self.MapWindow.QuerySurface(x, y)
  902. if vect:
  903. self.QueryMap(east, north, qdist, rast=[], vect=vect)
  904. def SetQueryLayersAndActivate(self, ltype, maps):
  905. """Activate query mode and set layers to query.
  906. This method is used for querying in d.mon using d.what.rast/vect"""
  907. self.toolbars["map"].SelectTool(self.toolbars["map"].query)
  908. if ltype == "vector":
  909. self._vectQueryLayers = maps
  910. elif ltype == "raster":
  911. self._rastQueryLayers = maps
  912. def QueryMap(self, east, north, qdist, rast, vect):
  913. """Query raster or vector map layers by r/v.what
  914. :param east,north: coordinates
  915. :param qdist: query distance
  916. :param rast: raster map names
  917. :param vect: vector map names
  918. """
  919. Debug.msg(
  920. 1, "QueryMap(): raster=%s vector=%s" % (",".join(rast), ",".join(vect))
  921. )
  922. if self._highlighter_layer is None:
  923. self._highlighter_layer = VectorSelectHighlighter(
  924. mapdisp=self._giface.GetMapDisplay(), giface=self._giface
  925. )
  926. # use display region settings instead of computation region settings
  927. self.tmpreg = os.getenv("GRASS_REGION")
  928. os.environ["GRASS_REGION"] = self.Map.SetRegion(windres=False)
  929. rastQuery = []
  930. vectQuery = []
  931. if rast:
  932. rastQuery = grass.raster_what(map=rast, coord=(east, north), localized=True)
  933. if vect:
  934. encoding = UserSettings.Get(group="atm", key="encoding", subkey="value")
  935. try:
  936. vectQuery = grass.vector_what(
  937. map=vect,
  938. coord=(east, north),
  939. distance=qdist,
  940. encoding=encoding,
  941. multiple=True,
  942. )
  943. except grass.ScriptError:
  944. GError(
  945. parent=self,
  946. message=_(
  947. "Failed to query vector map(s) <{maps}>. "
  948. "Check database settings and topology."
  949. ).format(maps=",".join(vect)),
  950. )
  951. self._QueryMapDone()
  952. self._highlighter_layer.Clear()
  953. if vectQuery and "Category" in vectQuery[0]:
  954. self._queryHighlight(vectQuery)
  955. result = rastQuery + vectQuery
  956. result = PrepareQueryResults(coordinates=(east, north), result=result)
  957. if self.dialogs["query"]:
  958. self.dialogs["query"].Raise()
  959. self.dialogs["query"].SetData(result)
  960. else:
  961. self.dialogs["query"] = QueryDialog(parent=self, data=result)
  962. self.dialogs["query"].Bind(wx.EVT_CLOSE, self._oncloseQueryDialog)
  963. self.dialogs["query"].redirectOutput.connect(self._onRedirectQueryOutput)
  964. self.dialogs["query"].Show()
  965. def _oncloseQueryDialog(self, event):
  966. self.dialogs["query"] = None
  967. self._vectQueryLayers = []
  968. self._rastQueryLayers = []
  969. self._highlighter_layer.Clear()
  970. self._highlighter_layer = None
  971. event.Skip()
  972. def _onRedirectQueryOutput(self, output, style="log"):
  973. """Writes query output into console"""
  974. if style == "log":
  975. self._giface.WriteLog(output, notification=Notification.MAKE_VISIBLE)
  976. elif style == "cmd":
  977. self._giface.WriteCmdLog(output)
  978. def _queryHighlight(self, vectQuery):
  979. """Highlight category from query."""
  980. if len(vectQuery) > 0:
  981. self._highlighter_layer.SetLayer(vectQuery[0]["Layer"])
  982. self._highlighter_layer.SetMap(
  983. vectQuery[0]["Map"] + "@" + vectQuery[0]["Mapset"]
  984. )
  985. tmp = list()
  986. for i in vectQuery:
  987. tmp.append(i["Category"])
  988. self._highlighter_layer.SetCats(tmp)
  989. self._highlighter_layer.DrawSelected()
  990. def _QueryMapDone(self):
  991. """Restore settings after querying (restore GRASS_REGION)"""
  992. if hasattr(self, "tmpreg"):
  993. if self.tmpreg:
  994. os.environ["GRASS_REGION"] = self.tmpreg
  995. elif "GRASS_REGION" in os.environ:
  996. del os.environ["GRASS_REGION"]
  997. elif "GRASS_REGION" in os.environ:
  998. del os.environ["GRASS_REGION"]
  999. if hasattr(self, "tmpreg"):
  1000. del self.tmpreg
  1001. def OnQuery(self, event):
  1002. """Query tools menu"""
  1003. self.MapWindow.mouse["use"] = "query"
  1004. self.MapWindow.mouse["box"] = "point"
  1005. self.MapWindow.zoomtype = 0
  1006. # change the cursor
  1007. self.MapWindow.SetNamedCursor("cross")
  1008. def AddTmpVectorMapLayer(self, name, cats, useId=False, addLayer=True):
  1009. """Add temporal vector map layer to map composition
  1010. :param name: name of map layer
  1011. :param useId: use feature id instead of category
  1012. """
  1013. # color settings from ATM
  1014. color = UserSettings.Get(group="atm", key="highlight", subkey="color")
  1015. colorStr = str(color[0]) + ":" + str(color[1]) + ":" + str(color[2])
  1016. # icon used in vector display and its size
  1017. icon = ""
  1018. size = 0
  1019. # here we know that there is one selected layer and it is vector
  1020. layerSelected = self._giface.GetLayerList().GetSelectedLayer()
  1021. if not layerSelected:
  1022. return None
  1023. vparam = layerSelected.cmd
  1024. for p in vparam:
  1025. if "=" in p:
  1026. parg, pval = p.split("=", 1)
  1027. if parg == "icon":
  1028. icon = pval
  1029. elif parg == "size":
  1030. size = float(pval)
  1031. pattern = [
  1032. "d.vect",
  1033. "map=%s" % name,
  1034. "color=%s" % colorStr,
  1035. "fill_color=%s" % colorStr,
  1036. "width=%d" % UserSettings.Get(group="atm", key="highlight", subkey="width"),
  1037. ]
  1038. if icon != "":
  1039. pattern.append("icon=%s" % icon)
  1040. if size > 0:
  1041. pattern.append("size=%i" % size)
  1042. if useId:
  1043. cmd = pattern
  1044. cmd.append("-i")
  1045. cmd.append("cats=%s" % str(cats))
  1046. else:
  1047. cmd = []
  1048. for layer in cats.keys():
  1049. cmd.append(copy.copy(pattern))
  1050. lcats = cats[layer]
  1051. cmd[-1].append("layer=%d" % layer)
  1052. cmd[-1].append("cats=%s" % ListOfCatsToRange(lcats))
  1053. if addLayer:
  1054. args = {}
  1055. if useId:
  1056. args["ltype"] = "vector"
  1057. else:
  1058. args["ltype"] = "command"
  1059. return self.Map.AddLayer(
  1060. name=globalvar.QUERYLAYER,
  1061. command=cmd,
  1062. active=True,
  1063. hidden=True,
  1064. opacity=1.0,
  1065. render=True,
  1066. **args,
  1067. )
  1068. else:
  1069. return cmd
  1070. def OnMeasureDistance(self, event):
  1071. self._onMeasure(MeasureDistanceController)
  1072. def OnMeasureArea(self, event):
  1073. self._onMeasure(MeasureAreaController)
  1074. def _onMeasure(self, controller):
  1075. """Starts measurement mode.
  1076. :param controller: measurement class (MeasureDistanceController, MeasureAreaController)
  1077. """
  1078. self.measureController = controller(self._giface, mapWindow=self.GetMapWindow())
  1079. # assure that the mode is ended and lines are cleared whenever other
  1080. # tool is selected
  1081. self._toolSwitcher.toggleToolChanged.connect(
  1082. lambda: self.measureController.Stop()
  1083. )
  1084. self.measureController.Start()
  1085. def OnProfile(self, event):
  1086. """Launch profile tool"""
  1087. rasters = []
  1088. layers = self._giface.GetLayerList().GetSelectedLayers()
  1089. for layer in layers:
  1090. if layer.type == "raster":
  1091. rasters.append(layer.maplayer.name)
  1092. self.Profile(rasters=rasters)
  1093. def Profile(self, rasters=None):
  1094. """Launch profile tool"""
  1095. from wxplot.profile import ProfileFrame
  1096. self.profileController = ProfileController(
  1097. self._giface, mapWindow=self.GetMapWindow()
  1098. )
  1099. win = ProfileFrame(
  1100. parent=self,
  1101. giface=self._giface,
  1102. rasterList=rasters,
  1103. units=self.Map.projinfo["units"],
  1104. controller=self.profileController,
  1105. )
  1106. win.Show()
  1107. # Open raster select dialog to make sure that a raster (and
  1108. # the desired raster) is selected to be profiled
  1109. win.OnSelectRaster(None)
  1110. def OnHistogramPyPlot(self, event):
  1111. """Init PyPlot histogram display canvas and tools"""
  1112. raster = []
  1113. for layer in self._giface.GetLayerList().GetSelectedLayers():
  1114. if layer.maplayer.GetType() == "raster":
  1115. raster.append(layer.maplayer.GetName())
  1116. from wxplot.histogram import HistogramPlotFrame
  1117. win = HistogramPlotFrame(parent=self, giface=self._giface, rasterList=raster)
  1118. win.CentreOnParent()
  1119. win.Show()
  1120. def OnScatterplot(self, event):
  1121. """Init PyPlot scatterplot display canvas and tools"""
  1122. raster = []
  1123. for layer in self._giface.GetLayerList().GetSelectedLayers():
  1124. if layer.maplayer.GetType() == "raster":
  1125. raster.append(layer.maplayer.GetName())
  1126. from wxplot.scatter import ScatterFrame
  1127. win = ScatterFrame(parent=self, giface=self._giface, rasterList=raster)
  1128. win.CentreOnParent()
  1129. win.Show()
  1130. # Open raster select dialog to make sure that at least 2 rasters (and the desired rasters)
  1131. # are selected to be plotted
  1132. win.OnSelectRaster(None)
  1133. def OnHistogram(self, event):
  1134. """Init histogram display canvas and tools"""
  1135. from modules.histogram import HistogramFrame
  1136. win = HistogramFrame(self, giface=self._giface)
  1137. win.CentreOnParent()
  1138. win.Show()
  1139. win.Refresh()
  1140. win.Update()
  1141. def _activateOverlay(self, overlayId):
  1142. """Launch decoration dialog according to overlay id.
  1143. :param overlayId: id of overlay
  1144. """
  1145. if overlayId in self.decorations:
  1146. dlg = self.decorations[overlayId].dialog
  1147. if dlg.IsShown():
  1148. dlg.SetFocus()
  1149. dlg.Raise()
  1150. else:
  1151. dlg.Show()
  1152. def RemoveOverlay(self, overlayId):
  1153. """Hide overlay.
  1154. :param overlayId: id of overlay
  1155. """
  1156. del self._decorationWindows[self.decorations[overlayId].dialog]
  1157. self.decorations[overlayId].Remove()
  1158. del self.decorations[overlayId]
  1159. def AddBarscale(self, cmd=None):
  1160. """Handler for scale bar map decoration menu selection."""
  1161. if self.IsPaneShown("3d"):
  1162. self.MapWindow3D.SetDrawScalebar((70, 70))
  1163. return
  1164. if cmd:
  1165. show = False
  1166. else:
  1167. show = True
  1168. cmd = ["d.barscale"]
  1169. # Decoration overlay control dialog
  1170. GUI(parent=self, giface=self._giface, show=show, modal=False).ParseCommand(
  1171. cmd, completed=(self.GetOptData, None, None)
  1172. )
  1173. self.MapWindow.mouse["use"] = "pointer"
  1174. def AddLegendRast(self, cmd=None):
  1175. """Handler for legend raster map decoration menu selection."""
  1176. if cmd:
  1177. show = False
  1178. else:
  1179. show = True
  1180. cmd = ["d.legend"]
  1181. layers = self._giface.GetLayerList().GetSelectedLayers()
  1182. for layer in layers:
  1183. if layer.type == "raster":
  1184. cmd.append("raster={rast}".format(rast=layer.maplayer.name))
  1185. break
  1186. GUI(parent=self, giface=self._giface, show=show, modal=False).ParseCommand(
  1187. cmd, completed=(self.GetOptData, None, None)
  1188. )
  1189. self.MapWindow.mouse["use"] = "pointer"
  1190. def AddLegendVect(self, cmd=None, showDialog=None):
  1191. """Handler for legend vector map decoration menu selection."""
  1192. if cmd:
  1193. show = False
  1194. else:
  1195. show = True
  1196. cmd = ["d.legend.vect"]
  1197. GUI(parent=self, giface=self._giface, show=show, modal=False).ParseCommand(
  1198. cmd, completed=(self.GetOptData, None, None)
  1199. )
  1200. self.MapWindow.mouse["use"] = "pointer"
  1201. def AddArrow(self, cmd=None):
  1202. """Handler for north arrow menu selection."""
  1203. if self.IsPaneShown("3d"):
  1204. # here was opening of appearance page of nviz notebook
  1205. # but now moved to MapWindow3D where are other problematic nviz
  1206. # calls
  1207. self.MapWindow3D.SetDrawArrow((70, 70))
  1208. return
  1209. if cmd:
  1210. show = False
  1211. else:
  1212. show = True
  1213. cmd = ["d.northarrow"]
  1214. # Decoration overlay control dialog
  1215. GUI(parent=self, giface=self._giface, show=show, modal=False).ParseCommand(
  1216. cmd, completed=(self.GetOptData, None, None)
  1217. )
  1218. self.MapWindow.mouse["use"] = "pointer"
  1219. def AddDtext(self, cmd=None):
  1220. """Handler for d.text menu selection."""
  1221. if cmd:
  1222. show = False
  1223. else:
  1224. show = True
  1225. cmd = ["d.text"]
  1226. # Decoration overlay control dialog
  1227. GUI(parent=self, giface=self._giface, show=show, modal=False).ParseCommand(
  1228. cmd, completed=(self.GetOptData, None, None)
  1229. )
  1230. self.MapWindow.mouse["use"] = "pointer"
  1231. def GetOptData(self, dcmd, layer, params, propwin):
  1232. """Called after options are set through module dialog.
  1233. :param dcmd: resulting command
  1234. :param layer: not used
  1235. :param params: module parameters (not used)
  1236. :param propwin: dialog window
  1237. """
  1238. if not dcmd:
  1239. return
  1240. if propwin in self._decorationWindows:
  1241. overlay = self._decorationWindows[propwin]
  1242. else:
  1243. cmd = dcmd[0]
  1244. if cmd == "d.northarrow":
  1245. overlay = ArrowController(self.Map, self._giface)
  1246. elif cmd == "d.barscale":
  1247. overlay = BarscaleController(self.Map, self._giface)
  1248. elif cmd == "d.legend":
  1249. overlay = LegendController(self.Map, self._giface)
  1250. elif cmd == "d.legend.vect":
  1251. overlay = LegendVectController(self.Map, self._giface)
  1252. elif cmd == "d.text":
  1253. overlay = DtextController(self.Map, self._giface)
  1254. self.decorations[overlay.id] = overlay
  1255. overlay.overlayChanged.connect(
  1256. lambda: self.MapWindow2D.UpdateMap(render=False, renderVector=False)
  1257. )
  1258. if self.IsPaneShown("3d"):
  1259. overlay.overlayChanged.connect(self.MapWindow3D.UpdateOverlays)
  1260. overlay.dialog = propwin
  1261. self._decorationWindows[propwin] = overlay
  1262. overlay.cmd = dcmd
  1263. overlay.Show()
  1264. def OnZoomToMap(self, event):
  1265. """Set display extents to match selected raster (including
  1266. NULLs) or vector map.
  1267. """
  1268. Debug.msg(3, "MapPanel.OnZoomToMap()")
  1269. self.MapWindow.ZoomToMap(layers=None)
  1270. def OnZoomToRaster(self, event):
  1271. """Set display extents to match selected raster map (ignore NULLs)"""
  1272. self.MapWindow.ZoomToMap(ignoreNulls=True)
  1273. def OnZoomToSaved(self, event):
  1274. """Set display geometry to match extents in
  1275. saved region file
  1276. """
  1277. self.MapWindow.SetRegion(zoomOnly=True)
  1278. def OnSetDisplayToWind(self, event):
  1279. """Set computational region (WIND file) to match display
  1280. extents
  1281. """
  1282. self.MapWindow.DisplayToWind()
  1283. def OnSetWindToRegion(self, event):
  1284. """Set computational region (WIND file) from named region
  1285. file
  1286. """
  1287. self.MapWindow.SetRegion(zoomOnly=False)
  1288. def OnSetExtentToWind(self, event):
  1289. """Set compulational region extent interactively"""
  1290. self.MapWindow.SetModeDrawRegion()
  1291. def OnSaveDisplayRegion(self, event):
  1292. """Save display extents to named region file."""
  1293. self.MapWindow.SaveRegion(display=True)
  1294. def OnSaveWindRegion(self, event):
  1295. """Save computational region to named region file."""
  1296. self.MapWindow.SaveRegion(display=False)
  1297. def OnZoomMenu(self, event):
  1298. """Popup Zoom menu"""
  1299. zoommenu = Menu()
  1300. for label, handler in (
  1301. (_("Zoom to default region"), self.OnZoomToDefault),
  1302. (_("Zoom to saved region"), self.OnZoomToSaved),
  1303. (None, None),
  1304. (
  1305. _("Set computational region extent from display"),
  1306. self.OnSetDisplayToWind,
  1307. ),
  1308. (
  1309. _("Set computational region extent interactively"),
  1310. self.OnSetExtentToWind,
  1311. ),
  1312. (_("Set computational region from named region"), self.OnSetWindToRegion),
  1313. (None, None),
  1314. (_("Save display geometry to named region"), self.OnSaveDisplayRegion),
  1315. (_("Save computational region to named region"), self.OnSaveWindRegion),
  1316. ):
  1317. if label:
  1318. mid = wx.MenuItem(zoommenu, wx.ID_ANY, label)
  1319. zoommenu.AppendItem(mid)
  1320. self.Bind(wx.EVT_MENU, handler, mid)
  1321. else:
  1322. zoommenu.AppendSeparator()
  1323. # Popup the menu. If an item is selected then its handler will
  1324. # be called before PopupMenu returns.
  1325. self.PopupMenu(zoommenu)
  1326. zoommenu.Destroy()
  1327. def SetProperties(
  1328. self,
  1329. render=False,
  1330. mode=0,
  1331. showCompExtent=False,
  1332. constrainRes=False,
  1333. projection=False,
  1334. alignExtent=True,
  1335. ):
  1336. """Set properties of map display window"""
  1337. self.mapWindowProperties.autoRender = render
  1338. if self.statusbarManager:
  1339. self.statusbarManager.SetMode(mode)
  1340. self.StatusbarUpdate()
  1341. self.mapWindowProperties.useDefinedProjection = projection
  1342. self.mapWindowProperties.showRegion = showCompExtent
  1343. self.mapWindowProperties.alignExtent = alignExtent
  1344. self.mapWindowProperties.resolution = constrainRes
  1345. def GetMapToolbar(self):
  1346. """Returns toolbar with zooming tools"""
  1347. return self.toolbars["map"] if "map" in self.toolbars else None
  1348. def GetDialog(self, name):
  1349. """Get selected dialog if exist"""
  1350. return self.dialogs.get(name, None)
  1351. def OnVNet(self, event):
  1352. """Dialog for v.net* modules"""
  1353. if self.dialogs["vnet"]:
  1354. self.dialogs["vnet"].Raise()
  1355. return
  1356. from vnet.dialogs import VNETDialog
  1357. self.dialogs["vnet"] = VNETDialog(parent=self, giface=self._giface)
  1358. self.closingVNETDialog.connect(self.dialogs["vnet"].OnCloseDialog)
  1359. self.dialogs["vnet"].CenterOnScreen()
  1360. self.dialogs["vnet"].Show()
  1361. def ResetPointer(self):
  1362. """Sets pointer mode.
  1363. Sets pointer and toggles it (e.g. after unregistration of mouse
  1364. handler).
  1365. """
  1366. self.GetMapToolbar().SelectDefault()
  1367. def _switchMapWindow(self, map_win):
  1368. """Notifies activated and disactivated map_wins."""
  1369. self.MapWindow.DisactivateWin()
  1370. map_win.ActivateWin()
  1371. self.MapWindow = map_win
  1372. def AddRDigit(self):
  1373. """Adds raster digitizer: creates toolbar and digitizer controller,
  1374. binds events and signals."""
  1375. from rdigit.controller import RDigitController, EVT_UPDATE_PROGRESS
  1376. from rdigit.toolbars import RDigitToolbar
  1377. self.rdigit = RDigitController(self._giface, mapWindow=self.GetMapWindow())
  1378. self.toolbars["rdigit"] = RDigitToolbar(
  1379. parent=self,
  1380. giface=self._giface,
  1381. controller=self.rdigit,
  1382. toolSwitcher=self._toolSwitcher,
  1383. )
  1384. # connect signals
  1385. self.rdigit.newRasterCreated.connect(self.toolbars["rdigit"].NewRasterAdded)
  1386. self.rdigit.newRasterCreated.connect(
  1387. lambda name: self._giface.mapCreated.emit(name=name, ltype="raster")
  1388. )
  1389. self.rdigit.newFeatureCreated.connect(self.toolbars["rdigit"].UpdateCellValues)
  1390. self.rdigit.uploadMapCategories.connect(
  1391. self.toolbars["rdigit"].UpdateCellValues
  1392. )
  1393. self.rdigit.showNotification.connect(lambda text: self.SetStatusText(text, 0))
  1394. self.rdigit.quitDigitizer.connect(self.QuitRDigit)
  1395. self.rdigit.Bind(
  1396. EVT_UPDATE_PROGRESS,
  1397. lambda evt: self.statusbarManager.SetProgress(
  1398. evt.range, evt.value, evt.text
  1399. ),
  1400. )
  1401. rasters = self.GetMap().GetListOfLayers(
  1402. ltype="raster", mapset=grass.gisenv()["MAPSET"]
  1403. )
  1404. self.toolbars["rdigit"].UpdateRasterLayers(rasters)
  1405. self.toolbars["rdigit"].SelectDefault()
  1406. self.GetMap().layerAdded.connect(self._updateRDigitLayers)
  1407. self.GetMap().layerRemoved.connect(self._updateRDigitLayers)
  1408. self.GetMap().layerChanged.connect(self._updateRDigitLayers)
  1409. self._mgr.AddPane(
  1410. self.toolbars["rdigit"],
  1411. wx.aui.AuiPaneInfo()
  1412. .Name("rdigit toolbar")
  1413. .Caption(_("Raster Digitizer Toolbar"))
  1414. .ToolbarPane()
  1415. .Top()
  1416. .Row(1)
  1417. .LeftDockable(False)
  1418. .RightDockable(False)
  1419. .BottomDockable(False)
  1420. .TopDockable(True)
  1421. .Floatable()
  1422. .CloseButton(False)
  1423. .Layer(2)
  1424. .DestroyOnClose()
  1425. .BestSize((self.toolbars["rdigit"].GetBestSize())),
  1426. )
  1427. self._mgr.Update()
  1428. self.rdigit.Start()
  1429. def _updateRDigitLayers(self, layer):
  1430. mapset = grass.gisenv()["MAPSET"]
  1431. self.toolbars["rdigit"].UpdateRasterLayers(
  1432. rasters=self.GetMap().GetListOfLayers(ltype="raster", mapset=mapset)
  1433. )
  1434. def QuitRDigit(self):
  1435. """Calls digitizer cleanup, removes digitizer object and disconnects
  1436. signals from Map."""
  1437. self.rdigit.CleanUp()
  1438. # disconnect updating layers
  1439. self.GetMap().layerAdded.disconnect(self._updateRDigitLayers)
  1440. self.GetMap().layerRemoved.disconnect(self._updateRDigitLayers)
  1441. self.GetMap().layerChanged.disconnect(self._updateRDigitLayers)
  1442. self._toolSwitcher.toggleToolChanged.disconnect(
  1443. self.toolbars["rdigit"].CheckSelectedTool,
  1444. )
  1445. self.RemoveToolbar("rdigit", destroy=True)
  1446. self.rdigit = None
  1447. def QuitVDigit(self):
  1448. """Quit VDigit"""
  1449. # disable the toolbar
  1450. self.RemoveToolbar("vdigit", destroy=True)
  1451. class MapDisplay(FrameMixin, MapPanel):
  1452. """Map display for wrapping map panel with frame methods"""
  1453. def __init__(self, parent, giface, id, tree, lmgr, idx, Map, title, **kwargs):
  1454. # init map panel
  1455. MapPanel.__init__(
  1456. self,
  1457. parent=parent,
  1458. giface=giface,
  1459. id=id,
  1460. tree=tree,
  1461. lmgr=lmgr,
  1462. Map=Map,
  1463. title=title,
  1464. **kwargs,
  1465. )
  1466. # set system icon
  1467. parent.SetIcon(
  1468. wx.Icon(
  1469. os.path.join(globalvar.ICONDIR, "grass_map.ico"), wx.BITMAP_TYPE_ICO
  1470. )
  1471. )
  1472. # use default frame window layout
  1473. if UserSettings.Get(group="general", key="defWindowPos", subkey="enabled"):
  1474. dim = UserSettings.Get(group="general", key="defWindowPos", subkey="dim")
  1475. idx = 4 + idx * 4
  1476. try:
  1477. x, y = map(int, dim.split(",")[idx : idx + 2])
  1478. w, h = map(int, dim.split(",")[idx + 2 : idx + 4])
  1479. parent.SetPosition((x, y))
  1480. parent.SetSize((w, h))
  1481. except Exception:
  1482. pass
  1483. # bindings
  1484. parent.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  1485. # extend shortcuts and create frame accelerator table
  1486. self.shortcuts_table.append((self.OnFullScreen, wx.ACCEL_NORMAL, wx.WXK_F11))
  1487. self._initShortcuts()
  1488. # add Map Display panel to Map Display frame
  1489. sizer = wx.BoxSizer(wx.VERTICAL)
  1490. sizer.Add(self, proportion=1, flag=wx.EXPAND)
  1491. parent.SetSizer(sizer)
  1492. parent.Layout()