statusbar.py 45 KB

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