statusbar.py 42 KB

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