statusbar.py 42 KB

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