mapdisp.py 21 KB

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