mapdisp.py 19 KB

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