mapdisp_statusbar.py 38 KB

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