statusbar.py 34 KB

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