statusbar.py 43 KB

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