statusbar.py 41 KB

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