statusbar.py 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126
  1. """!
  2. @package mapdisp.statusbar
  3. @brief Classes for statusbar management
  4. Classes:
  5. - statusbar::SbException
  6. - statusbar::SbManager
  7. - statusbar::SbItem
  8. - statusbar::SbRender
  9. - statusbar::SbShowRegion
  10. - statusbar::SbAlignExtent
  11. - statusbar::SbResolution
  12. - statusbar::SbMapScale
  13. - statusbar::SbGoTo
  14. - statusbar::SbProjection
  15. - statusbar::SbMask
  16. - statusbar::SbTextItem
  17. - statusbar::SbDisplayGeometry
  18. - statusbar::SbCoordinates
  19. - statusbar::SbRegionExtent
  20. - statusbar::SbCompRegionExtent
  21. - statusbar::SbProgress
  22. (C) 2006-2011 by the GRASS Development Team
  23. This program is free software under the GNU General Public License
  24. (>=v2). Read the file COPYING that comes with GRASS for details.
  25. @author Vaclav Petras <wenzeslaus gmail.com>
  26. @author Anna Kratochvilova <kratochanna gmail.com>
  27. """
  28. import copy
  29. import wx
  30. from core import utils
  31. from core.gcmd import GMessage, RunCommand
  32. from core.settings import UserSettings
  33. from core.utils import _
  34. from grass.script import core as grass
  35. from grass.pydispatch.signal import Signal
  36. class SbException:
  37. """! Exception class used in SbManager and SbItems"""
  38. def __init__(self, message):
  39. self.message = message
  40. def __str__(self):
  41. return self.message
  42. class SbManager:
  43. """!Statusbar manager for wx.Statusbar and SbItems.
  44. Statusbar manager manages items added by AddStatusbarItem method.
  45. Provides progress bar (SbProgress) and choice (wx.Choice).
  46. Items with position 0 are shown according to choice selection.
  47. Only one item of the same class is supposed to be in statusbar.
  48. Manager user have to create statusbar on his own, add items to manager
  49. and call Update method to show particular widgets.
  50. User settings (group = 'display', key = 'statusbarMode', subkey = 'selection')
  51. are taken into account.
  52. @todo generalize access to UserSettings (specify group, etc.)
  53. @todo add GetMode method using name instead of index
  54. """
  55. def __init__(self, mapframe, statusbar):
  56. """!Connects manager to statusbar
  57. Creates choice and progress bar.
  58. """
  59. self.mapFrame = mapframe
  60. self.statusbar = statusbar
  61. self.choice = wx.Choice(self.statusbar, wx.ID_ANY)
  62. self.choice.Bind(wx.EVT_CHOICE, self.OnToggleStatus)
  63. self.statusbarItems = dict()
  64. self._postInitialized = False
  65. self._modeIndexSet = False
  66. self.progressbar = SbProgress(self.mapFrame, self.statusbar, self)
  67. self.progressbar.progressShown.connect(self._progressShown)
  68. self.progressbar.progressHidden.connect(self._progressHidden)
  69. self._oldStatus = ''
  70. self._hiddenItems = {}
  71. def SetProperty(self, name, value):
  72. """!Sets property represented by one of contained SbItems
  73. @param name name of SbItem (from name attribute)
  74. @param value value to be set
  75. """
  76. self.statusbarItems[name].SetValue(value)
  77. def GetProperty(self, name):
  78. """!Returns property represented by one of contained SbItems
  79. @param name name of SbItem (from name attribute)
  80. """
  81. return self.statusbarItems[name].GetValue()
  82. def HasProperty(self, name):
  83. """!Checks whether property is represented by one of contained SbItems
  84. @param name name of SbItem (from name attribute)
  85. @returns True if particular SbItem is contained, False otherwise
  86. """
  87. if name in self.statusbarItems:
  88. return True
  89. return False
  90. def AddStatusbarItem(self, item):
  91. """!Adds item to statusbar
  92. If item position is 0, item is managed by choice.
  93. @see AddStatusbarItemsByClass
  94. """
  95. self.statusbarItems[item.name] = item
  96. if item.GetPosition() == 0:
  97. self.choice.Append(item.label, clientData = item) #attrError?
  98. def AddStatusbarItemsByClass(self, itemClasses, **kwargs):
  99. """!Adds items to statusbar
  100. @param itemClasses list of classes of items to be add
  101. @param kwargs SbItem constructor parameters
  102. @see AddStatusbarItem
  103. """
  104. for Item in itemClasses:
  105. item = Item(**kwargs)
  106. self.AddStatusbarItem(item)
  107. def HideStatusbarChoiceItemsByClass(self, itemClasses):
  108. """!Hides items showed in choice
  109. Hides items with position 0 (items showed in choice) by removing
  110. them from choice.
  111. @param itemClasses list of classes of items to be hided
  112. @see ShowStatusbarChoiceItemsByClass
  113. @todo consider adding similar function which would take item names
  114. """
  115. index = []
  116. for itemClass in itemClasses:
  117. for i in range(0, self.choice.GetCount() - 1):
  118. item = self.choice.GetClientData(i)
  119. if item.__class__ == itemClass:
  120. index.append(i)
  121. self._hiddenItems[i] = item
  122. # must be sorted in reverse order to be removed correctly
  123. for i in sorted(index, reverse = True):
  124. self.choice.Delete(i)
  125. def ShowStatusbarChoiceItemsByClass(self, itemClasses):
  126. """!Shows items showed in choice
  127. Shows items with position 0 (items showed in choice) by adding
  128. them to choice.
  129. Items are restored in their old positions.
  130. @param itemClasses list of classes of items to be showed
  131. @see HideStatusbarChoiceItemsByClass
  132. """
  133. # must be sorted to be inserted correctly
  134. for pos in sorted(self._hiddenItems.keys()):
  135. item = self._hiddenItems[pos]
  136. if item.__class__ in itemClasses:
  137. self.choice.Insert(item.label, pos, item)
  138. def ShowItem(self, itemName):
  139. """!Invokes showing of particular item
  140. @see Update
  141. """
  142. if self.statusbarItems[itemName].GetPosition() != 0 or \
  143. not self.progressbar.IsShown():
  144. self.statusbarItems[itemName].Show()
  145. def _postInit(self):
  146. """!Post-initialization method
  147. It sets internal user settings,
  148. set choice's selection (from user settings) and does reposition.
  149. It needs choice filled by items.
  150. it is called automatically.
  151. """
  152. UserSettings.Set(group = 'display',
  153. key = 'statusbarMode',
  154. subkey = 'choices',
  155. value = self.choice.GetItems(),
  156. internal = True)
  157. if not self._modeIndexSet:
  158. self.choice.SetSelection(UserSettings.Get(group = 'display',
  159. key = 'statusbarMode',
  160. subkey = 'selection'))
  161. self.Reposition()
  162. self._postInitialized = True
  163. def Update(self):
  164. """!Updates statusbar
  165. It always updates mask.
  166. """
  167. self.progressbar.Update()
  168. if not self._postInitialized:
  169. self._postInit()
  170. for item in self.statusbarItems.values():
  171. if item.GetPosition() == 0:
  172. if not self.progressbar.IsShown():
  173. item.Hide()
  174. else:
  175. item.Update() # mask, render
  176. if self.progressbar.IsShown():
  177. pass
  178. elif self.choice.GetCount() > 0:
  179. item = self.choice.GetClientData(self.choice.GetSelection())
  180. item.Update()
  181. def Reposition(self):
  182. """!Reposition items in statusbar
  183. Set positions to all items managed by statusbar manager.
  184. It should not be necessary to call it manually.
  185. """
  186. widgets = []
  187. for item in self.statusbarItems.values():
  188. widgets.append((item.GetPosition(), item.GetWidget()))
  189. widgets.append((1, self.choice))
  190. widgets.append((1, self.progressbar.GetWidget()))
  191. for idx, win in widgets:
  192. if not win:
  193. continue
  194. rect = self.statusbar.GetFieldRect(idx)
  195. if idx == 0: # show region / mapscale / process bar
  196. # -> size
  197. wWin, hWin = win.GetBestSize()
  198. # -> position
  199. # if win == self.statusbarWin['region']:
  200. # x, y = rect.x + rect.width - wWin, rect.y - 1
  201. # align left
  202. # else:
  203. x, y = rect.x + 3, rect.y - 1
  204. w, h = wWin, rect.height + 2
  205. else: # choice || auto-rendering
  206. x, y = rect.x, rect.y
  207. w, h = rect.width, rect.height + 1
  208. if win == self.progressbar.GetWidget():
  209. wWin = rect.width - 6
  210. if idx == 2: # mask
  211. x += 5
  212. y += 4
  213. elif idx == 3: # render
  214. x += 5
  215. win.SetPosition((x, y))
  216. win.SetSize((w, h))
  217. def GetProgressBar(self):
  218. """!Returns progress bar"""
  219. return self.progressbar
  220. def _progressShown(self):
  221. self._oldStatus = self.statusbar.GetStatusText(0)
  222. self.choice.GetClientData(self.choice.GetSelection()).Hide()
  223. def _progressHidden(self):
  224. self.statusbar.SetStatusText(self._oldStatus, 0)
  225. self.choice.GetClientData(self.choice.GetSelection()).Show()
  226. def OnToggleStatus(self, event):
  227. """!Toggle status text
  228. """
  229. self.Update()
  230. if event.GetSelection() == 3: # use something better than magic numbers
  231. # show computation region extent by default
  232. self.statusbarItems['region'].SetValue(True)
  233. # redraw map if auto-rendering is enabled
  234. if self.mapFrame.IsAutoRendered():
  235. self.mapFrame.OnRender(None)
  236. def SetMode(self, modeIndex):
  237. """!Sets current mode
  238. Mode is usually driven by user through choice.
  239. """
  240. self._modeIndexSet = True
  241. self.choice.SetSelection(modeIndex)
  242. def GetMode(self):
  243. """!Returns current mode"""
  244. return self.choice.GetSelection()
  245. def SetProgress(self, range, value, text):
  246. """Update progress."""
  247. self.progressbar.SetRange(range)
  248. self.progressbar.SetValue(value)
  249. if text:
  250. self.statusbar.SetStatusText(text)
  251. class SbItem:
  252. """!Base class for statusbar items.
  253. Each item represents functionality (or action) controlled by statusbar
  254. and related to MapFrame.
  255. One item is usually connected with one widget but it is not necessary.
  256. Item can represent property (depends on manager).
  257. Items are not widgets but can provide interface to them.
  258. Items usually has requirements to MapFrame instance
  259. (specified as MapFrame.methodname or MapWindow.methodname).
  260. @todo consider externalizing position (see SbProgress use in SbManager)
  261. """
  262. def __init__(self, mapframe, statusbar, position = 0):
  263. """!
  264. @param mapframe instance of class with MapFrame interface
  265. @param statusbar statusbar instance (wx.Statusbar)
  266. @param position item position in statusbar
  267. @todo rewrite Update also in derived classes to take in account item position
  268. """
  269. self.mapFrame = mapframe
  270. self.statusbar = statusbar
  271. self.position = position
  272. def Show(self):
  273. """!Invokes showing of underlying widget.
  274. In derived classes it can do what is appropriate for it,
  275. e.g. showing text on statusbar (only).
  276. """
  277. self.widget.Show()
  278. def Hide(self):
  279. self.widget.Hide()
  280. def SetValue(self, value):
  281. self.widget.SetValue(value)
  282. def GetValue(self):
  283. return self.widget.GetValue()
  284. def GetPosition(self):
  285. return self.position
  286. def GetWidget(self):
  287. """!Returns underlaying winget.
  288. @return widget or None if doesn't exist
  289. """
  290. return self.widget
  291. def _update(self, longHelp):
  292. """!Default implementation for Update method.
  293. @param longHelp True to enable long help (help from toolbars)
  294. """
  295. self.statusbar.SetStatusText("", 0)
  296. self.Show()
  297. self.mapFrame.StatusbarEnableLongHelp(longHelp)
  298. def Update(self):
  299. """!Called when statusbar action is activated (e.g. through wx.Choice).
  300. """
  301. self._update(longHelp = False)
  302. class SbRender(SbItem):
  303. """!Checkbox to enable and disable auto-rendering.
  304. Requires MapFrame.OnRender method.
  305. """
  306. def __init__(self, mapframe, statusbar, position = 0):
  307. SbItem.__init__(self, mapframe, statusbar, position)
  308. self.name = 'render'
  309. self._properties = mapframe.mapWindowProperties
  310. self.widget = wx.CheckBox(parent = self.statusbar, id = wx.ID_ANY,
  311. label = _("Render"))
  312. self.widget.SetValue(self._properties.autoRender)
  313. self.widget.Hide()
  314. self.widget.SetToolTip(wx.ToolTip (_("Enable/disable auto-rendering")))
  315. self._connectAutoRender()
  316. self.widget.Bind(wx.EVT_CHECKBOX, self._onCheckbox)
  317. def _setValue(self, value):
  318. self.widget.SetValue(value)
  319. def _connectAutoRender(self):
  320. self._properties.autoRenderChanged.connect(self._setValue)
  321. def _disconnectAutoRender(self):
  322. self._properties.autoRenderChanged.disconnect(self._setValue)
  323. def _onCheckbox(self, event):
  324. self._disconnectAutoRender()
  325. self._properties.autoRender = self.widget.GetValue()
  326. self._connectAutoRender()
  327. def Update(self):
  328. self.Show()
  329. class SbShowRegion(SbItem):
  330. """!Checkbox to enable and disable showing of computational region.
  331. Requires MapFrame.OnRender, MapFrame.IsAutoRendered, MapFrame.GetWindow.
  332. """
  333. def __init__(self, mapframe, statusbar, position = 0):
  334. SbItem.__init__(self, mapframe, statusbar, position)
  335. self.name = 'region'
  336. self.label = _("Show comp. extent")
  337. self._properties = mapframe.mapWindowProperties
  338. self.widget = wx.CheckBox(parent = self.statusbar, id = wx.ID_ANY,
  339. label = _("Show computational extent"))
  340. self.widget.SetValue(self._properties.showRegion)
  341. self.widget.Hide()
  342. self.widget.SetToolTip(wx.ToolTip (_("Show/hide computational "
  343. "region extent (set with g.region). "
  344. "Display region drawn as a blue box inside the "
  345. "computational region, "
  346. "computational region inside a display region "
  347. "as a red box).")))
  348. self.widget.Bind(wx.EVT_CHECKBOX, self.OnToggleShowRegion)
  349. self._connectShowRegion()
  350. def _setValue(self, value):
  351. self.widget.SetValue(value)
  352. def _connectShowRegion(self):
  353. self._properties.showRegionChanged.connect(self._setValue)
  354. def _disconnectShowRegion(self):
  355. self._properties.showRegionChanged.disconnect(self._setValue)
  356. def OnToggleShowRegion(self, event):
  357. """!Shows/Hides extent (comp. region) in map canvas.
  358. Shows or hides according to checkbox value.
  359. @todo needs refactoring
  360. """
  361. self._disconnectShowRegion()
  362. self._properties.showRegion = self.widget.GetValue()
  363. self._connectShowRegion()
  364. # redraw map if auto-rendering is enabled
  365. if self.mapFrame.IsAutoRendered():
  366. self.mapFrame.OnRender(None)
  367. def SetValue(self, value):
  368. self._disconnectShowRegion()
  369. self._properties.showRegion = value
  370. SbItem.SetValue(self, value)
  371. self._connectShowRegion()
  372. class SbAlignExtent(SbItem):
  373. """!Checkbox to select zoom behavior.
  374. Used by BufferedWindow (through MapFrame property).
  375. See tooltip for explanation.
  376. """
  377. def __init__(self, mapframe, statusbar, position = 0):
  378. SbItem.__init__(self, mapframe, statusbar, position)
  379. self.name = 'alignExtent'
  380. self.label = _("Display mode")
  381. self._properties = mapframe.mapWindowProperties
  382. self.widget = wx.CheckBox(parent = self.statusbar, id = wx.ID_ANY,
  383. label = _("Align region extent based on display size"))
  384. self.widget.SetValue(self._properties.alignExtent)
  385. self.widget.Hide()
  386. self.widget.SetToolTip(wx.ToolTip (_("Align region extent based on display "
  387. "size from center point. "
  388. "Default value for new map displays can "
  389. "be set up in 'User GUI settings' dialog.")))
  390. self._connectAlignExtent()
  391. self.widget.Bind(wx.EVT_CHECKBOX, self._onCheckbox)
  392. # TODO: these four methods are in many stitems
  393. # some generalization?
  394. # passing properties as stings and set/get attr would work, but it is nice?
  395. def _setValue(self, value):
  396. self.widget.SetValue(value)
  397. def _connectAlignExtent(self):
  398. self._properties.alignExtentChanged.connect(self._setValue)
  399. def _disconnectAlignExtent(self):
  400. self._properties.alignExtentChanged.disconnect(self._setValue)
  401. def _onCheckbox(self, event):
  402. self._disconnectAlignExtent()
  403. self._properties.alignExtent = self.widget.GetValue()
  404. self._connectAlignExtent()
  405. class SbResolution(SbItem):
  406. """!Checkbox to select used display resolution.
  407. Requires MapFrame.OnRender method.
  408. """
  409. def __init__(self, mapframe, statusbar, position = 0):
  410. SbItem.__init__(self, mapframe, statusbar, position)
  411. self.name = 'resolution'
  412. self.label = _("Display resolution")
  413. self._properties = self.mapFrame.mapWindowProperties
  414. self.widget = wx.CheckBox(parent = self.statusbar, id = wx.ID_ANY,
  415. label = _("Constrain display resolution to computational settings"))
  416. self.widget.SetValue(self._properties.resolution)
  417. self.widget.Hide()
  418. self.widget.SetToolTip(wx.ToolTip (_("Constrain display resolution "
  419. "to computational region settings. "
  420. "Default value for new map displays can "
  421. "be set up in 'User GUI settings' dialog.")))
  422. self.widget.Bind(wx.EVT_CHECKBOX, self.OnToggleUpdateMap)
  423. self._connectResolutionChange()
  424. def _setValue(self, value):
  425. self.widget.SetValue(value)
  426. def _connectResolutionChange(self):
  427. self._properties.resolutionChanged.connect(self._setValue)
  428. def _disconnectResolutionChange(self):
  429. self._properties.resolutionChanged.disconnect(self._setValue)
  430. def OnToggleUpdateMap(self, event):
  431. """!Update display when toggle display mode
  432. """
  433. self._disconnectResolutionChange()
  434. self._properties.resolution = self.widget.GetValue()
  435. self._connectResolutionChange()
  436. # redraw map if auto-rendering is enabled
  437. if self.mapFrame.IsAutoRendered():
  438. self.mapFrame.OnRender(None)
  439. class SbMapScale(SbItem):
  440. """!Editable combobox to get/set current map scale.
  441. Requires MapFrame.GetMapScale, MapFrame.SetMapScale
  442. and MapFrame.GetWindow (and GetWindow().UpdateMap()).
  443. """
  444. def __init__(self, mapframe, statusbar, position = 0):
  445. SbItem.__init__(self, mapframe, statusbar, position)
  446. self.name = 'mapscale'
  447. self.label = _("Map scale")
  448. self.widget = wx.ComboBox(parent = self.statusbar, id = wx.ID_ANY,
  449. style = wx.TE_PROCESS_ENTER,
  450. size = (150, -1))
  451. self.widget.SetItems(['1:1000',
  452. '1:5000',
  453. '1:10000',
  454. '1:25000',
  455. '1:50000',
  456. '1:100000',
  457. '1:1000000'])
  458. self.widget.Hide()
  459. self.widget.SetToolTip(wx.ToolTip (_("As everyone's monitors and resolutions "
  460. "are set differently these values are not "
  461. "true map scales, but should get you into "
  462. "the right neighborhood.")))
  463. self.widget.Bind(wx.EVT_TEXT_ENTER, self.OnChangeMapScale)
  464. self.widget.Bind(wx.EVT_COMBOBOX, self.OnChangeMapScale)
  465. self.lastMapScale = None
  466. def Update(self):
  467. scale = self.mapFrame.GetMapScale()
  468. self.statusbar.SetStatusText("")
  469. try:
  470. self.SetValue("1:%ld" % (scale + 0.5))
  471. except TypeError:
  472. pass # FIXME, why this should happen?
  473. self.lastMapScale = scale
  474. self.Show()
  475. # disable long help
  476. self.mapFrame.StatusbarEnableLongHelp(False)
  477. def OnChangeMapScale(self, event):
  478. """!Map scale changed by user
  479. """
  480. scale = event.GetString()
  481. try:
  482. if scale[:2] != '1:':
  483. raise ValueError
  484. value = int(scale[2:])
  485. except ValueError:
  486. self.SetValue('1:%ld' % int(self.lastMapScale))
  487. return
  488. self.mapFrame.SetMapScale(value)
  489. # redraw a map
  490. self.mapFrame.GetWindow().UpdateMap()
  491. self.GetWidget().SetFocus()
  492. class SbGoTo(SbItem):
  493. """!Textctrl to set coordinates which to focus on.
  494. Requires MapFrame.GetWindow, MapWindow.GoTo method.
  495. """
  496. def __init__(self, mapframe, statusbar, position = 0):
  497. SbItem.__init__(self, mapframe, statusbar, position)
  498. self.name = 'goto'
  499. self.label = _("Go to")
  500. self.widget = wx.TextCtrl(parent = self.statusbar, id = wx.ID_ANY,
  501. value = "", style = wx.TE_PROCESS_ENTER,
  502. size = (300, -1))
  503. self.widget.Hide()
  504. self.widget.Bind(wx.EVT_TEXT_ENTER, self.OnGoTo)
  505. def ReprojectENToMap(self, e, n, useDefinedProjection):
  506. """!Reproject east, north from user defined projection
  507. @param e,n coordinate (for DMS string, else float or string)
  508. @param useDefinedProjection projection defined by user in settings dialog
  509. @throws SbException if useDefinedProjection is True and projection is not defined in UserSettings
  510. """
  511. if useDefinedProjection:
  512. settings = UserSettings.Get(group = 'projection', key = 'statusbar', subkey = 'proj4')
  513. if not settings:
  514. raise SbException(_("Projection not defined (check the settings)"))
  515. else:
  516. # reproject values
  517. projIn = settings
  518. projOut = RunCommand('g.proj',
  519. flags = 'jf',
  520. read = True)
  521. proj = projIn.split(' ')[0].split('=')[1]
  522. if proj in ('ll', 'latlong', 'longlat'):
  523. e, n = utils.DMS2Deg(e, n)
  524. proj, coord1 = utils.ReprojectCoordinates(coord = (e, n),
  525. projIn = projIn,
  526. projOut = projOut, flags = 'd')
  527. e, n = coord1
  528. else:
  529. e, n = float(e), float(n)
  530. proj, coord1 = utils.ReprojectCoordinates(coord = (e, n),
  531. projIn = projIn,
  532. projOut = projOut, flags = 'd')
  533. e, n = coord1
  534. elif self.mapFrame.GetMap().projinfo['proj'] == 'll':
  535. e, n = utils.DMS2Deg(e, n)
  536. else:
  537. e, n = float(e), float(n)
  538. return e, n
  539. def OnGoTo(self, event):
  540. """!Go to position
  541. """
  542. try:
  543. e, n = self.GetValue().split(';')
  544. e, n = self.ReprojectENToMap(e, n, self.mapFrame.GetProperty('projection'))
  545. self.mapFrame.GetWindow().GoTo(e, n)
  546. self.widget.SetFocus()
  547. except ValueError:
  548. # FIXME: move this code to MapWindow/BufferedWindow/MapFrame
  549. region = self.mapFrame.GetMap().GetCurrentRegion()
  550. precision = int(UserSettings.Get(group = 'projection', key = 'format',
  551. subkey = 'precision'))
  552. format = UserSettings.Get(group = 'projection', key = 'format',
  553. subkey = 'll')
  554. if self.mapFrame.GetMap().projinfo['proj'] == 'll' and format == 'DMS':
  555. self.SetValue("%s" % utils.Deg2DMS(region['center_easting'],
  556. region['center_northing'],
  557. precision = precision))
  558. else:
  559. self.SetValue("%.*f; %.*f" % \
  560. (precision, region['center_easting'],
  561. precision, region['center_northing']))
  562. except SbException, e:
  563. # FIXME: this may be useless since statusbar update checks user defined projection and this exception raises when user def proj does not exists
  564. self.statusbar.SetStatusText(str(e), 0)
  565. def GetCenterString(self, map):
  566. """!Get current map center in appropriate format"""
  567. region = map.GetCurrentRegion()
  568. precision = int(UserSettings.Get(group = 'projection', key = 'format',
  569. subkey = 'precision'))
  570. format = UserSettings.Get(group = 'projection', key = 'format',
  571. subkey = 'll')
  572. projection = UserSettings.Get(group='projection', key='statusbar', subkey='proj4')
  573. if self.mapFrame.GetProperty('projection'):
  574. if not projection:
  575. raise SbException(_("Projection not defined (check the settings)"))
  576. else:
  577. proj, coord = utils.ReprojectCoordinates(coord = (region['center_easting'],
  578. region['center_northing']),
  579. projOut = projection,
  580. flags = 'd')
  581. if coord:
  582. if proj in ('ll', 'latlong', 'longlat') and format == 'DMS':
  583. return "%s" % utils.Deg2DMS(coord[0],
  584. coord[1],
  585. precision = precision)
  586. else:
  587. return "%.*f; %.*f" % (precision, coord[0], precision, coord[1])
  588. else:
  589. raise SbException(_("Error in projection (check the settings)"))
  590. else:
  591. if self.mapFrame.GetMap().projinfo['proj'] == 'll' and format == 'DMS':
  592. return "%s" % utils.Deg2DMS(region['center_easting'], region['center_northing'],
  593. precision = precision)
  594. else:
  595. return "%.*f; %.*f" % (precision, region['center_easting'], precision, region['center_northing'])
  596. def SetCenter(self):
  597. """!Set current map center as item value"""
  598. center = self.GetCenterString(self.mapFrame.GetMap())
  599. self.SetValue(center)
  600. def Update(self):
  601. self.statusbar.SetStatusText("")
  602. try:
  603. self.SetCenter()
  604. self.Show()
  605. except SbException, e:
  606. self.statusbar.SetStatusText(str(e), 0)
  607. # disable long help
  608. self.mapFrame.StatusbarEnableLongHelp(False)
  609. class SbProjection(SbItem):
  610. """!Checkbox to enable user defined projection (can be set in settings)"""
  611. def __init__(self, mapframe, statusbar, position = 0):
  612. SbItem.__init__(self, mapframe, statusbar, position)
  613. self.name = 'projection'
  614. self.label = _("Projection")
  615. self.defaultLabel = _("Use defined projection")
  616. self.widget = wx.CheckBox(parent = self.statusbar, id = wx.ID_ANY,
  617. label = self.defaultLabel)
  618. self.widget.SetValue(False)
  619. # necessary?
  620. size = self.widget.GetSize()
  621. self.widget.SetMinSize((size[0] + 150, size[1]))
  622. self.widget.Hide()
  623. self.widget.SetToolTip(wx.ToolTip (_("Reproject coordinates displayed "
  624. "in the statusbar. Projection can be "
  625. "defined in GUI preferences dialog "
  626. "(tab 'Projection')")))
  627. def Update(self):
  628. self.statusbar.SetStatusText("")
  629. epsg = UserSettings.Get(group = 'projection', key = 'statusbar', subkey = 'epsg')
  630. if epsg:
  631. label = '%s (EPSG: %s)' % (self.defaultLabel, epsg)
  632. self.widget.SetLabel(label)
  633. else:
  634. self.widget.SetLabel(self.defaultLabel)
  635. self.Show()
  636. # disable long help
  637. self.mapFrame.StatusbarEnableLongHelp(False)
  638. class SbMask(SbItem):
  639. """!StaticText to show whether mask is activated."""
  640. def __init__(self, mapframe, statusbar, position = 0):
  641. SbItem.__init__(self, mapframe, statusbar, position)
  642. self.name = 'mask'
  643. self.widget = wx.StaticText(parent = self.statusbar, id = wx.ID_ANY, label = _('MASK'))
  644. self.widget.SetForegroundColour(wx.Colour(255, 0, 0))
  645. self.widget.Hide()
  646. def Update(self):
  647. if grass.find_file(name = 'MASK', element = 'cell',
  648. mapset = grass.gisenv()['MAPSET'])['name']:
  649. self.Show()
  650. else:
  651. self.Hide()
  652. class SbTextItem(SbItem):
  653. """!Base class for items without widgets.
  654. Only sets statusbar text.
  655. """
  656. def __init__(self, mapframe, statusbar, position = 0):
  657. SbItem.__init__(self, mapframe, statusbar, position)
  658. self.text = None
  659. def Show(self):
  660. self.statusbar.SetStatusText(self.GetValue(), self.position)
  661. def Hide(self):
  662. self.statusbar.SetStatusText("", self.position)
  663. def SetValue(self, value):
  664. self.text = value
  665. def GetValue(self):
  666. return self.text
  667. def GetWidget(self):
  668. return None
  669. def Update(self):
  670. self._update(longHelp = True)
  671. class SbDisplayGeometry(SbTextItem):
  672. """!Show current display resolution."""
  673. def __init__(self, mapframe, statusbar, position = 0):
  674. SbTextItem.__init__(self, mapframe, statusbar, position)
  675. self.name = 'displayGeometry'
  676. self.label = _("Display geometry")
  677. def Show(self):
  678. region = copy.copy(self.mapFrame.GetMap().GetCurrentRegion())
  679. if self.mapFrame.mapWindowProperties.resolution:
  680. compRegion = self.mapFrame.GetMap().GetRegion(add3d = False)
  681. region['rows'] = abs(int((region['n'] - region['s']) / compRegion['nsres']) + 0.5)
  682. region['cols'] = abs(int((region['e'] - region['w']) / compRegion['ewres']) + 0.5)
  683. region['nsres'] = compRegion['nsres']
  684. region['ewres'] = compRegion['ewres']
  685. self.SetValue("rows=%d; cols=%d; nsres=%.2f; ewres=%.2f" %
  686. (region["rows"], region["cols"],
  687. region["nsres"], region["ewres"]))
  688. SbTextItem.Show(self)
  689. class SbCoordinates(SbTextItem):
  690. """!Show map coordinates when mouse moves.
  691. Requires MapWindow.GetLastEN method."""
  692. def __init__(self, mapframe, statusbar, position = 0):
  693. SbTextItem.__init__(self, mapframe, statusbar, position)
  694. self.name = 'coordinates'
  695. self.label = _("Coordinates")
  696. self._additionalInfo = None
  697. self._basicValue = None
  698. def Show(self):
  699. """Show the last map window coordinates.
  700. @todo remove last EN call and use coordinates comming from signal
  701. """
  702. precision = int(UserSettings.Get(group = 'projection', key = 'format',
  703. subkey = 'precision'))
  704. format = UserSettings.Get(group = 'projection', key = 'format',
  705. subkey = 'll')
  706. projection = self.mapFrame.GetProperty('projection')
  707. try:
  708. e, n = self.mapFrame.GetWindow().GetLastEN()
  709. self._basicValue = self.ReprojectENFromMap(e, n, projection, precision, format)
  710. if self._additionalInfo:
  711. value = "{coords} ({additionalInfo})".format(coords=self._basicValue,
  712. additionalInfo=self._additionalInfo)
  713. else:
  714. value = self._basicValue
  715. self.SetValue(value)
  716. except SbException, e:
  717. self.SetValue(e.message)
  718. # TODO: remove these excepts, they just hide errors, solve problems differently
  719. except TypeError, e:
  720. self.SetValue("")
  721. except AttributeError:
  722. self.SetValue("") # during initialization MapFrame has no MapWindow
  723. SbTextItem.Show(self)
  724. def SetAdditionalInfo(self, text):
  725. """Sets additional info to be shown together with coordinates.
  726. The format is translation dependent but the default is
  727. "coordinates (additional info)"
  728. It does not show the changed text immediately, it waits for the Show()
  729. method to be called.
  730. @param text string to be shown
  731. """
  732. self._additionalInfo = text
  733. def ReprojectENFromMap(self, e, n, useDefinedProjection, precision, format):
  734. """!Reproject east, north to user defined projection.
  735. @param e,n coordinate
  736. @throws SbException if useDefinedProjection is True and projection is not defined in UserSettings
  737. """
  738. if useDefinedProjection:
  739. settings = UserSettings.Get(group = 'projection', key = 'statusbar', subkey = 'proj4')
  740. if not settings:
  741. raise SbException(_("Projection not defined (check the settings)"))
  742. else:
  743. # reproject values
  744. proj, coord = utils.ReprojectCoordinates(coord = (e, n),
  745. projOut = settings,
  746. flags = 'd')
  747. if coord:
  748. e, n = coord
  749. if proj in ('ll', 'latlong', 'longlat') and format == 'DMS':
  750. return utils.Deg2DMS(e, n, precision = precision)
  751. else:
  752. return "%.*f; %.*f" % (precision, e, precision, n)
  753. else:
  754. raise SbException(_("Error in projection (check the settings)"))
  755. else:
  756. if self.mapFrame.GetMap().projinfo['proj'] == 'll' and format == 'DMS':
  757. return utils.Deg2DMS(e, n, precision = precision)
  758. else:
  759. return "%.*f; %.*f" % (precision, e, precision, n)
  760. class SbRegionExtent(SbTextItem):
  761. """!Shows current display region"""
  762. def __init__(self, mapframe, statusbar, position = 0):
  763. SbTextItem.__init__(self, mapframe, statusbar, position)
  764. self.name = 'displayRegion'
  765. self.label = _("Extent")
  766. def Show(self):
  767. precision = int(UserSettings.Get(group = 'projection', key = 'format',
  768. subkey = 'precision'))
  769. format = UserSettings.Get(group = 'projection', key = 'format',
  770. subkey = 'll')
  771. projection = self.mapFrame.GetProperty('projection')
  772. region = self._getRegion()
  773. try:
  774. regionReprojected = self.ReprojectRegionFromMap(region, projection, precision, format)
  775. self.SetValue(regionReprojected)
  776. except SbException, e:
  777. self.SetValue(e.message)
  778. SbTextItem.Show(self)
  779. def _getRegion(self):
  780. """!Get current display region"""
  781. return self.mapFrame.GetMap().GetCurrentRegion() # display region
  782. def _formatRegion(self, w, e, s, n, nsres, ewres, precision = None):
  783. """!Format display region string for statusbar
  784. @param nsres,ewres unused
  785. """
  786. if precision is not None:
  787. return "%.*f - %.*f, %.*f - %.*f" % (precision, w, precision, e,
  788. precision, s, precision, n)
  789. else:
  790. return "%s - %s, %s - %s" % (w, e, s, n)
  791. def ReprojectRegionFromMap(self, region, useDefinedProjection, precision, format):
  792. """!Reproject region values
  793. @todo reorganize this method to remove code useful only for derived class SbCompRegionExtent
  794. """
  795. if useDefinedProjection:
  796. settings = UserSettings.Get(group = 'projection', key = 'statusbar', subkey = 'proj4')
  797. if not settings:
  798. raise SbException(_("Projection not defined (check the settings)"))
  799. else:
  800. projOut = settings
  801. proj, coord1 = utils.ReprojectCoordinates(coord = (region["w"], region["s"]),
  802. projOut = projOut, flags = 'd')
  803. proj, coord2 = utils.ReprojectCoordinates(coord = (region["e"], region["n"]),
  804. projOut = projOut, flags = 'd')
  805. # useless, used in derived class
  806. proj, coord3 = utils.ReprojectCoordinates(coord = (0.0, 0.0),
  807. projOut = projOut, flags = 'd')
  808. proj, coord4 = utils.ReprojectCoordinates(coord = (region["ewres"], region["nsres"]),
  809. projOut = projOut, flags = 'd')
  810. if coord1 and coord2:
  811. if proj in ('ll', 'latlong', 'longlat') and format == 'DMS':
  812. w, s = utils.Deg2DMS(coord1[0], coord1[1], string = False,
  813. precision = precision)
  814. e, n = utils.Deg2DMS(coord2[0], coord2[1], string = False,
  815. precision = precision)
  816. ewres, nsres = utils.Deg2DMS(abs(coord3[0]) - abs(coord4[0]),
  817. abs(coord3[1]) - abs(coord4[1]),
  818. string = False, hemisphere = False,
  819. precision = precision)
  820. return self._formatRegion(w = w, s = s, e = e, n = n, ewres = ewres, nsres = nsres)
  821. else:
  822. w, s = coord1
  823. e, n = coord2
  824. ewres, nsres = coord3
  825. return self._formatRegion(w = w, s = s, e = e, n = n, ewres = ewres,
  826. nsres = nsres, precision = precision)
  827. else:
  828. raise SbException(_("Error in projection (check the settings)"))
  829. else:
  830. if self.mapFrame.GetMap().projinfo['proj'] == 'll' and format == 'DMS':
  831. w, s = utils.Deg2DMS(region["w"], region["s"],
  832. string = False, precision = precision)
  833. e, n = utils.Deg2DMS(region["e"], region["n"],
  834. string = False, precision = precision)
  835. ewres, nsres = utils.Deg2DMS(region['ewres'], region['nsres'],
  836. string = False, precision = precision)
  837. return self._formatRegion(w = w, s = s, e = e, n = n, ewres = ewres, nsres = nsres)
  838. else:
  839. w, s = region["w"], region["s"]
  840. e, n = region["e"], region["n"]
  841. ewres, nsres = region['ewres'], region['nsres']
  842. return self._formatRegion(w = w, s = s, e = e, n = n, ewres = ewres,
  843. nsres = nsres, precision = precision)
  844. class SbCompRegionExtent(SbRegionExtent):
  845. """!Shows computational region."""
  846. def __init__(self, mapframe, statusbar, position = 0):
  847. SbRegionExtent.__init__(self, mapframe, statusbar, position)
  848. self.name = 'computationalRegion'
  849. self.label = _("Computational region")
  850. def _formatRegion(self, w, e, s, n, ewres, nsres, precision = None):
  851. """!Format computational region string for statusbar"""
  852. if precision is not None:
  853. return "%.*f - %.*f, %.*f - %.*f (%.*f, %.*f)" % (precision, w, precision, e,
  854. precision, s, precision, n,
  855. precision, ewres, precision, nsres)
  856. else:
  857. return "%s - %s, %s - %s (%s, %s)" % (w, e, s, n, ewres, nsres)
  858. def _getRegion(self):
  859. """!Returns computational region."""
  860. return self.mapFrame.GetMap().GetRegion() # computational region
  861. class SbProgress(SbItem):
  862. """!General progress bar to show progress.
  863. Underlaying widget is wx.Gauge.
  864. """
  865. def __init__(self, mapframe, statusbar, sbManager, position = 0):
  866. self.progressShown = Signal('SbProgress.progressShown')
  867. self.progressHidden = Signal('SbProgress.progressHidden')
  868. SbItem.__init__(self, mapframe, statusbar, position)
  869. self.name = 'progress'
  870. self.sbManager = sbManager
  871. # on-render gauge
  872. self.widget = wx.Gauge(parent = self.statusbar, id = wx.ID_ANY,
  873. range = 0, style = wx.GA_HORIZONTAL)
  874. self.Hide()
  875. def GetRange(self):
  876. """!Returns progress range."""
  877. return self.widget.GetRange()
  878. def SetRange(self, range):
  879. """!Sets progress range."""
  880. if range > 0:
  881. if self.GetRange() != range:
  882. self.widget.SetRange(range)
  883. self.Show()
  884. else:
  885. self.Hide()
  886. def Show(self):
  887. if not self.IsShown():
  888. self.progressShown.emit()
  889. self.widget.Show()
  890. def Hide(self):
  891. if self.IsShown():
  892. self.progressHidden.emit()
  893. self.widget.Hide()
  894. def IsShown(self):
  895. """!Is progress bar shown
  896. """
  897. return self.widget.IsShown()
  898. def SetValue(self, value):
  899. """!Sets value of progressbar."""
  900. if value > self.GetRange():
  901. self.Hide()
  902. return
  903. self.widget.SetValue(value)
  904. if value == self.GetRange():
  905. self.Hide()
  906. def GetWidget(self):
  907. """!Returns underlaying winget.
  908. @return widget or None if doesn't exist
  909. """
  910. return self.widget
  911. def Update(self):
  912. pass