statusbar.py 32 KB

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