Beispiel #1
0
    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)
Beispiel #2
0
    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()[:])
Beispiel #3
0
    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 %s.") %
                     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.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()
Beispiel #4
0
    def OnStart(self, event):
        """'Start GRASS' button clicked"""
        dbase = self.tgisdbase.GetValue()
        location = self.listOfLocations[self.lblocations.GetSelection()]
        mapset = self.listOfMapsets[self.lbmapsets.GetSelection()]

        lockfile = os.path.join(dbase, location, mapset, '.gislock')
        if os.path.isfile(lockfile):
            dlg = wx.MessageDialog(
                parent=self,
                message=_(
                    "GRASS is already running in selected mapset <%(mapset)s>\n"
                    "(file %(lock)s found).\n\n"
                    "Concurrent use not allowed.\n\n"
                    "Do you want to try to remove .gislock (note that you "
                    "need permission for this operation) and continue?") % {
                        'mapset': mapset,
                        'lock': lockfile
                    },
                caption=_("Lock file found"),
                style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)

            ret = dlg.ShowModal()
            dlg.Destroy()
            if ret == wx.ID_YES:
                dlg1 = wx.MessageDialog(
                    parent=self,
                    message=
                    _("ARE YOU REALLY SURE?\n\n"
                      "If you really are running another GRASS session doing this "
                      "could corrupt your data. Have another look in the processor "
                      "manager just to be sure..."),
                    caption=_("Lock file found"),
                    style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION
                    | wx.CENTRE)

                ret = dlg1.ShowModal()
                dlg1.Destroy()

                if ret == wx.ID_YES:
                    try:
                        os.remove(lockfile)
                    except IOError as e:
                        GError(
                            _("Unable to remove '%(lock)s'.\n\n"
                              "Details: %(reason)s") % {
                                  'lock': lockfile,
                                  'reason': e
                              })
                else:
                    return
            else:
                return
        self.SetLocation(dbase, location, mapset)
        self.ExitSuccessfully()
Beispiel #5
0
    def SetEditCatDataDone(self, event):
        if not self.data_set:
            return

        self.render_mgr.RunningProcessDone()
        if event.exception:
            GError(_("Error occurred during computation of scatter plot category:\n%s"), 
                      parent = self.guiparent, showTraceback = False)

        cat_id = event.ret
        self.iclass_conn.RenderCatRast(cat_id)
Beispiel #6
0
 def SetDatasets(self, datasets):
     """Set data"""
     if not datasets:
         return
     try:
         datasets = self._checkDatasets(datasets)
         if not datasets:
             return
     except GException, e:
         GError(parent=self, message=unicode(e), showTraceback=False)
         return
Beispiel #7
0
    def OnCleaningRun(self, event):
        """Builds options and runs v.clean"""
        self.GetCmdStrings()

        err = list()
        for p, name in (
            (self.inmap, _("Name of input vector map")),
            (self.outmap, _("Name for output vector map")),
            (self.tools_string, _("Tools")),
            (self.thresh_string, _("Threshold")),
        ):
            if not p:
                err.append(_("'%s' not defined") % name)
        if err:
            GError(
                _("Some parameters not defined. Operation "
                  "canceled.\n\n%s") % "\n".join(err),
                parent=self,
            )
            return

        self.SetStatusText(_("Executing selected cleaning operations..."))
        snum = len(self.toolslines.keys())

        if self.log:
            cmd = [
                self.cmd,
                "input=%s" % self.inmap,
                "output=%s" % self.outmap,
                "tool=%s" % self.tools_string,
                "thres=%s" % self.thresh_string,
            ]
            if self.ftype_string:
                cmd.append("type=%s" % self.ftype_string)
            if self.overwrite.IsChecked():
                cmd.append("--overwrite")

            self.log.RunCmd(cmd, onDone=self.OnDone)
            self.parent.Raise()
        else:
            if self.overwrite.IsChecked():
                overwrite = True
            else:
                overwrite = False

            RunCommand(
                self.cmd,
                input=self.inmap,
                output=self.outmap,
                type=self.ftype_string,
                tool=self.tools_string,
                thresh=self.thresh_string,
                overwrite=overwrite,
            )
Beispiel #8
0
 def NoMap(self, name=None):
     """!No map for editing"""
     if name:
         message = _("Unable to open vector map <%s>.") % name
     else:
         message = _("No vector map open for editing.3")
     GError(
         message + " " + _("Operation canceled."),
         parent=self.parent,
         caption=self.caption,
     )
Beispiel #9
0
    def SelectByPoint(self, queryCoords, qdist):
        """Get attributes by coordinates (all available layers)

        Return line id or None if no line is found"""
        line = None
        nselected = 0

        try:
            data = grass.vector_what(
                map=self.map,
                coord=(float(queryCoords[0]), float(queryCoords[1])),
                distance=float(qdist),
            )
        except grass.ScriptError:
            GError(
                parent=None,
                message=_(
                    "Failed to query vector map <{map}>. "
                    "Check database settings and topology."
                ).format(map=self.map),
            )

        if len(data) < 1 or all(("Table" not in record) for record in data):
            return None

        # process attributes
        ret = dict()
        for key in ["Category", "Layer", "Table", "Id"]:
            ret[key] = list()

        for record in data:
            if "Table" not in record:
                continue

            table = record["Table"]
            for key, value in six.iteritems(record["Attributes"]):
                if len(value) < 1:
                    value = None
                else:
                    if self.tables[table][key]["ctype"] != str:
                        value = self.tables[table][key]["ctype"](value)
                    else:
                        value = GetUnicodeValue(value)
                self.tables[table][key]["values"].append(value)

            for key, value in six.iteritems(record):
                if key == "Attributes":
                    continue
                if key in ret:
                    ret[key].append(value)
            if "Id" not in record.keys():
                ret["Id"].append(None)

        return ret
Beispiel #10
0
    def GetGroupBandsErr(self, parent):
        """Get list of raster bands which are in the soubgroup of group with both having same name.
        If the group does not exists or it does not contain any bands in subgoup with same name,
        error dialog is shown.
        """
        gr, s = self.GetData()

        group = grass.find_file(name=gr, element="group")

        bands = []
        g = group["name"]

        if g:
            if self.use_subg:
                if s == "":
                    GError(_("Please choose a subgroup."), parent=parent)
                    return bands
                if s not in self.GetSubgroups(g):
                    GError(
                        _("Subgroup <%s> not found in group <%s>") % (s, g),
                        parent=parent,
                    )
                    return bands

            bands = self.GetGroupBands(g, s)
            if not bands:
                if self.use_subg:
                    GError(
                        _("No data found in subgroup <%s> of group <%s>.\n"
                          ".") % (s, g),
                        parent=parent,
                    )

                else:
                    GError(_("No data found in group <%s>.\n"
                             ".") % g,
                           parent=parent)
        else:
            GError(_("Group <%s> not found") % gr, parent=parent)

        return bands
Beispiel #11
0
    def _noVMapOpenForEditingErrDlg(self):
        """Show error message dialog if no vector map is open for editing

        :return: True if no vector map is open for editing else None
        """
        if not self.digit:
            GError(
                _("No vector map is open for editing. Please select first"
                  "a vector map from the combo box."),
                self.parent,
            )
            return True
Beispiel #12
0
 def SelectOldMap(self, name):
     """After selecting old raster, creates a backup copy for editing."""
     try:
         self._backupRaster(name)
     except ScriptError:
         GError(parent=self._mapWindow, message=_(
             "Failed to create backup copy of edited raster map."))
         return False
     self._editedRaster = name
     self._mapType = grast.raster_info(map=name)['datatype']
     self._editOldRaster = True
     return True
Beispiel #13
0
    def SelectByPoint(self, queryCoords, qdist):
        """Get attributes by coordinates (all available layers)

        Return line id or None if no line is found"""
        line = None
        nselected = 0

        try:
            data = grass.vector_what(
                map=self.map, coord=(
                    float(
                        queryCoords[0]), float(
                        queryCoords[1])), distance=float(qdist))
        except grass.ScriptError:
            GError(
                parent=None, message=_(
                    "Failed to query vector map <{map}>. "
                    "Check database settings and topology.").format(
                    map=self.map))

        if len(data) < 1 or all(('Table' not in record) for record in data):
            return None

        # process attributes
        ret = dict()
        for key in ['Category', 'Layer', 'Table', 'Id']:
            ret[key] = list()

        for record in data:
            if not 'Table' in record:
                continue

            table = record['Table']
            for key, value in six.iteritems(record['Attributes']):
                if len(value) < 1:
                    value = None
                else:
                    if self.tables[table][key]['ctype'] != types.StringType:
                        value = self.tables[table][key]['ctype'](value)
                    else:
                        value = GetUnicodeValue(value)
                self.tables[table][key]['values'].append(value)

            for key, value in six.iteritems(record):
                if key == 'Attributes':
                    continue
                if key in ret:
                    ret[key].append(value)
            if 'Id' not in record.keys():
                ret['Id'].append(None)

        return ret
Beispiel #14
0
    def SaveToFile(self, settings=None):
        """!Save settings to the file"""
        if settings is None:
            settings = self.userSettings

        dirPath = GetSettingsPath()
        if not os.path.exists(dirPath):
            try:
                os.mkdir(dirPath)
            except:
                GError(_('Unable to create settings directory'))
                return

        try:
            file = open(self.filePath, "w")
            for group in settings.keys():
                for key in settings[group].keys():
                    subkeys = settings[group][key].keys()
                    file.write('%s%s%s%s' % (group, self.sep, key, self.sep))
                    for idx in range(len(subkeys)):
                        value = settings[group][key][subkeys[idx]]
                        if type(value) == types.DictType:
                            if idx > 0:
                                file.write('%s%s%s%s%s' %
                                           (os.linesep, group, self.sep, key,
                                            self.sep))
                            file.write('%s%s' % (subkeys[idx], self.sep))
                            kvalues = settings[group][key][subkeys[idx]].keys()
                            srange = range(len(kvalues))
                            for sidx in srange:
                                svalue = self._parseValue(settings[group][key][
                                    subkeys[idx]][kvalues[sidx]])
                                file.write('%s%s%s' %
                                           (kvalues[sidx], self.sep, svalue))
                                if sidx < len(kvalues) - 1:
                                    file.write('%s' % self.sep)
                        else:
                            if idx > 0 and \
                                    type(settings[group][key][subkeys[idx - 1]]) == types.DictType:
                                file.write('%s%s%s%s%s' %
                                           (os.linesep, group, self.sep, key,
                                            self.sep))
                            value = self._parseValue(
                                settings[group][key][subkeys[idx]])
                            file.write('%s%s%s' %
                                       (subkeys[idx], self.sep, value))
                            if idx < len(subkeys) - 1 and \
                                    type(settings[group][key][subkeys[idx + 1]]) != types.DictType:
                                file.write('%s' % self.sep)
                    file.write(os.linesep)
        except IOError, e:
            raise GException(e)
Beispiel #15
0
 def _fetch(self):
     """Fetch list of available extensions"""
     wx.BeginBusyCursor()
     self.SetStatusText(
         _("Fetching list of modules from GRASS-Addons SVN (be patient)..."
           ), 0)
     try:
         self.thread.Run(callable=self.modelBuilder.Load,
                         url=self.repo.GetValue().strip(),
                         ondone=lambda event: self._fetchDone())
     except GException as e:
         self._fetchDone()
         GError(unicode(e), parent=self, showTraceback=False)
Beispiel #16
0
 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, e:
         GError(parent=self, message=unicode(e), showTraceback=False)
         return
Beispiel #17
0
    def CreateDatalist(self, rpair):
        """Build a list of cell value, frequency pairs for histogram
        frequency can be in cell counts, percents, or area
        """
        datalist = []

        if self.scattertype == "bubble":
            freqflag = "cn"
        else:
            freqflag = "n"

        try:
            ret = RunCommand(
                "r.stats",
                parent=self,
                input="%s,%s" % rpair,
                flags=freqflag,
                nsteps=self.bins,
                sep=",",
                quiet=True,
                read=True,
            )

            if not ret:
                return datalist

            for line in ret.splitlines():
                rast1, rast2 = line.strip().split(",")
                rast1 = rast1.strip()
                if "-" in rast1:
                    if rast1[0] == "-":
                        rast1 = "-" + rast1.split("-")[1]
                    else:
                        rast1 = rast1.split("-")[0]

                rast2 = rast2.strip()
                if "-" in rast2:
                    if rast2[0] == "-":
                        rast2 = "-" + rast2.split("-")[1]
                    else:
                        rast2 = rast2.split("-")[0]

                rast1 = rast1.encode("ascii", "ignore")
                rast2 = rast2.encode("ascii", "ignore")

                datalist.append((rast1, rast2))

            return datalist
        except GException as e:
            GError(parent=self, message=e.value)
            return None
Beispiel #18
0
    def _openFile(self, file_path):
        """Try open file and read content

        :param str file_path: file path

        :return str or None: file content or None
        """
        try:
            with open(file_path, "r") as f:
                content = f.read()
                return content
        except PermissionError:
            GError(
                message=_("Permission denied <{}>. Please change file "
                          "permission for reading.".format(file_path)),
                parent=self.guiparent,
                showTraceback=False,
            )
        except IOError:
            GError(
                message=_("Couldn't read file <{}>.".format(file_path)),
                parent=self.guiparent,
            )
Beispiel #19
0
    def OnSelectRaster(self, event):
        """!Opens dialog to select raster map"""
        dlg = ExampleMapDialog(self)

        if dlg.ShowModal() == wx.ID_OK:
            raster = gcore.find_file(name=dlg.GetRasterMap(), element='cell')
            if raster['fullname']:
                self.SetLayer(name=raster['fullname'])
            else:
                # show user that the map name is incorrect
                GError(parent=self,
                       message=_("Raster map <{raster}> not found").format(raster=dlg.GetRasterMap()))

        dlg.Destroy()
Beispiel #20
0
    def OnOk(self, event):
        """!Button 'OK' pressed"""
        # hide autocomplete
        if self.cmd_prompt.AutoCompActive():
            self.cmd_prompt.AutoCompCancel()

        self.btnOk.SetFocus()
        cmd = self.GetCmd()

        if len(cmd) < 1:
            GError(parent=self,
                   message=_("Command not defined.\n\n"
                             "Unable to add new action to the model."))
            return

        if cmd[0] not in globalvar.grassCmd:
            GError(parent=self,
                   message=_("'%s' is not a GRASS module.\n\n"
                             "Unable to add new action to the model.") %
                   cmd[0])
            return

        self.EndModal(wx.ID_OK)
Beispiel #21
0
    def CreateDatalist(self, rpair):
        """Build a list of cell value, frequency pairs for histogram
            frequency can be in cell counts, percents, or area
        """
        datalist = []

        if self.scattertype == 'bubble':
            freqflag = 'cn'
        else:
            freqflag = 'n'

        try:
            ret = RunCommand("r.stats",
                             parent=self,
                             input='%s,%s' % rpair,
                             flags=freqflag,
                             nsteps=self.bins,
                             sep=',',
                             quiet=True,
                             read=True)

            if not ret:
                return datalist

            for line in ret.splitlines():
                rast1, rast2 = line.strip().split(',')
                rast1 = rast1.strip()
                if '-' in rast1:
                    if rast1[0] == '-':
                        rast1 = '-' + rast1.split('-')[1]
                    else:
                        rast1 = rast1.split('-')[0]

                rast2 = rast2.strip()
                if '-' in rast2:
                    if rast2[0] == '-':
                        rast2 = '-' + rast2.split('-')[1]
                    else:
                        rast2 = rast2.split('-')[0]

                rast1 = rast1.encode('ascii', 'ignore')
                rast2 = rast2.encode('ascii', 'ignore')

                datalist.append((rast1, rast2))

            return datalist
        except GException as e:
            GError(parent=self,
                   message=e.value)
            return None
Beispiel #22
0
 def OnCreateMapset(self, event):
     """Create new mapset"""
     gisdbase = self.tgisdbase.GetValue()
     location = self.listOfLocations[self.lblocations.GetSelection()]
     try:
         mapset = create_mapset_interactively(self, gisdbase, location)
         if mapset:
             self.OnSelectLocation(None)
             self.lbmapsets.SetSelection(self.listOfMapsets.index(mapset))
             self.bstart.SetFocus()
     except Exception as e:
         GError(parent=self,
                message=_("Unable to create new mapset: %s") % e,
                showTraceback=False)
Beispiel #23
0
    def drawVCats(self):
        for i, name in enumerate(self.plotNameListV):
            # just name; with mapset it would be long
            labelname = name.replace('+', ' ')
            self.yticksNames.append(labelname)
            name_cat = name.split('+')
            name = name_cat[0]
            self.yticksPos.append(1)  # TODO
            xdata = []
            ydata = []
            for keys, values in self.timeDataV[name_cat[0]][
                    name_cat[1]].iteritems():
                if keys in [
                        'temporalType', 'granularity', 'validTopology', 'unit',
                        'temporalDataType'
                ]:
                    continue
                xdata.append(self.convert(values['start_datetime']))
                ydata.append(values['value'])

            if len(ydata) == ydata.count(None):
                GError(parent=self,
                       showTraceback=False,
                       message=_("Problem getting data from raster temporal"
                                 " dataset. Empty list of values."))
                return
            self.lookUp.AddDataset(yranges=ydata,
                                   xranges=xdata,
                                   datasetName=name)
            color = self.colors.next()

            self.plots.append(
                self.axes2d.plot(xdata,
                                 ydata,
                                 marker='o',
                                 color=color,
                                 label=labelname)[0])
        # ============================
        if self.temporalType == 'absolute':
            self.axes2d.set_xlabel(
                _("Temporal resolution: %s" %
                  self.timeDataV[name]['granularity']))
        else:
            self.axes2d.set_xlabel(_("Time [%s]") % self.unit)
        self.axes2d.set_ylabel(', '.join(self.yticksNames))

        # legend
        handles, labels = self.axes2d.get_legend_handles_labels()
        self.axes2d.legend(loc=0)
        self.listWhereConditions = []
Beispiel #24
0
    def CreateNewMapset(self, mapset):
        if mapset in self.listOfMapsets:
            GMessage(parent=self,
                     message=_("Mapset <%s> already exists.") % mapset)
            return False

        if mapset.lower() == 'ogr':
            dlg1 = wx.MessageDialog(
                parent=self,
                message=_(
                    "Mapset <%s> is reserved for direct "
                    "read access to OGR layers. Please consider to use "
                    "another name for your mapset.\n\n"
                    "Are you really sure that you want to create this mapset?") %
                mapset,
                caption=_("Reserved mapset name"),
                style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
            ret = dlg1.ShowModal()
            dlg1.Destroy()
            if ret == wx.ID_NO:
                dlg1.Destroy()
                return False

        try:
            self.gisdbase = self.tgisdbase.GetValue()
            location = self.listOfLocations[self.lblocations.GetSelection()]
            os.mkdir(os.path.join(self.gisdbase, location, mapset))
            # copy WIND file and its permissions from PERMANENT and set
            # permissions to u+rw,go+r
            shutil.copy(
                os.path.join(
                    self.gisdbase,
                    location,
                    'PERMANENT',
                    'WIND'),
                os.path.join(
                    self.gisdbase,
                    location,
                    mapset))
            # os.chmod(os.path.join(database,location,mapset,'WIND'), 0644)
            self.OnSelectLocation(None)
            self.lbmapsets.SetSelection(self.listOfMapsets.index(mapset))
            self.bstart.SetFocus()

            return True
        except Exception as e:
            GError(parent=self,
                   message=_("Unable to create new mapset: %s") % e,
                   showTraceback=False)
            return False
Beispiel #25
0
    def HandlersCaller(self, event, handlers):
        """Hepler function which calls all handlers registered for
        event
        """
        for handler in handlers:
            try:
                handler(event)
            except:
                handlers.remove(handler)
                GError(parent=self,
                       message=_("Error occurred during calling of handler: %s \n"
                                 "Handler was unregistered.") % handler.__name__)

        event.Skip() 
Beispiel #26
0
 def SetDatasets(self, datasets):
     """Set data"""
     if not datasets:
         return
     try:
         datasets = self._checkDatasets(datasets)
         if not datasets:
             return
     except GException as e:
         GError(parent=self, message=unicode(e), showTraceback=False)
         return
     self.datasets = datasets
     self.datasetSelect.SetValue(
         ','.join(map(lambda x: x[0] + '@' + x[1], datasets)))
     self._redraw()
Beispiel #27
0
    def _nameValidationFailed(self, layers_list):
        """Output map name validation callback

        :param layers_list: LayersList class instance
        """
        if isinstance(layers_list.output_map, list):
            maps = ['<{}>'.format(m) for m in layers_list.output_map]
            message = _("Output map names %(names)s exist. ") % {
                'names': ', '.join(maps)
            }
        else:
            message = _("Output map name <%(name)s> exist. ") % {
                'name': layers_list.output_map
            }
        GError(parent=self, message=message, caption=_("Invalid name"))
Beispiel #28
0
 def SetDatasets(self, datasets):
     """Set data"""
     if not datasets:
         return
     try:
         datasets = self._checkDatasets(datasets)
         if not datasets:
             return
     except GException:
         GError(parent=self, message=_("Invalid input data"))
         return
     self.datasets = datasets
     self.datasetSelect.SetValue(','.join(
         map(lambda x: x[0] + '@' + x[1], datasets)))
     self._redraw()
Beispiel #29
0
def sampleAreaVector(
    vect, rast, vect_cats, layer="1", overwrite=False, progDialog=None
):
    """Create the strings to add to the configuration file using vector"""
    areanum = len(vect_cats)
    output = []
    # TODO if areanum == 0 exit from the program
    if areanum == 0:
        GError(message=_("The polygon seems to have 0 areas"))
        return None
    for n in range(areanum):
        cat = str(vect_cats[n])
        outpref = "{rast}_{vect}_".format(
            vect=vect.split("@")[0], rast=rast.split("@")[0]
        )
        rast_name = "{pref}{cat}".format(pref=outpref, cat=cat)
        # check if raster already axist

        if (
            len(grass.list_strings("raster", pattern=rast_name, mapset=".")) == 1
            and not overwrite
        ):
            GError(
                message=_(
                    "The raster map <%s> already exists."
                    " Please remove or rename the maps "
                    "with the prefix '%s' or select the "
                    "option to overwrite existing maps" % (rast_name, outpref)
                )
            )
            return None
        convertFeature(vect, rast_name, cat, rast, layer, overwrite)
        output.append(obtainAreaVector(rast_name))
        if progDialog:
            progDialog.Update(n)
    return output
Beispiel #30
0
 def OnDeleteLocation(self, event):
     """
     Delete selected location
     """
     location = self.listOfLocations[self.lblocations.GetSelection()]
     try:
         if (delete_location_interactively(self, self.gisdbase, location)):
             self.UpdateLocations(self.gisdbase)
             self.lblocations.SetSelection(0)
             self.OnSelectLocation(None)
             self.lbmapsets.SetSelection(0)
     except Exception as e:
         GError(parent=self,
                message=_("Unable to delete location: %s") % e,
                showTraceback=False)