def _checkImportValues(self,): """Check if required widgets are selected/filled """ warning_str = "" show_war = False if not self.list or not self.list.GetSelectedLayers(): warning_str += _("Select layer in layer list.\n") show_war = True if self.params['format'] is not None and \ self.params['format'].GetSelection() == -1: warning_str += _("Select source image format.\n") show_war = True if self.params['srs'] is not None and \ self.params['srs'].GetSelection() == -1: warning_str += _("Select source projection.\n") show_war = True if not self.o_layer_name: warning_str += _("Choose output layer name.\n") show_war = True if show_war: GMessage(parent=self.parent, message=warning_str) return False return True
def __init__(self, parent, toolSwitcher): """GCP Display toolbar constructor """ BaseToolbar.__init__(self, parent, toolSwitcher) self.InitToolbar(self._toolbarData()) self._default = self.gcpset # add tool to toggle active map window self.togglemapid = wx.NewId() self.togglemap = wx.Choice(parent = self, id = self.togglemapid, choices = [_('source'), _('target')]) self.InsertControl(10, self.togglemap) self.SetToolShortHelp(self.togglemapid, '%s %s %s' % (_('Set map canvas for '), BaseIcons["zoomBack"].GetLabel(), _(' / Zoom to map'))) for tool in (self.gcpset, self.pan, self.zoomin, self.zoomout): self.toolSwitcher.AddToolToGroup(group='mouseUse', toolbar=self, tool=tool) # realize the toolbar self.Realize() self.EnableTool(self.zoomback, False)
def addlayer(layer, item): if self.ws != 'OnEarth': self.SetItemText(item, _('layer'), 1) styles = layer.GetLayerData('styles') def_st = None for st in styles: if st['name']: style_name = st['name'] else: continue if st['title']: style_name = st['title'] if st['isDefault']: def_st = st style_item = self.AppendItem(item, style_name) if self.ws != 'OnEarth': self.SetItemText(style_item, _('style'), 1) self.SetPyData(style_item, {'type': 'style', 'layer': layer, # it is parent layer of style 'style': st}) self.SetPyData(item, {'type': 'layer', # is it layer or style? 'layer': layer, # Layer instance from web_services.cap_interface 'style': def_st}) # layer can have assigned default style
def _layout(self): """Creates the main panel with all the controls on it: * mpl canvas * mpl navigation toolbar * Control panel for interaction """ self.panel = wx.Panel(self) # Create the mpl Figure and FigCanvas objects. # 5x4 inches, 100 dots-per-inch # # color = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BACKGROUND) self.fig = Figure((5.0, 4.0), facecolor=(1, 1, 1)) self.canvas = FigCanvas(self.panel, wx.ID_ANY, self.fig) # axes are initialized later self.axes2d = None self.axes3d = None # Create the navigation toolbar, tied to the canvas # self.toolbar = NavigationToolbar(self.canvas) # # Layout # self.vbox = wx.BoxSizer(wx.VERTICAL) self.vbox.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.EXPAND) self.vbox.Add(self.toolbar, 0, wx.EXPAND) self.vbox.AddSpacer(10) gridSizer = wx.GridBagSizer(hgap=5, vgap=5) self.datasetSelect = gselect.Select(parent=self.panel, id=wx.ID_ANY, size=globalvar.DIALOG_GSELECT_SIZE, type='stds', multiple=True) self.drawButton = wx.Button(self.panel, id=wx.ID_ANY, label=_("Draw")) self.drawButton.Bind(wx.EVT_BUTTON, self.OnRedraw) self.helpButton = wx.Button(self.panel, id=wx.ID_ANY, label=_("Help")) self.helpButton.Bind(wx.EVT_BUTTON, self.OnHelp) self.view3dCheck = wx.CheckBox(self.panel, id=wx.ID_ANY, label=_("3D plot of spatio-temporal extents")) self.view3dCheck.Bind(wx.EVT_CHECKBOX, self.OnRedraw) if not check_version(1, 0, 0): self.view3dCheck.SetLabel(_("3D plot of spatio-temporal extents " "(matplotlib >= 1.0.0)")) self.view3dCheck.Disable() gridSizer.Add(wx.StaticText(self.panel, id=wx.ID_ANY, label=_("Select space time dataset(s):")), pos=(0, 0), flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL) gridSizer.Add(self.datasetSelect, pos=(1, 0), flag=wx.EXPAND) gridSizer.Add(self.drawButton, pos=(1, 1), flag=wx.EXPAND) gridSizer.Add(self.helpButton, pos=(1, 2), flag=wx.EXPAND) gridSizer.Add(self.view3dCheck, pos=(2, 0), flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL) self.vbox.Add(gridSizer, proportion=0, flag=wx.EXPAND | wx.ALL, border=10) self.panel.SetSizer(self.vbox) self.vbox.Fit(self)
def __init__(self, parent, id = wx.ID_ANY, style = wx.DEFAULT_FRAME_STYLE, size = wx.Size(700, 400), rasterList = [], **kwargs): BasePlotFrame.__init__(self, parent, size = size, **kwargs) self.toolbar = HistogramPlotToolbar(parent = self) # workaround for http://trac.wxwidgets.org/ticket/13888 if sys.platform != 'darwin': self.SetToolBar(self.toolbar) self.SetTitle(_("GRASS GIS Histogramming Tool")) # # Init variables # self.rasterList = rasterList self.plottype = 'histogram' self.group = '' self.ptitle = _('Histogram of') # title of window self.xlabel = _("Raster cell values") # default X-axis label self.ylabel = _("Cell counts") # default Y-axis label self.maptype = 'raster' # default type of histogram to plot self.histtype = 'count' self.bins = 255 self.colorList = ["blue", "green", "red", "yellow", "magenta", "cyan", "aqua", "black", "grey", "orange", "brown", "purple", "violet", "indigo"] self._initOpts() if len(self.rasterList) > 0: # set raster name(s) from layer manager if a map is selected self.raster = self.InitRasterOpts(self.rasterList, self.plottype) wx.CallAfter(self.OnCreateHist, None) else: self.raster = {}
def __init__(self, parent, giface, title=_("3D view default settings"), settings=UserSettings): PreferencesBaseDialog.__init__( self, parent=parent, title=title, giface=giface, settings=settings) self.SetIcon( wx.Icon( os.path.join( globalvar.ICONDIR, 'grass_nviz.ico'), wx.BITMAP_TYPE_ICO)) self.toolWin = self.parent.nviz # create notebook pages self._createViewPage(self.notebook) self._createFlyPage(self.notebook) self._createLightPage(self.notebook) self._createSurfacePage(self.notebook) self._createVectorPage(self.notebook) self.SetMinSize(self.GetBestSize()) self.SetSize(self.size) self.btnDefault.SetToolTipString( _("Revert settings to default, changes are not applied"))
def OnMoveToolDown(self, event): """Move down tool button pressed""" id = self.selected snum = len(self.toolslines.keys()) if id > 0 and id < snum: id_down = id + 1 this_toolline = self.toolslines[id] down_toolline = self.toolslines[id_down] self.FindWindowById(id_down).SetValue(True) self.FindWindowById(id_down + 1000).SetValue(this_toolline['tool_desc']) self.FindWindowById(id_down + 2000).SetValue(this_toolline['thresh']) self.toolslines[id_down] = this_toolline self.FindWindowById(id).SetValue(False) self.FindWindowById(id + 1000).SetValue(down_toolline['tool_desc']) self.FindWindowById(id + 2000).SetValue(down_toolline['thresh']) self.toolslines[id] = down_toolline self.selected = id_down self.SetStatusText(_("%s. cleaning tool moved down") % id) elif id == snum: self.SetStatusText(_("Last cleaning tool can not be moved down ")) elif id == -1: self.SetStatusText(_("Please select a cleaning tool to move down"))
def AddLayer(self, name, ltype = 'auto'): """Add selected map to the layer tree :param name: name of raster/vector map to be added :param type: map type ('raster', 'vector', 'auto' for autodetection) """ fname = None if ltype == 'raster' or ltype != 'vector': # check for raster fname = grass.find_file(name, element = 'cell')['fullname'] if fname: ltype = 'raster' lcmd = 'd.rast' if not fname and (ltype == 'vector' or ltype != 'raster'): # if not found check for vector fname = grass.find_file(name, element = 'vector')['fullname'] if fname: ltype = 'vector' lcmd = 'd.vect' if not fname: return _("Raster or vector map <%s> not found") % (name) self.parent.GetLayerTree().AddLayer(ltype = ltype, lname = fname, lchecked = True, lcmd = [lcmd, 'map=%s' % fname]) if ltype == 'raster': return _('Raster map <%s> added') % fname return _('Vector map <%s> added') % fname
def Populate(self, cats, update = False): """Populate the list """ itemData = {} # requested by sorter if not update: self.InsertColumn(0, _("Layer")) self.InsertColumn(1, _("Category")) else: self.DeleteAllItems() i = 1 for layer in cats.keys(): catsList = cats[layer] for cat in catsList: index = self.InsertStringItem(sys.maxint, str(catsList[0])) self.SetStringItem(index, 0, str(layer)) self.SetStringItem(index, 1, str(cat)) self.SetItemData(index, i) itemData[i] = (str(layer), str(cat)) i = i + 1 if not update: self.SetColumnWidth(0, 100) self.SetColumnWidth(1, wx.LIST_AUTOSIZE) self.currentItem = 0 return itemData
def OnEndEdit(self, event): """Finish editing of item """ itemIndex = event.GetIndex() layerOld = int (self.list.GetItem(itemIndex, 0).GetText()) catOld = int (self.list.GetItem(itemIndex, 1).GetText()) if event.GetColumn() == 0: layerNew = int(event.GetLabel()) catNew = catOld else: layerNew = layerOld catNew = int(event.GetLabel()) try: if layerNew not in self.cats[self.fid].keys(): self.cats[self.fid][layerNew] = [] self.cats[self.fid][layerNew].append(catNew) self.cats[self.fid][layerOld].remove(catOld) except: event.Veto() self.list.SetStringItem(itemIndex, 0, str(layerNew)) self.list.SetStringItem(itemIndex, 1, str(catNew)) dlg = wx.MessageDialog(self, _("Unable to add new layer/category <%(layer)s/%(category)s>.\n" "Layer and category number must be integer.\n" "Layer number must be greater than zero.") % { 'layer': self.layerNew.GetStringSelection(), 'category' : str(self.catNew.GetValue()) }, _("Error"), wx.OK | wx.ICON_ERROR) dlg.ShowModal() dlg.Destroy() return False
def __init__(self, parent, toolSwitcher): """IClass Map toolbar constructor """ BaseToolbar.__init__(self, parent, toolSwitcher) self.InitToolbar(self._toolbarData()) self._default = self.pan # add tool to toggle active map window self.togglemapid = wx.NewId() self.togglemap = wx.Choice(parent=self, id=self.togglemapid, choices=[_('Training'), _('Preview')]) self.InsertControl(9, self.togglemap) self.SetToolShortHelp( self.togglemapid, '%s %s %s' % (_('Set map canvas for '), BaseIcons["zoomBack"].GetLabel(), _('/ Zoom to map'))) for tool in (self.pan, self.zoomIn, self.zoomOut): self.toolSwitcher.AddToolToGroup( group='mouseUse', toolbar=self, tool=tool) # realize the toolbar self.Realize() self.EnableTool(self.zoomBack, False)
def validateMapNames(names, etype): """Checks if maps exist and completes missing mapset. Input is list of map names. Raises GException if map doesn't exist. """ mapDict = grass.list_grouped(etype) newNames = [] for name in names: if name.find("@") >= 0: nameShort, mapset = name.split('@', 1) if nameShort in mapDict[mapset]: newNames.append(name) else: raise GException(_("Map <%s> not found.") % name) else: found = False for mapset, mapNames in mapDict.iteritems(): if name in mapNames: found = True newNames.append(name + "@" + mapset) if not found: raise GException(_("Map <%s> not found.") % name) return newNames
def _toolbarData(self): """Toolbar data """ icons = { 'newdisplay': MetaIcon(img='monitor-create', label=_('Start new map display')), 'workspaceNew': MetaIcon(img='create', label=_('Create new workspace (Ctrl+N)')), 'workspaceOpen': MetaIcon( img='open', label=_('Open existing workspace file (Ctrl+O)')), 'workspaceSave': MetaIcon( img='save', label=_('Save current workspace to file (Ctrl+S)')), } return self._getToolbarData(( ('newdisplay', icons["newdisplay"], self.parent.OnNewDisplay), ('workspaceNew', icons["workspaceNew"], self.parent.OnWorkspaceNew), ('workspaceOpen', icons["workspaceOpen"], self.parent.OnWorkspaceOpen), ('workspaceSave', icons["workspaceSave"], self.parent.OnWorkspaceSave), ))
def SetDatasets(self, datasets, coors, output, dpi): """Set the data :param list datasets: a list of temporal dataset's name :param list coors: a list with x/y coordinates :param str output: the name of output png file :param int dpi: the dpi value for png file """ if not datasets or not coors: return try: datasets = self._checkDatasets(datasets) if not datasets: return except GException: GError(parent=self, message=_("Invalid input temporal dataset")) return try: self.poi = Point(float(coors[0]), float(coors[1])) except GException: GError(parent=self, message=_("Invalid input coordinates")) return self.datasets = datasets self.output = output self.dpi = dpi self.datasetSelect.SetValue(','.join(map(lambda x: x[0] + '@' + x[1], datasets))) self.coorval.SetValue(','.join(coors)) self._redraw()
def OnRedraw(self, event): """Required redrawing.""" datasets = self.datasetSelect.GetValue().strip() if not datasets: return datasets = datasets.split(',') try: datasets = self._checkDatasets(datasets) if not datasets: return except GException: GError(parent=self, message=_("Invalid input data")) return self.datasets = datasets try: coordx, coordy = self.coorval.GetValue().split(',') coordx, coordy = float(coordx), float(coordy) except ValueError: GMessage(_("Incorrect format of coordinates, should be: x,y")) coors = [coordx, coordy] if coors: try: self.poi = Point(float(coors[0]), float(coors[1])) except GException: GError(parent=self, message=_("Invalid input coordinates")) return self._redraw()
def _langBox(self, par, k, v): """Return box""" langBox = wx.FlexGridSizer(cols = 4, vgap = 5, hgap = 5) tkey = wx.StaticText(parent = par, id = wx.ID_ANY, label = k.upper()) langBox.Add(item = tkey) try: tgood = wx.StaticText(parent = par, id = wx.ID_ANY, label = _("%d translated" % v['good'])) tgood.SetForegroundColour(wx.Colour(35, 142, 35)) langBox.Add(item = tgood) except: tgood = wx.StaticText(parent = par, id = wx.ID_ANY, label = "") langBox.Add(item = tgood) try: tfuzzy = wx.StaticText(parent = par, id = wx.ID_ANY, label = _(" %d fuzzy" % v['fuzzy'])) tfuzzy.SetForegroundColour(wx.Colour(255, 142, 0)) langBox.Add(item = tfuzzy) except: tfuzzy = wx.StaticText(parent = par, id = wx.ID_ANY, label = "") langBox.Add(item = tfuzzy) try: tbad = wx.StaticText(parent = par, id = wx.ID_ANY, label = _(" %d untranslated" % v['bad'])) tbad.SetForegroundColour(wx.Colour(255, 0, 0)) langBox.Add(item = tbad) except: tbad = wx.StaticText(parent = par, id = wx.ID_ANY, label = "") langBox.Add(item = tbad) return langBox
def main(): options, flags = gscript.parser() import wx from grass.script.setup import set_gui_path set_gui_path() from core.utils import _ from dbmgr.manager import AttributeManager mapName = gscript.find_file(options['map'], element='vector')['fullname'] if not mapName: gscript.set_raise_on_error(False) gscript.fatal(_("Vector map <%s> not found") % options['map']) app = wx.App() gscript.message(_("Loading attribute data for vector map <%s>...") % mapName) f = AttributeManager(parent=None, id=wx.ID_ANY, title="%s - <%s>" % (_("GRASS GIS Attribute Table Manager"), mapName), size=(900, 600), vectorName=mapName) f.Show() app.MainLoop()
def GetWindow(self): """Read WIND file and set up self.wind dictionary""" # FIXME: duplicated region WIND == g.region (at least some values) env = grass.gisenv() filename = os.path.join (env['GISDBASE'], env['LOCATION_NAME'], env['MAPSET'], "WIND") try: windfile = open (filename, "r") except IOError as e: sys.exit(_("Error: Unable to open '%(file)s'. Reason: %(ret)s. wxGUI exited.\n") % \ { 'file' : filename, 'ret' : e}) for line in windfile.readlines(): line = line.strip() try: key, value = line.split(":", 1) except ValueError as e: sys.stderr.write(_("\nERROR: Unable to read WIND file: %s\n") % e) return None self.wind[key.strip()] = value.strip() windfile.close() return self.wind
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('projection'): 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 __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 main(): options, flags = gcore.parser() if options["input"]: map_name = gcore.find_file(name=options["input"], element="cell")["fullname"] if not map_name: gcore.fatal(_("Raster map <{raster}> not found").format(raster=options["input"])) # define display driver (avoid 'no graphics device selected' error at start up) driver = UserSettings.Get(group="display", key="driver", subkey="type") if driver == "png": os.environ["GRASS_RENDER_IMMEDIATE"] = "png" else: os.environ["GRASS_RENDER_IMMEDIATE"] = "cairo" # launch application app = wx.App() if not CheckWxVersion([2, 9]): wx.InitAllImageHandlers() # show main frame giface = StandaloneGrassInterface() frame = ExampleMapFrame(parent=None, giface=giface) if options["input"]: giface.WriteLog(_("Loading raster map <{raster}>...").format(raster=map_name)) frame.SetLayer(map_name) frame.Show() app.MainLoop()
def __init__(self, parent, conf, giface=None, id=wx.ID_ANY, title=_("Modify the configuration file"), style=wx.DEFAULT_FRAME_STYLE | wx.RESIZE_BORDER, **kwargs): # VARIABLES self.parent = parent self.rlipath = retRLiPath() self.confile = conf self.pathfile = os.path.join(self.rlipath, conf) wx.Frame.__init__(self, parent=parent, id=id, title=title, **kwargs) self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO)) self.panel = wx.Panel(parent=self, id=wx.ID_ANY) self.confilesBox = wx.StaticBox( parent=self.panel, id=wx.ID_ANY, label=_( "View and modify the " "configuration file '{name}'".format( name=self.confile))) self.textCtrl = wx.TextCtrl(parent=self.panel, id=wx.ID_ANY, style=wx.TE_MULTILINE, size=(-1, 75)) self.textCtrl.Bind(wx.EVT_TEXT, self.OnFileText) f = open(self.pathfile) self.textCtrl.SetValue(''.join(f.readlines())) f.close() # BUTTONS #definition self.btn_close = wx.Button(parent=self, id=wx.ID_EXIT) self.btn_ok = wx.Button(parent=self, id=wx.ID_SAVE) self.btn_close.Bind(wx.EVT_BUTTON, self.OnClose) self.btn_ok.Bind(wx.EVT_BUTTON, self.OnOk) self._layout() self.enc = locale.getdefaultlocale()[1]
def SaveToFile(self, event): """Save map to image """ img = self.firstMapWindow.img or self.secondMapWindow.img if not img: GMessage(parent = self, message = _("Nothing to render (empty map). Operation canceled.")) return filetype, ltype = GetImageHandlers(img) # get filename dlg = wx.FileDialog(parent = self, message = _("Choose a file name to save the image " "(no need to add extension)"), wildcard = filetype, style = wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() if not path: dlg.Destroy() return base, ext = os.path.splitext(path) fileType = ltype[dlg.GetFilterIndex()]['type'] extType = ltype[dlg.GetFilterIndex()]['ext'] if ext != extType: path = base + '.' + extType self._saveToFile(path, fileType) dlg.Destroy()
def __init__(self, mapframe, statusbar, position=0): SbItem.__init__(self, mapframe, statusbar, position) self.name = "projection" self.label = _("Projection") self.defaultLabel = _("Use defined projection") self.widget = wx.CheckBox(parent=self.statusbar, id=wx.ID_ANY, label=self.defaultLabel) self.widget.SetValue(False) # necessary? size = self.widget.GetSize() self.widget.SetMinSize((size[0] + 150, size[1])) self.widget.Hide() self.widget.SetToolTip( wx.ToolTip( _( "Reproject coordinates displayed " "in the statusbar. Projection can be " "defined in GUI preferences dialog " "(tab 'Projection')" ) ) )
def __init__(self, parent, id = wx.ID_ANY, style = wx.DEFAULT_FRAME_STYLE, size = wx.Size(700, 400), rasterList = [], **kwargs): BasePlotFrame.__init__(self, parent, size = size, **kwargs) self.toolbar = ScatterToolbar(parent = self) # workaround for http://trac.wxwidgets.org/ticket/13888 if sys.platform != 'darwin': self.SetToolBar(self.toolbar) self.SetTitle(_("GRASS Bivariate Scatterplot Tool")) # # Init variables # self.rasterList = rasterList self.plottype = 'scatter' self.ptitle = _('Bivariate Scatterplot') # title of window self.xlabel = _("Raster cell values") # default X-axis label self.ylabel = _("Raster cell values") # default Y-axis label self.maptype = 'raster' # default type of scatterplot self.scattertype = 'normal' self.bins = 255 self.colorList = ["blue", "red", "black", "green", "yellow", "magenta", "cyan", \ "aqua", "grey", "orange", "brown", "purple", "violet", \ "indigo"] self._initOpts() if len(self.rasterList) > 1: # set raster name(s) from layer manager if a map is selected self.InitRasterOpts(self.rasterList, 'scatter') else: self.raster = {}
def SetupScatterplot(self): """Build data list for ploting each raster """ # # initialize title string # self.ptitle = _('Bivariate Scatterplot of ') # # create a datalist for plotting for each raster pair # if len(self.rasterList) == 0: return # at least 1 pair of maps needed to plot for rpair in self.rasterList: self.raster[rpair]['datalist'] = self.CreateDatalist(rpair) # update title self.ptitle += '%s vs %s, ' % (rpair[0].split('@')[0], rpair[1].split('@')[0]) self.ptitle = self.ptitle.strip(', ') # # set xlabel & ylabel based on raster maps of first pair to be plotted # self.xlabel = _('Raster <%s> cell values') % rpair[0].split('@')[0] self.ylabel = _('Raster <%s> cell values') % rpair[1].split('@')[0] units = self.raster[self.rasterList[0]][0]['units'] if units != '': self.xlabel += _(': %s') % units units = self.raster[self.rasterList[0]][1]['units'] if units != '': self.ylabel += _(': %s') % units
def OnRegression(self, event): """Displays regression information in messagebox """ message = [] title = _('Regression Statistics for Scatterplot(s)') for rpair in self.rasterList: if isinstance(rpair, tuple) == False: continue rast1, rast2 = rpair rast1 = rast1.split('@')[0] rast2 = rast2.split('@')[0] ret = grass.parse_command('r.regression.line', mapx = rast1, mapy = rast2, flags = 'g', quiet = True, parse = (grass.parse_key_val, { 'sep' : '=' })) eqtitle = _('Regression equation for raster map <%(rast1)s> vs. <%(rast2)s>:\n\n') % \ { 'rast1' : rast1, 'rast2' : rast2 } eq = ' %s = %s + %s(%s)\n\n' % (rast2, ret['a'], ret['b'], rast1) num = 'N = %s\n' % ret['N'] rval = 'R = %s\n' % ret['R'] rsq = 'R-squared = %f\n' % pow(float(ret['R']), 2) ftest = 'F = %s\n' % ret['F'] str = eqtitle + eq + num + rval + rsq + ftest message.append(str) stats = PlotStatsFrame(self, id = wx.ID_ANY, message = message, title = title) if stats.Show() == wx.ID_CLOSE: stats.Destroy()
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("projection"): 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 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)
def Start(self): """Init measurement routine that calculates map distance along transect drawn on map display """ if self.IsActive(): return AnalysisControllerBase.Start(self) self._totaldist = 0.0 # total measured distance # initiating output (and write a message) # e.g., in Layer Manager switch to output console # TODO: this should be something like: write important message or write tip # TODO: mixed 'switching' and message? no, measuring handles 'swithing' on its own self._giface.WriteWarning(_('Click and drag with left mouse button ' 'to measure.%s' 'Double click with left button to clear.') % (os.linesep)) if self._projInfo['proj'] != 'xy': mapunits = self._projInfo['units'] self._giface.WriteCmdLog(_('Measuring distance') + ' (' + mapunits + '):') else: self._giface.WriteCmdLog(_('Measuring distance:')) if self._projInfo['proj'] == 'll': try: import grass.lib.gis as gislib gislib.G_begin_distance_calculations() self._useCtypes = True except ImportError as e: self._giface.WriteWarning(_('Geodesic distance calculation ' 'is not available.\n' 'Reason: %s' % e))
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 __init__(self, mapframe, statusbar, position=0): SbTextItem.__init__(self, mapframe, statusbar, position) self.name = 'displayGeometry' self.label = _("Display geometry")
def _createVectorPage(self, notebook): """Create notebook page for vector settings""" panel = wx.Panel(parent=notebook, id=wx.ID_ANY) notebook.AddPage(page=panel, text=" %s " % _("Vector")) pageSizer = wx.BoxSizer(wx.VERTICAL) # vector lines box = wx.StaticBox(parent=panel, id=wx.ID_ANY, label=" %s " % (_("Vector lines"))) boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL) gridSizer = wx.GridBagSizer(vgap=3, hgap=3) row = 0 # icon size gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Width:")), pos=(row, 0), flag=wx.ALIGN_CENTER_VERTICAL) iwidth = SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1), initial=12, min=1, max=100) self.winId['nviz:vector:lines:width'] = iwidth.GetId() iwidth.SetValue( UserSettings.Get(group='nviz', key='vector', subkey=['lines', 'width'])) gridSizer.Add(item=iwidth, pos=(row, 1), flag=wx.ALIGN_CENTER_VERTICAL) # icon color gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Color:")), pos=(row, 4), flag=wx.ALIGN_CENTER_VERTICAL) icolor = csel.ColourSelect(panel, id=wx.ID_ANY, size=globalvar.DIALOG_COLOR_SIZE) icolor.SetName('GetColour') self.winId['nviz:vector:lines:color'] = icolor.GetId() icolor.SetColour( UserSettings.Get(group='nviz', key='vector', subkey=['lines', 'color'])) gridSizer.Add(item=icolor, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 5)) boxSizer.Add(item=gridSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=5) pageSizer.Add(item=boxSizer, proportion=0, flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5) # vector points box = wx.StaticBox(parent=panel, id=wx.ID_ANY, label=" %s " % (_("Vector points"))) boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL) gridSizer = wx.GridBagSizer(vgap=3, hgap=5) row = 0 # icon size autosize = wx.CheckBox(parent=panel, label=_("Automatic size")) autosize.SetToolTipString( _("Icon size is set automatically based on landscape dimensions.")) gridSizer.Add(autosize, pos=(row, 0), flag=wx.ALIGN_CENTER_VERTICAL) self.winId['nviz:vector:points:autosize'] = autosize.GetId() autosize.SetValue( UserSettings.Get(group='nviz', key='vector', subkey=['points', 'autosize'])) row += 1 gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Size:")), pos=(row, 0), flag=wx.ALIGN_CENTER_VERTICAL) isize = SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1), initial=100, min=1, max=1e6) self.winId['nviz:vector:points:size'] = isize.GetId() isize.SetValue( UserSettings.Get(group='nviz', key='vector', subkey=['points', 'size'])) gridSizer.Add(item=isize, pos=(row, 1), flag=wx.ALIGN_CENTER_VERTICAL) # icon symbol row += 1 gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Marker:")), pos=(row, 0), flag=wx.ALIGN_CENTER_VERTICAL) isym = wx.Choice(parent=panel, id=wx.ID_ANY, size=(100, -1), choices=UserSettings.Get(group='nviz', key='vector', subkey=['points', 'marker'], settings_type='internal')) isym.SetName("GetSelection") self.winId['nviz:vector:points:marker'] = isym.GetId() isym.SetSelection( UserSettings.Get(group='nviz', key='vector', subkey=['points', 'marker'])) gridSizer.Add(item=isym, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 1)) # icon color row += 1 gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Color:")), pos=(row, 0), flag=wx.ALIGN_CENTER_VERTICAL) icolor = csel.ColourSelect(panel, id=wx.ID_ANY, size=globalvar.DIALOG_COLOR_SIZE) icolor.SetName('GetColour') self.winId['nviz:vector:points:color'] = icolor.GetId() icolor.SetColour( UserSettings.Get(group='nviz', key='vector', subkey=['points', 'color'])) gridSizer.Add(item=icolor, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 1)) boxSizer.Add(item=gridSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=5) pageSizer.Add(item=boxSizer, proportion=0, flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5) panel.SetSizer(pageSizer) return panel
def _createQueryPage(self, notebook): """Create notebook page for query tool""" panel = wx.Panel(parent=notebook, id=wx.ID_ANY) notebook.AddPage(page=panel, text=_("Query tool")) border = wx.BoxSizer(wx.VERTICAL) # # query tool box # box = wx.StaticBox(parent=panel, id=wx.ID_ANY, label=" %s " % _("Choose query tool")) sizer = wx.StaticBoxSizer(box, wx.VERTICAL) LocUnits = self.parent.MapWindow.Map.GetProjInfo()['units'] self.queryBox = wx.CheckBox(parent=panel, id=wx.ID_ANY, label=_("Select by box")) self.queryBox.SetValue( UserSettings.Get(group='vdigit', key="query", subkey='box')) sizer.Add(item=self.queryBox, proportion=0, flag=wx.ALL | wx.EXPAND, border=1) sizer.Add((0, 5)) # # length # self.queryLength = wx.RadioButton(parent=panel, id=wx.ID_ANY, label=_("length")) self.queryLength.Bind(wx.EVT_RADIOBUTTON, self.OnChangeQuery) sizer.Add(item=self.queryLength, proportion=0, flag=wx.ALL | wx.EXPAND, border=1) flexSizer = wx.FlexGridSizer(cols=4, hgap=5, vgap=5) flexSizer.AddGrowableCol(0) txt = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Select lines")) self.queryLengthSL = wx.Choice( parent=panel, id=wx.ID_ANY, choices=[_("shorter than"), _("longer than")]) self.queryLengthSL.SetSelection( UserSettings.Get(group='vdigit', key="queryLength", subkey='than-selection')) self.queryLengthValue = wx.SpinCtrl(parent=panel, id=wx.ID_ANY, size=(100, -1), initial=1, min=0, max=1e6) self.queryLengthValue.SetValue( UserSettings.Get(group='vdigit', key="queryLength", subkey='thresh')) units = wx.StaticText(parent=panel, id=wx.ID_ANY, label="%s" % LocUnits) flexSizer.Add(txt, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL) flexSizer.Add(self.queryLengthSL, proportion=0, flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE) flexSizer.Add(self.queryLengthValue, proportion=0, flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE) flexSizer.Add(units, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL) sizer.Add(item=flexSizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=1) # # dangle # self.queryDangle = wx.RadioButton(parent=panel, id=wx.ID_ANY, label=_("dangle")) self.queryDangle.Bind(wx.EVT_RADIOBUTTON, self.OnChangeQuery) sizer.Add(item=self.queryDangle, proportion=0, flag=wx.ALL | wx.EXPAND, border=1) flexSizer = wx.FlexGridSizer(cols=4, hgap=5, vgap=5) flexSizer.AddGrowableCol(0) txt = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Select dangles")) self.queryDangleSL = wx.Choice( parent=panel, id=wx.ID_ANY, choices=[_("shorter than"), _("longer than")]) self.queryDangleSL.SetSelection( UserSettings.Get(group='vdigit', key="queryDangle", subkey='than-selection')) self.queryDangleValue = wx.SpinCtrl(parent=panel, id=wx.ID_ANY, size=(100, -1), initial=1, min=0, max=1e6) self.queryDangleValue.SetValue( UserSettings.Get(group='vdigit', key="queryDangle", subkey='thresh')) units = wx.StaticText(parent=panel, id=wx.ID_ANY, label="%s" % LocUnits) flexSizer.Add(txt, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL) flexSizer.Add(self.queryDangleSL, proportion=0, flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE) flexSizer.Add(self.queryDangleValue, proportion=0, flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE) flexSizer.Add(units, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL) sizer.Add(item=flexSizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=1) if UserSettings.Get(group='vdigit', key="query", subkey='selection') == 0: self.queryLength.SetValue(True) else: self.queryDangle.SetValue(True) # enable & disable items self.OnChangeQuery(None) border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5) panel.SetSizer(border) return panel
def UpdateDialog(self, map=None, query=None, cats=None, fid=-1, action=None): """Update dialog :param map: name of vector map :param query: :param cats: :param fid: feature id :param action: add, update, display or None :return: True if updated :return: False """ if action: self.action = action if action == 'display': enabled = False else: enabled = True self.closeDialog.Enable(enabled) self.FindWindowById(wx.ID_OK).Enable(enabled) if map: self.map = map # get layer/table/column information self.mapDBInfo = VectorDBInfo(self.map) if not self.mapDBInfo: return False self.mapDBInfo.Reset() layers = self.mapDBInfo.layers.keys() # get available layers # id of selected line if query: # select by position data = self.mapDBInfo.SelectByPoint(query[0], query[1]) self.cats = {} if data and 'Layer' in data: idx = 0 for layer in data['Layer']: layer = int(layer) if data['Id'][idx] is not None: tfid = int(data['Id'][idx]) else: tfid = 0 # Area / Volume if not tfid in self.cats: self.cats[tfid] = {} if not layer in self.cats[tfid]: self.cats[tfid][layer] = [] cat = int(data['Category'][idx]) self.cats[tfid][layer].append(cat) idx += 1 else: self.cats = cats if fid > 0: self.fid = fid elif len(self.cats.keys()) > 0: self.fid = self.cats.keys()[0] else: self.fid = -1 if len(self.cats.keys()) == 1: self.fidMulti.Show(False) self.fidText.Show(True) if self.fid > 0: self.fidText.SetLabel("%d" % self.fid) else: self.fidText.SetLabel(_("Unknown")) else: self.fidMulti.Show(True) self.fidText.Show(False) choices = [] for tfid in self.cats.keys(): choices.append(str(tfid)) self.fidMulti.SetItems(choices) self.fidMulti.SetStringSelection(str(self.fid)) # reset notebook self.notebook.DeleteAllPages() for layer in layers: # for each layer if not query: # select by layer/cat if self.fid > 0 and layer in self.cats[self.fid]: for cat in self.cats[self.fid][layer]: nselected = self.mapDBInfo.SelectFromTable(layer, where = "%s=%d" % \ (self.mapDBInfo.layers[layer]['key'], cat)) else: nselected = 0 # if nselected <= 0 and self.action != "add": # continue # nothing selected ... if self.action == "add": if nselected <= 0: if layer in self.cats[self.fid]: table = self.mapDBInfo.layers[layer]["table"] key = self.mapDBInfo.layers[layer]["key"] columns = self.mapDBInfo.tables[table] for name in columns.keys(): if name == key: for cat in self.cats[self.fid][layer]: self.mapDBInfo.tables[table][name][ 'values'].append(cat) else: self.mapDBInfo.tables[table][name][ 'values'].append(None) else: # change status 'add' -> 'update' self.action = "update" table = self.mapDBInfo.layers[layer]["table"] key = self.mapDBInfo.layers[layer]["key"] columns = self.mapDBInfo.tables[table] for idx in range(len(columns[key]['values'])): for name in columns.keys(): if name == key: cat = int(columns[name]['values'][idx]) break # use scrolled panel instead (and fix initial max height of the window to 480px) panel = scrolled.ScrolledPanel(parent=self.notebook, id=wx.ID_ANY, size=(-1, 150)) panel.SetupScrolling(scroll_x=False) self.notebook.AddPage(page=panel, text=" %s %d / %s %d" % (_("Layer"), layer, _("Category"), cat)) # notebook body border = wx.BoxSizer(wx.VERTICAL) flexSizer = wx.FlexGridSizer(cols=3, hgap=3, vgap=3) flexSizer.AddGrowableCol(2) # columns (sorted by index) names = [''] * len(columns.keys()) for name in columns.keys(): names[columns[name]['index']] = name for name in names: if name == key: # skip key column (category) continue vtype = columns[name]['type'].lower() ctype = columns[name]['ctype'] if columns[name]['values'][idx] is not None: if columns[name]['ctype'] != types.StringType: value = str(columns[name]['values'][idx]) else: value = columns[name]['values'][idx] else: value = '' colName = wx.StaticText(parent=panel, id=wx.ID_ANY, label=name) colType = wx.StaticText(parent=panel, id=wx.ID_ANY, label="[%s]:" % vtype) colValue = wx.TextCtrl(parent=panel, id=wx.ID_ANY, value=value) colValue.SetName(name) if ctype == int: colValue.SetValidator(IntegerValidator()) elif ctype == float: colValue.SetValidator(FloatValidator()) self.Bind(wx.EVT_TEXT, self.OnSQLStatement, colValue) if self.action == 'display': colValue.SetWindowStyle(wx.TE_READONLY) flexSizer.Add(colName, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL) flexSizer.Add(colType, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT) flexSizer.Add(colValue, proportion=1, flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL) # add widget reference to self.columns columns[name]['ids'].append( colValue.GetId()) # name, type, values, id # for each attribute (including category) END border.Add(item=flexSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=5) panel.SetSizer(border) # for each category END # for each layer END if self.notebook.GetPageCount() == 0: self.noFoundMsg.Show(True) else: self.noFoundMsg.Show(False) self.Layout() return True
def __init__(self, parent, map, query=None, cats=None, line=None, style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, pos=wx.DefaultPosition, action="add", ignoreError=False): """Standard dialog used to add/update/display attributes linked to the vector map. Attribute data can be selected based on layer and category number or coordinates. :param parent: :param map: vector map :param query: query coordinates and distance (used for v.edit) :param cats: {layer: cats} :param line: feature id (requested for cats) :param style: :param pos: :param action: (add, update, display) :param ignoreError: True to ignore errors """ self.parent = parent # mapdisplay.BufferedWindow self.map = map self.action = action # ids/cats of selected features # fid : {layer : cats} self.cats = {} self.fid = -1 # feature id # get layer/table/column information self.mapDBInfo = VectorDBInfo(self.map) layers = self.mapDBInfo.layers.keys() # get available layers # check if db connection / layer exists if len(layers) <= 0: if not ignoreError: dlg = wx.MessageDialog( parent=self.parent, message=_("No attribute table found.\n\n" "Do you want to create a new attribute table " "and defined a link to vector map <%s>?") % self.map, caption=_("Create table?"), style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION) if dlg.ShowModal() == wx.ID_YES: lmgr = self.parent.lmgr lmgr.OnShowAttributeTable(event=None, selection='layers') dlg.Destroy() self.mapDBInfo = None wx.Dialog.__init__(self, parent=self.parent, id=wx.ID_ANY, title="", style=style, pos=pos) # dialog body mainSizer = wx.BoxSizer(wx.VERTICAL) # notebook self.notebook = wx.Notebook(parent=self, id=wx.ID_ANY, style=wx.BK_DEFAULT) self.closeDialog = wx.CheckBox(parent=self, id=wx.ID_ANY, label=_("Close dialog on submit")) self.closeDialog.SetValue(True) if self.action == 'display': self.closeDialog.Enable(False) # feature id (text/choice for duplicates) self.fidMulti = wx.Choice(parent=self, id=wx.ID_ANY, size=(150, -1)) self.fidMulti.Bind(wx.EVT_CHOICE, self.OnFeature) self.fidText = wx.StaticText(parent=self, id=wx.ID_ANY) self.noFoundMsg = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("No attributes found")) self.UpdateDialog(query=query, cats=cats) # set title if self.action == "update": self.SetTitle(_("Update attributes")) elif self.action == "add": self.SetTitle(_("Define attributes")) else: self.SetTitle(_("Display attributes")) # buttons btnCancel = wx.Button(self, wx.ID_CANCEL) btnReset = wx.Button(self, wx.ID_UNDO, _("&Reload")) btnSubmit = wx.Button(self, wx.ID_OK, _("&Submit")) if self.action == 'display': btnSubmit.Enable(False) btnSizer = wx.StdDialogButtonSizer() btnSizer.AddButton(btnCancel) btnSizer.AddButton(btnReset) btnSizer.SetNegativeButton(btnReset) btnSubmit.SetDefault() btnSizer.AddButton(btnSubmit) btnSizer.Realize() mainSizer.Add(item=self.noFoundMsg, proportion=0, flag=wx.EXPAND | wx.ALL, border=5) mainSizer.Add(item=self.notebook, proportion=1, flag=wx.EXPAND | wx.ALL, border=5) fidSizer = wx.BoxSizer(wx.HORIZONTAL) fidSizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Feature id:")), proportion=0, border=5, flag=wx.ALIGN_CENTER_VERTICAL) fidSizer.Add(item=self.fidMulti, proportion=0, flag=wx.EXPAND | wx.ALL, border=5) fidSizer.Add(item=self.fidText, proportion=0, flag=wx.EXPAND | wx.ALL, border=5) mainSizer.Add(item=fidSizer, proportion=0, flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=5) mainSizer.Add(item=self.closeDialog, proportion=0, flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=5) mainSizer.Add(item=btnSizer, proportion=0, flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5) # bindigs btnReset.Bind(wx.EVT_BUTTON, self.OnReset) btnSubmit.Bind(wx.EVT_BUTTON, self.OnSubmit) btnCancel.Bind(wx.EVT_BUTTON, self.OnClose) self.Bind(wx.EVT_CLOSE, self.OnClose) self.SetSizer(mainSizer) mainSizer.Fit(self) # set min size for dialog w, h = self.GetBestSize() w += 50 if h < 200: self.SetMinSize((w, 200)) else: self.SetMinSize((w, h)) if self.notebook.GetPageCount() == 0: Debug.msg(2, "DisplayAttributesDialog(): Nothing found!")
def GetSQLString(self, updateValues=False): """Create SQL statement string based on self.sqlStatement Show error message when invalid values are entered. If updateValues is True, update dataFrame according to values in textfields. """ sqlCommands = [] # find updated values for each layer/category for layer in self.mapDBInfo.layers.keys(): # for each layer table = self.mapDBInfo.GetTable(layer) key = self.mapDBInfo.GetKeyColumn(layer) columns = self.mapDBInfo.GetTableDesc(table) for idx in range(len(columns[key]['values'])): # for each category updatedColumns = [] updatedValues = [] for name in columns.keys(): if name == key: cat = columns[name]['values'][idx] continue ctype = columns[name]['ctype'] value = columns[name]['values'][idx] id = columns[name]['ids'][idx] try: newvalue = self.FindWindowById(id).GetValue() except: newvalue = self.FindWindowById(id).GetLabel() if newvalue: try: if ctype == int: newvalue = int(newvalue) elif ctype == float: newvalue = float(newvalue) except ValueError: GError(parent = self, message = _("Column <%(col)s>: Value '%(value)s' needs to be entered as %(type)s.") % \ {'col' : name, 'value' : str(newvalue), 'type' : columns[name]['type'].lower()}, showTraceback = False) sqlCommands.append(None) continue else: if self.action == 'add': continue if newvalue != value: updatedColumns.append(name) if not newvalue: updatedValues.append('NULL') else: if ctype != str: updatedValues.append(str(newvalue)) else: updatedValues.append("'" + newvalue + "'") columns[name]['values'][idx] = newvalue if self.action != "add" and len(updatedValues) == 0: continue if self.action == "add": sqlString = "INSERT INTO %s (%s," % (table, key) else: sqlString = "UPDATE %s SET " % table for idx in range(len(updatedColumns)): name = updatedColumns[idx] if self.action == "add": sqlString += name + "," else: sqlString += name + "=" + updatedValues[idx] + "," sqlString = sqlString[:-1] # remove last comma if self.action == "add": sqlString += ") VALUES (%s," % cat for value in updatedValues: sqlString += value + "," sqlString = sqlString[:-1] # remove last comma sqlString += ")" else: sqlString += " WHERE %s=%s" % (key, cat) sqlCommands.append(sqlString) # for each category # for each layer END Debug.msg(3, "DisplayAttributesDialog.GetSQLString(): %s" % sqlCommands) return sqlCommands
def _createViewPage(self, notebook): """Create notebook page for view settings""" panel = wx.Panel(parent=notebook, id=wx.ID_ANY) notebook.AddPage(page=panel, text=" %s " % _("View")) pageSizer = wx.BoxSizer(wx.VERTICAL) box = wx.StaticBox(parent=panel, id=wx.ID_ANY, label=" %s " % (_("View"))) boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL) gridSizer = wx.GridBagSizer(vgap=3, hgap=3) row = 0 # perspective pvals = UserSettings.Get(group='nviz', key='view', subkey='persp') ipvals = UserSettings.Get(group='nviz', key='view', subkey='persp', settings_type='internal') gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Perspective:")), pos=(row, 0), flag=wx.ALIGN_CENTER_VERTICAL) gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("value:")), pos=(row, 1), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT) pval = SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1), initial=pvals['value'], min=ipvals['min'], max=ipvals['max']) self.winId['nviz:view:persp:value'] = pval.GetId() gridSizer.Add(item=pval, pos=(row, 2), flag=wx.ALIGN_CENTER_VERTICAL) gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("step:")), pos=(row, 3), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT) pstep = SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1), initial=pvals['step'], min=ipvals['min'], max=ipvals['max'] - 1) self.winId['nviz:view:persp:step'] = pstep.GetId() gridSizer.Add(item=pstep, pos=(row, 4), flag=wx.ALIGN_CENTER_VERTICAL) row += 1 # position posvals = UserSettings.Get(group='nviz', key='view', subkey='position') gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Position:")), pos=(row, 0), flag=wx.ALIGN_CENTER_VERTICAL) gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("x:")), pos=(row, 1), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT) px = SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1), initial=posvals['x'] * 100, min=0, max=100) self.winId['nviz:view:position:x'] = px.GetId() gridSizer.Add(item=px, pos=(row, 2), flag=wx.ALIGN_CENTER_VERTICAL) gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label="y:"), pos=(row, 3), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT) py = SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1), initial=posvals['y'] * 100, min=0, max=100) self.winId['nviz:view:position:y'] = py.GetId() gridSizer.Add(item=py, pos=(row, 4), flag=wx.ALIGN_CENTER_VERTICAL) row += 1 # height is computed dynamically # twist tvals = UserSettings.Get(group='nviz', key='view', subkey='twist') itvals = UserSettings.Get(group='nviz', key='view', subkey='twist', settings_type='internal') gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Twist:")), pos=(row, 0), flag=wx.ALIGN_CENTER_VERTICAL) gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("value:")), pos=(row, 1), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT) tval = SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1), initial=tvals['value'], min=itvals['min'], max=itvals['max']) self.winId['nviz:view:twist:value'] = tval.GetId() gridSizer.Add(item=tval, pos=(row, 2), flag=wx.ALIGN_CENTER_VERTICAL) row += 1 # z-exag zvals = UserSettings.Get(group='nviz', key='view', subkey='z-exag') gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Z-exag:")), pos=(row, 0), flag=wx.ALIGN_CENTER_VERTICAL) gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("value:")), pos=(row, 1), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT) zval = SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1), initial=zvals['value'], min=-1e6, max=1e6) self.winId['nviz:view:z-exag:value'] = zval.GetId() gridSizer.Add(item=zval, pos=(row, 2), flag=wx.ALIGN_CENTER_VERTICAL) boxSizer.Add(item=gridSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=3) pageSizer.Add(item=boxSizer, proportion=0, flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border=3) box = wx.StaticBox(parent=panel, id=wx.ID_ANY, label=" %s " % (_("Image Appearance"))) boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL) gridSizer = wx.GridBagSizer(vgap=3, hgap=3) # background color gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Background color:")), pos=(0, 0), flag=wx.ALIGN_CENTER_VERTICAL) color = csel.ColourSelect(panel, id=wx.ID_ANY, colour=UserSettings.Get( group='nviz', key='view', subkey=['background', 'color']), size=globalvar.DIALOG_COLOR_SIZE) color.SetName('GetColour') self.winId['nviz:view:background:color'] = color.GetId() gridSizer.Add(item=color, pos=(0, 1)) gridSizer.AddGrowableCol(0) boxSizer.Add(item=gridSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=5) pageSizer.Add(item=boxSizer, proportion=0, flag=wx.EXPAND | wx.ALL, border=5) panel.SetSizer(pageSizer) return panel
def _createGeneralPage(self, notebook): """Create notebook page concerning general settings""" panel = wx.Panel(parent=notebook, id=wx.ID_ANY) notebook.AddPage(page=panel, text=_("General")) border = wx.BoxSizer(wx.VERTICAL) # # display section # box = wx.StaticBox(parent=panel, id=wx.ID_ANY, label=" %s " % _("Display")) sizer = wx.StaticBoxSizer(box, wx.VERTICAL) flexSizer = wx.FlexGridSizer(cols=3, hgap=5, vgap=5) flexSizer.AddGrowableCol(0) # line width text = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Line width")) self.lineWidthValue = wx.SpinCtrl(parent=panel, id=wx.ID_ANY, size=(75, -1), initial=UserSettings.Get( group='vdigit', key="lineWidth", subkey='value'), min=1, max=1e6) units = wx.StaticText(parent=panel, id=wx.ID_ANY, size=(115, -1), label=UserSettings.Get(group='vdigit', key="lineWidth", subkey='units'), style=wx.ALIGN_LEFT) flexSizer.Add(text, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL) flexSizer.Add(self.lineWidthValue, proportion=0, flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE) flexSizer.Add(units, proportion=0, flag=wx.ALIGN_RIGHT | wx.FIXED_MINSIZE | wx.ALIGN_CENTER_VERTICAL | wx.LEFT, border=10) sizer.Add(item=flexSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=1) border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5) # # snapping section # box = wx.StaticBox(parent=panel, id=wx.ID_ANY, label=" %s " % _("Snapping")) sizer = wx.StaticBoxSizer(box, wx.VERTICAL) flexSizer = wx.FlexGridSizer(cols=3, hgap=5, vgap=5) flexSizer.AddGrowableCol(0) # snapping text = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Snapping threshold")) self.snappingValue = wx.SpinCtrl(parent=panel, id=wx.ID_ANY, size=(75, -1), initial=UserSettings.Get( group='vdigit', key="snapping", subkey='value'), min=-1, max=1e6) self.snappingValue.Bind(wx.EVT_SPINCTRL, self.OnChangeSnappingValue) self.snappingValue.Bind(wx.EVT_TEXT, self.OnChangeSnappingValue) self.snappingUnit = wx.Choice( parent=panel, id=wx.ID_ANY, size=(125, -1), choices=[_("screen pixels"), _("map units")]) self.snappingUnit.SetStringSelection( UserSettings.Get(group='vdigit', key="snapping", subkey='units')) self.snappingUnit.Bind(wx.EVT_CHOICE, self.OnChangeSnappingUnits) flexSizer.Add(text, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL) flexSizer.Add(self.snappingValue, proportion=0, flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE) flexSizer.Add(self.snappingUnit, proportion=0, flag=wx.ALIGN_RIGHT | wx.FIXED_MINSIZE) vertexSizer = wx.BoxSizer(wx.VERTICAL) self.snapVertex = wx.CheckBox(parent=panel, id=wx.ID_ANY, label=_("Snap also to vertex")) self.snapVertex.SetValue( UserSettings.Get(group='vdigit', key="snapToVertex", subkey='enabled')) vertexSizer.Add(item=self.snapVertex, proportion=0, flag=wx.EXPAND) self.mapUnits = self.parent.MapWindow.Map.GetProjInfo()['units'] self.snappingInfo = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("Snapping threshold is %(value).1f %(units)s") % \ {'value' : self.digit.GetDisplay().GetThreshold(), 'units' : self.mapUnits}) vertexSizer.Add(item=self.snappingInfo, proportion=0, flag=wx.ALL | wx.EXPAND, border=1) sizer.Add(item=flexSizer, proportion=1, flag=wx.EXPAND) sizer.Add(item=vertexSizer, proportion=1, flag=wx.EXPAND) border.Add(item=sizer, proportion=0, flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=5) # # select box # box = wx.StaticBox(parent=panel, id=wx.ID_ANY, label=" %s " % _("Select vector features")) # feature type sizer = wx.StaticBoxSizer(box, wx.VERTICAL) inSizer = wx.BoxSizer(wx.HORIZONTAL) self.selectFeature = {} for feature in ('point', 'line', 'centroid', 'boundary'): chkbox = wx.CheckBox(parent=panel, label=feature) self.selectFeature[feature] = chkbox.GetId() chkbox.SetValue( UserSettings.Get(group='vdigit', key='selectType', subkey=[feature, 'enabled'])) inSizer.Add(item=chkbox, proportion=0, flag=wx.EXPAND | wx.ALL, border=5) sizer.Add(item=inSizer, proportion=0, flag=wx.EXPAND) # threshold flexSizer = wx.FlexGridSizer(cols=3, hgap=5, vgap=5) flexSizer.AddGrowableCol(0) text = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Select threshold")) self.selectThreshValue = wx.SpinCtrl(parent=panel, id=wx.ID_ANY, size=(75, -1), initial=UserSettings.Get( group='vdigit', key="selectThresh", subkey='value'), min=1, max=1e6) units = wx.StaticText(parent=panel, id=wx.ID_ANY, size=(115, -1), label=UserSettings.Get(group='vdigit', key="lineWidth", subkey='units'), style=wx.ALIGN_LEFT) flexSizer.Add(text, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL) flexSizer.Add(self.selectThreshValue, proportion=0, flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE) flexSizer.Add(units, proportion=0, flag=wx.ALIGN_RIGHT | wx.FIXED_MINSIZE | wx.ALIGN_CENTER_VERTICAL | wx.LEFT, border=10) self.selectIn = wx.CheckBox( parent=panel, id=wx.ID_ANY, label=_("Select only features inside of selection bounding box")) self.selectIn.SetValue( UserSettings.Get(group='vdigit', key="selectInside", subkey='enabled')) self.selectIn.SetToolTipString( _("By default are selected all features overlapping selection bounding box " )) self.checkForDupl = wx.CheckBox(parent=panel, id=wx.ID_ANY, label=_("Check for duplicates")) self.checkForDupl.SetValue( UserSettings.Get(group='vdigit', key="checkForDupl", subkey='enabled')) sizer.Add(item=flexSizer, proportion=0, flag=wx.EXPAND) sizer.Add(item=self.selectIn, proportion=0, flag=wx.EXPAND | wx.ALL, border=1) sizer.Add(item=self.checkForDupl, proportion=0, flag=wx.EXPAND | wx.ALL, border=1) border.Add(item=sizer, proportion=0, flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5) # # digitize lines box # box = wx.StaticBox(parent=panel, id=wx.ID_ANY, label=" %s " % _("Digitize lines/boundaries")) sizer = wx.StaticBoxSizer(box, wx.VERTICAL) self.intersect = wx.CheckBox(parent=panel, label=_("Break lines at intersection")) self.intersect.SetValue( UserSettings.Get(group='vdigit', key='breakLines', subkey='enabled')) sizer.Add(item=self.intersect, proportion=0, flag=wx.ALL | wx.EXPAND, border=1) border.Add(item=sizer, proportion=0, flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5) # # digitize areas box # box = wx.StaticBox(parent=panel, id=wx.ID_ANY, label=" %s " % _("Digitize areas")) sizer = wx.StaticBoxSizer(box, wx.VERTICAL) self.closeBoundary = wx.CheckBox( parent=panel, label=_("Close boundary (snap to the start node)")) self.closeBoundary.SetValue( UserSettings.Get(group='vdigit', key='closeBoundary', subkey='enabled')) sizer.Add(item=self.closeBoundary, proportion=0, flag=wx.ALL | wx.EXPAND, border=1) border.Add(item=sizer, proportion=0, flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5) # # save-on-exit box # box = wx.StaticBox(parent=panel, id=wx.ID_ANY, label=" %s " % _("Save changes")) # save changes on exit? sizer = wx.StaticBoxSizer(box, wx.VERTICAL) self.save = wx.CheckBox(parent=panel, label=_("Save changes on exit")) self.save.SetValue( UserSettings.Get(group='vdigit', key='saveOnExit', subkey='enabled')) sizer.Add(item=self.save, proportion=0, flag=wx.ALL | wx.EXPAND, border=1) border.Add(item=sizer, proportion=0, flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5) panel.SetSizer(border) return panel
def _createLightPage(self, notebook): """Create notebook page for light settings""" panel = wx.Panel(parent=notebook, id=wx.ID_ANY) notebook.AddPage(page=panel, text=" %s " % _("Lighting")) pageSizer = wx.BoxSizer(wx.VERTICAL) box = wx.StaticBox(parent=panel, id=wx.ID_ANY, label=" %s " % (_("Light"))) boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL) gridSizer = wx.GridBagSizer(vgap=3, hgap=3) # position posvals = UserSettings.Get(group='nviz', key='light', subkey='position') gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Position:")), pos=(0, 0), flag=wx.ALIGN_CENTER_VERTICAL) gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("x:")), pos=(0, 1), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT) px = SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1), initial=posvals['x'] * 100, min=-100, max=100) self.winId['nviz:light:position:x'] = px.GetId() gridSizer.Add(item=px, pos=(0, 2), flag=wx.ALIGN_CENTER_VERTICAL) gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label="y:"), pos=(0, 3), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT) py = SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1), initial=posvals['y'] * 100, min=-100, max=100) self.winId['nviz:light:position:y'] = py.GetId() gridSizer.Add(item=py, pos=(0, 4), flag=wx.ALIGN_CENTER_VERTICAL) gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("z:")), pos=(0, 5), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT) pz = SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1), initial=posvals['z'], min=0, max=100) self.winId['nviz:light:position:z'] = pz.GetId() gridSizer.Add(item=pz, pos=(0, 6), flag=wx.ALIGN_CENTER_VERTICAL) # brightness brightval = UserSettings.Get(group='nviz', key='light', subkey='bright') gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Brightness:")), pos=(1, 0), flag=wx.ALIGN_CENTER_VERTICAL) bright = SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1), initial=brightval, min=0, max=100) self.winId['nviz:light:bright'] = bright.GetId() gridSizer.Add(item=bright, pos=(1, 2), flag=wx.ALIGN_CENTER_VERTICAL) # ambient ambval = UserSettings.Get(group='nviz', key='light', subkey='ambient') gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Ambient:")), pos=(2, 0), flag=wx.ALIGN_CENTER_VERTICAL) amb = SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1), initial=ambval, min=0, max=100) self.winId['nviz:light:ambient'] = amb.GetId() gridSizer.Add(item=amb, pos=(2, 2), flag=wx.ALIGN_CENTER_VERTICAL) # light color gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Color:")), pos=(3, 0), flag=wx.ALIGN_CENTER_VERTICAL) color = csel.ColourSelect(panel, id=wx.ID_ANY, colour=UserSettings.Get(group='nviz', key='light', subkey='color'), size=globalvar.DIALOG_COLOR_SIZE) color.SetName('GetColour') self.winId['nviz:light:color'] = color.GetId() gridSizer.Add(item=color, pos=(3, 2)) boxSizer.Add(item=gridSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=5) pageSizer.Add(item=boxSizer, proportion=0, flag=wx.EXPAND | wx.ALL, border=5) panel.SetSizer(pageSizer) return panel
def __init__(self, parent, giface, title=_("Digitization settings"), style=wx.DEFAULT_DIALOG_STYLE): """Standard settings dialog for digitization purposes """ wx.Dialog.__init__(self, parent=parent, id=wx.ID_ANY, title=title, style=style) self._giface = giface self.parent = parent # MapFrame self.digit = self.parent.MapWindow.digit # notebook notebook = wx.Notebook(parent=self, id=wx.ID_ANY, style=wx.BK_DEFAULT) self._createGeneralPage(notebook) self._createSymbologyPage(notebook) self.digit.SetCategory() self._createAttributesPage(notebook) self._createQueryPage(notebook) # buttons btnApply = wx.Button(self, wx.ID_APPLY) btnCancel = wx.Button(self, wx.ID_CANCEL) btnSave = wx.Button(self, wx.ID_SAVE) btnSave.SetDefault() # bindigs btnApply.Bind(wx.EVT_BUTTON, self.OnApply) btnApply.SetToolTipString(_("Apply changes for this session")) btnApply.SetDefault() btnSave.Bind(wx.EVT_BUTTON, self.OnSave) btnSave.SetToolTipString( _("Close dialog and save changes to user settings file")) btnCancel.Bind(wx.EVT_BUTTON, self.OnCancel) btnCancel.SetToolTipString(_("Close dialog and ignore changes")) # sizers btnSizer = wx.StdDialogButtonSizer() btnSizer.AddButton(btnCancel) btnSizer.AddButton(btnApply) btnSizer.AddButton(btnSave) btnSizer.Realize() mainSizer = wx.BoxSizer(wx.VERTICAL) mainSizer.Add(item=notebook, proportion=1, flag=wx.EXPAND | wx.ALL, border=5) mainSizer.Add(item=btnSizer, proportion=0, flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5) self.Bind(wx.EVT_CLOSE, self.OnCancel) self.SetSizer(mainSizer) mainSizer.Fit(self)
def __init__(self, mapframe, statusbar, position=0): SbRegionExtent.__init__(self, mapframe, statusbar, position) self.name = 'computationalRegion' self.label = _("Computational region")
def _createFlyPage(self, notebook): """Create notebook page for view settings""" panel = wx.Panel(parent=notebook, id=wx.ID_ANY) notebook.AddPage(page=panel, text=" %s " % _("Fly-through")) pageSizer = wx.BoxSizer(wx.VERTICAL) # fly throuhg mode box = wx.StaticBox(parent=panel, id=wx.ID_ANY, label=" %s " % (_("Fly-through mode"))) boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL) gridSizer = wx.GridBagSizer(vgap=3, hgap=3) # move exag gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Move exag:")), pos=(0, 0), flag=wx.ALIGN_CENTER_VERTICAL) moveExag = SpinCtrl(panel, id=wx.ID_ANY, min=1, max=20, initial=UserSettings.Get(group='nviz', key='fly', subkey=['exag', 'move']), size=(65, -1)) self.winId['nviz:fly:exag:move'] = moveExag.GetId() gridSizer.Add(item=moveExag, pos=(0, 1)) # turn exag gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Turn exag:")), pos=(1, 0), flag=wx.ALIGN_CENTER_VERTICAL) turnExag = SpinCtrl(panel, id=wx.ID_ANY, min=1, max=20, initial=UserSettings.Get(group='nviz', key='fly', subkey=['exag', 'turn']), size=(65, -1)) self.winId['nviz:fly:exag:turn'] = turnExag.GetId() gridSizer.Add(item=turnExag, pos=(1, 1)) gridSizer.AddGrowableCol(0) boxSizer.Add(item=gridSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=5) pageSizer.Add(item=boxSizer, proportion=0, flag=wx.EXPAND | wx.ALL, border=5) panel.SetSizer(pageSizer) return panel
def _createSurfacePage(self, notebook): """Create notebook page for surface settings""" panel = wx.Panel(parent=notebook, id=wx.ID_ANY) notebook.AddPage(page=panel, text=" %s " % _("Surface")) pageSizer = wx.BoxSizer(wx.VERTICAL) # draw box = wx.StaticBox(parent=panel, id=wx.ID_ANY, label=" %s " % (_("Draw"))) boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL) gridSizer = wx.GridBagSizer(vgap=3, hgap=3) # mode gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Mode:")), flag=wx.ALIGN_CENTER_VERTICAL, pos=(0, 0)) mode = wx.Choice(parent=panel, id=wx.ID_ANY, size=(-1, -1), choices=[_("coarse"), _("fine"), _("both")]) self.winId['nviz:surface:draw:mode'] = mode.GetId() mode.SetName('GetSelection') mode.SetSelection( UserSettings.Get(group='nviz', key='surface', subkey=['draw', 'mode'])) gridSizer.Add(item=mode, flag=wx.ALIGN_CENTER_VERTICAL, pos=(0, 1)) # fine gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Fine mode:")), flag=wx.ALIGN_CENTER_VERTICAL, pos=(1, 0)) res = UserSettings.Get(group='nviz', key='surface', subkey=['draw', 'res-fine']) gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("resolution:")), flag=wx.ALIGN_CENTER_VERTICAL, pos=(1, 1)) fine = SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1), initial=res, min=1, max=100) self.winId['nviz:surface:draw:res-fine'] = fine.GetId() gridSizer.Add(item=fine, flag=wx.ALIGN_CENTER_VERTICAL, pos=(1, 2)) # coarse gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Coarse mode:")), flag=wx.ALIGN_CENTER_VERTICAL, pos=(2, 0)) res = UserSettings.Get(group='nviz', key='surface', subkey=['draw', 'res-coarse']) gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("resolution:")), flag=wx.ALIGN_CENTER_VERTICAL, pos=(2, 1)) coarse = SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1), initial=res, min=1, max=100) self.winId['nviz:surface:draw:res-coarse'] = coarse.GetId() gridSizer.Add(item=coarse, flag=wx.ALIGN_CENTER_VERTICAL, pos=(2, 2)) # style gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("style:")), flag=wx.ALIGN_CENTER_VERTICAL, pos=(3, 1)) style = wx.Choice(parent=panel, id=wx.ID_ANY, size=(-1, -1), choices=[_("wire"), _("surface")]) self.winId['nviz:surface:draw:style'] = style.GetId() style.SetName('GetSelection') style.SetSelection( UserSettings.Get(group='nviz', key='surface', subkey=['draw', 'style'])) self.winId['nviz:surface:draw:style'] = style.GetId() gridSizer.Add(item=style, flag=wx.ALIGN_CENTER_VERTICAL, pos=(3, 2)) # wire color gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("wire color:")), flag=wx.ALIGN_CENTER_VERTICAL, pos=(4, 1)) color = csel.ColourSelect(panel, id=wx.ID_ANY, colour=UserSettings.Get( group='nviz', key='surface', subkey=['draw', 'wire-color']), size=globalvar.DIALOG_COLOR_SIZE) color.SetName('GetColour') self.winId['nviz:surface:draw:wire-color'] = color.GetId() gridSizer.Add(item=color, flag=wx.ALIGN_CENTER_VERTICAL, pos=(4, 2)) boxSizer.Add(item=gridSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=5) pageSizer.Add(item=boxSizer, proportion=0, flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5) panel.SetSizer(pageSizer) return panel
def _updateProgress(self, current, text): text += _(" ({c} out of {p})").format(c=current, p=self._progressDlgMax) keepGoing, skip = self._progressDlg.Update(current, text) if not keepGoing: self.provider.RequestStopRendering()
def __layout(self): """Do layout""" sizer = wx.BoxSizer(wx.VERTICAL) dataSizer = wx.BoxSizer(wx.VERTICAL) dataSizer.Add(wx.StaticText(parent=self.panel, id=wx.ID_ANY, label=_("Enter name of signature file:")), proportion=0, flag=wx.ALL, border=3) self.fileNameCtrl = wx.TextCtrl(parent=self.panel, id=wx.ID_ANY, size=(400, -1)) if self.fileName: self.fileNameCtrl.SetValue(self.fileName) dataSizer.Add(self.fileNameCtrl, proportion=0, flag=wx.ALL | wx.EXPAND, border=3) dataSizer.Add(wx.StaticText(parent=self.panel, id=wx.ID_ANY, label=_("Signature file path:")), proportion=0, flag=wx.ALL, border=3) self.pathPanel = scrolled.ScrolledPanel(self.panel, size=(-1, 40)) pathSizer = wx.BoxSizer() self.filePathText = wx.StaticText(parent=self.pathPanel, id=wx.ID_ANY, label=self.baseFilePath) pathSizer.Add(self.filePathText, proportion=1, flag=wx.ALL | wx.EXPAND, border=1) self.pathPanel.SetupScrolling(scroll_x=True, scroll_y=False) self.pathPanel.SetSizer(pathSizer) dataSizer.Add(self.pathPanel, proportion=0, flag=wx.ALL | wx.EXPAND, border=3) # buttons btnSizer = wx.StdDialogButtonSizer() btnSizer.AddButton(self.btnCancel) btnSizer.AddButton(self.btnOK) btnSizer.Realize() sizer.Add(dataSizer, proportion=1, flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5) sizer.Add(btnSizer, proportion=0, flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5) self.panel.SetSizer(sizer) sizer.Fit(self) self.SetMinSize(self.GetSize())
import wx from core.settings import UserSettings from core.utils import _ # default icon set import grass_icons iconSetDefault = grass_icons.iconSet iconPathDefault = grass_icons.iconPath iconTheme = UserSettings.Get(group='appearance', key='iconTheme', subkey='type') if iconTheme != 'grass': sys.stderr.write( _("Unknown iconset '%s', using default 'grass'...\n") % (iconTheme)) iconSet = iconSetDefault iconPath = iconPathDefault # join paths try: if iconPath and not os.path.exists(iconPath): raise OSError for key, img in iconSet.iteritems(): if key not in iconSet or \ iconSet[key] is None: # add key iconSet[key] = img iconSet[key] = os.path.join(iconPath, iconSet[key])
def __init__(self, parent, giface, title=_("GRASS GIS Animation tool"), rasters=None, timeseries=None): wx.Frame.__init__(self, parent, title=title, style=wx.DEFAULT_FRAME_STYLE, size=(800, 600)) self._giface = giface self.SetClientSize(self.GetSize()) self.iconsize = (16, 16) self.SetIcon( wx.Icon(os.path.join(globalvar.ICONDIR, 'grass_map.ico'), wx.BITMAP_TYPE_ICO)) # Make sure the temporal database exists tgis.init() # create temporal directory and ensure it's deleted after programs ends # (stored in MAPSET/.tmp/) global TMP_DIR TMP_DIR = gcore.tempdir() self.animations = [Animation() for i in range(MAX_COUNT)] self.windows = [] self.animationPanel = AnimationsPanel(self, self.windows, initialCount=MAX_COUNT) bitmapPool = BitmapPool() mapFilesPool = MapFilesPool() self._progressDlg = None self._progressDlgMax = None self.provider = BitmapProvider(bitmapPool=bitmapPool, mapFilesPool=mapFilesPool, tempDir=TMP_DIR) self.animationSliders = {} self.animationSliders['nontemporal'] = SimpleAnimationSlider(self) self.animationSliders['temporal'] = TimeAnimationSlider(self) self.controller = AnimationController(frame=self, sliders=self.animationSliders, animations=self.animations, mapwindows=self.windows, provider=self.provider, bitmapPool=bitmapPool, mapFilesPool=mapFilesPool) for win in self.windows: win.Bind(wx.EVT_SIZE, self.FrameSizeChanged) self.provider.mapsLoaded.connect(lambda: self.SetStatusText('')) self.provider.renderingStarted.connect(self._showRenderingProgress) self.provider.renderingContinues.connect(self._updateProgress) self.provider.renderingFinished.connect(self._closeProgress) self.provider.compositionStarted.connect( self._showRenderingProgress) self.provider.compositionContinues.connect(self._updateProgress) self.provider.compositionFinished.connect(self._closeProgress) self.InitStatusbar() self._mgr = wx.aui.AuiManager(self) # toolbars self.toolbars = {} tb = ['miscToolbar', 'animationToolbar', 'mainToolbar'] if sys.platform == 'win32': tb.reverse() for toolb in tb: self._addToolbar(toolb) self._addPanes() self._mgr.Update() self.dialogs = dict() self.dialogs['speed'] = None self.dialogs['preferences'] = None self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
def __init__(self, parent, giface, id=wx.ID_ANY, title=_( "Fetch & install extension from GRASS Addons"), **kwargs): self.parent = parent self._giface = giface self.options = dict() # list of options wx.Frame.__init__(self, parent=parent, id=id, title=title, **kwargs) self.SetIcon( wx.Icon( os.path.join( globalvar.ICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO)) self.panel = wx.Panel(parent=self, id=wx.ID_ANY) # self.repoBox = StaticBox( # parent=self.panel, id=wx.ID_ANY, label=" %s " % # _("Repository (leave empty to use the official one)")) self.treeBox = StaticBox( parent=self.panel, id=wx.ID_ANY, label=" %s " % _("List of extensions - double-click to install")) # self.repo = TextCtrl(parent=self.panel, id=wx.ID_ANY) # modelBuilder loads data into tree model self.modelBuilder = ExtensionTreeModelBuilder() # tree view displays model data self.tree = CTreeView( parent=self.panel, model=self.modelBuilder.GetModel()) self.search = SearchModuleWidget( parent=self.panel, model=self.modelBuilder.GetModel(), showChoice=False) self.search.showSearchResult.connect( lambda result: self.tree.Select(result)) # show text in statusbar when notification appears self.search.showNotification.connect( lambda message: self.SetStatusText(message)) # load data in different thread self.thread = gThread() self.optionBox = StaticBox(parent=self.panel, id=wx.ID_ANY, label=" %s " % _("Options")) task = gtask.parse_interface('g.extension') ignoreFlags = ['l', 'c', 'g', 'a', 'f', 't', 'help', 'quiet'] if sys.platform == 'win32': ignoreFlags.append('d') ignoreFlags.append('i') for f in task.get_options()['flags']: name = f.get('name', '') desc = f.get('label', '') if not desc: desc = f.get('description', '') if not name and not desc: continue if name in ignoreFlags: continue self.options[name] = wx.CheckBox(parent=self.panel, id=wx.ID_ANY, label=desc) # defaultUrl = '' # default/official one will be used when option empty # self.repo.SetValue( # task.get_param( # value='url').get( # 'default', # defaultUrl)) self.statusbar = self.CreateStatusBar(number=1) # self.btnFetch = Button(parent=self.panel, id=wx.ID_ANY, # label=_("&Fetch")) # self.btnFetch.SetToolTip(_("Fetch list of available modules " # "from GRASS Addons SVN repository")) self.btnClose = Button(parent=self.panel, id=wx.ID_CLOSE) self.btnInstall = Button(parent=self.panel, id=wx.ID_ANY, label=_("&Install")) self.btnInstall.SetToolTip( _("Install selected add-ons GRASS module")) self.btnInstall.Enable(False) self.btnHelp = Button(parent=self.panel, id=wx.ID_HELP) self.btnHelp.SetToolTip(_("Show g.extension manual page")) self.btnClose.Bind(wx.EVT_BUTTON, lambda evt: self.Close()) # self.btnFetch.Bind(wx.EVT_BUTTON, self.OnFetch) self.btnInstall.Bind(wx.EVT_BUTTON, self.OnInstall) self.btnHelp.Bind(wx.EVT_BUTTON, self.OnHelp) self.tree.selectionChanged.connect(self.OnItemSelected) self.tree.itemActivated.connect(self.OnItemActivated) self.tree.contextMenu.connect(self.OnContextMenu) wx.CallAfter(self._fetch) self._layout()
def __init__(self, parent, transforms, title=_("Select datum transformation"), pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER): wx.Dialog.__init__(self, parent, wx.ID_ANY, title, pos, size, style) global transformlist self.CentreOnParent() # default transform number self.transnum = 0 panel = scrolled.ScrolledPanel(self, wx.ID_ANY) sizer = wx.BoxSizer(wx.VERTICAL) # # set panel sizer # panel.SetSizer(sizer) panel.SetupScrolling() # # dialog body # bodyBox = StaticBox(parent=panel, id=wx.ID_ANY, label=" %s " % _("Select from list of datum transformations")) bodySizer = wx.StaticBoxSizer(bodyBox) # add no transform option transforms = '---\n\n0\nDo not apply any datum transformations\n\n' + transforms transformlist = transforms.split('---') tlistlen = len(transformlist) # calculate size for transform list height = 0 width = 0 for line in transforms.splitlines(): w, h = self.GetTextExtent(line) height += h width = max(width, w) height = height + 5 if height > 400: height = 400 width = width + 5 if width > 400: width = 400 # # VListBox for displaying and selecting transformations # self.translist = TransList(panel, id=-1, size=(width, height), style=wx.SUNKEN_BORDER) self.translist.SetItemCount(tlistlen) self.translist.SetSelection(2) self.translist.SetFocus() self.Bind(wx.EVT_LISTBOX, self.ClickTrans, self.translist) bodySizer.Add(self.translist, proportion=1, flag=wx.ALIGN_CENTER | wx.ALL | wx.EXPAND) # # buttons # btnsizer = wx.StdDialogButtonSizer() btn = Button(parent=panel, id=wx.ID_OK) btn.SetDefault() btnsizer.AddButton(btn) btn = Button(parent=panel, id=wx.ID_CANCEL) btnsizer.AddButton(btn) btnsizer.Realize() sizer.Add(bodySizer, proportion=1, flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5) sizer.Add(btnsizer, proportion=0, flag=wx.ALL | wx.ALIGN_RIGHT, border=5) sizer.Fit(panel) self.SetSize(self.GetBestSize()) self.Layout()
def _createMirrorModePage(self, notebook): """Create notebook page for general settings""" panel = SP.ScrolledPanel(parent=notebook) panel.SetupScrolling(scroll_x=False, scroll_y=True) notebook.AddPage(page=panel, text=_("Mirror mode")) border = wx.BoxSizer(wx.VERTICAL) box = wx.StaticBox(parent=panel, label=" %s " % _("Mirrored cursor")) sizer = wx.StaticBoxSizer(box, wx.VERTICAL) gridSizer = wx.GridBagSizer(hgap=3, vgap=3) row = 0 gridSizer.Add(item=wx.StaticText(parent=panel, label=_("Color:")), flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL, pos=(row, 0)) color = csel.ColourSelect(parent=panel, colour=UserSettings.Get(group='mapswipe', key='cursor', subkey='color'), size=globalvar.DIALOG_COLOR_SIZE) color.SetName('GetColour') self.winId['mapswipe:cursor:color'] = color.GetId() gridSizer.Add(item=color, pos=(row, 1), flag=wx.ALIGN_RIGHT) row += 1 gridSizer.Add(item=wx.StaticText(parent=panel, label=_("Shape:")), flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL, pos=(row, 0)) cursors = wx.Choice(parent=panel, choices=self.settings.Get( group='mapswipe', key='cursor', subkey=['type', 'choices'], settings_type='internal'), name="GetSelection") cursors.SetSelection( self.settings.Get(group='mapswipe', key='cursor', subkey=['type', 'selection'])) self.winId['mapswipe:cursor:type:selection'] = cursors.GetId() gridSizer.Add(item=cursors, flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, pos=(row, 1)) row += 1 gridSizer.Add(item=wx.StaticText(parent=panel, label=_("Line width:")), flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL, pos=(row, 0)) width = wx.SpinCtrl(parent=panel, min=1, max=10, initial=self.settings.Get(group='mapswipe', key='cursor', subkey='width'), name="GetValue") self.winId['mapswipe:cursor:width'] = width.GetId() gridSizer.Add(item=width, flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, pos=(row, 1)) row += 1 gridSizer.Add(item=wx.StaticText(parent=panel, label=_("Size:")), flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL, pos=(row, 0)) size = wx.SpinCtrl(parent=panel, min=4, max=50, initial=self.settings.Get(group='mapswipe', key='cursor', subkey='size'), name="GetValue") self.winId['mapswipe:cursor:size'] = size.GetId() gridSizer.Add(item=size, flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, pos=(row, 1)) gridSizer.AddGrowableCol(1) sizer.Add(item=gridSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=3) border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=3) panel.SetSizer(border) return panel
def __init__(self, parent): GListCtrl.__init__(self, parent) # load extensions self.InsertColumn(0, _('Extension')) self.LoadData()
def __DoLayout(self, panel): """Window layout""" frameSizer = wx.BoxSizer(wx.VERTICAL) gridSizer = wx.GridBagSizer(vgap=0, hgap=0) settings3DSizer = wx.BoxSizer(wx.VERTICAL) buttonSizer = wx.BoxSizer(wx.HORIZONTAL) # north gridSizer.Add(self.MakeLabel(text=_("North"), parent=panel), flag=wx.ALIGN_BOTTOM | wx.ALIGN_CENTER_HORIZONTAL | wx.TOP | wx.LEFT | wx.RIGHT, border=5, pos=(0, 2)) gridSizer.Add(self.tnorth, flag=wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5, pos=(1, 2)) # west gridSizer.Add(self.MakeLabel(text=_("West"), parent=panel), flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.TOP | wx.BOTTOM, border=5, pos=(2, 0)) gridSizer.Add(self.twest, flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5, pos=(2, 1)) gridSizer.Add( wx.StaticBitmap(panel, wx.ID_ANY, self.img, (-1, -1), (self.img.GetWidth(), self.img.GetHeight())), flag=wx.ALIGN_CENTER | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5, pos=(2, 2)) # east gridSizer.Add(self.teast, flag=wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5, pos=(2, 3)) gridSizer.Add(self.MakeLabel(text=_("East"), parent=panel), flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.RIGHT | wx.TOP | wx.BOTTOM, border=5, pos=(2, 4)) # south gridSizer.Add(self.tsouth, flag=wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5, pos=(3, 2)) gridSizer.Add(self.MakeLabel(text=_("South"), parent=panel), flag=wx.ALIGN_TOP | wx.ALIGN_CENTER_HORIZONTAL | wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5, pos=(4, 2)) # ns-res gridSizer.Add(self.MakeLabel(text=_("N-S resolution"), parent=panel), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER | wx.TOP | wx.LEFT | wx.RIGHT, border=5, pos=(5, 1)) gridSizer.Add(self.tnsres, flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5, pos=(6, 1)) # ew-res gridSizer.Add(self.MakeLabel(text=_("E-W resolution"), parent=panel), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER | wx.TOP | wx.LEFT | wx.RIGHT, border=5, pos=(5, 3)) gridSizer.Add(self.tewres, flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5, pos=(6, 3)) # rows/cols/cells gridSizer.Add(self.lrows, flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER | wx.ALL, border=5, pos=(7, 1)) gridSizer.Add(self.lcells, flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER | wx.ALL, border=5, pos=(7, 2)) gridSizer.Add(self.lcols, flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER | wx.ALL, border=5, pos=(7, 3)) # 3D settings3DSizer.Add(self.settings3D, flag=wx.ALL, border=5) # buttons buttonSizer.Add(self.bcancel, proportion=1, flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=10) buttonSizer.Add(self.bset, proportion=1, flag=wx.ALIGN_CENTER | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=10) frameSizer.Add(gridSizer, proportion=1, flag=wx.ALL | wx.ALIGN_CENTER, border=5) frameSizer.Add(settings3DSizer, proportion=0, flag=wx.ALL | wx.ALIGN_CENTER, border=5) frameSizer.Add(buttonSizer, proportion=0, flag=wx.ALL | wx.ALIGN_RIGHT, border=5) self.SetAutoLayout(True) panel.SetSizer(frameSizer) frameSizer.Fit(panel) self.Layout()
def _toolbarData(self): """Toolbar data""" icons = { 'new': MetaIcon(img='create', label=_('Create new model (Ctrl+N)')), 'open': MetaIcon(img='open', label=_('Load model from file (Ctrl+O)')), 'save': MetaIcon(img='save', label=_('Save current model to file (Ctrl+S)')), 'toImage': MetaIcon(img='image-export', label=_('Export model to image')), 'toPython': MetaIcon(img='python-export', label=_('Export model to Python script')), 'actionAdd': MetaIcon(img='module-add', label=_('Add command (GRASS module) to model')), 'dataAdd': MetaIcon(img='data-add', label=_('Add data to model')), 'relation': MetaIcon(img='relation-create', label=_('Manually define relation between data and commands')), 'loop': MetaIcon(img='loop-add', label=_('Add loop/series to model')), 'comment': MetaIcon(img='label-add', label=_('Add comment to model')), 'run': MetaIcon(img='execute', label=_('Run model')), 'validate': MetaIcon(img='check', label=_('Validate model')), 'settings': BaseIcons['settings'].SetLabel(_('Modeler settings')), 'properties': MetaIcon(img='options', label=_('Show model properties')), 'variables': MetaIcon(img='modeler-variables', label=_('Manage model variables')), 'redraw': MetaIcon(img='redraw', label=_('Redraw model canvas')), 'quit': BaseIcons['quit'].SetLabel(_('Quit Graphical Modeler')), } return self._getToolbarData((('new', icons['new'], self.parent.OnModelNew), ('open', icons['open'], self.parent.OnModelOpen), ('save', icons['save'], self.parent.OnModelSave), ('image', icons['toImage'], self.parent.OnExportImage), ('python', icons['toPython'], self.parent.OnExportPython), (None, ), ('action', icons['actionAdd'], self.parent.OnAddAction), ('data', icons['dataAdd'], self.parent.OnAddData), ('relation', icons['relation'], self.parent.OnDefineRelation), ('loop', icons['loop'], self.parent.OnDefineLoop), ('comment', icons['comment'], self.parent.OnAddComment), (None, ), ('redraw', icons['redraw'], self.parent.OnCanvasRefresh), ('validate', icons['validate'], self.parent.OnValidateModel), ('run', icons['run'], self.parent.OnRunModel), (None, ), ("variables", icons['variables'], self.parent.OnVariables), ("settings", icons['settings'], self.parent.OnPreferences), ("help", BaseIcons['help'], self.parent.OnHelp), (None, ), ('quit', icons['quit'], self.parent.OnCloseWindow)) )
def MakeSettings3DPaneContent(self, pane): """Create 3D region settings pane""" border = wx.BoxSizer(wx.VERTICAL) gridSizer = wx.GridBagSizer(vgap=0, hgap=0) # inputs self.ttop = TextCtrl(parent=pane, id=wx.ID_ANY, value=str(self.top), size=(150, -1)) self.tbottom = TextCtrl(parent=pane, id=wx.ID_ANY, value=str(self.bottom), size=(150, -1)) self.ttbres = TextCtrl(parent=pane, id=wx.ID_ANY, value=str(self.tbres), size=(150, -1)) # self.tnsres3 = wx.TextCtrl(parent = pane, id = wx.ID_ANY, value = str(self.nsres3), # size = (150, -1)) # self.tewres3 = wx.TextCtrl(parent = pane, id = wx.ID_ANY, value = str(self.ewres3), # size = (150, -1)) # labels self.ldepth = StaticText(parent=pane, label=_("Depth: %d") % self.depth) self.lcells3 = StaticText(parent=pane, label=_("3D Cells: %d") % self.cells3) # top gridSizer.Add(StaticText(parent=pane, label=_("Top")), flag=wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT | wx.TOP, border=5, pos=(0, 1)) gridSizer.Add(self.ttop, flag=wx.ALIGN_CENTER_HORIZONTAL | wx.ALL, border=5, pos=(1, 1)) # bottom gridSizer.Add(StaticText(parent=pane, label=_("Bottom")), flag=wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT | wx.TOP, border=5, pos=(0, 2)) gridSizer.Add(self.tbottom, flag=wx.ALIGN_CENTER_HORIZONTAL | wx.ALL, border=5, pos=(1, 2)) # tbres gridSizer.Add(StaticText(parent=pane, label=_("T-B resolution")), flag=wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT | wx.TOP, border=5, pos=(0, 3)) gridSizer.Add(self.ttbres, flag=wx.ALIGN_CENTER_HORIZONTAL | wx.ALL, border=5, pos=(1, 3)) # res # gridSizer.Add(item = wx.StaticText(parent = pane, label = _("3D N-S resolution")), # flag = wx.ALIGN_CENTER | # wx.LEFT | wx.RIGHT | wx.TOP, border = 5, # pos = (2, 1)) # gridSizer.Add(item = self.tnsres3, # flag = wx.ALIGN_CENTER_HORIZONTAL | # wx.ALL, border = 5, pos = (3, 1)) # gridSizer.Add(item = wx.StaticText(parent = pane, label = _("3D E-W resolution")), # flag = wx.ALIGN_CENTER | # wx.LEFT | wx.RIGHT | wx.TOP, border = 5, # pos = (2, 3)) # gridSizer.Add(item = self.tewres3, # flag = wx.ALIGN_CENTER_HORIZONTAL | # wx.ALL, border = 5, pos = (3, 3)) # rows/cols/cells gridSizer.Add(self.ldepth, flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER | wx.ALL, border=5, pos=(2, 1)) gridSizer.Add(self.lcells3, flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER | wx.ALL, border=5, pos=(2, 2)) border.Add(gridSizer, proportion=1, flag=wx.ALL | wx.ALIGN_CENTER | wx.EXPAND, border=5) pane.SetSizer(border) border.Fit(pane)
def __init__(self, parent, id=wx.ID_ANY, size=(800, 600), title=_("Set default region extent and resolution"), location=None): wx.Dialog.__init__(self, parent, id, title, size=size) panel = wx.Panel(self, id=wx.ID_ANY) self.SetIcon( wx.Icon(os.path.join(globalvar.ICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO)) self.parent = parent self.location = location # # default values # # 2D self.north = 1.0 self.south = 0.0 self.east = 1.0 self.west = 0.0 self.nsres = 1.0 self.ewres = 1.0 # 3D self.top = 1.0 self.bottom = 0.0 # self.nsres3 = 1.0 # self.ewres3 = 1.0 self.tbres = 1.0 # # inputs # # 2D self.tnorth = self.MakeTextCtrl(text=str(self.north), size=(150, -1), parent=panel) self.tsouth = self.MakeTextCtrl(str(self.south), size=(150, -1), parent=panel) self.twest = self.MakeTextCtrl(str(self.west), size=(150, -1), parent=panel) self.teast = self.MakeTextCtrl(str(self.east), size=(150, -1), parent=panel) self.tnsres = self.MakeTextCtrl(str(self.nsres), size=(150, -1), parent=panel) self.tewres = self.MakeTextCtrl(str(self.ewres), size=(150, -1), parent=panel) # # labels # self.lrows = self.MakeLabel(parent=panel) self.lcols = self.MakeLabel(parent=panel) self.lcells = self.MakeLabel(parent=panel) # # buttons # self.bset = self.MakeButton(text=_("&Set region"), id=wx.ID_OK, parent=panel) self.bcancel = Button(panel, id=wx.ID_CANCEL) self.bset.SetDefault() # # image # self.img = wx.Image(os.path.join(globalvar.IMGDIR, "qgis_world.png"), wx.BITMAP_TYPE_PNG).ConvertToBitmap() # # set current working environment to PERMANENT mapset # in selected location in order to set default region (WIND) # envval = {} ret = RunCommand('g.gisenv', read=True) if ret: for line in ret.splitlines(): key, val = line.split('=') envval[key] = val self.currlocation = envval['LOCATION_NAME'].strip("';") self.currmapset = envval['MAPSET'].strip("';") if self.currlocation != self.location or self.currmapset != 'PERMANENT': RunCommand('g.gisenv', set='LOCATION_NAME=%s' % self.location) RunCommand('g.gisenv', set='MAPSET=PERMANENT') else: dlg = wx.MessageBox(parent=self, message=_('Invalid location selected.'), caption=_("Error"), style=wx.ID_OK | wx.ICON_ERROR) return # # get current region settings # region = {} ret = RunCommand('g.region', read=True, flags='gp3') if ret: for line in ret.splitlines(): key, val = line.split('=') region[key] = float(val) else: dlg = wx.MessageBox(parent=self, message=_("Invalid region"), caption=_("Error"), style=wx.ID_OK | wx.ICON_ERROR) dlg.ShowModal() dlg.Destroy() return # # update values # 2D self.north = float(region['n']) self.south = float(region['s']) self.east = float(region['e']) self.west = float(region['w']) self.nsres = float(region['nsres']) self.ewres = float(region['ewres']) self.rows = int(region['rows']) self.cols = int(region['cols']) self.cells = int(region['cells']) # 3D self.top = float(region['t']) self.bottom = float(region['b']) # self.nsres3 = float(region['nsres3']) # self.ewres3 = float(region['ewres3']) self.tbres = float(region['tbres']) self.depth = int(region['depths']) self.cells3 = int(region['cells3']) # # 3D box collapsable # self.infoCollapseLabelExp = _("Click here to show 3D settings") self.infoCollapseLabelCol = _("Click here to hide 3D settings") self.settings3D = wx.CollapsiblePane(parent=panel, label=self.infoCollapseLabelExp, style=wx.CP_DEFAULT_STYLE | wx.CP_NO_TLW_RESIZE | wx.EXPAND) self.MakeSettings3DPaneContent(self.settings3D.GetPane()) self.settings3D.Collapse(False) # FIXME self.Bind(wx.EVT_COLLAPSIBLEPANE_CHANGED, self.OnSettings3DPaneChanged, self.settings3D) # # set current region settings # self.tnorth.SetValue(str(self.north)) self.tsouth.SetValue(str(self.south)) self.twest.SetValue(str(self.west)) self.teast.SetValue(str(self.east)) self.tnsres.SetValue(str(self.nsres)) self.tewres.SetValue(str(self.ewres)) self.ttop.SetValue(str(self.top)) self.tbottom.SetValue(str(self.bottom)) # self.tnsres3.SetValue(str(self.nsres3)) # self.tewres3.SetValue(str(self.ewres3)) self.ttbres.SetValue(str(self.tbres)) self.lrows.SetLabel(_("Rows: %d") % self.rows) self.lcols.SetLabel(_("Cols: %d") % self.cols) self.lcells.SetLabel(_("Cells: %d") % self.cells) # # bindings # self.Bind(wx.EVT_BUTTON, self.OnSetButton, self.bset) self.Bind(wx.EVT_BUTTON, self.OnCancel, self.bcancel) self.tnorth.Bind(wx.EVT_TEXT, self.OnValue) self.tsouth.Bind(wx.EVT_TEXT, self.OnValue) self.teast.Bind(wx.EVT_TEXT, self.OnValue) self.twest.Bind(wx.EVT_TEXT, self.OnValue) self.tnsres.Bind(wx.EVT_TEXT, self.OnValue) self.tewres.Bind(wx.EVT_TEXT, self.OnValue) self.ttop.Bind(wx.EVT_TEXT, self.OnValue) self.tbottom.Bind(wx.EVT_TEXT, self.OnValue) # self.tnsres3.Bind(wx.EVT_TEXT, self.OnValue) # self.tewres3.Bind(wx.EVT_TEXT, self.OnValue) self.ttbres.Bind(wx.EVT_TEXT, self.OnValue) self.__DoLayout(panel) self.SetMinSize(self.GetBestSize()) self.minWindowSize = self.GetMinSize() wx.CallAfter(self.settings3D.Collapse, True)
def __init__(self, mapframe, statusbar, position=0): SbTextItem.__init__(self, mapframe, statusbar, position) self.name = 'displayRegion' self.label = _("Extent")
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)
def __init__(self, parent, title, data, keyEditable=(-1, True), id=wx.ID_ANY, style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER): """Dialog for inserting/updating table record :param data: a list: [(column, value)] :param keyEditable: (id, editable?) indicates if textarea for key column is editable(True) or not """ # parent -> VDigitWindow wx.Dialog.__init__(self, parent, id, title, style=style) self.CenterOnParent() self.keyId = keyEditable[0] box = wx.StaticBox(parent=self, id=wx.ID_ANY) box.Hide() self.dataPanel = scrolled.ScrolledPanel(parent=self, id=wx.ID_ANY, style=wx.TAB_TRAVERSAL) self.dataPanel.SetupScrolling(scroll_x=False) # buttons self.btnCancel = wx.Button(self, wx.ID_CANCEL) self.btnSubmit = wx.Button(self, wx.ID_OK, _("&Submit")) self.btnSubmit.SetDefault() # data area self.widgets = [] cId = 0 self.usebox = False self.cat = None winFocus = False for column, ctype, ctypeStr, value in data: if self.keyId == cId: self.cat = int(value) if not keyEditable[1]: self.usebox = True box.SetLabel(" %s %d " % (_("Category"), self.cat)) box.Show() self.boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL) cId += 1 continue else: valueWin = wx.SpinCtrl(parent=self.dataPanel, id=wx.ID_ANY, value=value, min=-1e9, max=1e9, size=(250, -1)) else: valueWin = wx.TextCtrl(parent=self.dataPanel, id=wx.ID_ANY, value=value, size=(250, -1)) if ctype == int: valueWin.SetValidator(IntegerValidator()) elif ctype == float: valueWin.SetValidator(FloatValidator()) if not winFocus: wx.CallAfter(valueWin.SetFocus) winFocus = True label = wx.StaticText(parent=self.dataPanel, id=wx.ID_ANY, label=column) ctype = wx.StaticText(parent=self.dataPanel, id=wx.ID_ANY, label="[%s]:" % ctypeStr.lower()) self.widgets.append( (label.GetId(), ctype.GetId(), valueWin.GetId())) cId += 1 self._layout()
def __init__(self, parent, id=wx.ID_ANY, title=_('Set up vector cleaning tools'), style=wx.DEFAULT_FRAME_STYLE | wx.RESIZE_BORDER, **kwargs): """ Dialog for interactively defining vector cleaning tools """ wx.Frame.__init__(self, parent, id, title, style=style, **kwargs) self.parent = parent # GMFrame if self.parent: self.log = self.parent.GetLogWindow() else: self.log = None # grass command self.cmd = 'v.clean' # statusbar self.CreateStatusBar() # icon self.SetIcon( wx.Icon(os.path.join(globalvar.ICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO)) self.panel = wx.Panel(parent=self, id=wx.ID_ANY) # input map to clean self.inmap = '' # cleaned output map self.outmap = '' self.ftype = '' # cleaning tools self.toolslines = {} self.tool_desc_list = [ _('break lines/boundaries'), _('remove duplicates'), _('remove dangles'), _('change boundary dangles to lines'), _('remove bridges'), _('change bridges to lines'), _('snap lines/boundaries'), _('remove duplicate area centroids'), _('break polygons'), _('prune lines/boundaries'), _('remove small areas'), _('remove lines/boundaries of zero length'), _('remove small angles at nodes') ] self.tool_list = [ 'break', 'rmdupl', 'rmdangle', 'chdangle', 'rmbridge', 'chbridge', 'snap', 'rmdac', 'bpol', 'prune', 'rmarea', 'rmline', 'rmsa' ] self.ftype = ['point', 'line', 'boundary', 'centroid', 'area', 'face'] self.n_ftypes = len(self.ftype) self.tools_string = '' self.thresh_string = '' self.ftype_string = '' self.SetStatusText(_("Set up vector cleaning tools")) self.elem = 'vector' self.ctlabel = _('Choose cleaning tools and set thresholds') # top controls self.inmaplabel = wx.StaticText(parent=self.panel, id=wx.ID_ANY, label=_('Select input vector map:')) self.selectionInput = Select(parent=self.panel, id=wx.ID_ANY, size=globalvar.DIALOG_GSELECT_SIZE, type='vector') self.ftype_check = {} ftypeBox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY, label=_(' Feature type: ')) self.ftypeSizer = wx.StaticBoxSizer(ftypeBox, wx.HORIZONTAL) self.outmaplabel = wx.StaticText(parent=self.panel, id=wx.ID_ANY, label=_('Select output vector map:')) self.selectionOutput = Select(parent=self.panel, id=wx.ID_ANY, size=globalvar.DIALOG_GSELECT_SIZE, mapsets=[ grass.gisenv()['MAPSET'], ], fullyQualified=False, type='vector') self.overwrite = wx.CheckBox( parent=self.panel, id=wx.ID_ANY, label=_('Allow output files to overwrite existing files')) self.overwrite.SetValue( UserSettings.Get(group='cmd', key='overwrite', subkey='enabled')) # cleaning tools self.ct_label = wx.StaticText(parent=self.panel, id=wx.ID_ANY, label=self.ctlabel) self.ct_panel = self._toolsPanel() # buttons to manage cleaning tools self.btn_add = wx.Button(parent=self.panel, id=wx.ID_ADD) self.btn_remove = wx.Button(parent=self.panel, id=wx.ID_REMOVE) self.btn_moveup = wx.Button(parent=self.panel, id=wx.ID_UP) self.btn_movedown = wx.Button(parent=self.panel, id=wx.ID_DOWN) # add one tool as default self.AddTool() self.selected = -1 # Buttons self.btn_close = wx.Button(parent=self.panel, id=wx.ID_CLOSE) self.btn_run = wx.Button(parent=self.panel, id=wx.ID_ANY, label=_("&Run")) self.btn_run.SetDefault() self.btn_clipboard = wx.Button(parent=self.panel, id=wx.ID_COPY) self.btn_clipboard.SetToolTipString( _("Copy the current command string to the clipboard (Ctrl+C)")) self.btn_help = wx.Button(parent=self.panel, id=wx.ID_HELP) # bindings self.btn_close.Bind(wx.EVT_BUTTON, self.OnClose) self.btn_run.Bind(wx.EVT_BUTTON, self.OnCleaningRun) self.btn_clipboard.Bind(wx.EVT_BUTTON, self.OnCopy) self.btn_help.Bind(wx.EVT_BUTTON, self.OnHelp) self.btn_add.Bind(wx.EVT_BUTTON, self.OnAddTool) self.btn_remove.Bind(wx.EVT_BUTTON, self.OnClearTool) self.btn_moveup.Bind(wx.EVT_BUTTON, self.OnMoveToolUp) self.btn_movedown.Bind(wx.EVT_BUTTON, self.OnMoveToolDown) # layout self._layout() self.SetMinSize(self.GetBestSize()) self.CentreOnScreen()