frame.py 48 KB

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