statusbar.py 41 KB

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