mapdisp.py 22 KB

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