mapdisp_statusbar.py 41 KB

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