statusbar.py 41 KB

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