mapdisp_statusbar.py 41 KB

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