mapdisp.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. """
  2. @package gui_core.mapdisp
  3. @brief Base classes for Map display window
  4. Classes:
  5. - mapdisp::MapFrameBase
  6. - mapdisp::SingleMapFrame
  7. - mapdisp::DoubleMapFrame
  8. (C) 2009-2014 by the GRASS Development Team
  9. This program is free software under the GNU General Public License
  10. (>=v2). Read the file COPYING that comes with GRASS for details.
  11. @author Martin Landa <landa.martin gmail.com>
  12. @author Michael Barton <michael.barton@asu.edu>
  13. @author Vaclav Petras <wenzeslaus gmail.com>
  14. @author Anna Kratochvilova <kratochanna gmail.com>
  15. """
  16. import os
  17. import sys
  18. import wx
  19. import wx.aui
  20. from core import globalvar
  21. from core.debug import Debug
  22. from core.utils import _
  23. from gui_core.toolbars import ToolSwitcher
  24. from grass.script import core as grass
  25. class MapFrameBase(wx.Frame):
  26. """Base class for map display window
  27. Derived class must use (create and initialize) \c statusbarManager
  28. or override
  29. GetProperty(), SetProperty() and HasProperty() methods.
  30. Several methods has to be overriden or
  31. \c NotImplementedError("MethodName") will be raised.
  32. If derived class enables and disables auto-rendering,
  33. it should override IsAutoRendered method.
  34. It is expected that derived class will call _setUpMapWindow().
  35. Derived class can has one or more map windows (and map renderes)
  36. but implementation of MapFrameBase expects that one window and
  37. one map will be current.
  38. Current instances of map window and map renderer should be returned
  39. by methods GetWindow() and GetMap() respectively.
  40. AUI manager is stored in \c self._mgr.
  41. """
  42. def __init__(self, parent = None, id = wx.ID_ANY, title = None,
  43. style = wx.DEFAULT_FRAME_STYLE,
  44. auimgr = None, name = None, **kwargs):
  45. """
  46. .. warning::
  47. Use \a auimgr parameter only if you know what you are doing.
  48. :param parent: gui parent
  49. :param id: wx id
  50. :param title: window title
  51. :param style: \c wx.Frame style
  52. :param toolbars: array of activated toolbars, e.g. ['map', 'digit']
  53. :param auimgr: AUI manager (if \c None, wx.aui.AuiManager is used)
  54. :param name: frame name
  55. :param kwargs: arguments passed to \c wx.Frame
  56. """
  57. self.parent = parent
  58. wx.Frame.__init__(self, parent, id, title, style = style, name = name, **kwargs)
  59. #
  60. # set the size & system icon
  61. #
  62. self.SetClientSize(self.GetSize())
  63. self.iconsize = (16, 16)
  64. self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass_map.ico'), wx.BITMAP_TYPE_ICO))
  65. # toolbars
  66. self.toolbars = {}
  67. #
  68. # Fancy gui
  69. #
  70. if auimgr == None:
  71. self._mgr = wx.aui.AuiManager(self)
  72. else:
  73. self._mgr = auimgr
  74. # handles switching between tools in different toolbars
  75. self._toolSwitcher = ToolSwitcher()
  76. self._toolSwitcher.toggleToolChanged.connect(self._onToggleTool)
  77. def _initMap(self, Map):
  78. """Initialize map display, set dimensions and map region
  79. """
  80. if not grass.find_program('g.region', '--help'):
  81. sys.exit(_("GRASS module '%s' not found. Unable to start map "
  82. "display window.") % 'g.region')
  83. Debug.msg(2, "MapFrame._initMap():")
  84. Map.ChangeMapSize(self.GetClientSize())
  85. Map.region = Map.GetRegion() # g.region -upgc
  86. # self.Map.SetRegion() # adjust region to match display window
  87. def _onToggleTool(self):
  88. self.GetWindow().UnregisterAllHandlers()
  89. def OnSize(self, event):
  90. """Adjust statusbar on changing size"""
  91. # reposition checkbox in statusbar
  92. self.StatusbarReposition()
  93. # update statusbar
  94. self.StatusbarUpdate()
  95. def GetToolSwitcher(self):
  96. return self._toolSwitcher
  97. def SetProperty(self, name, value):
  98. """Sets property"""
  99. self.statusbarManager.SetProperty(name, value)
  100. def GetProperty(self, name):
  101. """Returns property"""
  102. return self.statusbarManager.GetProperty(name)
  103. def HasProperty(self, name):
  104. """Checks whether object has property"""
  105. return self.statusbarManager.HasProperty(name)
  106. def GetPPM(self):
  107. """Get pixel per meter
  108. .. todo::
  109. now computed every time, is it necessary?
  110. .. todo::
  111. enable user to specify ppm (and store it in UserSettings)
  112. """
  113. # TODO: need to be fixed...
  114. ### screen X region problem
  115. ### user should specify ppm
  116. dc = wx.ScreenDC()
  117. dpSizePx = wx.DisplaySize() # display size in pixels
  118. dpSizeMM = wx.DisplaySizeMM() # display size in mm (system)
  119. dpSizeIn = (dpSizeMM[0] / 25.4, dpSizeMM[1] / 25.4) # inches
  120. sysPpi = dc.GetPPI()
  121. comPpi = (dpSizePx[0] / dpSizeIn[0],
  122. dpSizePx[1] / dpSizeIn[1])
  123. ppi = comPpi # pixel per inch
  124. ppm = ((ppi[0] / 2.54) * 100, # pixel per meter
  125. (ppi[1] / 2.54) * 100)
  126. Debug.msg(4, "MapFrameBase.GetPPM(): size: px=%d,%d mm=%f,%f "
  127. "in=%f,%f ppi: sys=%d,%d com=%d,%d; ppm=%f,%f" % \
  128. (dpSizePx[0], dpSizePx[1], dpSizeMM[0], dpSizeMM[1],
  129. dpSizeIn[0], dpSizeIn[1],
  130. sysPpi[0], sysPpi[1], comPpi[0], comPpi[1],
  131. ppm[0], ppm[1]))
  132. return ppm
  133. def SetMapScale(self, value, map = None):
  134. """Set current map scale
  135. :param value: scale value (n if scale is 1:n)
  136. :param map: Map instance (if none self.Map is used)
  137. """
  138. if not map:
  139. map = self.Map
  140. region = self.Map.region
  141. dEW = value * (region['cols'] / self.GetPPM()[0])
  142. dNS = value * (region['rows'] / self.GetPPM()[1])
  143. region['n'] = region['center_northing'] + dNS / 2.
  144. region['s'] = region['center_northing'] - dNS / 2.
  145. region['w'] = region['center_easting'] - dEW / 2.
  146. region['e'] = region['center_easting'] + dEW / 2.
  147. # add to zoom history
  148. self.GetWindow().ZoomHistory(region['n'], region['s'],
  149. region['e'], region['w'])
  150. def GetMapScale(self, map = None):
  151. """Get current map scale
  152. :param map: Map instance (if none self.Map is used)
  153. """
  154. if not map:
  155. map = self.GetMap()
  156. region = map.region
  157. ppm = self.GetPPM()
  158. heightCm = region['rows'] / ppm[1] * 100
  159. widthCm = region['cols'] / ppm[0] * 100
  160. Debug.msg(4, "MapFrame.GetMapScale(): width_cm=%f, height_cm=%f" %
  161. (widthCm, heightCm))
  162. xscale = (region['e'] - region['w']) / (region['cols'] / ppm[0])
  163. yscale = (region['n'] - region['s']) / (region['rows'] / ppm[1])
  164. scale = (xscale + yscale) / 2.
  165. Debug.msg(3, "MapFrame.GetMapScale(): xscale=%f, yscale=%f -> scale=%f" % \
  166. (xscale, yscale, scale))
  167. return scale
  168. def GetProgressBar(self):
  169. """Returns progress bar
  170. Progress bar can be used by other classes.
  171. """
  172. return self.statusbarManager.GetProgressBar()
  173. def GetMap(self):
  174. """Returns current map (renderer) instance"""
  175. raise NotImplementedError("GetMap")
  176. def GetWindow(self):
  177. """Returns current map window"""
  178. raise NotImplementedError("GetWindow")
  179. def GetWindows(self):
  180. """Returns list of map windows"""
  181. raise NotImplementedError("GetWindows")
  182. def GetMapToolbar(self):
  183. """Returns toolbar with zooming tools"""
  184. raise NotImplementedError("GetMapToolbar")
  185. def GetToolbar(self, name):
  186. """Returns toolbar if exists else None.
  187. Toolbars dictionary contains currently used toolbars only.
  188. """
  189. if name in self.toolbars:
  190. return self.toolbars[name]
  191. return None
  192. def StatusbarUpdate(self):
  193. """Update statusbar content"""
  194. Debug.msg(5, "MapFrameBase.StatusbarUpdate()")
  195. self.statusbarManager.Update()
  196. def IsAutoRendered(self):
  197. """Check if auto-rendering is enabled"""
  198. # TODO: this is now not the right place to access this attribute
  199. # TODO: add mapWindowProperties to init parameters
  200. # and pass the right object in the init of derived class?
  201. # or do not use this method at all, let mapwindow decide
  202. return self.mapWindowProperties.autoRender
  203. def CoordinatesChanged(self):
  204. """Shows current coordinates on statusbar.
  205. """
  206. # assuming that the first mode is coordinates
  207. # probably shold not be here but good solution is not available now
  208. if self.statusbarManager.GetMode() == 0:
  209. self.statusbarManager.ShowItem('coordinates')
  210. def StatusbarReposition(self):
  211. """Reposition items in statusbar"""
  212. self.statusbarManager.Reposition()
  213. def StatusbarEnableLongHelp(self, enable = True):
  214. """Enable/disable toolbars long help"""
  215. for toolbar in self.toolbars.itervalues():
  216. toolbar.EnableLongHelp(enable)
  217. def IsStandalone(self):
  218. """Check if map frame is standalone"""
  219. raise NotImplementedError("IsStandalone")
  220. def OnRender(self, event):
  221. """Re-render map composition (each map layer)
  222. """
  223. raise NotImplementedError("OnRender")
  224. def OnDraw(self, event):
  225. """Re-display current map composition
  226. """
  227. self.MapWindow.UpdateMap(render = False)
  228. def OnErase(self, event):
  229. """Erase the canvas
  230. """
  231. self.MapWindow.EraseMap()
  232. def OnZoomIn(self, event):
  233. """Zoom in the map."""
  234. self.MapWindow.SetModeZoomIn()
  235. def OnZoomOut(self, event):
  236. """Zoom out the map."""
  237. self.MapWindow.SetModeZoomOut()
  238. def _setUpMapWindow(self, mapWindow):
  239. """Binds map windows' zoom history signals to map toolbar."""
  240. # enable or disable zoom history tool
  241. mapWindow.zoomHistoryAvailable.connect(
  242. lambda:
  243. self.GetMapToolbar().Enable('zoomBack', enable=True))
  244. mapWindow.zoomHistoryUnavailable.connect(
  245. lambda:
  246. self.GetMapToolbar().Enable('zoomBack', enable=False))
  247. mapWindow.mouseMoving.connect(self.CoordinatesChanged)
  248. def OnPointer(self, event):
  249. """Sets mouse mode to pointer."""
  250. self.MapWindow.SetModePointer()
  251. def OnPan(self, event):
  252. """Panning, set mouse to drag
  253. """
  254. self.MapWindow.SetModePan()
  255. def OnZoomBack(self, event):
  256. """Zoom last (previously stored position)
  257. """
  258. self.MapWindow.ZoomBack()
  259. def OnZoomToMap(self, event):
  260. """
  261. Set display extents to match selected raster (including NULLs)
  262. or vector map.
  263. """
  264. self.MapWindow.ZoomToMap(layers = self.Map.GetListOfLayers())
  265. def OnZoomToWind(self, event):
  266. """Set display geometry to match computational region
  267. settings (set with g.region)
  268. """
  269. self.MapWindow.ZoomToWind()
  270. def OnZoomToDefault(self, event):
  271. """Set display geometry to match default region settings
  272. """
  273. self.MapWindow.ZoomToDefault()
  274. class SingleMapFrame(MapFrameBase):
  275. """Frame with one map window.
  276. It is base class for frames which needs only one map.
  277. Derived class should have \c self.MapWindow or
  278. it has to override GetWindow() methods.
  279. @note To access maps use getters only
  280. (when using class or when writing class itself).
  281. """
  282. def __init__(self, parent = None, giface = None, id = wx.ID_ANY, title = None,
  283. style = wx.DEFAULT_FRAME_STYLE,
  284. Map = None,
  285. auimgr = None, name = None, **kwargs):
  286. """
  287. :param parent: gui parent
  288. :param id: wx id
  289. :param title: window title
  290. :param style: \c wx.Frame style
  291. :param map: instance of render.Map
  292. :param name: frame name
  293. :param kwargs: arguments passed to MapFrameBase
  294. """
  295. MapFrameBase.__init__(self, parent = parent, id = id, title = title,
  296. style = style,
  297. auimgr = auimgr, name = name, **kwargs)
  298. self.Map = Map # instance of render.Map
  299. #
  300. # initialize region values
  301. #
  302. self._initMap(Map = self.Map)
  303. def GetMap(self):
  304. """Returns map (renderer) instance"""
  305. return self.Map
  306. def GetWindow(self):
  307. """Returns map window"""
  308. return self.MapWindow
  309. def GetWindows(self):
  310. """Returns list of map windows"""
  311. return [self.MapWindow]
  312. def OnRender(self, event):
  313. """Re-render map composition (each map layer)
  314. """
  315. self.GetWindow().UpdateMap(render = True, renderVector = True)
  316. # update statusbar
  317. self.StatusbarUpdate()
  318. class DoubleMapFrame(MapFrameBase):
  319. """Frame with two map windows.
  320. It is base class for frames which needs two maps.
  321. There is no primary and secondary map. Both maps are equal.
  322. However, one map is current.
  323. It is expected that derived class will call _bindWindowsActivation()
  324. when both map windows will be initialized.
  325. Drived class should have method GetMapToolbar() returns toolbar
  326. which has methods SetActiveMap() and Enable().
  327. @note To access maps use getters only
  328. (when using class or when writing class itself).
  329. .. todo:
  330. Use it in GCP manager (probably changes to both DoubleMapFrame
  331. and GCP MapFrame will be neccessary).
  332. """
  333. def __init__(self, parent = None, id = wx.ID_ANY, title = None,
  334. style = wx.DEFAULT_FRAME_STYLE,
  335. firstMap = None, secondMap = None,
  336. auimgr = None, name = None, **kwargs):
  337. """
  338. \a firstMap is set as active (by assign it to \c self.Map).
  339. Derived class should assging to \c self.MapWindow to make one
  340. map window current by dafault.
  341. :param parent: gui parent
  342. :param id: wx id
  343. :param title: window title
  344. :param style: \c wx.Frame style
  345. :param name: frame name
  346. :param kwargs: arguments passed to MapFrameBase
  347. """
  348. MapFrameBase.__init__(self, parent = parent, id = id, title = title,
  349. style = style,
  350. auimgr = auimgr, name = name, **kwargs)
  351. self.firstMap = firstMap
  352. self.secondMap = secondMap
  353. self.Map = firstMap
  354. #
  355. # initialize region values
  356. #
  357. self._initMap(Map = self.firstMap)
  358. self._initMap(Map = self.secondMap)
  359. self._bindRegions = False
  360. def _bindWindowsActivation(self):
  361. self.GetFirstWindow().Bind(wx.EVT_ENTER_WINDOW, self.ActivateFirstMap)
  362. self.GetSecondWindow().Bind(wx.EVT_ENTER_WINDOW, self.ActivateSecondMap)
  363. def _onToggleTool(self):
  364. self.GetFirstWindow().UnregisterAllHandlers()
  365. self.GetSecondWindow().UnregisterAllHandlers()
  366. def GetFirstMap(self):
  367. """Returns first Map instance
  368. """
  369. return self.firstMap
  370. def GetSecondMap(self):
  371. """Returns second Map instance
  372. """
  373. return self.secondMap
  374. def GetFirstWindow(self):
  375. """Get first map window"""
  376. return self.firstMapWindow
  377. def GetSecondWindow(self):
  378. """Get second map window"""
  379. return self.secondMapWindow
  380. def GetMap(self):
  381. """Returns current map (renderer) instance
  382. @note Use this method to access current map renderer.
  383. (It is not guarented that current map will be stored in
  384. \c self.Map in future versions.)
  385. """
  386. return self.Map
  387. def GetWindow(self):
  388. """Returns current map window
  389. :func:`GetMap()`
  390. """
  391. return self.MapWindow
  392. def GetWindows(self):
  393. """Return list of all windows"""
  394. return [self.firstMapWindow, self.secondMapWindow]
  395. def ActivateFirstMap(self, event = None):
  396. """Make first Map and MapWindow active and (un)bind regions of the two Maps."""
  397. if self.MapWindow == self.firstMapWindow:
  398. return
  399. self.Map = self.firstMap
  400. self.MapWindow = self.firstMapWindow
  401. self.GetMapToolbar().SetActiveMap(0)
  402. # bind/unbind regions
  403. if self._bindRegions:
  404. self.firstMapWindow.zoomChanged.connect(self.OnZoomChangedFirstMap)
  405. self.secondMapWindow.zoomChanged.disconnect(self.OnZoomChangedSecondMap)
  406. def ActivateSecondMap(self, event = None):
  407. """Make second Map and MapWindow active and (un)bind regions of the two Maps."""
  408. if self.MapWindow == self.secondMapWindow:
  409. return
  410. self.Map = self.secondMap
  411. self.MapWindow = self.secondMapWindow
  412. self.GetMapToolbar().SetActiveMap(1)
  413. if self._bindRegions:
  414. self.secondMapWindow.zoomChanged.connect(self.OnZoomChangedSecondMap)
  415. self.firstMapWindow.zoomChanged.disconnect(self.OnZoomChangedFirstMap)
  416. def SetBindRegions(self, on):
  417. """Set or unset binding display regions."""
  418. self._bindRegions = on
  419. if on:
  420. if self.MapWindow == self.firstMapWindow:
  421. self.firstMapWindow.zoomChanged.connect(self.OnZoomChangedFirstMap)
  422. else:
  423. self.secondMapWindow.zoomChanged.connect(self.OnZoomChangedSecondMap)
  424. else:
  425. if self.MapWindow == self.firstMapWindow:
  426. self.firstMapWindow.zoomChanged.disconnect(self.OnZoomChangedFirstMap)
  427. else:
  428. self.secondMapWindow.zoomChanged.disconnect(self.OnZoomChangedSecondMap)
  429. def OnZoomChangedFirstMap(self):
  430. """Display region of the first window (Map) changed.
  431. Synchronize the region of the second map and re-render it.
  432. This is the default implementation which can be overridden.
  433. """
  434. region = self.GetFirstMap().GetCurrentRegion()
  435. self.GetSecondMap().region.update(region)
  436. self.Render(mapToRender = self.GetSecondWindow())
  437. def OnZoomChangedSecondMap(self):
  438. """Display region of the second window (Map) changed.
  439. Synchronize the region of the second map and re-render it.
  440. This is the default implementation which can be overridden.
  441. """
  442. region = self.GetSecondMap().GetCurrentRegion()
  443. self.GetFirstMap().region.update(region)
  444. self.Render(mapToRender = self.GetFirstWindow())
  445. def OnZoomIn(self, event):
  446. """Zoom in the map."""
  447. self.GetFirstWindow().SetModeZoomIn()
  448. self.GetSecondWindow().SetModeZoomIn()
  449. def OnZoomOut(self, event):
  450. """Zoom out the map."""
  451. self.GetFirstWindow().SetModeZoomOut()
  452. self.GetSecondWindow().SetModeZoomOut()
  453. def OnPan(self, event):
  454. """Panning, set mouse to pan"""
  455. self.GetFirstWindow().SetModePan()
  456. self.GetSecondWindow().SetModePan()
  457. def OnPointer(self, event):
  458. """Set pointer mode (dragging overlays)"""
  459. self.GetFirstWindow().SetModePointer()
  460. self.GetSecondWindow().SetModePointer()
  461. def OnQuery(self, event):
  462. """Set query mode"""
  463. self.GetFirstWindow().SetModeQuery()
  464. self.GetSecondWindow().SetModeQuery()
  465. def OnRender(self, event):
  466. """Re-render map composition (each map layer)
  467. """
  468. self.Render(mapToRender = self.GetFirstWindow())
  469. self.Render(mapToRender = self.GetSecondWindow())
  470. def Render(self, mapToRender):
  471. """Re-render map composition"""
  472. mapToRender.UpdateMap(render = True,
  473. renderVector = mapToRender == self.GetFirstWindow())
  474. # update statusbar
  475. self.StatusbarUpdate()
  476. def OnErase(self, event):
  477. """Erase the canvas
  478. """
  479. self.Erase(mapToErase = self.GetFirstWindow())
  480. self.Erase(mapToErase = self.GetSecondWindow())
  481. def Erase(self, mapToErase):
  482. """Erase the canvas
  483. """
  484. mapToErase.EraseMap()
  485. def OnDraw(self, event):
  486. """Re-display current map composition
  487. """
  488. self.Draw(mapToDraw = self.GetFirstWindow())
  489. self.Draw(mapToDraw = self.GetSecondWindow())
  490. def Draw(self, mapToDraw):
  491. """Re-display current map composition
  492. """
  493. mapToDraw.UpdateMap(render = False)