statusbar.py 42 KB

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