mapdisp.py 22 KB

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