frame.py 48 KB

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