frame.py 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231
  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.MapWindow3D.overlays = self.MapWindow2D.overlays
  309. self.MapWindow3D.textdict = self.MapWindow2D.textdict
  310. # update overlays needs to be called after because getClientSize
  311. # is called during update and it must give reasonable values
  312. wx.CallAfter(self.MapWindow3D.UpdateOverlays)
  313. self.SetStatusText("", 0)
  314. self._mgr.Update()
  315. def RemoveNviz(self):
  316. """!Restore 2D view"""
  317. try:
  318. self.toolbars['map'].RemoveTool(self.toolbars['map'].rotate)
  319. self.toolbars['map'].RemoveTool(self.toolbars['map'].flyThrough)
  320. except AttributeError:
  321. pass
  322. # update status bar
  323. self.statusbarManager.ShowStatusbarChoiceItemsByClass(self.statusbarItemsHiddenInNviz)
  324. self.statusbarManager.SetMode(UserSettings.Get(group = 'display',
  325. key = 'statusbarMode',
  326. subkey = 'selection'))
  327. self.SetStatusText(_("Please wait, unloading data..."), 0)
  328. self._giface.WriteCmdLog(_("Switching back to 2D view mode..."))
  329. if self.MapWindow3D:
  330. self.MapWindow3D.OnClose(event = None)
  331. # switch from MapWindowGL to MapWindow
  332. self._mgr.GetPane('2d').Show()
  333. self._mgr.GetPane('3d').Hide()
  334. self.MapWindow = self.MapWindow2D
  335. # remove nviz notebook page
  336. self._layerManager.RemoveNvizTools()
  337. try:
  338. self.MapWindow2D.overlays = self.MapWindow3D.overlays
  339. self.MapWindow2D.textdict = self.MapWindow3D.textdict
  340. except AttributeError:
  341. pass
  342. self.MapWindow.UpdateMap()
  343. self._mgr.Update()
  344. def AddToolbar(self, name, fixed = False):
  345. """!Add defined toolbar to the window
  346. Currently recognized toolbars are:
  347. - 'map' - basic map toolbar
  348. - 'vdigit' - vector digitizer
  349. @param name toolbar to add
  350. @param fixed fixed toolbar
  351. """
  352. # default toolbar
  353. if name == "map":
  354. self.toolbars['map'] = MapToolbar(self, self.Map)
  355. self._mgr.AddPane(self.toolbars['map'],
  356. wx.aui.AuiPaneInfo().
  357. Name("maptoolbar").Caption(_("Map Toolbar")).
  358. ToolbarPane().Top().Name('mapToolbar').
  359. LeftDockable(False).RightDockable(False).
  360. BottomDockable(False).TopDockable(True).
  361. CloseButton(False).Layer(2).
  362. BestSize((self.toolbars['map'].GetBestSize())))
  363. # vector digitizer
  364. elif name == "vdigit":
  365. self.toolbars['map'].combo.SetValue(_("Digitize"))
  366. self._addToolbarVDigit()
  367. if fixed:
  368. self.toolbars['map'].combo.Disable()
  369. self._mgr.Update()
  370. def RemoveToolbar (self, name):
  371. """!Removes defined toolbar from the window
  372. @todo Only hide, activate by calling AddToolbar()
  373. """
  374. # cannot hide main toolbar
  375. if name == "map":
  376. return
  377. self._mgr.DetachPane(self.toolbars[name])
  378. self.toolbars[name].Destroy()
  379. self.toolbars.pop(name)
  380. if name == 'vdigit':
  381. self._mgr.GetPane('vdigit').Hide()
  382. self._mgr.GetPane('2d').Show()
  383. self.MapWindow = self.MapWindow2D
  384. self.toolbars['map'].combo.SetValue(_("2D view"))
  385. self.toolbars['map'].Enable2D(True)
  386. self._mgr.Update()
  387. def IsPaneShown(self, name):
  388. """!Check if pane (toolbar, mapWindow ...) of given name is currently shown"""
  389. if self._mgr.GetPane(name).IsOk():
  390. return self._mgr.GetPane(name).IsShown()
  391. return False
  392. def OnFocus(self, event):
  393. """!Change choicebook page to match display.
  394. """
  395. # change bookcontrol page to page associated with display
  396. if self.page:
  397. pgnum = self.layerbook.GetPageIndex(self.page)
  398. if pgnum > -1:
  399. self.layerbook.SetSelection(pgnum)
  400. self._layerManager.currentPage = self.layerbook.GetCurrentPage()
  401. event.Skip()
  402. def RemoveQueryLayer(self):
  403. """!Removes temporary map layers (queries)"""
  404. qlayer = self.GetMap().GetListOfLayers(name = globalvar.QUERYLAYER)
  405. for layer in qlayer:
  406. self.GetMap().DeleteLayer(layer)
  407. def OnRender(self, event):
  408. """!Re-render map composition (each map layer)
  409. """
  410. self.RemoveQueryLayer()
  411. # deselect features in vdigit
  412. if self.GetToolbar('vdigit'):
  413. if self.MapWindow.digit:
  414. self.MapWindow.digit.GetDisplay().SetSelected([])
  415. self.MapWindow.UpdateMap(render = True, renderVector = True)
  416. else:
  417. self.MapWindow.UpdateMap(render = True)
  418. # update statusbar
  419. self.StatusbarUpdate()
  420. def OnPointer(self, event):
  421. """!Pointer button clicked
  422. """
  423. if self.GetMapToolbar():
  424. if event:
  425. self.SwitchTool(self.toolbars['map'], event)
  426. self.toolbars['map'].action['desc'] = ''
  427. self.MapWindow.mouse['use'] = "pointer"
  428. self.MapWindow.mouse['box'] = "point"
  429. # change the cursor
  430. if self.GetToolbar('vdigit'):
  431. # digitization tool activated
  432. self.MapWindow.SetNamedCursor('cross')
  433. # reset mouse['box'] if needed
  434. if self.toolbars['vdigit'].GetAction() in ['addLine']:
  435. if self.toolbars['vdigit'].GetAction('type') in ['point', 'centroid']:
  436. self.MapWindow.mouse['box'] = 'point'
  437. else: # line, boundary
  438. self.MapWindow.mouse['box'] = 'line'
  439. elif self.toolbars['vdigit'].GetAction() in ['addVertex', 'removeVertex', 'splitLine',
  440. 'editLine', 'displayCats', 'queryMap',
  441. 'copyCats']:
  442. self.MapWindow.mouse['box'] = 'point'
  443. else: # moveLine, deleteLine
  444. self.MapWindow.mouse['box'] = 'box'
  445. else:
  446. self.MapWindow.SetNamedCursor('default')
  447. def OnRotate(self, event):
  448. """!Rotate 3D view
  449. """
  450. if self.GetMapToolbar():
  451. self.SwitchTool(self.toolbars['map'], event)
  452. self.toolbars['map'].action['desc'] = ''
  453. self.MapWindow.mouse['use'] = "rotate"
  454. # change the cursor
  455. self.MapWindow.SetNamedCursor('hand')
  456. def OnFlyThrough(self, event):
  457. """!Fly-through mode
  458. """
  459. if self.GetMapToolbar():
  460. self.SwitchTool(self.toolbars['map'], event)
  461. self.toolbars['map'].action['desc'] = ''
  462. self.MapWindow.mouse['use'] = "fly"
  463. # change the cursor
  464. self.MapWindow.SetNamedCursor('hand')
  465. self.MapWindow.SetFocus()
  466. def SaveToFile(self, event):
  467. """!Save map to image
  468. """
  469. if self.IsPaneShown('3d'):
  470. filetype = "TIF file (*.tif)|*.tif|PPM file (*.ppm)|*.ppm"
  471. ltype = [{ 'ext' : 'tif', 'type' : 'tif' },
  472. { 'ext' : 'ppm', 'type' : 'ppm' }]
  473. else:
  474. img = self.MapWindow.img
  475. if not img:
  476. GMessage(parent = self,
  477. message = _("Nothing to render (empty map). Operation canceled."))
  478. return
  479. filetype, ltype = GetImageHandlers(img)
  480. # get size
  481. dlg = ImageSizeDialog(self)
  482. dlg.CentreOnParent()
  483. if dlg.ShowModal() != wx.ID_OK:
  484. dlg.Destroy()
  485. return
  486. width, height = dlg.GetValues()
  487. dlg.Destroy()
  488. # get filename
  489. dlg = wx.FileDialog(parent = self,
  490. message = _("Choose a file name to save the image "
  491. "(no need to add extension)"),
  492. wildcard = filetype,
  493. style = wx.SAVE | wx.FD_OVERWRITE_PROMPT)
  494. if dlg.ShowModal() == wx.ID_OK:
  495. path = dlg.GetPath()
  496. if not path:
  497. dlg.Destroy()
  498. return
  499. base, ext = os.path.splitext(path)
  500. fileType = ltype[dlg.GetFilterIndex()]['type']
  501. extType = ltype[dlg.GetFilterIndex()]['ext']
  502. if ext != extType:
  503. path = base + '.' + extType
  504. self.MapWindow.SaveToFile(path, fileType,
  505. width, height)
  506. dlg.Destroy()
  507. def PrintMenu(self, event):
  508. """
  509. Print options and output menu for map display
  510. """
  511. printmenu = wx.Menu()
  512. # Add items to the menu
  513. setup = wx.MenuItem(printmenu, wx.ID_ANY, _('Page setup'))
  514. printmenu.AppendItem(setup)
  515. self.Bind(wx.EVT_MENU, self.printopt.OnPageSetup, setup)
  516. preview = wx.MenuItem(printmenu, wx.ID_ANY, _('Print preview'))
  517. printmenu.AppendItem(preview)
  518. self.Bind(wx.EVT_MENU, self.printopt.OnPrintPreview, preview)
  519. doprint = wx.MenuItem(printmenu, wx.ID_ANY, _('Print display'))
  520. printmenu.AppendItem(doprint)
  521. self.Bind(wx.EVT_MENU, self.printopt.OnDoPrint, doprint)
  522. # Popup the menu. If an item is selected then its handler
  523. # will be called before PopupMenu returns.
  524. self.PopupMenu(printmenu)
  525. printmenu.Destroy()
  526. def OnCloseWindow(self, event):
  527. """!Window closed.
  528. Also close associated layer tree page
  529. """
  530. pgnum = None
  531. self.Map.Clean()
  532. # close edited map and 3D tools properly
  533. if self.GetToolbar('vdigit'):
  534. maplayer = self.toolbars['vdigit'].GetLayer()
  535. if maplayer:
  536. self.toolbars['vdigit'].OnExit()
  537. if self.IsPaneShown('3d'):
  538. self.RemoveNviz()
  539. if not self._layerManager:
  540. self.Destroy()
  541. elif self.page:
  542. pgnum = self.layerbook.GetPageIndex(self.page)
  543. if pgnum > -1:
  544. self.layerbook.DeletePage(pgnum)
  545. def Query(self, x, y):
  546. """!Query selected layers.
  547. @param x,y coordinates
  548. @param layers selected tree item layers
  549. """
  550. layers = self._giface.GetLayerList().GetSelectedLayers(checkedOnly=False)
  551. rast = []
  552. vect = []
  553. for layer in layers:
  554. name, found = GetLayerNameFromCmd(layer.cmd)
  555. if not found:
  556. continue
  557. ltype = layer.maplayer.GetType()
  558. if ltype == 'raster':
  559. rast.append(name)
  560. elif ltype in ('rgb', 'his'):
  561. for iname in name.split('\n'):
  562. rast.append(iname)
  563. elif ltype in ('vector', 'thememap', 'themechart'):
  564. vect.append(name)
  565. if vect:
  566. # check for vector maps open to be edited
  567. digitToolbar = self.GetToolbar('vdigit')
  568. if digitToolbar:
  569. lmap = digitToolbar.GetLayer().GetName()
  570. for name in vect:
  571. if lmap == name:
  572. self._giface.WriteWarning(_("Vector map <%s> "
  573. "opened for editing - skipped.") % lmap)
  574. vect.remove(name)
  575. if not (rast + vect):
  576. GMessage(parent = self,
  577. message = _('No raster or vector map layer selected for querying.'))
  578. return
  579. # set query snap distance for v.what at map unit equivalent of 10 pixels
  580. qdist = 10.0 * ((self.Map.region['e'] - self.Map.region['w']) / self.Map.width)
  581. # TODO: replace returning None by exception or so
  582. try:
  583. east, north = self.MapWindow.Pixel2Cell((x, y))
  584. except TypeError:
  585. return
  586. if not self.IsPaneShown('3d'):
  587. self.QueryMap(east, north, qdist, rast, vect)
  588. else:
  589. if rast:
  590. self.MapWindow.QuerySurface(x, y)
  591. if vect:
  592. self.QueryMap(east, north, qdist, rast = [], vect = vect)
  593. def QueryMap(self, east, north, qdist, rast, vect):
  594. """!Query raster or vector map layers by r/v.what
  595. @param east,north coordinates
  596. @param qdist query distance
  597. @param rast raster map names
  598. @param vect vector map names
  599. """
  600. Debug.msg(1, "QueryMap(): raster=%s vector=%s" % (','.join(rast),
  601. ','.join(vect)))
  602. # use display region settings instead of computation region settings
  603. self.tmpreg = os.getenv("GRASS_REGION")
  604. os.environ["GRASS_REGION"] = self.Map.SetRegion(windres = False)
  605. rastQuery = []
  606. vectQuery = []
  607. if rast:
  608. rastQuery = grass.raster_what(map=rast, coord=(east, north))
  609. if vect:
  610. vectQuery = grass.vector_what(map=vect, coord=(east, north), distance=qdist)
  611. self._QueryMapDone()
  612. if 'Id' in vectQuery:
  613. self._queryHighlight(vectQuery)
  614. result = rastQuery + vectQuery
  615. result = PrepareQueryResults(coordinates = (east, north), result = result)
  616. if self.dialogs['query']:
  617. self.dialogs['query'].Raise()
  618. self.dialogs['query'].SetData(result)
  619. else:
  620. self.dialogs['query'] = QueryDialog(parent = self, data = result)
  621. self.dialogs['query'].Bind(wx.EVT_CLOSE, self._oncloseQueryDialog)
  622. self.dialogs['query'].Show()
  623. def _oncloseQueryDialog(self, event):
  624. self.dialogs['query'] = None
  625. event.Skip()
  626. def _queryHighlight(self, vectQuery):
  627. """!Highlight category from query."""
  628. cats = name = None
  629. for res in vectQuery:
  630. cats = {res['Layer']: [res['Category']]}
  631. name = res['Map']
  632. try:
  633. qlayer = self.Map.GetListOfLayers(name = globalvar.QUERYLAYER)[0]
  634. except IndexError:
  635. qlayer = None
  636. if not (cats and name):
  637. if qlayer:
  638. self.Map.DeleteLayer(qlayer)
  639. self.MapWindow.UpdateMap(render = False, renderVector = False)
  640. return
  641. if not self.IsPaneShown('3d') and self.IsAutoRendered():
  642. # highlight feature & re-draw map
  643. if qlayer:
  644. qlayer.SetCmd(self.AddTmpVectorMapLayer(name, cats,
  645. useId = False,
  646. addLayer = False))
  647. else:
  648. qlayer = self.AddTmpVectorMapLayer(name, cats, useId = False)
  649. # set opacity based on queried layer
  650. # TODO fix
  651. # opacity = layer.maplayer.GetOpacity(float = True)
  652. # qlayer.SetOpacity(opacity)
  653. self.MapWindow.UpdateMap(render = False, renderVector = False)
  654. def _QueryMapDone(self):
  655. """!Restore settings after querying (restore GRASS_REGION)
  656. """
  657. if hasattr(self, "tmpreg"):
  658. if self.tmpreg:
  659. os.environ["GRASS_REGION"] = self.tmpreg
  660. elif 'GRASS_REGION' in os.environ:
  661. del os.environ["GRASS_REGION"]
  662. elif 'GRASS_REGION' in os.environ:
  663. del os.environ["GRASS_REGION"]
  664. if hasattr(self, "tmpreg"):
  665. del self.tmpreg
  666. def OnQuery(self, event):
  667. """!Query tools menu"""
  668. if self.GetMapToolbar():
  669. self.SwitchTool(self.toolbars['map'], event)
  670. self.toolbars['map'].action['desc'] = 'queryMap'
  671. self.MapWindow.mouse['use'] = "query"
  672. self.MapWindow.mouse['box'] = "point"
  673. self.MapWindow.zoomtype = 0
  674. # change the cursor
  675. self.MapWindow.SetNamedCursor('cross')
  676. def AddTmpVectorMapLayer(self, name, cats, useId = False, addLayer = True):
  677. """!Add temporal vector map layer to map composition
  678. @param name name of map layer
  679. @param useId use feature id instead of category
  680. """
  681. # color settings from ATM
  682. color = UserSettings.Get(group = 'atm', key = 'highlight', subkey = 'color')
  683. colorStr = str(color[0]) + ":" + \
  684. str(color[1]) + ":" + \
  685. str(color[2])
  686. # icon used in vector display and its size
  687. icon = ''
  688. size = 0
  689. # here we know that there is one selected layer and it is vector
  690. vparam = self._giface.GetLayerList().GetSelectedLayers()[0].cmd
  691. for p in vparam:
  692. if '=' in p:
  693. parg,pval = p.split('=', 1)
  694. if parg == 'icon': icon = pval
  695. elif parg == 'size': size = float(pval)
  696. pattern = ["d.vect",
  697. "map=%s" % name,
  698. "color=%s" % colorStr,
  699. "fcolor=%s" % colorStr,
  700. "width=%d" % UserSettings.Get(group = 'atm', key = 'highlight', subkey = 'width')]
  701. if icon != '':
  702. pattern.append('icon=%s' % icon)
  703. if size > 0:
  704. pattern.append('size=%i' % size)
  705. if useId:
  706. cmd = pattern
  707. cmd.append('-i')
  708. cmd.append('cats=%s' % str(cats))
  709. else:
  710. cmd = []
  711. for layer in cats.keys():
  712. cmd.append(copy.copy(pattern))
  713. lcats = cats[layer]
  714. cmd[-1].append("layer=%d" % layer)
  715. cmd[-1].append("cats=%s" % ListOfCatsToRange(lcats))
  716. if addLayer:
  717. if useId:
  718. return self.Map.AddLayer(ltype = 'vector', name = globalvar.QUERYLAYER, command = cmd,
  719. active = True, hidden = True, opacity = 1.0)
  720. else:
  721. return self.Map.AddLayer(ltype = 'command', name = globalvar.QUERYLAYER, command = cmd,
  722. active = True, hidden = True, opacity = 1.0)
  723. else:
  724. return cmd
  725. def OnMeasure(self, event):
  726. if not self.measureDistController:
  727. self.measureDistController = MeasureDistanceController(self._giface,
  728. mapWindow=self.GetMapWindow())
  729. self.measureDistController.Start()
  730. def OnProfile(self, event):
  731. """!Launch profile tool
  732. """
  733. self.profileController = ProfileController(self._giface, mapWindow=self.GetMapWindow())
  734. rasters = []
  735. layers = self._giface.GetLayerList().GetSelectedLayers()
  736. for layer in layers:
  737. if layer.type == 'raster':
  738. rasters.append(layer.maplayer.name)
  739. win = ProfileFrame(parent=self, rasterList=rasters,
  740. controller=self.profileController)
  741. win.CentreOnParent()
  742. win.Show()
  743. # Open raster select dialog to make sure that a raster (and
  744. # the desired raster) is selected to be profiled
  745. win.OnSelectRaster(None)
  746. def OnHistogramPyPlot(self, event):
  747. """!Init PyPlot histogram display canvas and tools
  748. """
  749. raster = []
  750. for layer in self._giface.GetLayerList().GetSelectedLayers():
  751. if layer.maplayer.GetType() == 'raster':
  752. raster.append(layer.maplayer.GetName())
  753. win = HistogramPlotFrame(parent = self, rasterList = raster)
  754. win.CentreOnParent()
  755. win.Show()
  756. def OnScatterplot(self, event):
  757. """!Init PyPlot scatterplot display canvas and tools
  758. """
  759. raster = []
  760. for layer in self._giface.GetLayerList().GetSelectedLayers():
  761. if layer.maplayer.GetType() == 'raster':
  762. raster.append(layer.maplayer.GetName())
  763. win = ScatterFrame(parent = self, rasterList = raster)
  764. win.CentreOnParent()
  765. win.Show()
  766. # Open raster select dialog to make sure that at least 2 rasters (and the desired rasters)
  767. # are selected to be plotted
  768. win.OnSelectRaster(None)
  769. def OnHistogram(self, event):
  770. """!Init histogram display canvas and tools
  771. """
  772. win = HistogramFrame(self)
  773. win.CentreOnParent()
  774. win.Show()
  775. win.Refresh()
  776. win.Update()
  777. def _activateOverlay(self, overlayId):
  778. """!Launch decoratio dialog according to overlay id.
  779. @param overlayId id of overlay
  780. """
  781. if overlayId > 100:
  782. self.OnAddText(None)
  783. elif overlayId == 0:
  784. self.AddBarscale()
  785. elif overlayId == 1:
  786. self.AddLegend()
  787. def AddBarscale(self, cmd = None, showDialog = True):
  788. """!Handler for scale/arrow map decoration menu selection.
  789. """
  790. if cmd:
  791. self.barscale.cmd = cmd
  792. if not showDialog:
  793. self.barscale.Show()
  794. self.MapWindow.UpdateMap()
  795. return
  796. # Decoration overlay control dialog
  797. if self.dialogs['barscale']:
  798. if self.dialogs['barscale'].IsShown():
  799. self.dialogs['barscale'].SetFocus()
  800. else:
  801. self.dialogs['barscale'].Show()
  802. else:
  803. # If location is latlon, only display north arrow (scale won't work)
  804. # proj = self.Map.projinfo['proj']
  805. # if proj == 'll':
  806. # barcmd = 'd.barscale -n'
  807. # else:
  808. # barcmd = 'd.barscale'
  809. # decoration overlay control dialog
  810. self.dialogs['barscale'] = \
  811. DecorationDialog(parent=self, title=_('Scale and North arrow'),
  812. giface=self._giface,
  813. overlayController=self.barscale,
  814. ddstyle=DECOR_DIALOG_BARSCALE,
  815. size=(350, 200),
  816. style=wx.DEFAULT_DIALOG_STYLE | wx.CENTRE)
  817. self.dialogs['barscale'].CentreOnParent()
  818. ### dialog cannot be show as modal - in the result d.barscale is not selectable
  819. ### self.dialogs['barscale'].ShowModal()
  820. self.dialogs['barscale'].Show()
  821. self.MapWindow.mouse['use'] = 'pointer'
  822. def AddLegend(self, cmd = None, showDialog = True):
  823. """!Handler for legend map decoration menu selection.
  824. """
  825. if cmd:
  826. self.legend.cmd = cmd
  827. else:
  828. layers = self._giface.GetLayerList().GetSelectedLayers()
  829. for layer in layers:
  830. if layer.type == 'raster':
  831. self.legend.cmd.append('map=%s' % layer.maplayer.name)
  832. break
  833. if not showDialog:
  834. self.legend.Show()
  835. self.MapWindow.UpdateMap()
  836. return
  837. # Decoration overlay control dialog
  838. if self.dialogs['legend']:
  839. if self.dialogs['legend'].IsShown():
  840. self.dialogs['legend'].SetFocus()
  841. else:
  842. self.dialogs['legend'].Show()
  843. else:
  844. self.dialogs['legend'] = \
  845. DecorationDialog(parent=self, title=_("Legend"),
  846. overlayController=self.legend,
  847. giface=self._giface,
  848. ddstyle=DECOR_DIALOG_LEGEND,
  849. size=(350, 200),
  850. style=wx.DEFAULT_DIALOG_STYLE | wx.CENTRE)
  851. self.dialogs['legend'].CentreOnParent()
  852. ### dialog cannot be show as modal - in the result d.legend is not selectable
  853. ### self.dialogs['legend'].ShowModal()
  854. self.dialogs['legend'].Show()
  855. self.MapWindow.mouse['use'] = 'pointer'
  856. def OnAddText(self, event):
  857. """!Handler for text decoration menu selection.
  858. """
  859. self.SwitchTool(self.toolbars['map'], event)
  860. if self.MapWindow.dragid > -1:
  861. id = self.MapWindow.dragid
  862. self.MapWindow.dragid = -1
  863. else:
  864. # index for overlay layer in render
  865. if len(self.MapWindow.textdict.keys()) > 0:
  866. id = max(self.MapWindow.textdict.keys()) + 1
  867. else:
  868. id = 101
  869. self.dialogs['text'] = TextLayerDialog(parent = self, ovlId = id,
  870. title = _('Add text layer'),
  871. size = (400, 200))
  872. self.dialogs['text'].CenterOnParent()
  873. # If OK button pressed in decoration control dialog
  874. if self.dialogs['text'].ShowModal() == wx.ID_OK:
  875. text = self.dialogs['text'].GetValues()['text']
  876. active = self.dialogs['text'].GetValues()['active']
  877. # delete object if it has no text or is not active
  878. if text == '' or active == False:
  879. try:
  880. self.MapWindow2D.pdc.ClearId(id)
  881. self.MapWindow2D.pdc.RemoveId(id)
  882. del self.MapWindow.textdict[id]
  883. if self.IsPaneShown('3d'):
  884. self.MapWindow3D.UpdateOverlays()
  885. self.MapWindow.UpdateMap()
  886. else:
  887. self.MapWindow2D.UpdateMap(render = False, renderVector = False)
  888. except:
  889. pass
  890. return
  891. self.MapWindow.textdict[id] = self.dialogs['text'].GetValues()
  892. if self.IsPaneShown('3d'):
  893. self.MapWindow3D.UpdateOverlays()
  894. self.MapWindow3D.UpdateMap()
  895. else:
  896. self.MapWindow2D.pdc.ClearId(id)
  897. self.MapWindow2D.pdc.SetId(id)
  898. self.MapWindow2D.UpdateMap(render = False, renderVector = False)
  899. self.MapWindow.mouse['use'] = 'pointer'
  900. def OnAddArrow(self, event):
  901. """!Handler for north arrow menu selection.
  902. Opens Appearance page of nviz notebook.
  903. """
  904. self._layerManager.nviz.SetPage('decoration')
  905. self.MapWindow3D.SetDrawArrow((70, 70))
  906. def GetOptData(self, dcmd, type, params, propwin):
  907. """!Callback method for decoration overlay command generated by
  908. dialog created in menuform.py
  909. """
  910. # Reset comand and rendering options in render.Map. Always render decoration.
  911. # Showing/hiding handled by PseudoDC
  912. self.Map.ChangeOverlay(ovltype = type, type = 'overlay', name = '', command = dcmd,
  913. active = True, render = False)
  914. self.params[type] = params
  915. self.propwin[type] = propwin
  916. def OnZoomToMap(self, event):
  917. """!Set display extents to match selected raster (including
  918. NULLs) or vector map.
  919. """
  920. layers = None
  921. if self.IsStandalone():
  922. layers = self.MapWindow.GetMap().GetListOfLayers(active = False)
  923. self.MapWindow.ZoomToMap(layers = layers)
  924. def OnZoomToRaster(self, event):
  925. """!Set display extents to match selected raster map (ignore NULLs)
  926. """
  927. self.MapWindow.ZoomToMap(ignoreNulls = True)
  928. def OnZoomToSaved(self, event):
  929. """!Set display geometry to match extents in
  930. saved region file
  931. """
  932. self.MapWindow.ZoomToSaved()
  933. def OnDisplayToWind(self, event):
  934. """!Set computational region (WIND file) to match display
  935. extents
  936. """
  937. self.MapWindow.DisplayToWind()
  938. def OnSaveDisplayRegion(self, event):
  939. """!Save display extents to named region file.
  940. """
  941. self.MapWindow.SaveRegion(display = True)
  942. def OnSaveWindRegion(self, event):
  943. """!Save computational region to named region file.
  944. """
  945. self.MapWindow.SaveRegion(display = False)
  946. def OnZoomMenu(self, event):
  947. """!Popup Zoom menu
  948. """
  949. zoommenu = wx.Menu()
  950. for label, handler in ((_('Zoom to computational region'), self.OnZoomToWind),
  951. (_('Zoom to default region'), self.OnZoomToDefault),
  952. (_('Zoom to saved region'), self.OnZoomToSaved),
  953. (_('Set computational region from display extent'), self.OnDisplayToWind),
  954. (_('Save display geometry to named region'), self.OnSaveDisplayRegion),
  955. (_('Save computational region to named region'), self.OnSaveWindRegion)):
  956. mid = wx.MenuItem(zoommenu, wx.ID_ANY, label)
  957. zoommenu.AppendItem(mid)
  958. self.Bind(wx.EVT_MENU, handler, mid)
  959. # Popup the menu. If an item is selected then its handler will
  960. # be called before PopupMenu returns.
  961. self.PopupMenu(zoommenu)
  962. zoommenu.Destroy()
  963. def SetProperties(self, render = False, mode = 0, showCompExtent = False,
  964. constrainRes = False, projection = False, alignExtent = True):
  965. """!Set properies of map display window"""
  966. self.mapWindowProperties.autoRender = render
  967. self.statusbarManager.SetMode(mode)
  968. self.StatusbarUpdate()
  969. self.mapWindowProperties.showRegion = showCompExtent
  970. self.mapWindowProperties.alignExtent = alignExtent
  971. self.mapWindowProperties.resolution = constrainRes
  972. self.SetProperty('projection', projection)
  973. def IsStandalone(self):
  974. """!Check if Map display is standalone"""
  975. if self._layerManager:
  976. return False
  977. return True
  978. def GetLayerManager(self):
  979. """!Get reference to Layer Manager
  980. @return window reference
  981. @return None (if standalone)
  982. """
  983. return self._layerManager
  984. def GetMapToolbar(self):
  985. """!Returns toolbar with zooming tools"""
  986. return self.toolbars['map']
  987. def OnVNet(self, event):
  988. """!Dialog for v.net* modules
  989. """
  990. if self.dialogs['vnet']:
  991. self.dialogs['vnet'].Raise()
  992. return
  993. from vnet.dialogs import VNETDialog
  994. self.dialogs['vnet'] = VNETDialog(parent=self, giface=self._giface)
  995. self.dialogs['vnet'].CenterOnScreen()
  996. self.dialogs['vnet'].Show()
  997. def SwitchTool(self, toolbar, event):
  998. """!Calls UpdateTools to manage connected toolbars"""
  999. self.UpdateTools(event)
  1000. SingleMapFrame.SwitchTool(self, toolbar, event)
  1001. def UpdateTools(self, event):
  1002. """!Method deals with relations of toolbars and other
  1003. elements"""
  1004. # untoggles button in other toolbars
  1005. for toolbar in self.toolbars.itervalues():
  1006. if hasattr(event, 'GetEventObject') == True:
  1007. if event.GetEventObject() == toolbar:
  1008. continue
  1009. toolbar.ToggleTool(toolbar.action['id'], False)
  1010. toolbar.action['id'] = -1
  1011. toolbar.OnTool(None)
  1012. # mouse settings
  1013. self.MapWindow.mouse['box'] = 'point'
  1014. self.MapWindow.mouse['use'] = 'pointer'
  1015. # untoggles button in add legend dialog
  1016. # FIXME: remove this mess
  1017. if self.dialogs['legend']:
  1018. btn = self.dialogs['legend'].resizeBtn
  1019. if btn.GetValue():
  1020. btn.SetValue(0)
  1021. self.dialogs['legend'].DisconnectResizing()
  1022. if self.measureDistController and self.measureDistController.IsActive():
  1023. self.measureDistController.Stop(restore=False)
  1024. def ResetPointer(self):
  1025. """Sets pointer mode.
  1026. Sets pointer and toggles it (e.g. after unregistration of mouse
  1027. handler).
  1028. Somehow related to UpdateTools.
  1029. """
  1030. # sets pointer mode
  1031. toolbar = self.toolbars['map']
  1032. toolbar.action['id'] = vars(toolbar)["pointer"]
  1033. toolbar.OnTool(None)
  1034. self.OnPointer(event=None)