def AddAnimation(self): # check if we can add more animations found = False indices = [anim.windowIndex for anim in self.animationData] for windowIndex in range(len(self.animations)): if windowIndex not in indices: found = True break if not found: GMessage(parent=self.frame, message=_("Maximum number of animations is %d.") % len(self.animations)) return # running = False # if self.timer.IsRunning(): # running = True self.EndAnimation() # self.PauseAnimation(True) animData = AnimationData() # number of active animations animationIndex = len( [anim for anim in self.animations if anim.IsActive()]) animData.SetDefaultValues(windowIndex, animationIndex) dlg = InputDialog(parent=self.frame, mode='add', animationData=animData) dlg.CenterOnParent() if dlg.ShowModal() == wx.ID_CANCEL: dlg.UnInit() dlg.Destroy() return dlg.Destroy() # check compatibility if animData.windowIndex in indices: GMessage( parent=self.frame, message=_( "More animations are using one window." " Please select different window for each animation.")) return try: temporalMode, tempManager = self.EvaluateInput(self.animationData + [animData]) except GException as e: GError(parent=self.frame, message=e.value, showTraceback=False) return # if ok, set temporal mode self.temporalMode = temporalMode self.temporalManager = tempManager # add data windowIndex = animData.windowIndex self.animationData.append(animData) self._setAnimations()
def ValidatorCallback(self, win): if self._switchSizer.IsShown(self._secondPanel): return if win == self._firstRaster.GetTextCtrl(): GMessage(parent=self, message=_("Name of the first map is missing.")) else: GMessage(parent=self, message=_("Name of the second map is missing."))
def OnExportCatRastDone(self, event): ret, err = event.ret if ret == 0: cat_attrs = self.GetCategoryAttrs(event.kwds['cat_id']) GMessage( _("Scatter plot raster of class <%s> exported to raster map <%s>.") % (event.userdata['name'], event.kwds['rast_name'])) else: GMessage( _("Export of scatter plot raster of class <%s> to map <%s> failed.\n%s") % (event.userdata['name'], event.kwds['rast_name'], err))
def switch_mapset_interactively(guiparent, giface, dbase, location, mapset, show_confirmation=False): """Switch current mapset. Emits giface.currentMapsetChanged signal.""" if dbase: if RunCommand('g.mapset', parent=guiparent, location=location, mapset=mapset, dbase=dbase) == 0: if show_confirmation: GMessage(parent=guiparent, message=_("Current GRASS database is <%(dbase)s>.\n" "Current location is <%(loc)s>.\n" "Current mapset is <%(mapset)s>.") % { 'dbase': dbase, 'loc': location, 'mapset': mapset }) giface.currentMapsetChanged.emit(dbase=dbase, location=location, mapset=mapset) elif location: if RunCommand('g.mapset', parent=guiparent, location=location, mapset=mapset) == 0: if show_confirmation: GMessage(parent=guiparent, message=_("Current location is <%(loc)s>.\n" "Current mapset is <%(mapset)s>.") % { 'loc': location, 'mapset': mapset }) giface.currentMapsetChanged.emit(dbase=None, location=location, mapset=mapset) else: if RunCommand('g.mapset', parent=guiparent, mapset=mapset) == 0: if show_confirmation: GMessage(parent=guiparent, message=_("Current mapset is <%s>.") % mapset) giface.currentMapsetChanged.emit(dbase=None, location=None, mapset=mapset)
def OnOK(self, event): if self.dsnInput.GetType() == "native": RunCommand("v.external.out", parent=self, flags="r") else: dsn = self.dsnInput.GetDsn() frmt = self.dsnInput.GetFormat(getFormatAbbreviation=True) extension = self.dsnInput.GetFormatExt() options = self.dsnInput.GetOptions() if not dsn: GMessage(_("No data source selected."), parent=self) return if self.ogr: cmd, params = "v.external.out", {"output": dsn} else: cmd, params = ( "r.external.out", {"directory": dsn, "extension": extension}, ) RunCommand( cmd, parent=self, format=frmt, options=options, **params, ) self.Close()
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 createCricle(self, c): dlg = wx.TextEntryDialog( None, "Name of sample circle region", "Create circle region", "circle" + str(self.catId), ) ret = dlg.ShowModal() while True: if ret == wx.ID_OK: raster = dlg.GetValue() if checkMapExists(raster): GMessage( parent=self, message=_( "The raster file %s already" " exists, please change name" ) % raster, ) ret = dlg.ShowModal() else: dlg.Destroy() circle = self.writeCircle(c, raster) self.nextCircle(next=True, circle=circle) break else: self.nextCircle(next=False) break
def createRegion(self): dlg = wx.TextEntryDialog( None, "Name of sample region", "Create region", "region" + str(self.catId) ) ret = dlg.ShowModal() while True: if ret == wx.ID_OK: raster = dlg.GetValue() if checkMapExists(raster): GMessage( parent=self, message=_( "The raster file %s already" " exists, please change name" ) % raster, ) ret = dlg.ShowModal() else: dlg.Destroy() marea = self.writeArea( self._registeredGraphics.GetItem(0).GetCoords(), raster ) self.nextRegion(next=True, area=marea) break else: self.nextRegion(next=False) break
def OnPaste(self, event): """Paste layer or mapset""" # copying between mapsets of one location if (self.copy_layer == None): return if (self.selected_location == self.copy_location and self.selected_mapset): if (self.selected_type != None): if (self.GetItemText(self.copy_type) != self.GetItemText( self.selected_type) ): # copy raster to vector or vice versa GError(_("Failed to copy layer: invalid type."), parent=self) return self.new_name = self._getUserEntry( _('New name'), _('Copy map'), self.GetItemText(self.copy_layer) + '_copy') if not self.new_name: return if (self.GetItemText(self.copy_layer) == self.new_name): GMessage( _("Layer was not copied: new layer has the same name"), parent=self) return string = self.GetItemText( self.copy_layer) + '@' + self.GetItemText( self.copy_mapset) + ',' + self.new_name self.ChangeEnvironment(self.GetItemText(self.selected_location), self.GetItemText(self.selected_mapset)) pasted = 0 type = None label = _("Copying") + " " + string + " ..." self.showNotification.emit(message=label) if (self.GetItemText(self.copy_type) == 'vect'): pasted = RunCommand('g.copy', vect=string) node = 'vect' elif (self.GetItemText(self.copy_type) == 'rast'): pasted = RunCommand('g.copy', rast=string) node = 'rast' else: pasted = RunCommand('g.copy', rast3d=string) node = 'rast3d' if (pasted == 0): if (self.selected_type == None): self.selected_type = self.getItemByName( node, self.selected_mapset) self.AppendItem(self.selected_type, self.new_name) self.SortChildren(self.selected_type) Debug.msg(1, "COPIED TO: " + self.new_name) label = "g.copy " + self.GetItemText( self.copy_type ) + "=" + string + " -- completed" # generate this message (command) automatically? self.showNotification.emit(message=label) else: GError(_( "Failed to copy layer: action is allowed only within the same location." ), parent=self) self.RestoreBackup()
def OnOk(self, event): if not self.GetBands(): GMessage(parent=self, message=_("No scatter plots selected.")) return event.Skip()
def ChangeLocationMapset(self, mapset, location=None): """Change mapset or location""" if location: if RunCommand('g.mapset', parent=self, location=location, mapset=mapset) == 0: GMessage(parent=self, message=_("Current location is <%(loc)s>.\n" "Current mapset is <%(mapset)s>.") % {'loc': location, 'mapset': mapset}) else: if RunCommand('g.mapset', parent=self, mapset=mapset) == 0: GMessage(parent=self, message=_("Current mapset is <%s>.") % mapset)
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 OnRun(self, event): """Import/Link data (each layes as separate vector map)""" self.commandId = -1 data = self.list.GetLayers() data = self._getLayersToReprojetion(3, 4) if data is None: return if not data: GMessage(_("No layers selected. Operation canceled."), parent=self) return dsn = self.dsnInput.GetDsn() ext = self.dsnInput.GetFormatExt() # determine data driver for PostGIS links self.popOGR = False if self.dsnInput.GetType() == 'db' and \ self.dsnInput.GetFormat() == 'PostgreSQL' and \ 'GRASS_VECTOR_OGR' not in os.environ: self.popOGR = True os.environ['GRASS_VECTOR_OGR'] = '1' for layer, output, listId in data: userData = {} if ext and layer.rfind(ext) > -1: layer = layer.replace('.' + ext, '') if '|' in layer: layer, geometry = layer.split('|', 1) else: geometry = None # TODO: v.import has no geometry option # if geometry: # cmd.append('geometry=%s' % geometry) cmd = self.getSettingsPageCmd() cmd.append('input=%s' % dsn) cmd.append('layer=%s' % layer) cmd.append('output=%s' % output) if self.override.IsChecked(): cmd.append('-o') if self.overwrite.IsChecked(): cmd.append('--overwrite') # TODO options if UserSettings.Get(group='cmd', key='overwrite', subkey='enabled') and '--overwrite' not in cmd: cmd.append('--overwrite') # run in Layer Manager self._giface.RunCmd(cmd, onDone=self.OnCmdDone, userData=userData, addLayer=False)
def _start(self, x, y): """Start digitizing a new object. :param x: x coordinate in map units :param y: y coordinate in map units """ if self._running: return if not self._editedRaster: GMessage(parent=self._mapWindow, message=_("Please select first the raster map")) return if not self._drawing: if self._graphicsType == 'area': item = self._areas.AddItem(coords=[]) item.SetPropertyVal('penName', 'pen1') self._all.append(item) elif self._graphicsType == 'line': item = self._lines.AddItem(coords=[]) item.SetPropertyVal('penName', 'pen1') self._all.append(item) elif self._graphicsType == 'point': item = self._points.AddItem(coords=[]) item.SetPropertyVal('penName', 'pen1') self._all.append(item) self._drawing = True
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 OnRun(self, event): """Import/Link data (each layes as separate vector map)""" data = self.list.GetLayers() if not data: GMessage(_("No layers selected."), parent=self) return if not self._validateOutputMapName(): return # hide dialog self.Hide() inputDxf = self.dsnInput.GetValue() for layer, output, itemId in data: cmd = self.getSettingsPageCmd() cmd.append('input=%s' % inputDxf) cmd.append('layer=%s' % layer) cmd.append('output=%s' % output) for key in self.options.keys(): if self.options[key].IsChecked(): cmd.append('-%s' % key) if self.overwrite.IsChecked() or UserSettings.Get( group='cmd', key='overwrite', subkey='enabled'): cmd.append('--overwrite') # run in Layer Manager self._giface.RunCmd(cmd, onDone=self.OnCmdDone, addLayer=False)
def OnSaveSettings(self, evt=None, toFile=True): try: self.settings = self.dataMgrMW.saveSettings(sett=self.settings) except: pass try: self.settings = self.databasePnl.saveSettings(sett=self.settings) except: pass try: self.settings = self.baselinePnl.saveSettings(sett=self.settings) except: pass try: self.settings = self.grassLayers.saveSettings(sett=self.settings) except: pass self.settings['workSchema'] = self.profilSelection.GetValue() if self.schema.GetValue() is not None: self.settings['workSchema'] = self.schema.GetValue() else: GMessage("Set working profile") return False tmpPath = os.path.join(self.workPath, 'save', self.settings['workSchema']) if toFile: saveDict(tmpPath, self.settings) self.findProject() return True
def DeleteMapset(self, event): """Delete selected mapset """ location = self.listOfLocations[self.lblocations.GetSelection()] mapset = self.listOfMapsets[self.lbmapsets.GetSelection()] if mapset == 'PERMANENT': GMessage( parent=self, message=_( 'Mapset <PERMANENT> is required for valid GRASS location.\n\n' 'This mapset cannot be deleted.')) return dlg = wx.MessageDialog( parent=self, message=_( "Do you want to continue with deleting mapset <%(mapset)s> " "from location <%(location)s>?\n\n" "ALL MAPS included in this mapset will be " "PERMANENTLY DELETED!") % { 'mapset': mapset, 'location': location }, caption=_("Delete selected mapset"), style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION) if dlg.ShowModal() == wx.ID_YES: try: sutils.delete_mapset(self.gisdbase, location, mapset) self.OnSelectLocation(None) self.lbmapsets.SetSelection(0) except: wx.MessageBox(message=_('Unable to delete mapset')) dlg.Destroy()
def checkConn(self): try: self.conninfo = {'name': self.settings['database']} return True except: GMessage('name of database is missing') self.connStatus = False return False
def checkConn(self): try: self.conninfo = {"name": self.settings["database"]} return True except: GMessage("name of database is missing") self.connStatus = False return False
def Update(self): """Update histogram after changing options""" self.SetGraphStyle() p = self.CreatePlotList() if p: self.DrawPlot(p) else: GMessage(_("Nothing to plot."), parent=self)
def CheckBands(self, b_1, b_2): bands = self.core.GetBands() added_scatts_ids = self.plots.keys() b_1_id = self.all_bands_to_bands[self.all_bands[b_1]] b_2_id = self.all_bands_to_bands[self.all_bands[b_1]] scatt_id = idBandsToidScatt(b_1_id, b_2_id, len(bands)) if scatt_id in added_scatts_ids: GWarning( parent=self.guiparent, message=_( "Scatter plot with same band combination (regardless x y order) " "is already displayed.")) return False b_1_name = self.all_bands[b_1] b_2_name = self.all_bands[b_2] b_1_i = self.bands_info[b_1_name] b_2_i = self.bands_info[b_2_name] err = "" for b in [b_1_name, b_2_name]: if self.bands_info[b] is None: err += _("Band <%s> is not CELL (integer) type.\n" % b) if err: GMessage(parent=self.guiparent, message=_("Scatter plot cannot be added.\n" + err)) return False mrange = b_1_i['range'] * b_2_i['range'] if mrange > MAX_SCATT_SIZE: GWarning(parent=self.guiparent, message=_("Scatter plot cannot be added.\n" "Multiple of bands ranges <%s:%d * %s:%d = %d> " "is higher than maximum limit <%d>.\n" % (b_1_name, b_1_i['range'], b_1_name, b_2_i['range'], mrange, MAX_SCATT_SIZE))) return False elif mrange > WARN_SCATT_SIZE: dlg = wx.MessageDialog( parent=self.guiparent, message=_( "Multiple of bands ranges <%s:%d * %s:%d = %d> " "is higher than recommended limit <%d>.\n" "It is strongly advised to reduce range extend of bands" "(e. g. using r.rescale) below recommended threshold.\n\n" "Do you really want to add this scatter plot?" % (b_1_name, b_1_i['range'], b_1_name, b_2_i['range'], mrange, WARN_SCATT_SIZE)), style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_WARNING) ret = dlg.ShowModal() if ret != wx.ID_YES: return False return True
def onAbout(self, evt): dir = os.path.dirname(os.path.realpath(__file__)) GMessage( "wx.mwprecip\n\nVersion: {} \nDirectory: {}".format( VERSION, dir, ), self, )
def _getSelectedExtensions(self): eList = self.extList.GetExtensions() if not eList: GMessage(_("No extension selected. " "Operation canceled."), parent=self) return [] return eList
def OnExportMap(self, event): """Export selected features to a new map Add new map layer to layer tree and checked it @todo: set color of map to higlight color """ if len(self.selectedFeatures) == 0: GMessage(_("No features selected")) return lst = "" for (cat) in (self.selectedFeatures ): # build text string of categories for v.extract input lst += str(cat["Category"]) + "," lst = lst[:-1] outMap = (str(self.selectedFeatures[0]["Map"]) + "_selection" + str(self._id_generator(3))) ret, err = RunCommand( "v.extract", input=self.selectedFeatures[0]["Map"], layer=self.selectedFeatures[0]["Layer"], output=outMap, cats=lst, getErrorMsg=True, ) if ret == 0: tree = self._giface.GetLayerTree() if tree: tree.AddLayer( ltype="vector", lname=outMap, lcmd=["d.vect", "map=%s" % outMap], lchecked=True, ) # TODO colorize new map self.Reset() else: GMessage(_("Vector map <%s> was created") % outMap) self.Reset() else: GError(_("Unable to create a new vector map.\n\nReason: %s") % err)
def _onLeftDown(self, event): """!Left mouse button donw - raster digitizer various actions""" mapLayer = self.toolbar.GetMapName() if not mapLayer: GError(parent=self, message=_("No raster map selected for editing.")) event.Skip() return action = self.toolbar.GetAction() # print action if not action: GMessage( parent=self, message=_( "Nothing to do. " "Choose appropriate tool from digitizer toolbar." ), ) event.Skip() return # set pen self.pen = wx.Pen( colour=UserSettings.Get( group="vdigit", key="symbol", subkey=["newSegment", "color"] ), width=2, style=wx.SHORT_DASH, ) self.polypen = wx.Pen( colour=UserSettings.Get( group="vdigit", key="symbol", subkey=["newLine", "color"] ), width=2, style=wx.SOLID, ) if action == "addLine": self.OnLeftDownAddLine(event) elif action == "deleteCircle": # print "delete:Circle" x, y = event.GetPositionTuple() ids = self.pdcVector.FindObjects(x, y) # print ids if len(ids) > 0: self.selectid_circle = ids[0] else: self.selectid_circle = None ids = [] self.polycoords = [] elif action == "addCircle": if len(self.polycoords) < 1: # ignore 'one-point' lines self.polycoords.append(event.GetPositionTuple()[:])
def SaveProfileToFile(self, event): """Save r.profile data to a csv file """ dlg = wx.FileDialog( parent=self, message=_( "Choose prefix for file(s) where to save profile values..."), defaultDir=os.getcwd(), wildcard=_("Comma separated value (*.csv)|*.csv"), style=wx.FD_SAVE) pfile = [] if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() for r in self.rasterList: pfile.append(path + '_' + str(r.replace('@', '_')) + '.csv') if os.path.exists(pfile[-1]): dlgOv = wx.MessageDialog( self, message=_( "File <%s> already exists. " "Do you want to overwrite this file?") % pfile [-1], caption=_("Overwrite file?"), style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION) if dlgOv.ShowModal() != wx.ID_YES: pfile.pop() dlgOv.Destroy() continue try: fd = open(pfile[-1], "w") except IOError as e: GError(parent=self, message=_("Unable to open file <%s> for writing.\n" "Reason: %s") % (pfile[-1], e)) dlg.Destroy() return for datapair in self.raster[r]['datalist']: fd.write( '%.6f,%.6f\n' % (float( datapair[0]), float( datapair[1]))) fd.close() dlg.Destroy() if pfile: message = _("%d files created:\n%s") % ( len(pfile), '\n'.join(pfile)) else: message = _("No files generated.") GMessage(parent=self, message=message)
def RenameMapset(self, event): """Rename selected mapset""" location = self.listOfLocations[self.lblocations.GetSelection()] mapset = self.listOfMapsets[self.lbmapsets.GetSelection()] if mapset == "PERMANENT": GMessage( parent=self, message=_( "Mapset <PERMANENT> is required for valid GRASS location.\n\n" "This mapset cannot be renamed."), ) return dlg = TextEntryDialog( parent=self, message=_("Current name: %s\n\nEnter new name:") % mapset, caption=_("Rename selected mapset"), validator=GenericValidator(grass.legal_name, self._nameValidationFailed), ) if dlg.ShowModal() == wx.ID_OK: newmapset = dlg.GetValue() if newmapset == mapset: dlg.Destroy() return if newmapset in self.listOfMapsets: wx.MessageBox( parent=self, caption=_("Message"), message=_("Unable to rename mapset.\n\n" "Mapset <%s> already exists in location.") % newmapset, style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE, ) else: try: os.rename( os.path.join(self.gisdbase, location, mapset), os.path.join(self.gisdbase, location, newmapset), ) self.OnSelectLocation(None) self.lbmapsets.SetSelection( self.listOfMapsets.index(newmapset)) except Exception as e: wx.MessageBox( parent=self, caption=_("Error"), message=_("Unable to rename mapset.\n\n%s") % e, style=wx.OK | wx.ICON_ERROR | wx.CENTRE, ) dlg.Destroy()
def _getExistingCategories(self, mapp, cats): """Get a list of categories for a vector map""" vdb = grass.read_command('v.category', input=mapp, option='print') categories = vdb.splitlines() for cat in cats: if str(cat) not in categories: GMessage(message=_("Category {ca} is not on vector map" " {ma} and it will be not used").format( ma=mapp, ca=cat), parent=self) cats.remove(cat) return cats
def OnAddFunc(self, event): """Add function to the query""" if self.driver == 'dbf': GMessage(parent = self, message = _("Dbf driver does not support usage of SQL functions.")) return idx = self.list_func.GetSelections() for i in idx: func = self.sqlFuncs['sqlite'][self.list_func.GetString(i)][0] self._add(element = 'func', value = func)