statusbar.py 45 KB

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