mapdisp.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  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-2011 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. if toolbar:
  244. toolbar.OnTool(event)
  245. toolbar.action['desc'] = ''
  246. def OnPan(self, event):
  247. """!Panning, set mouse to drag
  248. """
  249. toolbar = self.GetMapToolbar()
  250. self._switchTool(toolbar, event)
  251. win = self.GetWindow()
  252. self._preparePan(mapWindow = win)
  253. def _preparePan(self, mapWindow):
  254. """!Prepares MapWindow for pan, toggles toolbar
  255. @param mapWindow MapWindow to prepare
  256. """
  257. mapWindow.mouse['use'] = "pan"
  258. mapWindow.mouse['box'] = "pan"
  259. mapWindow.zoomtype = 0
  260. # change the cursor
  261. mapWindow.SetCursor(self.cursors["hand"])
  262. def OnZoomBack(self, event):
  263. """!Zoom last (previously stored position)
  264. """
  265. self.MapWindow.ZoomBack()
  266. def OnZoomToMap(self, event):
  267. """!
  268. Set display extents to match selected raster (including NULLs)
  269. or vector map.
  270. """
  271. self.MapWindow.ZoomToMap(layers = self.Map.GetListOfLayers())
  272. def OnZoomToWind(self, event):
  273. """!Set display geometry to match computational region
  274. settings (set with g.region)
  275. """
  276. self.MapWindow.ZoomToWind()
  277. def OnZoomToDefault(self, event):
  278. """!Set display geometry to match default region settings
  279. """
  280. self.MapWindow.ZoomToDefault()
  281. class SingleMapFrame(MapFrameBase):
  282. """! Frame with one map window.
  283. It is base class for frames which needs only one map.
  284. Derived class should have \c self.MapWindow or
  285. it has to override GetWindow() methods.
  286. @note To access maps use getters only
  287. (when using class or when writing class itself).
  288. """
  289. def __init__(self, parent = None, id = wx.ID_ANY, title = None,
  290. style = wx.DEFAULT_FRAME_STYLE,
  291. Map = None,
  292. auimgr = None, name = None, **kwargs):
  293. """!
  294. @param parent gui parent
  295. @param id wx id
  296. @param title window title
  297. @param style \c wx.Frame style
  298. @param Map instance of render.Map
  299. @param name frame name
  300. @param kwargs arguments passed to MapFrameBase
  301. """
  302. MapFrameBase.__init__(self, parent = parent, id = id, title = title,
  303. style = style,
  304. auimgr = auimgr, name = name, **kwargs)
  305. self.Map = Map # instance of render.Map
  306. #
  307. # initialize region values
  308. #
  309. self._initMap(Map = self.Map)
  310. def GetMap(self):
  311. """!Returns map (renderer) instance"""
  312. return self.Map
  313. def GetWindow(self):
  314. """!Returns map window"""
  315. return self.MapWindow
  316. def OnRender(self, event):
  317. """!Re-render map composition (each map layer)
  318. """
  319. self.GetWindow().UpdateMap(render = True, renderVector = True)
  320. # update statusbar
  321. self.StatusbarUpdate()
  322. class DoubleMapFrame(MapFrameBase):
  323. """! Frame with two map windows.
  324. It is base class for frames which needs two maps.
  325. There is no primary and secondary map. Both maps are equal.
  326. However, one map is current.
  327. It is expected that derived class will call _bindWindowsActivation()
  328. when both map windows will be initialized.
  329. Drived class should have method GetMapToolbar() returns toolbar
  330. which has method SetActiveMap().
  331. @note To access maps use getters only
  332. (when using class or when writing class itself).
  333. @todo Use it in GCP manager
  334. (probably changes to both DoubleMapFrame and GCP MapFrame will be neccessary).
  335. """
  336. def __init__(self, parent = None, id = wx.ID_ANY, title = None,
  337. style = wx.DEFAULT_FRAME_STYLE,
  338. firstMap = None, secondMap = None,
  339. auimgr = None, name = None, **kwargs):
  340. """!
  341. \a firstMap is set as active (by assign it to \c self.Map).
  342. Derived class should assging to \c self.MapWindow to make one
  343. map window current by dafault.
  344. @param parent gui parent
  345. @param id wx id
  346. @param title window title
  347. @param style \c wx.Frame style
  348. @param name frame name
  349. @param kwargs arguments passed to MapFrameBase
  350. """
  351. MapFrameBase.__init__(self, parent = parent, id = id, title = title,
  352. style = style,
  353. auimgr = auimgr, name = name, **kwargs)
  354. self.firstMap = firstMap
  355. self.secondMap = secondMap
  356. self.Map = firstMap
  357. #
  358. # initialize region values
  359. #
  360. self._initMap(Map = self.firstMap)
  361. self._initMap(Map = self.secondMap)
  362. def _bindWindowsActivation(self):
  363. self.GetFirstWindow().Bind(wx.EVT_ENTER_WINDOW, self.ActivateFirstMap)
  364. self.GetSecondWindow().Bind(wx.EVT_ENTER_WINDOW, self.ActivateSecondMap)
  365. def GetFirstMap(self):
  366. """!Returns first Map instance
  367. """
  368. return self.firstMap
  369. def GetSecondMap(self):
  370. """!Returns second Map instance
  371. """
  372. return self.secondMap
  373. def GetFirstWindow(self):
  374. """!Get first map window"""
  375. return self.firstMapWindow
  376. def GetSecondWindow(self):
  377. """!Get second map window"""
  378. return self.secondMapWindow
  379. def GetMap(self):
  380. """!Returns current map (renderer) instance
  381. @note Use this method to access current map renderer.
  382. (It is not guarented that current map will be stored in
  383. \c self.Map in future versions.)
  384. """
  385. return self.Map
  386. def GetWindow(self):
  387. """!Returns current map window
  388. @see GetMap()
  389. """
  390. return self.MapWindow
  391. def ActivateFirstMap(self, event = None):
  392. """!Make first Map and MapWindow active"""
  393. self.Map = self.firstMap
  394. self.MapWindow = self.firstMapWindow
  395. self.GetMapToolbar().SetActiveMap(0)
  396. def ActivateSecondMap(self, event = None):
  397. """!Make second Map and MapWindow active"""
  398. self.Map = self.secondMap
  399. self.MapWindow = self.secondMapWindow
  400. self.GetMapToolbar().SetActiveMap(1)
  401. def OnZoomIn(self, event):
  402. """!Zoom in the map.
  403. Set mouse cursor, zoombox attributes, and zoom direction
  404. """
  405. toolbar = self.GetMapToolbar()
  406. self._switchTool(toolbar, event)
  407. win = self.GetFirstWindow()
  408. self._prepareZoom(mapWindow = win, zoomType = 1)
  409. win = self.GetSecondWindow()
  410. self._prepareZoom(mapWindow = win, zoomType = 1)
  411. def OnZoomOut(self, event):
  412. """!Zoom out the map.
  413. Set mouse cursor, zoombox attributes, and zoom direction
  414. """
  415. toolbar = self.GetMapToolbar()
  416. self._switchTool(toolbar, event)
  417. win = self.GetFirstWindow()
  418. self._prepareZoom(mapWindow = win, zoomType = -1)
  419. win = self.GetSecondWindow()
  420. self._prepareZoom(mapWindow = win, zoomType = -1)
  421. def OnPan(self, event):
  422. """!Panning, set mouse to drag
  423. """
  424. toolbar = self.GetMapToolbar()
  425. self._switchTool(toolbar, event)
  426. win = self.GetFirstWindow()
  427. self._preparePan(mapWindow = win)
  428. win = self.GetSecondWindow()
  429. self._preparePan(mapWindow = win)
  430. def OnPointer(self, event):
  431. self.GetFirstWindow().mouse['use'] = 'pointer'
  432. def OnRender(self, event):
  433. """!Re-render map composition (each map layer)
  434. """
  435. self.Render(mapToRender = self.GetFirstWindow())
  436. self.Render(mapToRender = self.GetSecondWindow())
  437. def Render(self, mapToRender):
  438. """!Re-render map composition"""
  439. mapToRender.UpdateMap(render = True,
  440. renderVector = mapToRender == self.GetFirstWindow())
  441. # update statusbar
  442. self.StatusbarUpdate()
  443. def OnErase(self, event):
  444. """!Erase the canvas
  445. """
  446. self.Erase(mapToErase = self.GetFirstWindow())
  447. self.Erase(mapToErase = self.GetSecondWindow())
  448. def Erase(self, mapToErase):
  449. """!Erase the canvas
  450. """
  451. mapToErase.EraseMap()
  452. def OnDraw(self, event):
  453. """!Re-display current map composition
  454. """
  455. self.Draw(mapToDraw = self.GetFirstWindow())
  456. self.Draw(mapToDraw = self.GetSecondWindow())
  457. def Draw(self, mapToDraw):
  458. """!Re-display current map composition
  459. """
  460. mapToDraw.UpdateMap(render = False)