statusbar.py 44 KB

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