statusbar.py 41 KB

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