mapdisp.py 19 KB

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