Exemplo n.º 1
0
 def _saveToFile( self, sender, startFolder=None ):
     filter =  "OGC GeoPackage (*.gpkg);;ESRI Shape Files (*.shp);;SpatiaLite (*.sqlite);;Geojson File (*.geojson);;GML ( *.gml);;Comma separated value File (excel) (*.csv);;MapInfo TAB (*.TAB);;Any File (*.*)" 
     Fdlg = QFileDialog()
     Fdlg.setFileMode(QFileDialog.AnyFile)
     fName, __ = QFileDialog.getSaveFileName(sender, "open file", filter=filter, directory=startFolder)
     if fName:
         ext = os.path.splitext( fName )[1]
         if "GPKG" in ext.upper():
           flType = "GPKG"
         elif "SHP" in ext.upper():
           flType = "ESRI Shapefile"
         elif "SQLITE" in ext.upper():
           flType = "SQLite" 
         elif "GEOJSON" in ext.upper():  #no update possible -> hidden
           flType = "GeoJSON"
         elif "GML" in ext.upper():
           flType = "GML"
         elif 'TAB' in ext.upper():
           flType = 'MapInfo File'
         elif 'CSV' in ext.upper():
           flType = 'CSV'
         else:
           fName = fName + ".shp"
           flType = "ESRI Shapefile"
         return (fName , flType )
     else:
         return None
Exemplo n.º 2
0
    def showSelectionDialog(self):
        # Find the file dialog's working directory
        settings = QSettings()
        text = self.leText.text()
        if os.path.isdir(text):
            path = text
        elif os.path.isdir(os.path.dirname(text)):
            path = os.path.dirname(text)
        elif settings.contains('/Processing/LastInputPath'):
            path = settings.value('/Processing/LastInputPath')
        else:
            path = ''

        if self.isFolder:
            folder = QFileDialog.getExistingDirectory(self,
                                                      self.tr('Select folder'), path)
            if folder:
                self.leText.setText(folder)
                settings.setValue('/Processing/LastInputPath',
                                  os.path.dirname(folder))
        else:
            filenames, selected_filter = QFileDialog.getOpenFileNames(self,
                                                                      self.tr('Select file'), path, '*.' + self.ext)
            if filenames:
                self.leText.setText(u';'.join(filenames))
                settings.setValue('/Processing/LastInputPath',
                                  os.path.dirname(filenames[0]))
Exemplo n.º 3
0
    def select_file(self):
        """select file ops"""

        label = self.tr('eXtensible Markup Language (*.xml *.XML)')

        if self.mode == 0:
            slabel = self.tr('Save connections')
            self.filename, filter = QFileDialog.getSaveFileName(self, slabel,
                                                                '.', label)
        else:
            slabel = self.tr('Load connections')
            self.filename, selected_filter = QFileDialog.getOpenFileName(self, slabel,
                                                                         '.', label)

        if not self.filename:
            return

        # ensure the user never omitted the extension from the file name
        if not self.filename.lower().endswith('.xml'):
            self.filename = '%s.xml' % self.filename

        self.leFileName.setText(self.filename)

        if self.mode == 1:
            self.populate()

        self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(True)
    def showFileDialog(self, seldir):
        settings = QgsSettings()
        text = str(self.text.text())
        if os.path.isdir(text):
            path = text
        elif not seldir and os.path.isdir(os.path.dirname(text)):
            path = os.path.dirname(text)
        elif settings.contains('/Processing/LastInputPath'):
            path = str(settings.value('/Processing/LastInputPath'))
        else:
            path = ''

        if not seldir:
            ret, selected_filter = QFileDialog.getOpenFileNames(
                self, self.tr('Select Files'), path, getFileFilter(self.param)
            )
        else:
            ret = QFileDialog.getExistingDirectory(self, self.tr('Select Directory'), path)

        if ret:
            if seldir:
                settings.setValue('/Processing/LastInputPath', ret)

                files = []
                for pp in Path(ret).rglob("*"):
                    if not pp.is_file():
                        continue

                    p = pp.as_posix()

                    if ((isinstance(self.param, QgsProcessingParameterRasterLayer)
                         or (isinstance(self.param, QgsProcessingParameterMultipleLayers) and self.param.layerType() == QgsProcessing.TypeRaster)) and
                            not QgsRasterLayer.isValidRasterFileName(p)):
                        continue

                    files.append(p)

                if not files:
                    return

            else:
                files = list(ret)
                settings.setValue('/Processing/LastInputPath', os.path.dirname(str(files[0])))

            for i, filename in enumerate(files):
                files[i] = dataobjects.getRasterSublayer(filename, self.param)
            if len(files) == 1:
                self.text.setText(files[0])
                self.textEditingFinished()
            else:
                if isinstance(self.param, QgsProcessingParameterMultipleLayers):
                    self.text.setText(';'.join(str(f) for f in files))
                else:
                    rowdif = len(files) - (self._table().rowCount() - self.row)
                    for i in range(rowdif):
                        self._panel().addRow()
                    for i, f in enumerate(files):
                        self._table().cellWidget(i + self.row,
                                                 self.col).setValue(f)
Exemplo n.º 5
0
    def openOutput(sender=None, startFolder=None):
        fd = QFileDialog()
        filter =  "OGC GeoPackage (*.gpkg);;ESRI Shape File (*.shp);;Comma separated value File (excel) (*.csv);;geojson (*.geojson);;GML File (*.gml);;MapInfo TAB (*.tab);;SpatiaLite (*.sqlite);;KML (google earth) (*.kml);;Any File (*.*)"
        fName = fd.getSaveFileName( sender, "open file", filter=filter, directory=startFolder)

        if fName:
            return fName[0]
        else:
            return None
Exemplo n.º 6
0
    def openScript(self):
        if self.hasChanged:
            ret = QMessageBox.warning(self, self.tr('Unsaved changes'),
                                      self.tr('There are unsaved changes in script. Continue?'),
                                      QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            if ret == QMessageBox.No:
                return

        if self.algType == self.SCRIPT_PYTHON:
            scriptDir = ScriptUtils.scriptsFolders()[0]
            filterName = self.tr('Python scripts (*.py)')
        elif self.algType == self.SCRIPT_R:
            scriptDir = RUtils.RScriptsFolders()[0]
            filterName = self.tr('Processing R script (*.rsx)')

        self.filename, fileFilter = QFileDialog.getOpenFileName(
            self, self.tr('Open script'), scriptDir, filterName)

        if self.filename == '':
            return

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        with codecs.open(self.filename, 'r', encoding='utf-8') as f:
            txt = f.read()

        self.editor.setText(txt)
        self.hasChanged = False
        self.editor.setModified(False)
        self.editor.recolor()
        QApplication.restoreOverrideCursor()
Exemplo n.º 7
0
    def saveAsScriptFile(self, index=None):
        tabWidget = self.tabEditorWidget.currentWidget()
        if not index:
            index = self.tabEditorWidget.currentIndex()
        if not tabWidget.path:
            fileName = self.tabEditorWidget.tabText(index) + '.py'
            folder = self.settings.value("pythonConsole/lastDirPath", QDir.homePath())
            pathFileName = os.path.join(folder, fileName)
            fileNone = True
        else:
            pathFileName = tabWidget.path
            fileNone = False
        saveAsFileTr = QCoreApplication.translate("PythonConsole", "Save File As")
        filename, filter = QFileDialog.getSaveFileName(self,
                                                       saveAsFileTr,
                                                       pathFileName, "Script file (*.py)")
        if filename:
            try:
                tabWidget.save(filename)
            except (IOError, OSError) as error:
                msgText = QCoreApplication.translate('PythonConsole',
                                                     'The file <b>{0}</b> could not be saved. Error: {1}').format(tabWidget.path,
                                                                                                                  error.strerror)
                self.callWidgetMessageBarEditor(msgText, 2, False)
                if fileNone:
                    tabWidget.path = None
                else:
                    tabWidget.path = pathFileName
                return

            if not fileNone:
                self.updateTabListScript(pathFileName, action='remove')
Exemplo n.º 8
0
    def on_btnSave_clicked(self):
        fileName, _ = QFileDialog.getSaveFileName(None,
                                                  self.tr('Export Colors and elevations as XML'),
                                                  QDir.homePath(),
                                                  self.tr('XML files (*.xml *.XML)'))

        if fileName == '':
            return

        if not fileName.lower().endswith('.xml'):
            fileName += '.xml'

        doc = QDomDocument()
        colorsElem = doc.createElement('ReliefColors')
        doc.appendChild(colorsElem)

        colors = self.reliefColors()
        for c in colors:
            elem = doc.createElement('ReliefColor')
            elem.setAttribute('MinElevation', str(c.minElevation))
            elem.setAttribute('MaxElevation', str(c.maxElevation))
            elem.setAttribute('red', str(c.color.red()))
            elem.setAttribute('green', str(c.color.green()))
            elem.setAttribute('blue', str(c.color.blue()))
            colorsElem.appendChild(elem)

        with codecs.open(fileName, 'w', encoding='utf-8') as f:
            f.write(doc.toString(2))
Exemplo n.º 9
0
    def saveScript(self, saveAs):
        newPath = None
        if self.filePath is None or saveAs:
            scriptDir = ScriptUtils.scriptsFolders()[0]
            newPath, _ = QFileDialog.getSaveFileName(self,
                                                     self.tr("Save script"),
                                                     scriptDir,
                                                     self.tr("Processing scripts (*.py *.PY)"))

            if newPath:
                if not newPath.lower().endswith(".py"):
                    newPath += ".py"

                self.filePath = newPath

        if self.filePath:
            text = self.editor.text()
            try:
                with codecs.open(self.filePath, "w", encoding="utf-8") as f:
                    f.write(text)
            except IOError as e:
                QMessageBox.warning(self,
                                    self.tr("I/O error"),
                                    self.tr("Unable to save edits:\n{}").format(str(e))
                                    )
                return

            self.setHasChanged(False)

        QgsApplication.processingRegistry().providerById("script").refreshAlgorithms()
Exemplo n.º 10
0
    def exportAsImage(self):
        self.repaintModel(controls=False)
        filename, fileFilter = QFileDialog.getSaveFileName(self,
                                                           self.tr('Save Model As Image'), '',
                                                           self.tr('PNG files (*.png *.PNG)'))
        if not filename:
            return

        if not filename.lower().endswith('.png'):
            filename += '.png'

        totalRect = self.scene.itemsBoundingRect()
        totalRect.adjust(-10, -10, 10, 10)
        imgRect = QRectF(0, 0, totalRect.width(), totalRect.height())

        img = QImage(totalRect.width(), totalRect.height(),
                     QImage.Format_ARGB32_Premultiplied)
        img.fill(Qt.white)
        painter = QPainter()
        painter.setRenderHint(QPainter.Antialiasing)
        painter.begin(img)
        self.scene.render(painter, imgRect, totalRect)
        painter.end()

        img.save(filename)

        self.bar.pushMessage("", "Model was correctly exported as image", level=Qgis.Success, duration=5)
        self.repaintModel(controls=True)
Exemplo n.º 11
0
    def on_btnLoad_clicked(self):
        fileName, _ = QFileDialog.getOpenFileName(None,
                                                  self.tr('Import Colors and elevations from XML'),
                                                  QDir.homePath(),
                                                  self.tr('XML files (*.xml *.XML)'))
        if fileName == '':
            return

        doc = QDomDocument()
        with codecs.open(fileName, 'r', encoding='utf-8') as f:
            content = f.read()

        if not doc.setContent(content):
            QMessageBox.critical(None,
                                 self.tr('Error parsing XML'),
                                 self.tr('The XML file could not be loaded'))
            return

        self.reliefClassTree.clear()
        reliefColorList = doc.elementsByTagName('ReliefColor')
        for i in range(reliefColorList.length()):
            elem = reliefColorList.at(i).toElement()
            item = QTreeWidgetItem()
            item.setText(0, elem.attribute('MinElevation'))
            item.setText(1, elem.attribute('MaxElevation'))
            item.setBackground(2, QBrush(QColor(int(elem.attribute('red')),
                                                int(elem.attribute('green')),
                                                int(elem.attribute('blue')))))
            self.reliefClassTree.addTopLevelItem(item)
Exemplo n.º 12
0
    def execute(self):
        settings = QSettings()
        lastDir = settings.value('Processing/lastModelsDir', '')
        filename, selected_filter = QFileDialog.getOpenFileName(self.toolbox,
                                                                self.tr('Open model', 'AddModelFromFileAction'), lastDir,
                                                                self.tr('Processing model files (*.model *.MODEL)', 'AddModelFromFileAction'))
        if filename:
            try:
                settings.setValue('Processing/lastModelsDir',
                                  QFileInfo(filename).absoluteDir().absolutePath())

                ModelerAlgorithm.fromFile(filename)
            except WrongModelException:
                QMessageBox.warning(
                    self.toolbox,
                    self.tr('Error reading model', 'AddModelFromFileAction'),
                    self.tr('The selected file does not contain a valid model', 'AddModelFromFileAction'))
                return
            except:
                QMessageBox.warning(self.toolbox,
                                    self.tr('Error reading model', 'AddModelFromFileAction'),
                                    self.tr('Cannot read file', 'AddModelFromFileAction'))
                return
            destFilename = os.path.join(ModelerUtils.modelsFolders()[0], os.path.basename(filename))
            shutil.copyfile(filename, destFilename)
            algList.reloadProvider('model')
Exemplo n.º 13
0
    def select(self):
        lastDir = ''
        if not self.selectFile:
            selectedPath = QFileDialog.getExistingDirectory(None,
                                                            self.tr('Select directory'), lastDir,
                                                            QFileDialog.ShowDirsOnly)
        else:
            selectedPath, selected_filter = QFileDialog.getOpenFileName(None,
                                                                        self.tr('Select file'), lastDir, self.tr('All files (*.*)')
                                                                        )

        if not selectedPath:
            return

        self.lineEdit.setText(selectedPath)
        self.canFocusOut = True
Exemplo n.º 14
0
    def openModel(self):
        filename = unicode(QFileDialog.getOpenFileName(self,
                                                       self.tr('Open Model'), ModelerUtils.modelsFolder(),
                                                       self.tr('Processing models (*.model *.MODEL)')))
        if filename:
            try:
                alg = ModelerAlgorithm.fromFile(filename)
                self.alg = alg
                self.alg.setModelerView(self)
                self.textGroup.setText(alg.group)
                self.textName.setText(alg.name)
                self.repaintModel()

                self.view.centerOn(0, 0)
                self.hasChanged = False
            except WrongModelException as e:
                ProcessingLog.addToLog(ProcessingLog.LOG_ERROR,
                                       self.tr('Could not load model %s\n%s') % (filename, e.msg))
                QMessageBox.critical(self, self.tr('Could not open model'),
                                     self.tr('The selected model could not be loaded.\n'
                                             'See the log for more information.'))
            except Exception as e:
                ProcessingLog.addToLog(ProcessingLog.LOG_ERROR,
                                       self.tr('Could not load model %s\n%s') % (filename, e.args[0]))
                QMessageBox.critical(self, self.tr('Could not open model'),
                                     self.tr('The selected model could not be loaded.\n'
                                             'See the log for more information.'))
Exemplo n.º 15
0
    def showFileSelectionDialog(self):
        settings = QSettings()
        text = str(self.text.text())
        if os.path.isdir(text):
            path = text
        elif os.path.isdir(os.path.dirname(text)):
            path = os.path.dirname(text)
        elif settings.contains('/Processing/LastInputPath'):
            path = str(settings.value('/Processing/LastInputPath'))
        else:
            path = ''

        ret, selected_filter = QFileDialog.getOpenFileNames(self, self.tr('Open file'), path,
                                                            self.tr('All files(*.*);;') + self.param.getFileFilter())
        if ret:
            files = list(ret)
            settings.setValue('/Processing/LastInputPath',
                              os.path.dirname(str(files[0])))
            for i, filename in enumerate(files):
                files[i] = dataobjects.getRasterSublayer(filename, self.param)
            if len(files) == 1:
                self.text.setText(files[0])
                self.textEditingFinished()
            else:
                if isinstance(self.param, ParameterMultipleInput):
                    self.text.setText(';'.join(str(f) for f in files))
                else:
                    rowdif = len(files) - (self._table().rowCount() - self.row)
                    for i in range(rowdif):
                        self._panel().addRow()
                    for i, f in enumerate(files):
                        self._table().cellWidget(i + self.row,
                                                 self.col).setValue(f)
Exemplo n.º 16
0
 def openModel(self):
     filename, selected_filter = QFileDialog.getOpenFileName(self,
                                                             self.tr('Open Model'),
                                                             ModelerUtils.modelsFolders()[0],
                                                             self.tr('Processing models (*.model3 *.MODEL3)'))
     if filename:
         self.loadModel(filename)
Exemplo n.º 17
0
    def exportAsImage(self):
        filename = unicode(QFileDialog.getSaveFileName(self,
                                                       self.tr('Save Model As Image'), '',
                                                       self.tr('PNG files (*.png *.PNG)')))
        if not filename:
            return

        if not filename.lower().endswith('.png'):
            filename += '.png'

        totalRect = QRectF(0, 0, 1, 1)
        for item in self.scene.items():
            totalRect = totalRect.united(item.sceneBoundingRect())
        totalRect.adjust(-10, -10, 10, 10)

        img = QImage(totalRect.width(), totalRect.height(),
                     QImage.Format_ARGB32_Premultiplied)
        img.fill(Qt.white)
        painter = QPainter()
        painter.setRenderHint(QPainter.Antialiasing)
        painter.begin(img)
        self.scene.render(painter, totalRect, totalRect)
        painter.end()

        img.save(filename)
Exemplo n.º 18
0
    def exportAsSvg(self):
        self.repaintModel(controls=False)
        filename, fileFilter = QFileDialog.getSaveFileName(self,
                                                           self.tr('Save Model As SVG'), '',
                                                           self.tr('SVG files (*.svg *.SVG)'))
        if not filename:
            return

        if not filename.lower().endswith('.svg'):
            filename += '.svg'

        totalRect = self.scene.itemsBoundingRect()
        totalRect.adjust(-10, -10, 10, 10)
        svgRect = QRectF(0, 0, totalRect.width(), totalRect.height())

        svg = QSvgGenerator()
        svg.setFileName(filename)
        svg.setSize(QSize(totalRect.width(), totalRect.height()))
        svg.setViewBox(svgRect)
        svg.setTitle(self.model.displayName())

        painter = QPainter(svg)
        self.scene.render(painter, svgRect, totalRect)
        painter.end()

        self.bar.pushMessage("", self.tr("Successfully exported model as SVG to <a href=\"{}\">{}</a>").format(QUrl.fromLocalFile(filename).toString(), QDir.toNativeSeparators(filename)), level=Qgis.Success, duration=5)
        self.repaintModel(controls=True)
Exemplo n.º 19
0
    def saveModel(self, saveAs):
        if not self.can_save():
            return
        self.model.setName(str(self.textName.text()))
        self.model.setGroup(str(self.textGroup.text()))
        if self.model.sourceFilePath() and not saveAs:
            filename = self.model.sourceFilePath()
        else:
            filename, filter = QFileDialog.getSaveFileName(self,
                                                           self.tr('Save Model'),
                                                           ModelerUtils.modelsFolders()[0],
                                                           self.tr('Processing models (*.model3 *.MODEL3)'))
            if filename:
                if not filename.endswith('.model3'):
                    filename += '.model3'
                self.model.setSourceFilePath(filename)
        if filename:
            if not self.model.toFile(filename):
                if saveAs:
                    QMessageBox.warning(self, self.tr('I/O error'),
                                        self.tr('Unable to save edits. Reason:\n {0}').format(str(sys.exc_info()[1])))
                else:
                    QMessageBox.warning(self, self.tr("Can't save model"), QCoreApplication.translate('QgsPluginInstallerInstallingDialog', (
                        "This model can't be saved in its original location (probably you do not "
                        "have permission to do it). Please, use the 'Save as…' option."))
                    )
                return
            self.update_model.emit()
            if saveAs:
                self.bar.pushMessage("", self.tr("Model was correctly saved to <a href=\"{}\">{}</a>").format(QUrl.fromLocalFile(filename).toString(), QDir.toNativeSeparators(filename)), level=Qgis.Success, duration=5)
            else:
                self.bar.pushMessage("", self.tr("Model was correctly saved"), level=Qgis.Success, duration=5)

            self.hasChanged = False
Exemplo n.º 20
0
    def exportAsImage(self):
        self.repaintModel(controls=False)
        filename, fileFilter = QFileDialog.getSaveFileName(self,
                                                           self.tr('Save Model As Image'), '',
                                                           self.tr('PNG files (*.png *.PNG)'))
        if not filename:
            return

        if not filename.lower().endswith('.png'):
            filename += '.png'

        totalRect = self.scene.itemsBoundingRect()
        totalRect.adjust(-10, -10, 10, 10)
        imgRect = QRectF(0, 0, totalRect.width(), totalRect.height())

        img = QImage(totalRect.width(), totalRect.height(),
                     QImage.Format_ARGB32_Premultiplied)
        img.fill(Qt.white)
        painter = QPainter()
        painter.setRenderHint(QPainter.Antialiasing)
        painter.begin(img)
        self.scene.render(painter, imgRect, totalRect)
        painter.end()

        img.save(filename)

        self.bar.pushMessage("", self.tr("Successfully exported model as image to <a href=\"{}\">{}</a>").format(QUrl.fromLocalFile(filename).toString(), QDir.toNativeSeparators(filename)), level=Qgis.Success, duration=5)
        self.repaintModel(controls=True)
Exemplo n.º 21
0
    def exportAsPdf(self):
        self.repaintModel(controls=False)
        filename, fileFilter = QFileDialog.getSaveFileName(self,
                                                           self.tr('Save Model As PDF'), '',
                                                           self.tr('PDF files (*.pdf *.PDF)'))
        if not filename:
            return

        if not filename.lower().endswith('.pdf'):
            filename += '.pdf'

        totalRect = self.scene.itemsBoundingRect()
        totalRect.adjust(-10, -10, 10, 10)
        printerRect = QRectF(0, 0, totalRect.width(), totalRect.height())

        printer = QPrinter()
        printer.setOutputFormat(QPrinter.PdfFormat)
        printer.setOutputFileName(filename)
        printer.setPaperSize(QSizeF(printerRect.width(), printerRect.height()), QPrinter.DevicePixel)
        printer.setFullPage(True)

        painter = QPainter(printer)
        self.scene.render(painter, printerRect, totalRect)
        painter.end()

        self.bar.pushMessage("", self.tr("Successfully exported model as PDF to <a href=\"{}\">{}</a>").format(QUrl.fromLocalFile(filename).toString(), QDir.toNativeSeparators(filename)), level=Qgis.Success, duration=5)
        self.repaintModel(controls=True)
Exemplo n.º 22
0
 def getSaveFileName(self, parent=None, caption='', filter='', selectedFilter=None, useEncoding=False):
     if useEncoding:
         return self.getDialog(parent, caption, QFileDialog.AcceptSave, QFileDialog.AnyFile, filter, selectedFilter, useEncoding)
     res, filter = QFileDialog.getSaveFileName(parent, caption, getLastUsedDir(), filter)
     if res:
         setLastUsedDir(res)
     return res
Exemplo n.º 23
0
    def exportAsSvg(self):
        self.repaintModel(controls=False)
        filename, fileFilter = QFileDialog.getSaveFileName(self,
                                                           self.tr('Save Model As SVG'), '',
                                                           self.tr('SVG files (*.svg *.SVG)'))
        if not filename:
            return

        if not filename.lower().endswith('.svg'):
            filename += '.svg'

        totalRect = self.scene.itemsBoundingRect()
        totalRect.adjust(-10, -10, 10, 10)
        svgRect = QRectF(0, 0, totalRect.width(), totalRect.height())

        svg = QSvgGenerator()
        svg.setFileName(filename)
        svg.setSize(QSize(totalRect.width(), totalRect.height()))
        svg.setViewBox(svgRect)
        svg.setTitle(self.model.displayName())

        painter = QPainter(svg)
        self.scene.render(painter, svgRect, totalRect)
        painter.end()

        self.bar.pushMessage("", self.tr("Model was correctly exported as SVG"), level=Qgis.Success, duration=5)
        self.repaintModel(controls=True)
Exemplo n.º 24
0
 def execute(self):
     settings = QSettings()
     lastDir = settings.value('Processing/lastScriptsDir', '')
     filenames, selected_filter = QFileDialog.getOpenFileNames(self.toolbox,
                                                             self.tr('Script files', 'AddScriptFromFileAction'), lastDir,
                                                             self.tr('Script files (*.py *.PY)', 'AddScriptFromFileAction'))
     if filenames:
         validAlgs = 0
         wrongAlgs = []
         for filename in filenames:
             try:
                 settings.setValue('Processing/lastScriptsDir',
                                   QFileInfo(filename).absoluteDir().absolutePath())
                 script = ScriptAlgorithm(filename)
                 destFilename = os.path.join(ScriptUtils.scriptsFolders()[0], os.path.basename(filename))
                 with open(destFilename, 'w') as f:
                     f.write(script.script)
                 validAlgs += 1
             except WrongScriptException:
                 wrongAlgs.append(os.path.basename(filename))
         if validAlgs:
             algList.reloadProvider('script')
         if wrongAlgs:
             QMessageBox.warning(self.toolbox,
                                     self.tr('Error reading scripts', 'AddScriptFromFileAction'),
                                     self.tr('The following files do not contain a valid script:\n-', 'AddScriptFromFileAction')
                                     + "\n-".join(wrongAlgs))
Exemplo n.º 25
0
    def saveToGeopackage(self):
        file_filter = self.tr('GeoPackage files (*.gpkg);;All files (*.*)', 'OutputFile')

        settings = QgsSettings()
        if settings.contains('/Processing/LastOutputPath'):
            path = settings.value('/Processing/LastOutputPath')
        else:
            path = ProcessingConfig.getSetting(ProcessingConfig.OUTPUT_FOLDER)

        filename, filter = QFileDialog.getSaveFileName(self, self.tr("Save to GeoPackage"), path,
                                                       file_filter, options=QFileDialog.DontConfirmOverwrite)

        if not filename:
            return

        layer_name, ok = QInputDialog.getText(self, self.tr('Save to GeoPackage'), self.tr('Layer name'), text=self.parameter.name().lower())
        if ok:
            self.use_temporary = False
            if not filename.lower().endswith('.gpkg'):
                filename += '.gpkg'
            settings.setValue('/Processing/LastOutputPath',
                              os.path.dirname(filename))

            uri = QgsDataSourceUri()
            uri.setDatabase(filename)
            uri.setDataSource('', layer_name,
                              'geom' if isinstance(self.parameter, QgsProcessingParameterFeatureSink) and self.parameter.hasGeometry() else None)
            self.leText.setText("ogr:" + uri.uri())

            self.skipOutputChanged.emit(False)
            self.destinationChanged.emit()
Exemplo n.º 26
0
    def saveModel(self, saveAs):
        if str(self.textGroup.text()).strip() == '' \
                or str(self.textName.text()).strip() == '':
            QMessageBox.warning(
                self, self.tr('Warning'), self.tr('Please enter group and model names before saving')
            )
            return
        self.model.setName(str(self.textName.text()))
        self.model.setGroup(str(self.textGroup.text()))
        if self.model.sourceFilePath() and not saveAs:
            filename = self.model.sourceFilePath()
        else:
            filename, filter = QFileDialog.getSaveFileName(self,
                                                           self.tr('Save Model'),
                                                           ModelerUtils.modelsFolders()[0],
                                                           self.tr('Processing models (*.model3)'))
            if filename:
                if not filename.endswith('.model3'):
                    filename += '.model3'
                self.model.setSourceFilePath(filename)
        if filename:
            if not self.model.toFile(filename):
                if saveAs:
                    QMessageBox.warning(self, self.tr('I/O error'),
                                        self.tr('Unable to save edits. Reason:\n {0}').format(str(sys.exc_info()[1])))
                else:
                    QMessageBox.warning(self, self.tr("Can't save model"), QCoreApplication.translate('QgsPluginInstallerInstallingDialog', (
                        "This model can't be saved in its original location (probably you do not "
                        "have permission to do it). Please, use the 'Save as…' option."))
                    )
                return
            self.update_model.emit()
            self.bar.pushMessage("", "Model was correctly saved", level=Qgis.Success, duration=5)

            self.hasChanged = False
Exemplo n.º 27
0
 def onOpenDialog(self):
     title = u"Output Pfad auswählen"
     directory = QFileDialog.getExistingDirectory(self, title,
         self.options['outputPath'])
     
     self.tool.updateCommonPathList(directory)
     self.fillInDropDown(self.tool.commonPaths)
Exemplo n.º 28
0
    def exportAsPdf(self):
        self.repaintModel(controls=False)
        filename, fileFilter = QFileDialog.getSaveFileName(self,
                                                           self.tr('Save Model As PDF'), '',
                                                           self.tr('PDF files (*.pdf *.PDF)'))
        if not filename:
            return

        if not filename.lower().endswith('.pdf'):
            filename += '.pdf'

        totalRect = self.scene.itemsBoundingRect()
        totalRect.adjust(-10, -10, 10, 10)
        printerRect = QRectF(0, 0, totalRect.width(), totalRect.height())

        printer = QPrinter()
        printer.setOutputFormat(QPrinter.PdfFormat)
        printer.setOutputFileName(filename)
        printer.setPaperSize(QSizeF(printerRect.width(), printerRect.height()), QPrinter.DevicePixel)
        printer.setFullPage(True)

        painter = QPainter(printer)
        self.scene.render(painter, printerRect, totalRect)
        painter.end()

        self.bar.pushMessage("", "Model was correctly exported as PDF", level=Qgis.Success, duration=5)
        self.repaintModel(controls=True)
Exemplo n.º 29
0
 def getExistingDirectory(self, parent=None, caption='', useEncoding=False):
     if useEncoding:
         return self.getDialog(parent, caption, QFileDialog.AcceptOpen, QFileDialog.DirectoryOnly, '', None, useEncoding)
     res = QFileDialog.getExistingDirectory(parent, caption, getLastUsedDir(), QFileDialog.ShowDirsOnly)
     if res:
         setLastUsedDir(res)
     return res
Exemplo n.º 30
0
 def getOpenFileNames(self, parent=None, caption='', filter='', selectedFilter=None, useEncoding=False):
     if useEncoding:
         return self.getDialog(parent, caption, QFileDialog.AcceptOpen, QFileDialog.ExistingFiles, filter, selectedFilter, useEncoding)
     res, selected_filter = QFileDialog.getOpenFileNames(parent, caption, getLastUsedDir(), filter)
     if len(res) > 0:
         setLastUsedDir(res[-1])
     return res
Exemplo n.º 31
0
def import_layer_from_csv(parent,
                          csv_path,
                          layer_name,
                          iface,
                          longitude_field='lon',
                          latitude_field='lat',
                          delimiter=',',
                          quote='"',
                          lines_to_skip_count=0,
                          wkt_field=None,
                          save_format=None,
                          save_dest=None,
                          zoom_to_layer=True,
                          has_geom=True,
                          subset=None,
                          add_to_legend=True,
                          add_on_top=False):
    if not lines_to_skip_count:
        lines_to_skip_count = count_heading_commented_lines(csv_path)
    url = QUrl.fromLocalFile(csv_path)
    url_query = QUrlQuery()
    url_query.addQueryItem('type', 'csv')
    if has_geom:
        if wkt_field is not None:
            url_query.addQueryItem('wktField', wkt_field)
        else:
            url_query.addQueryItem('xField', longitude_field)
            url_query.addQueryItem('yField', latitude_field)
        url_query.addQueryItem('spatialIndex', 'no')
        url_query.addQueryItem('crs', 'epsg:4326')
    url_query.addQueryItem('subsetIndex', 'no')
    url_query.addQueryItem('watchFile', 'no')
    url_query.addQueryItem('delimiter', delimiter)
    url_query.addQueryItem('quote', quote)
    url_query.addQueryItem('skipLines', str(lines_to_skip_count))
    url_query.addQueryItem('trimFields', 'yes')
    if subset is not None:
        # NOTE: it loads all features and applies a filter in visualization
        url_query.addQueryItem('subset', subset)  # i.e. '"fieldname" != 0'
    url.setQuery(url_query)
    layer_uri = url.toString()
    layer = QgsVectorLayer(layer_uri, layer_name, "delimitedtext")
    if save_format:
        if save_format == 'ESRI Shapefile':
            fmt = '.shp'
            fmt_text = 'Shapefiles (*.shp)'
        elif save_format == 'GPKG':
            fmt = '.gpkg'
            fmt_text = 'Geopackages (*.gpkg)'
        else:
            raise NotImplementedError(
                'Only shapefiles and geopackages are supported. Got %s' %
                save_format)
        dest_filename = save_dest
        if not dest_filename:
            dest_filename, file_filter = QFileDialog.getSaveFileName(
                parent, 'Save as...', os.path.expanduser("~"), fmt_text)
        if dest_filename:
            if os.path.splitext(dest_filename)[1] != fmt:
                dest_filename += fmt
        else:
            return
        writer_error, error_msg = save_layer_as(
            layer, dest_filename, save_format)
        if writer_error:
            raise RuntimeError(
                'Could not save layer. %s: %s' % (writer_error,
                                                  error_msg))
        layer = QgsVectorLayer(dest_filename, layer_name, 'ogr')
    if layer.isValid():
        if add_to_legend:
            if add_on_top:
                root = QgsProject.instance().layerTreeRoot()
                QgsProject.instance().addMapLayer(layer, False)
                root.insertLayer(0, layer)
            else:
                QgsProject.instance().addMapLayer(layer, True)
            iface.setActiveLayer(layer)
            if zoom_to_layer:
                iface.zoomToActiveLayer()
    else:
        raise RuntimeError('Unable to load layer')
    return layer
Exemplo n.º 32
0
 def selectFolder(self):
     folder = QFileDialog.getExistingDirectory(self, 'Select folder')
     if folder:
         self.folderBox.setText(folder)
Exemplo n.º 33
0
 def select_input_file_temp(self):
     filename, _filter = QFileDialog.getOpenFileName(self.dlg, "Select temperature map:")
     self.dlg.TB_temp.setText(filename)
 def selectFile():
     self.animationDialog.lineEdit.setText(
         QFileDialog.getOpenFileName())
Exemplo n.º 35
0
    def getDirectory(self):
        directory = QFileDialog.getExistingDirectory(
            self, "Scegli una directory", "Seleziona una directory:",
            QFileDialog.ShowDirsOnly)

        if not directory:
            return

        QMessageBox.warning(self, "Alert", str(dir(directory)), QMessageBox.Ok)
        for image in sorted(os.listdir(directory)):
            if image.endswith(".png") or image.endswith(
                    ".PNG") or image.endswith(".JPG") or image.endswith(
                        ".jpg") or image.endswith(".jpeg") or image.endswith(
                            ".JPEG") or image.endswith(
                                ".tif") or image.endswith(
                                    ".TIF") or image.endswith(
                                        ".tiff") or image.endswith(".TIFF"):

                filename, filetype = image.split(".")[0], image.split(".")[
                    1]  # db definisce nome immagine originale
                filepath = directory + '/' + filename + "." + filetype  # db definisce il path immagine originale
                idunique_image_check = self.db_search_check(
                    self.MAPPER_TABLE_CLASS, 'filepath', filepath
                )  # controlla che l'immagine non sia già presente nel db sulla base del suo path

                if not bool(idunique_image_check):
                    mediatype = 'image'  # db definisce il tipo di immagine originale
                    self.insert_record_media(
                        mediatype, filename, filetype, filepath
                    )  # db inserisce i dati nella tabella media originali
                    MU = Media_utility()
                    conn = Connection()
                    media_max_num_id = self.DB_MANAGER.max_num_id(
                        self.MAPPER_TABLE_CLASS, self.ID_TABLE
                    )  # db recupera il valore più alto ovvero l'ultimo immesso per l'immagine originale

                    thumb_path = conn.thumb_path()
                    thumb_path_str = thumb_path['thumb_path']

                    media_thumb_suffix = '_pay.png'

                    filenameorig = filename
                    filename_thumb = str(
                        media_max_num_id) + "_" + filename + media_thumb_suffix
                    filepath_thumb = thumb_path_str + filename_thumb
                    # crea la thumbnail
                    try:
                        MU.resample_images(media_max_num_id, filepath,
                                           filenameorig, thumb_path_str,
                                           media_thumb_suffix)
                    except Exception as e:
                        QMessageBox.warning(self, "Cucu", str(e),
                                            QMessageBox.Ok)

                        # inserisce i dati nel DB
                    self.insert_record_mediathumb(media_max_num_id, mediatype,
                                                  filename, filename_thumb,
                                                  filetype, filepath_thumb)

                    # visualizza le immagini nella gui
                    item = QListWidgetItem(str(media_max_num_id))
                    item.setData(Qt.UserRole, str(media_max_num_id))
                    icon = QIcon(
                        filepath_thumb
                    )  # os.path.join('%s/%s' % (directory.toUtf8(), image)))
                    item.setIcon(icon)
                    self.iconListWidget.addItem(item)

                elif bool(idunique_image_check):

                    # recupero il valore id_media basato sul path dell'immagine

                    data = idunique_image_check
                    id_media = data[0].id_media

                    # visualizza le immagini nella gui
                    item = QListWidgetItem(str(id_media))

                    data_for_thumb = self.db_search_check(
                        self.MAPPER_TABLE_CLASS_thumb, 'id_media', id_media
                    )  # recupera i valori della thumb in base al valore id_media del file originale

                    thumb_path = data_for_thumb[0].filepath
                    item.setData(Qt.UserRole, thumb_path)
                    icon = QIcon(
                        thumb_path
                    )  # os.path.join('%s/%s' % (directory.toUtf8(), image)))
                    item.setIcon(icon)
                    self.iconListWidget.addItem(item)
Exemplo n.º 36
0
 def t0_Upload_Pipeline_Layer(self):
     pipes_file, _filter = QFileDialog.getSaveFileName(
         self.dlg, "Select  PipeLine file ", "", '*.shp')
     self.dlg.lineEdit_21.setText(pipes_file)
Exemplo n.º 37
0
 def showSelectionDialog(self):
     filename, selected_filter = QFileDialog.getOpenFileName(self,
                                                             self.tr('Select Style File'), '',
                                                             self.tr('QGIS Layer Style File (*.qml *.QML)'))
     if filename:
         self.leText.setText(filename)
Exemplo n.º 38
0
    def showSelectionDialog(self):
        if isinstance(self.output, QgsProcessingParameterFolderDestination):
            self.selectDirectory()
            return

        filefilter = getFileFilter(self.output)
        settings = QgsSettings()
        if settings.contains('/Processing/LastBatchOutputPath'):
            path = str(settings.value('/Processing/LastBatchOutputPath'))
        else:
            path = ''
        filename, selectedFileFilter = QFileDialog.getSaveFileName(
            self, self.tr('Save file'), path, filefilter)
        if filename:
            if not filename.lower().endswith(
                    tuple(re.findall("\\*(\\.[a-z]{1,10})", filefilter))):
                ext = re.search("\\*(\\.[a-z]{1,10})", selectedFileFilter)
                if ext:
                    filename += ext.group(1)
            settings.setValue('/Processing/LastBatchOutputPath',
                              os.path.dirname(filename))
            dlg = AutofillDialog(self.alg)
            dlg.exec_()
            if dlg.mode is not None:
                try:
                    if dlg.mode == AutofillDialog.DO_NOT_AUTOFILL:
                        self.table.cellWidget(self.row,
                                              self.col).setValue(filename)
                    elif dlg.mode == AutofillDialog.FILL_WITH_NUMBERS:
                        n = self.table.rowCount() - self.row
                        for i in range(n):
                            name = filename[:filename.rfind('.')] \
                                + str(i + 1) + filename[filename.rfind('.'):]
                            self.table.cellWidget(i + self.row,
                                                  self.col).setValue(name)
                    elif dlg.mode == AutofillDialog.FILL_WITH_PARAMETER:
                        n = self.table.rowCount() - self.row
                        for i in range(n):
                            widget = self.table.cellWidget(
                                i + self.row, dlg.param_index)
                            param = self.alg.parameterDefinitions()[
                                dlg.param_index]
                            if isinstance(
                                    param,
                                (QgsProcessingParameterRasterLayer,
                                 QgsProcessingParameterFeatureSource,
                                 QgsProcessingParameterVectorLayer,
                                 QgsProcessingParameterMultipleLayers)):
                                v = widget.value()
                                if isinstance(v, QgsMapLayer):
                                    s = v.name()
                                else:
                                    s = os.path.basename(v)
                                    s = os.path.splitext(s)[0]
                            elif isinstance(param,
                                            QgsProcessingParameterBoolean):
                                s = str(widget.currentIndex() == 0)
                            elif isinstance(param, QgsProcessingParameterEnum):
                                s = str(widget.currentText())
                            elif isinstance(param,
                                            QgsProcessingParameterMatrix):
                                s = str(widget.table)
                            else:
                                s = str(widget.text())
                            name = filename[:filename.rfind('.')] + s \
                                + filename[filename.rfind('.'):]
                            self.table.cellWidget(i + self.row,
                                                  self.col).setValue(name)
                except:
                    pass
 def onFolderSelectClicked(self):
     mydir = QFileDialog.getExistingDirectory(self, "Sélectionner un dossier")
     if mydir:
         self.lineEdit_folder_path.setText(mydir)
Exemplo n.º 40
0
    def save(self):
        toSave = []
        for row in range(self.tblParameters.rowCount()):
            algParams = {}
            algOutputs = {}
            col = 0
            alg = self.alg.getCopy()
            for param in alg.parameters:
                if param.hidden:
                    continue
                if isinstance(param, ParameterExtent):
                    col += 1
                    continue
                widget = self.tblParameters.cellWidget(row, col)
                if not self.setParamValue(param, widget, alg):
                    self.parent.lblProgress.setText(
                        self.tr('<b>Missing parameter value: %s (row %d)</b>')
                        % (param.description, row + 1))
                    return
                algParams[param.name] = param.getValueAsCommandLineParameter()
                col += 1

            col = 0
            for param in alg.parameters:
                if param.hidden:
                    continue
                if isinstance(param, ParameterExtent):
                    widget = self.tblParameters.cellWidget(row, col)
                    if not self.setParamValue(param, widget, alg):
                        self.parent.lblProgress.setText(
                            self.
                            tr('<b>Missing parameter value: %s (row %d)</b>') %
                            (param.description, row + 1))
                        return
                    algParams[param.name] = unicode(param.value)
                col += 1

            for out in alg.outputs:
                if out.hidden:
                    continue
                widget = self.tblParameters.cellWidget(row, col)
                text = widget.getValue()
                if text.strip() != '':
                    algOutputs[out.name] = text.strip()
                    col += 1
                else:
                    self.parent.lblProgress.setText(
                        self.
                        tr('<b>Wrong or missing parameter value: %s (row %d)</b>'
                           ) % (out.description, row + 1))
                    return
            toSave.append({
                self.PARAMETERS: algParams,
                self.OUTPUTS: algOutputs
            })

        filename = unicode(
            QFileDialog.getSaveFileName(self, self.tr('Save batch'), None,
                                        self.tr('JSON files (*.json)')))
        if filename:
            if not filename.endswith('.json'):
                filename += '.json'
            with open(filename, 'w') as f:
                json.dump(toSave, f)
Exemplo n.º 41
0
 def select_output(self):
     self.dlg.lineEdit.setText("")
     self.shpPath, self._filter = QFileDialog.getSaveFileName(
         self.dlg, "Select input shp file", "", '*.shp')
     self.dlg.lineEdit.setText(self.shpPath)
 def onFileSelectClicked(self):
     myfile, _ = QFileDialog.getOpenFileName(self, "Sélectionner un fichier",
         filter="Fichiers 7zip (*.7z)")
     if myfile:
         self.lineEdit_file_path.setText(myfile)
Exemplo n.º 43
0
class PotentialSlopeFailure(object):
    """QGIS Plugin Implementation."""
    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir, 'i18n',
            'PotentialSlopeFailure_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)

            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

        self.dlg = PotentialSlopeFailureDialog(self.iface)
        self.dlg.runButton.clicked.connect(self.start_progress)
        self.dlg.pushButtonHelp.clicked.connect(self.help)
        self.dlg.pushButtonSave.clicked.connect(self.folder_path)
        self.fileDialog = QFileDialog()
        self.fileDialog.setFileMode(QFileDialog.Directory)
        self.fileDialog.setOption(QFileDialog.ShowDirsOnly, True)

        # Declare instance attributes
        #self.actions = []
        #self.menu = self.tr(u'&Potential Slope Failure')
        # TODO: We are going to let the user set this up in a future iteration
        #self.toolbar = self.iface.addToolBar(u'PotentialSlopeFailure')
        #self.toolbar.setObjectName(u'PotentialSlopeFailure')

        # self.layerComboManagerDEM = RasterLayerCombo(self.dlg.comboBoxDem)
        # RasterLayerCombo(self.dlg.comboBoxDem, initLayer="")
        # self.layerComboManagerSOIL = RasterLayerCombo(self.dlg.comboBoxSoil)
        # RasterLayerCombo(self.dlg.comboBoxSoil, initLayer="")
        self.layerComboManagerDEM = QgsMapLayerComboBox(self.dlg.widgetDEM)
        self.layerComboManagerDEM.setFilters(QgsMapLayerProxyModel.RasterLayer)
        self.layerComboManagerDEM.setFixedWidth(175)
        self.layerComboManagerSOIL = QgsMapLayerComboBox(self.dlg.widgetSOIL)
        self.layerComboManagerSOIL.setFilters(
            QgsMapLayerProxyModel.RasterLayer)
        self.layerComboManagerSOIL.setFixedWidth(175)
        self.folderPath = 'None'

    # noinspection PyMethodMayBeStatic
    def tr(self, message):
        """Get the translation for a string using Qt translation API.

        We implement this ourselves since we do not inherit QObject.

        :param message: String for translation.
        :type message: str, QString

        :returns: Translated version of message.
        :rtype: QString
        """
        # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
        return QCoreApplication.translate('PotentialSlopeFailure', message)

    # def add_action(
    #     self,
    #     icon_path,
    #     text,
    #     callback,
    #     enabled_flag=True,
    #     add_to_menu=True,
    #     add_to_toolbar=True,
    #     status_tip=None,
    #     whats_this=None,
    #     parent=None):
    #     """Add a toolbar icon to the toolbar.
    #
    #     :param icon_path: Path to the icon for this action. Can be a resource
    #         path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
    #     :type icon_path: str
    #
    #     :param text: Text that should be shown in menu items for this action.
    #     :type text: str
    #
    #     :param callback: Function to be called when the action is triggered.
    #     :type callback: function
    #
    #     :param enabled_flag: A flag indicating if the action should be enabled
    #         by default. Defaults to True.
    #     :type enabled_flag: bool
    #
    #     :param add_to_menu: Flag indicating whether the action should also
    #         be added to the menu. Defaults to True.
    #     :type add_to_menu: bool
    #
    #     :param add_to_toolbar: Flag indicating whether the action should also
    #         be added to the toolbar. Defaults to True.
    #     :type add_to_toolbar: bool
    #
    #     :param status_tip: Optional text to show in a popup when mouse pointer
    #         hovers over the action.
    #     :type status_tip: str
    #
    #     :param parent: Parent widget for the new action. Defaults None.
    #     :type parent: QWidget
    #
    #     :param whats_this: Optional text to show in the status bar when the
    #         mouse pointer hovers over the action.
    #
    #     :returns: The action that was created. Note that the action is also
    #         added to self.actions list.
    #     :rtype: QAction
    #     """
    #
    #     # Create the dialog (after translation) and keep reference
    #     # self.dlg = PotentialSlopeFailureDialog()
    #
    #     icon = QIcon(icon_path)
    #     action = QAction(icon, text, parent)
    #     action.triggered.connect(callback)
    #     action.setEnabled(enabled_flag)
    #
    #     if status_tip is not None:
    #         action.setStatusTip(status_tip)
    #
    #     if whats_this is not None:
    #         action.setWhatsThis(whats_this)
    #
    #     if add_to_toolbar:
    #         self.toolbar.addAction(action)
    #
    #     if add_to_menu:
    #         self.iface.addPluginToMenu(self.menu, action)
    #
    #     self.actions.append(action)
    #
    #     return action

    def initGui(self):
        # Create action that will start plugin configuration
        self.action = QAction(
            QIcon(':/plugins/PotentialSlopeFailure/slopeicon.png'),
            'Calculates areas prone to slope failures in cohesive soils',
            self.iface.mainWindow())
        # connect the action to the run method
        self.action.triggered.connect(self.run)

        # Add toolbar button and menu item
        self.iface.addToolBarIcon(self.action)
        self.iface.addPluginToMenu(self.tr("&Potential Slope Failure"),
                                   self.action)

        #"""Create the menu entries and toolbar icons inside the QGIS GUI."""
        #
        #icon_path = ':/plugins/PotentialSlopeFailure/icon.png'
        #self.add_action(
        #    icon_path,
        #   text=self.tr(u'Calculates areas prone to slope failures in cohesive soils'),
        #   callback=self.run,
        #   parent=self.iface.mainWindow())

    def unload(self):
        # Remove the plugin menu item and icon
        self.iface.removePluginMenu("&Potential Slope Failure", self.action)
        self.iface.removeToolBarIcon(self.action)
        # """Removes the plugin menu item and icon from QGIS GUI."""
        # for action in self.actions: self.iface.removePluginMenu(
        #         self.tr(u'&Potential Slope Failure'),
        #         action)
        #     self.iface.removeToolBarIcon(action)
        # remove the toolbar
        # del self.toolbar

    def run(self):
        self.dlg.show()
        self.dlg.exec_()

    def folder_path(self):
        self.fileDialog.open()
        result = self.fileDialog.exec_()
        if result == 1:
            self.folderPath = self.fileDialog.selectedFiles()
            self.dlg.textOutput.setText(self.folderPath[0])

    def start_progress(self):
        if self.folderPath == 'None':
            QMessageBox.critical(None, "Error", "Select a valid output folder")
            return

        # Load DEM
        demlayer = self.layerComboManagerDEM.currentLayer()

        if demlayer is None:
            QMessageBox.critical(None, "Error",
                                 "No valid DEM raster layer is selected")
            return

        provider = demlayer.dataProvider()
        filepath_dem = str(provider.dataSourceUri())

        gdal_dem = gdal.Open(filepath_dem)

        dem = gdal_dem.ReadAsArray().astype(np.float)
        sizex = dem.shape[0]
        sizey = dem.shape[1]

        geotransform = gdal_dem.GetGeoTransform()
        scale = 1 / geotransform[1]

        # Load Soil
        soillayer = self.layerComboManagerSOIL.currentLayer()

        if soillayer is None:
            QMessageBox.critical(None, "Error",
                                 "No valid Soil raster selected")
            return

        # load raster
        gdal.AllRegister()
        provider = soillayer.dataProvider()
        filePathOld = str(provider.dataSourceUri())
        dataSet = gdal.Open(filePathOld)
        soil = dataSet.ReadAsArray().astype(np.float)

        soilsizex = soil.shape[0]
        soilsizey = soil.shape[1]

        if not (soilsizex == sizex) & (soilsizey == sizey):
            QMessageBox.critical(
                None, "Error",
                "The grids must be of same extent and resolution")
            return

        itera = int(360 / self.dlg.spinBoxIter.value())
        alt = self.dlg.spinBoxAlt.value()
        shtot = np.zeros((sizex, sizey))
        index = 0

        # Inverting dem
        dem = dem * (-1.) + np.max(dem)

        self.dlg.progressBar.setRange(0, self.dlg.spinBoxIter.value())

        for i in range(0, self.dlg.spinBoxIter.value()):
            azi = itera * i
            self.dlg.progressBar.setValue(i + 1)
            # self.iface.messageBar().pushMessage("ShadowGenerator", str(azi))
            sh = shadow.shadowingfunctionglobalradiation(
                dem, azi, alt, scale, self.dlg, 1)
            shtot = shtot + sh
            index += 1

        zon1 = shtot / index

        zon1[zon1 == 1] = 2
        zon1[zon1 < 1] = 1
        karta1a = zon1 * soil
        karta1a[karta1a == 0] = 3

        filename = self.folderPath[0] + '/map1a.tif'
        self.saveraster(gdal_dem, filename, karta1a)

        # load result into canvas
        if self.dlg.checkBoxIntoCanvas.isChecked():
            rlayer = self.iface.addRasterLayer(filename)

            # Trigger a repaint
            if hasattr(rlayer, "setCacheImage"):
                rlayer.setCacheImage(None)
            rlayer.triggerRepaint()

            rlayer.loadNamedStyle(self.plugin_dir + '/misc/map1a.qml')

            if hasattr(rlayer, "setCacheImage"):
                rlayer.setCacheImage(None)
            rlayer.triggerRepaint()

        self.dlg.progressBar.setValue(0)

        QMessageBox.information(
            self.dlg, "Calculation done!",
            "Output (map1a.tif) created in: " + self.folderPath[0] + "/")

    def help(self):
        url = "https://github.com/biglimp/PotentialSlopeFailure/wiki/Potential-Slope-Failure-plugin-for-QGIS"
        webbrowser.open_new_tab(url)

    def saveraster(self, gdal_data, filename, raster):
        rows = gdal_data.RasterYSize
        cols = gdal_data.RasterXSize

        outDs = gdal.GetDriverByName("GTiff").Create(filename, cols, rows,
                                                     int(1), GDT_Float32)
        outBand = outDs.GetRasterBand(1)

        # write the data
        outBand.WriteArray(raster, 0, 0)
        # flush data to disk, set the NoData value and calculate stats
        outBand.FlushCache()
        outBand.SetNoDataValue(-9999)

        # georeference the image and set the projection
        outDs.SetGeoTransform(gdal_data.GetGeoTransform())
        outDs.SetProjection(gdal_data.GetProjection())
Exemplo n.º 44
0
    def save(self):
        toSave = []
        context = dataobjects.createContext()
        for row in range(self.tblParameters.rowCount()):
            algParams = {}
            algOutputs = {}
            col = 0
            alg = self.alg
            for param in alg.parameterDefinitions():
                if param.flags() & QgsProcessingParameterDefinition.FlagHidden:
                    continue
                if param.isDestination():
                    continue
                wrapper = self.wrappers[row][col]

                # For compatibility with 3.x API, we need to check whether the wrapper is
                # the deprecated WidgetWrapper class. If not, it's the newer
                # QgsAbstractProcessingParameterWidgetWrapper class
                # TODO QGIS 4.0 - remove
                if issubclass(wrapper.__class__, WidgetWrapper):
                    widget = wrapper.widget
                else:
                    widget = wrapper.wrappedWidget()

                value = wrapper.parameterValue()

                if not param.checkValueIsAcceptable(value, context):
                    self.parent.messageBar().pushMessage(
                        "",
                        self.tr(
                            'Wrong or missing parameter value: {0} (row {1})').
                        format(param.description(), row + 1),
                        level=Qgis.Warning,
                        duration=5)
                    return
                algParams[param.name()] = param.valueAsPythonString(
                    value, context)
                col += 1
            for out in alg.destinationParameterDefinitions():
                if out.flags() & QgsProcessingParameterDefinition.FlagHidden:
                    continue
                widget = self.tblParameters.cellWidget(row, col)
                text = widget.getValue()
                if text.strip() != '':
                    algOutputs[out.name()] = text.strip()
                    col += 1
                else:
                    self.parent.messageBar().pushMessage(
                        "",
                        self.tr('Wrong or missing output value: {0} (row {1})'
                                ).format(out.description(), row + 1),
                        level=Qgis.Warning,
                        duration=5)
                    return
            toSave.append({
                self.PARAMETERS: algParams,
                self.OUTPUTS: algOutputs
            })

        settings = QgsSettings()
        last_path = settings.value("/Processing/LastBatchPath",
                                   QDir.homePath())
        filename, __ = QFileDialog.getSaveFileName(
            self, self.tr('Save Batch'), last_path,
            self.tr('JSON files (*.json)'))
        if filename:
            if not filename.endswith('.json'):
                filename += '.json'
            last_path = QFileInfo(filename).path()
            settings.setValue('/Processing/LastBatchPath', last_path)
            with open(filename, 'w') as f:
                json.dump(toSave, f)
Exemplo n.º 45
0
    def select_output_file(self):
		# define the interface for selecting a file
        filename, _filter = QFileDialog.getSaveFileName(self.dlg, "Select output file ","", '*.Data')
        self.dlg.lineEdit_2.setText(filename)
Exemplo n.º 46
0
 def on_btnBrowseProjectsRootDir_clicked(self):
     dir_path = QFileDialog.getExistingDirectory(self, tr(
             "Choose projects root directory"), self.projects_root_directory)
     dir_info = QFileInfo(dir_path)
     self.lineEditProjectsRootDir.setText(dir_info.absoluteFilePath())
Exemplo n.º 47
0
 def toolButtonOut(self):
     self.outEpanetName = QFileDialog.getSaveFileName(
         None, 'Save File',
         os.path.join(os.path.join(os.path.expanduser('~')), 'Desktop'),
         'Epanet Inp File (*.inp)')
     self.dlg.out.setText(self.outEpanetName[0])
Exemplo n.º 48
0
 def on_gmlasConfigButton_clicked(self):
     path, filter = QFileDialog.getOpenFileName(
         self, self.tr("Open GMLAS config file"),
         self.gmlasConfigLineEdit.text(), self.tr("XML Files (*.xml)"))
     if path:
         self.gmlasConfigLineEdit.setText(path)
Exemplo n.º 49
0
 def saveDialog(self):
     filename = QFileDialog.getSaveFileName(None, "Save File", self.dirname,
                                            "Text CSV (*.csv)")[0]
     if filename:
         self.dirname = os.path.dirname(filename)
         self.saveFile(filename)
Exemplo n.º 50
0
 def select_input(self):
     filename = QFileDialog.getOpenFileName(self.dlg, "select input file",
                                            '', '*.shp')
     pathname = filename[0]
     layer = iface.addVectorLayer(pathname, "Shapefile", "ogr")
Exemplo n.º 51
0
 def select_input_file_landuse(self):
     global filelanduse
     filelanduse, _filter = QFileDialog.getOpenFileName(self.dlg, "Select land use map:")
     self.dlg.TB_landuse.setText(filelanduse)
Exemplo n.º 52
0
 def cargacapadepuntos(self):
     """seleciono la capa de puntos con los datos de entrada""" 
     capaptos = QFileDialog.getOpenFileName( self.dlg , "Selecciona capa de puntos",filter = "shp(*.shp)")
     self.dlg.rutaptos.setText(capaptos[0])
     print (capaptos[0])
Exemplo n.º 53
0
    def showFileDialog(self, seldir):
        settings = QgsSettings()
        text = str(self.text.text())
        if os.path.isdir(text):
            path = text
        elif not seldir and os.path.isdir(os.path.dirname(text)):
            path = os.path.dirname(text)
        elif settings.contains('/Processing/LastInputPath'):
            path = str(settings.value('/Processing/LastInputPath'))
        else:
            path = ''

        if not seldir:
            ret, selected_filter = QFileDialog.getOpenFileNames(
                self, self.tr('Select Files'), path,
                self.param.createFileFilter())
        else:
            ret = QFileDialog.getExistingDirectory(self,
                                                   self.tr('Select Directory'),
                                                   path)

        if ret:
            if seldir:
                settings.setValue('/Processing/LastInputPath', ret)

                files = []
                for pp in Path(ret).rglob("*"):
                    if not pp.is_file():
                        continue

                    p = pp.as_posix()

                    if ((isinstance(self.param,
                                    QgsProcessingParameterRasterLayer) or
                         (isinstance(self.param,
                                     QgsProcessingParameterMultipleLayers) and
                          self.param.layerType() == QgsProcessing.TypeRaster))
                            and not QgsRasterLayer.isValidRasterFileName(p)):
                        continue

                    files.append(p)

                if not files:
                    return

            else:
                files = list(ret)
                settings.setValue('/Processing/LastInputPath',
                                  os.path.dirname(str(files[0])))

            for i, filename in enumerate(files):
                files[i] = dataobjects.getRasterSublayer(filename, self.param)
            if len(files) == 1:
                self.text.setText(files[0])
                self.textEditingFinished()
            else:
                if isinstance(self.param,
                              QgsProcessingParameterMultipleLayers):
                    self.text.setText(';'.join(str(f) for f in files))
                else:
                    rowdif = len(files) - (self._table().rowCount() - self.row)
                    for i in range(rowdif):
                        self._panel().addRow()
                    for i, f in enumerate(files):
                        self._table().cellWidget(i + self.row,
                                                 self.col).setValue(f)
Exemplo n.º 54
0
 def setSourceFile(self):
     # Set the file path to the source file
     filters = "Comma Separated Value (*.csv);;ESRI Shapefile (*.shp);;AutoCAD DXF (*.dxf)"
     sourceFile, _ = QFileDialog.getOpenFileName(self, "Select Source File", vectorFileDir(), filters)
     if sourceFile:
         self.txtDataSource.setText(sourceFile)
Exemplo n.º 55
0
 def select_output_file(self):
     filename, _filter = QFileDialog.getSaveFileName(self.dlg, "Select output file:", "", '*.tif')
     self.dlg.LE_output.setText(filename)
Exemplo n.º 56
0
 def getSQLFile(self):
     fd = QFileDialog()
     filename = fd.getOpenFileName(caption=self.tr('Select a SQL file'),
                                   filter=self.tr('sql file (*.sql)'))
     return filename