123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002 |
- """
- @package mapdisp.statusbar
- @brief Classes for statusbar management
- Classes:
- - statusbar::SbException
- - statusbar::SbManager
- - statusbar::SbItem
- - statusbar::SbRender
- - statusbar::SbMapScale
- - statusbar::SbGoTo
- - statusbar::SbTextItem
- - statusbar::SbDisplayGeometry
- - statusbar::SbCoordinates
- - statusbar::SbRegionExtent
- - statusbar::SbCompRegionExtent
- - statusbar::SbProgress
- (C) 2006-2011 by the GRASS Development Team
- This program is free software under the GNU General Public License
- (>=v2). Read the file COPYING that comes with GRASS for details.
- @author Vaclav Petras <wenzeslaus gmail.com>
- @author Anna Kratochvilova <kratochanna gmail.com>
- """
- import copy
- import wx
- from core import utils
- from core.gcmd import RunCommand
- from core.settings import UserSettings
- from gui_core.wrap import TextCtrl
- from grass.pydispatch.signal import Signal
- class SbException(Exception):
- """Exception class used in SbManager and SbItems"""
- def __init__(self, message):
- # Exception.__init__(self, message)
- self.message = message
- def __str__(self):
- return self.message
- class SbManager:
- """Statusbar manager for wx.Statusbar and SbItems.
- Statusbar manager manages items added by AddStatusbarItem method.
- Provides progress bar (SbProgress).
- Items with position 0 are shown according to selection in Map Display settings dialog.
- Only one item of the same class is supposed to be in statusbar.
- Manager user have to create statusbar on his own, add items to manager
- and call Update method to show particular widgets.
- User settings (group = 'display', key = 'statusbarMode', subkey = 'selection')
- are taken into account.
- .. todo::
- generalize access to UserSettings (specify group, etc.)
- .. todo::
- add GetMode method using name instead of index
- """
- def __init__(self, mapframe, statusbar):
- """Connects manager to statusbar
- Creates progress bar.
- """
- self.mapFrame = mapframe
- self.statusbar = statusbar
- self.statusbarItems = dict()
- self._postInitialized = False
- self._modeIndexSet = False
- self._mode = 0
- self.progressbar = SbProgress(self.mapFrame, self.statusbar, self)
- self.progressbar.progressShown.connect(self._progressShown)
- self.progressbar.progressHidden.connect(self._progressHidden)
- self._oldStatus = ""
- self.disabledItems = {}
- def SetProperty(self, name, value):
- """Sets property represented by one of contained SbItems
- :param name: name of SbItem (from name attribute)
- :param value: value to be set
- """
- self.statusbarItems[name].SetValue(value)
- def GetProperty(self, name):
- """Returns property represented by one of contained SbItems
- :param name: name of SbItem (from name attribute)
- """
- return self.statusbarItems[name].GetValue()
- def HasProperty(self, name):
- """Checks whether property is represented by one of contained SbItems
- :param name: name of SbItem (from name attribute)
- :return: True if particular SbItem is contained, False otherwise
- """
- if name in self.statusbarItems:
- return True
- return False
- def AddStatusbarItem(self, item):
- """Adds item to statusbar"""
- self.statusbarItems[item.name] = item
- def AddStatusbarItemsByClass(self, itemClasses, **kwargs):
- """Adds items to statusbar
- :param list itemClasses: list of classes of items to be add
- :param kwargs: SbItem constructor parameters
- :func:`AddStatusbarItem`
- """
- for Item in itemClasses:
- item = Item(**kwargs)
- self.AddStatusbarItem(item)
- def DisableStatusbarItemsByClass(self, itemClasses):
- """Fill list of item indexes that are disabled.
- :param itemClasses list of classes of items to be disabled
- """
- for itemClass in itemClasses:
- for i in range(0, len(self.statusbarItems.values())):
- item = list(self.statusbarItems.values())[i]
- if item.__class__ == itemClass:
- self.disabledItems[i] = item
- def GetItemLabels(self):
- """Get list of item labels"""
- return [
- value.label
- for value in self.statusbarItems.values()
- if value.GetPosition() == 0
- ]
- def ShowItem(self, itemName):
- """Invokes showing of particular item
- :func:`Update`
- """
- if (
- self.statusbarItems[itemName].GetPosition() != 0
- or not self.progressbar.IsShown()
- ):
- self.statusbarItems[itemName].Show()
- def _postInit(self):
- """Post-initialization method
- It sets internal user settings,
- set selection (from map display settings) and does reposition.
- It is called automatically.
- """
- UserSettings.Set(
- group="display",
- key="statusbarMode",
- subkey="choices",
- value=self.GetItemLabels(),
- settings_type="internal",
- )
- if not self._modeIndexSet:
- self.SetMode(
- UserSettings.Get(
- group="display", key="statusbarMode", subkey="selection"
- )
- )
- self.Reposition()
- self._postInitialized = True
- def Update(self):
- """Updates statusbar"""
- self.progressbar.Update()
- if not self._postInitialized:
- self._postInit()
- for item in self.statusbarItems.values():
- if item.GetPosition() == 0:
- if not self.progressbar.IsShown():
- item.Hide()
- else:
- item.Update() # render
- if self.progressbar.IsShown():
- pass
- else:
- item = list(self.statusbarItems.values())[self.GetMode()]
- item.Update()
- def Reposition(self):
- """Reposition items in statusbar
- Set positions to all items managed by statusbar manager.
- It should not be necessary to call it manually.
- """
- widgets = []
- for item in self.statusbarItems.values():
- widgets.append((item.GetPosition(), item.GetWidget()))
- widgets.append((1, self.progressbar.GetWidget()))
- for idx, win in widgets:
- if not win:
- continue
- rect = self.statusbar.GetFieldRect(idx)
- if idx == 0: # show region / mapscale / process bar
- # -> size
- wWin, hWin = win.GetBestSize()
- # -> position
- # if win == self.statusbarWin['region']:
- # x, y = rect.x + rect.width - wWin, rect.y - 1
- # align left
- # else:
- x, y = rect.x + 3, rect.y - 1
- w, h = wWin, rect.height + 2
- else: # auto-rendering
- x, y = rect.x, rect.y
- w, h = rect.width, rect.height + 1
- if win == self.progressbar.GetWidget():
- wWin = rect.width - 6
- if idx == 2: # render
- x += 5
- win.SetPosition((x, y))
- win.SetSize((w, h))
- def GetProgressBar(self):
- """Returns progress bar"""
- return self.progressbar
- def _progressShown(self):
- self._oldStatus = self.statusbar.GetStatusText(0)
- def _progressHidden(self):
- self.statusbar.SetStatusText(self._oldStatus, 0)
- def SetMode(self, mode):
- """Sets current mode
- Mode is usually driven by user through map display settings.
- """
- self._mode = mode
- self._modeIndexSet = True
- def GetMode(self):
- """Returns current mode"""
- return self._mode
- def SetProgress(self, range, value, text):
- """Update progress."""
- self.progressbar.SetRange(range)
- self.progressbar.SetValue(value)
- if text:
- self.statusbar.SetStatusText(text)
- class SbItem:
- """Base class for statusbar items.
- Each item represents functionality (or action) controlled by statusbar
- and related to MapFrame.
- One item is usually connected with one widget but it is not necessary.
- Item can represent property (depends on manager).
- Items are not widgets but can provide interface to them.
- Items usually has requirements to MapFrame instance
- (specified as MapFrame.methodname or MapWindow.methodname).
- .. todo::
- consider externalizing position (see SbProgress use in SbManager)
- """
- def __init__(self, mapframe, statusbar, position=0):
- """
- :param mapframe: instance of class with MapFrame interface
- :param statusbar: statusbar instance (wx.Statusbar)
- :param position: item position in statusbar
- .. todo::
- rewrite Update also in derived classes to take in account item position
- """
- self.mapFrame = mapframe
- self.statusbar = statusbar
- self.position = position
- def Show(self):
- """Invokes showing of underlying widget.
- In derived classes it can do what is appropriate for it,
- e.g. showing text on statusbar (only).
- """
- self.widget.Show()
- def Hide(self):
- self.widget.Hide()
- def SetValue(self, value):
- self.widget.SetValue(value)
- def GetValue(self):
- return self.widget.GetValue()
- def GetPosition(self):
- return self.position
- def GetWidget(self):
- """Returns underlying widget.
- :return: widget or None if doesn't exist
- """
- return self.widget
- def _update(self, longHelp):
- """Default implementation for Update method.
- :param longHelp: True to enable long help (help from toolbars)
- """
- self.statusbar.SetStatusText("", 0)
- self.Show()
- self.mapFrame.StatusbarEnableLongHelp(longHelp)
- def Update(self):
- """Called when statusbar action is activated (e.g. through Map Display settings)."""
- self._update(longHelp=False)
- class SbRender(SbItem):
- """Checkbox to enable and disable auto-rendering.
- Requires MapFrame.OnRender method.
- """
- def __init__(self, mapframe, statusbar, position=0):
- SbItem.__init__(self, mapframe, statusbar, position)
- self.name = "render"
- self._properties = mapframe.mapWindowProperties
- self.widget = wx.CheckBox(
- parent=self.statusbar, id=wx.ID_ANY, label=_("Render")
- )
- self.widget.SetValue(self._properties.autoRender)
- self.widget.Hide()
- self.widget.SetToolTip(wx.ToolTip(_("Enable/disable auto-rendering")))
- self._connectAutoRender()
- self.widget.Bind(wx.EVT_CHECKBOX, self._onCheckbox)
- def _setValue(self, value):
- self.widget.SetValue(value)
- def _connectAutoRender(self):
- self._properties.autoRenderChanged.connect(self._setValue)
- def _disconnectAutoRender(self):
- self._properties.autoRenderChanged.disconnect(self._setValue)
- def _onCheckbox(self, event):
- self._disconnectAutoRender()
- self._properties.autoRender = self.widget.GetValue()
- self._connectAutoRender()
- def Update(self):
- self.Show()
- class SbMapScale(SbItem):
- """Editable combobox to get/set current map scale.
- Requires MapFrame.GetMapScale, MapFrame.SetMapScale
- and MapFrame.GetWindow (and GetWindow().UpdateMap()).
- """
- def __init__(self, mapframe, statusbar, position=0):
- SbItem.__init__(self, mapframe, statusbar, position)
- self.name = "mapscale"
- self.label = _("Map scale")
- self.widget = wx.ComboBox(
- parent=self.statusbar,
- id=wx.ID_ANY,
- style=wx.TE_PROCESS_ENTER,
- size=(150, -1),
- )
- self.widget.SetItems(
- [
- "1:1000",
- "1:5000",
- "1:10000",
- "1:25000",
- "1:50000",
- "1:100000",
- "1:1000000",
- ]
- )
- self.widget.Hide()
- self.widget.SetToolTip(
- wx.ToolTip(
- _(
- "As everyone's monitors and resolutions "
- "are set differently these values are not "
- "true map scales, but should get you into "
- "the right neighborhood."
- )
- )
- )
- self.widget.Bind(wx.EVT_TEXT_ENTER, self.OnChangeMapScale)
- self.widget.Bind(wx.EVT_COMBOBOX, self.OnChangeMapScale)
- self.lastMapScale = None
- def Update(self):
- scale = self.mapFrame.GetMapScale()
- self.statusbar.SetStatusText("")
- try:
- self.SetValue("1:%ld" % (scale + 0.5))
- except TypeError:
- pass # FIXME, why this should happen?
- self.lastMapScale = scale
- self.Show()
- # disable long help
- self.mapFrame.StatusbarEnableLongHelp(False)
- def OnChangeMapScale(self, event):
- """Map scale changed by user"""
- scale = event.GetString()
- try:
- if scale[:2] != "1:":
- raise ValueError
- value = int(scale[2:])
- except ValueError:
- self.SetValue("1:%ld" % int(self.lastMapScale))
- return
- self.mapFrame.SetMapScale(value)
- # redraw a map
- self.mapFrame.GetWindow().UpdateMap()
- self.GetWidget().SetFocus()
- class SbGoTo(SbItem):
- """Textctrl to set coordinates which to focus on.
- Requires MapFrame.GetWindow, MapWindow.GoTo method.
- """
- def __init__(self, mapframe, statusbar, position=0):
- SbItem.__init__(self, mapframe, statusbar, position)
- self.name = "goto"
- self.label = _("Go to XY coordinates")
- self.widget = TextCtrl(
- parent=self.statusbar,
- id=wx.ID_ANY,
- value="",
- style=wx.TE_PROCESS_ENTER,
- size=(300, -1),
- )
- self.widget.Hide()
- self.widget.Bind(wx.EVT_TEXT_ENTER, self.OnGoTo)
- def ReprojectENToMap(self, e, n, useDefinedProjection):
- """Reproject east, north from user defined projection
- :param e,n: coordinate (for DMS string, else float or string)
- :param useDefinedProjection: projection defined by user in settings dialog
- @throws SbException if useDefinedProjection is True and projection is not defined in UserSettings
- """
- if useDefinedProjection:
- settings = UserSettings.Get(
- group="projection", key="statusbar", subkey="proj4"
- )
- if not settings:
- raise SbException(_("Projection not defined (check the settings)"))
- else:
- # reproject values
- projIn = settings
- projOut = RunCommand("g.proj", flags="jf", read=True)
- proj = projIn.split(" ")[0].split("=")[1]
- if proj in ("ll", "latlong", "longlat"):
- e, n = utils.DMS2Deg(e, n)
- proj, coord1 = utils.ReprojectCoordinates(
- coord=(e, n), projIn=projIn, projOut=projOut, flags="d"
- )
- e, n = coord1
- else:
- e, n = float(e), float(n)
- proj, coord1 = utils.ReprojectCoordinates(
- coord=(e, n), projIn=projIn, projOut=projOut, flags="d"
- )
- e, n = coord1
- elif self.mapFrame.GetMap().projinfo["proj"] == "ll":
- e, n = utils.DMS2Deg(e, n)
- else:
- e, n = float(e), float(n)
- return e, n
- def OnGoTo(self, event):
- """Go to position"""
- try:
- e, n = self.GetValue().split(";")
- e, n = self.ReprojectENToMap(
- e, n, self.mapFrame.GetProperty("useDefinedProjection")
- )
- self.mapFrame.GetWindow().GoTo(e, n)
- self.widget.SetFocus()
- except ValueError:
- # FIXME: move this code to MapWindow/BufferedWindow/MapFrame
- region = self.mapFrame.GetMap().GetCurrentRegion()
- precision = int(
- UserSettings.Get(group="projection", key="format", subkey="precision")
- )
- format = UserSettings.Get(group="projection", key="format", subkey="ll")
- if self.mapFrame.GetMap().projinfo["proj"] == "ll" and format == "DMS":
- self.SetValue(
- "%s"
- % utils.Deg2DMS(
- region["center_easting"],
- region["center_northing"],
- precision=precision,
- )
- )
- else:
- self.SetValue(
- "%.*f; %.*f"
- % (
- precision,
- region["center_easting"],
- precision,
- region["center_northing"],
- )
- )
- except SbException as e:
- # FIXME: this may be useless since statusbar update checks user
- # defined projection and this exception raises when user def proj
- # does not exists
- self.statusbar.SetStatusText(str(e), 0)
- def GetCenterString(self, map):
- """Get current map center in appropriate format"""
- region = map.GetCurrentRegion()
- precision = int(
- UserSettings.Get(group="projection", key="format", subkey="precision")
- )
- format = UserSettings.Get(group="projection", key="format", subkey="ll")
- projection = UserSettings.Get(
- group="projection", key="statusbar", subkey="proj4"
- )
- if self.mapFrame.GetProperty("useDefinedProjection"):
- if not projection:
- raise SbException(_("Projection not defined (check the settings)"))
- else:
- proj, coord = utils.ReprojectCoordinates(
- coord=(region["center_easting"], region["center_northing"]),
- projOut=projection,
- flags="d",
- )
- if coord:
- if proj in ("ll", "latlong", "longlat") and format == "DMS":
- return "%s" % utils.Deg2DMS(
- coord[0], coord[1], precision=precision
- )
- else:
- return "%.*f; %.*f" % (precision, coord[0], precision, coord[1])
- else:
- raise SbException(_("Error in projection (check the settings)"))
- else:
- if self.mapFrame.GetMap().projinfo["proj"] == "ll" and format == "DMS":
- return "%s" % utils.Deg2DMS(
- region["center_easting"],
- region["center_northing"],
- precision=precision,
- )
- else:
- return "%.*f; %.*f" % (
- precision,
- region["center_easting"],
- precision,
- region["center_northing"],
- )
- def SetCenter(self):
- """Set current map center as item value"""
- center = self.GetCenterString(self.mapFrame.GetMap())
- self.SetValue(center)
- def Update(self):
- self.statusbar.SetStatusText("")
- try:
- self.SetCenter()
- self.Show()
- except SbException as e:
- self.statusbar.SetStatusText(str(e), 0)
- # disable long help
- self.mapFrame.StatusbarEnableLongHelp(False)
- class SbTextItem(SbItem):
- """Base class for items without widgets.
- Only sets statusbar text.
- """
- def __init__(self, mapframe, statusbar, position=0):
- SbItem.__init__(self, mapframe, statusbar, position)
- self.text = None
- def Show(self):
- self.statusbar.SetStatusText(self.GetValue(), self.position)
- def Hide(self):
- self.statusbar.SetStatusText("", self.position)
- def SetValue(self, value):
- self.text = value
- def GetValue(self):
- return self.text
- def GetWidget(self):
- return None
- def Update(self):
- self._update(longHelp=True)
- class SbDisplayGeometry(SbTextItem):
- """Show current display resolution."""
- def __init__(self, mapframe, statusbar, position=0):
- SbTextItem.__init__(self, mapframe, statusbar, position)
- self.name = "displayGeometry"
- self.label = _("Display geometry")
- def Show(self):
- region = copy.copy(self.mapFrame.GetMap().GetCurrentRegion())
- if self.mapFrame.mapWindowProperties.resolution:
- compRegion = self.mapFrame.GetMap().GetRegion(add3d=False)
- region["rows"] = abs(
- int((region["n"] - region["s"]) / compRegion["nsres"]) + 0.5
- )
- region["cols"] = abs(
- int((region["e"] - region["w"]) / compRegion["ewres"]) + 0.5
- )
- region["nsres"] = compRegion["nsres"]
- region["ewres"] = compRegion["ewres"]
- self.SetValue(
- "rows=%d; cols=%d; nsres=%.2f; ewres=%.2f"
- % (region["rows"], region["cols"], region["nsres"], region["ewres"])
- )
- SbTextItem.Show(self)
- class SbCoordinates(SbTextItem):
- """Show map coordinates when mouse moves.
- Requires MapWindow.GetLastEN method."""
- def __init__(self, mapframe, statusbar, position=0):
- SbTextItem.__init__(self, mapframe, statusbar, position)
- self.name = "coordinates"
- self.label = _("Coordinates")
- self._additionalInfo = None
- self._basicValue = None
- def Show(self):
- """Show the last map window coordinates.
- .. todo::
- remove last EN call and use coordinates coming from signal
- """
- precision = int(
- UserSettings.Get(group="projection", key="format", subkey="precision")
- )
- format = UserSettings.Get(group="projection", key="format", subkey="ll")
- projection = self.mapFrame.GetProperty("useDefinedProjection")
- try:
- e, n = self.mapFrame.GetWindow().GetLastEN()
- self._basicValue = self.ReprojectENFromMap(
- e, n, projection, precision, format
- )
- if self._additionalInfo:
- value = "{coords} ({additionalInfo})".format(
- coords=self._basicValue, additionalInfo=self._additionalInfo
- )
- else:
- value = self._basicValue
- self.SetValue(value)
- except SbException as e:
- self.SetValue(e.message)
- # TODO: remove these excepts, they just hide errors, solve problems
- # differently
- except TypeError as e:
- self.SetValue("")
- except AttributeError:
- # during initialization MapFrame has no MapWindow
- self.SetValue("")
- SbTextItem.Show(self)
- def SetAdditionalInfo(self, text):
- """Sets additional info to be shown together with coordinates.
- The format is translation dependent but the default is
- "coordinates (additional info)"
- It does not show the changed text immediately, it waits for the Show()
- method to be called.
- :param text: string to be shown
- """
- self._additionalInfo = text
- def ReprojectENFromMap(self, e, n, useDefinedProjection, precision, format):
- """Reproject east, north to user defined projection.
- :param e,n: coordinate
- @throws SbException if useDefinedProjection is True and projection is not defined in UserSettings
- """
- if useDefinedProjection:
- settings = UserSettings.Get(
- group="projection", key="statusbar", subkey="proj4"
- )
- if not settings:
- raise SbException(_("Projection not defined (check the settings)"))
- else:
- # reproject values
- proj, coord = utils.ReprojectCoordinates(
- coord=(e, n), projOut=settings, flags="d"
- )
- if coord:
- e, n = coord
- if proj in ("ll", "latlong", "longlat") and format == "DMS":
- return utils.Deg2DMS(e, n, precision=precision)
- else:
- return "%.*f; %.*f" % (precision, e, precision, n)
- else:
- raise SbException(_("Error in projection (check the settings)"))
- else:
- if self.mapFrame.GetMap().projinfo["proj"] == "ll" and format == "DMS":
- return utils.Deg2DMS(e, n, precision=precision)
- else:
- return "%.*f; %.*f" % (precision, e, precision, n)
- class SbRegionExtent(SbTextItem):
- """Shows current display region"""
- def __init__(self, mapframe, statusbar, position=0):
- SbTextItem.__init__(self, mapframe, statusbar, position)
- self.name = "displayRegion"
- self.label = _("Display extent")
- def Show(self):
- precision = int(
- UserSettings.Get(group="projection", key="format", subkey="precision")
- )
- format = UserSettings.Get(group="projection", key="format", subkey="ll")
- projection = self.mapFrame.GetProperty("useDefinedProjection")
- region = self._getRegion()
- try:
- regionReprojected = self.ReprojectRegionFromMap(
- region, projection, precision, format
- )
- self.SetValue(regionReprojected)
- except SbException as e:
- self.SetValue(e.message)
- SbTextItem.Show(self)
- def _getRegion(self):
- """Get current display region"""
- return self.mapFrame.GetMap().GetCurrentRegion() # display region
- def _formatRegion(self, w, e, s, n, nsres, ewres, precision=None):
- """Format display region string for statusbar
- :param nsres,ewres: unused
- """
- if precision is not None:
- return "%.*f - %.*f, %.*f - %.*f" % (
- precision,
- w,
- precision,
- e,
- precision,
- s,
- precision,
- n,
- )
- else:
- return "%s - %s, %s - %s" % (w, e, s, n)
- def ReprojectRegionFromMap(self, region, useDefinedProjection, precision, format):
- """Reproject region values
- .. todo::
- reorganize this method to remove code useful only for derived class SbCompRegionExtent
- """
- if useDefinedProjection:
- settings = UserSettings.Get(
- group="projection", key="statusbar", subkey="proj4"
- )
- if not settings:
- raise SbException(_("Projection not defined (check the settings)"))
- else:
- projOut = settings
- proj, coord1 = utils.ReprojectCoordinates(
- coord=(region["w"], region["s"]), projOut=projOut, flags="d"
- )
- proj, coord2 = utils.ReprojectCoordinates(
- coord=(region["e"], region["n"]), projOut=projOut, flags="d"
- )
- # useless, used in derived class
- proj, coord3 = utils.ReprojectCoordinates(
- coord=(0.0, 0.0), projOut=projOut, flags="d"
- )
- proj, coord4 = utils.ReprojectCoordinates(
- coord=(region["ewres"], region["nsres"]), projOut=projOut, flags="d"
- )
- if coord1 and coord2:
- if proj in ("ll", "latlong", "longlat") and format == "DMS":
- w, s = utils.Deg2DMS(
- coord1[0], coord1[1], string=False, precision=precision
- )
- e, n = utils.Deg2DMS(
- coord2[0], coord2[1], string=False, precision=precision
- )
- ewres, nsres = utils.Deg2DMS(
- abs(coord3[0]) - abs(coord4[0]),
- abs(coord3[1]) - abs(coord4[1]),
- string=False,
- hemisphere=False,
- precision=precision,
- )
- return self._formatRegion(
- w=w, s=s, e=e, n=n, ewres=ewres, nsres=nsres
- )
- else:
- w, s = coord1
- e, n = coord2
- ewres, nsres = coord3
- return self._formatRegion(
- w=w,
- s=s,
- e=e,
- n=n,
- ewres=ewres,
- nsres=nsres,
- precision=precision,
- )
- else:
- raise SbException(_("Error in projection (check the settings)"))
- else:
- if self.mapFrame.GetMap().projinfo["proj"] == "ll" and format == "DMS":
- w, s = utils.Deg2DMS(
- region["w"], region["s"], string=False, precision=precision
- )
- e, n = utils.Deg2DMS(
- region["e"], region["n"], string=False, precision=precision
- )
- ewres, nsres = utils.Deg2DMS(
- region["ewres"], region["nsres"], string=False, precision=precision
- )
- return self._formatRegion(w=w, s=s, e=e, n=n, ewres=ewres, nsres=nsres)
- else:
- w, s = region["w"], region["s"]
- e, n = region["e"], region["n"]
- ewres, nsres = region["ewres"], region["nsres"]
- return self._formatRegion(
- w=w, s=s, e=e, n=n, ewres=ewres, nsres=nsres, precision=precision
- )
- class SbCompRegionExtent(SbRegionExtent):
- """Shows computational region."""
- def __init__(self, mapframe, statusbar, position=0):
- SbRegionExtent.__init__(self, mapframe, statusbar, position)
- self.name = "computationalRegion"
- self.label = _("Computational region")
- def _formatRegion(self, w, e, s, n, ewres, nsres, precision=None):
- """Format computational region string for statusbar"""
- if precision is not None:
- return "%.*f - %.*f, %.*f - %.*f (%.*f, %.*f)" % (
- precision,
- w,
- precision,
- e,
- precision,
- s,
- precision,
- n,
- precision,
- ewres,
- precision,
- nsres,
- )
- else:
- return "%s - %s, %s - %s (%s, %s)" % (w, e, s, n, ewres, nsres)
- def _getRegion(self):
- """Returns computational region."""
- return self.mapFrame.GetMap().GetRegion() # computational region
- class SbProgress(SbItem):
- """General progress bar to show progress.
- Underlaying widget is wx.Gauge.
- """
- def __init__(self, mapframe, statusbar, sbManager, position=0):
- self.progressShown = Signal("SbProgress.progressShown")
- self.progressHidden = Signal("SbProgress.progressHidden")
- SbItem.__init__(self, mapframe, statusbar, position)
- self.name = "progress"
- self.sbManager = sbManager
- # on-render gauge
- self.widget = wx.Gauge(
- parent=self.statusbar, id=wx.ID_ANY, range=0, style=wx.GA_HORIZONTAL
- )
- self.Hide()
- def GetRange(self):
- """Returns progress range."""
- return self.widget.GetRange()
- def SetRange(self, range):
- """Sets progress range."""
- if range > 0:
- if self.GetRange() != range:
- self.widget.SetRange(range)
- self.Show()
- else:
- self.Hide()
- def Show(self):
- if not self.IsShown():
- self.progressShown.emit()
- self.widget.Show()
- def Hide(self):
- if self.IsShown():
- self.progressHidden.emit()
- self.widget.Hide()
- def IsShown(self):
- """Is progress bar shown"""
- return self.widget.IsShown()
- def SetValue(self, value):
- """Sets value of progressbar."""
- if value > self.GetRange():
- self.Hide()
- return
- self.widget.SetValue(value)
- if value == self.GetRange():
- self.Hide()
- def GetWidget(self):
- """Returns underlaying winget.
- :return: widget or None if doesn't exist
- """
- return self.widget
- def Update(self):
- pass
|