statusbar.py 44 KB

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