Ejemplo n.º 1
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')
Ejemplo n.º 2
0
 def selFile(self):
     sf = QFileInfo(QFileDialog.getOpenFileName(self, 'Open logo file', QDir.homePath(), 'Image files (*.png)'))
     f = sf.fileName()
     if f!='':
         self.logopath = sf.absoluteFilePath()
         self.label.setPixmap(QPixmap(self.logopath))
     return f
Ejemplo n.º 3
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)
Ejemplo n.º 4
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))
Ejemplo n.º 5
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))
Ejemplo n.º 6
0
    def filer(self):
        if self.comboBox.currentText()=='ESRI shape file':
            a = 'Save as ESRI shape file'
            sf = QFileDialog.getExistingDirectory(self, a, QDir.homePath())
            # b = 'ESRI shape files (*.shp)'
        elif self.comboBox.currentText()=='Comma separated value (CSV)':
            a = 'Save as comma separated value (CSV)'
            sf = QFileDialog.getExistingDirectory(self, a, QDir.homePath())
            # b = 'CSV files (*.csv)'
        elif self.comboBox.currentText()=='SQLite database':
            a = 'SQLite database'
            sf = QFileDialog.getOpenFileName(self, a, QDir.homePath())
        elif self.comboBox.currentText()=='Copy complete database':
            a = 'Copy complete database'
            sf = QFileDialog.getSaveFileName(self, a, QDir.homePath())

        self.lineEdit.setText(sf)
Ejemplo n.º 7
0
    def selectDirectory(self):
        lastDir = self.leText.text()
        settings = QgsSettings()
        if not lastDir:
            lastDir = settings.value("/Processing/LastOutputPath", QDir.homePath())

        dirName = QFileDialog.getExistingDirectory(self, self.tr('Select directory'),
                                                   lastDir, QFileDialog.ShowDirsOnly)
        if dirName:
            self.leText.setText(QDir.toNativeSeparators(dirName))
            settings.setValue('/Processing/LastOutputPath', dirName)
Ejemplo n.º 8
0
    def selectDirectory(self):
        lastDir = self.leText.text()
        settings = QgsSettings()
        if not lastDir:
            lastDir = settings.value("/Processing/LastOutputPath", QDir.homePath())

        dirName = QFileDialog.getExistingDirectory(self, self.tr('Select Directory'),
                                                   lastDir, QFileDialog.ShowDirsOnly)
        if dirName:
            self.leText.setText(QDir.toNativeSeparators(dirName))
            settings.setValue('/Processing/LastOutputPath', dirName)
            self.use_temporary = False
            self.skipOutputChanged.emit(False)
            self.destinationChanged.emit()
def local_collection_path(id=None):
    """Get the path to the local collection dir.

    If id is not passed, it will just return the root dir of the collections.
    """
    path = os.path.join(
        QDir.homePath(),
        'QGIS',
        'Resource Sharing')
    if id:
        collection_name = config.COLLECTIONS[id]['name']
        dir_name = '%s (%s)' % (collection_name, id)
        path = os.path.join(path, dir_name)
    return path
Ejemplo n.º 10
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]
                if not param.checkValueIsAcceptable(wrapper.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(wrapper.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)
Ejemplo n.º 11
0
    def load(self):
        settings = QgsSettings()
        last_path = settings.value("/Processing/LastBatchPath",
                                   QDir.homePath())
        filename, selected_filter = QFileDialog.getOpenFileName(
            self, self.tr('Open Batch'), last_path,
            self.tr('JSON files (*.json)'))
        if filename:
            last_path = QFileInfo(filename).path()
            settings.setValue('/Processing/LastBatchPath', last_path)
            with open(filename) as f:
                values = json.load(f)
        else:
            # If the user clicked on the cancel button.
            return

        self.tblParameters.setRowCount(0)
        try:
            for row, alg in enumerate(values):
                self.addRow()
                params = alg[self.PARAMETERS]
                outputs = alg[self.OUTPUTS]
                column = 0
                for param in self.alg.parameterDefinitions():
                    if param.flags(
                    ) & QgsProcessingParameterDefinition.FlagHidden:
                        continue
                    if param.isDestination():
                        continue
                    if param.name() in params:
                        value = eval(params[param.name()])
                        wrapper = self.wrappers[row][column]
                        wrapper.setValue(value)
                    column += 1

                for out in self.alg.destinationParameterDefinitions():
                    if out.flags(
                    ) & QgsProcessingParameterDefinition.FlagHidden:
                        continue
                    if out.name() in outputs:
                        value = outputs[out.name()].strip("'")
                        widget = self.tblParameters.cellWidget(row, column)
                        widget.setValue(value)
                    column += 1
        except TypeError:
            QMessageBox.critical(
                self, self.tr('Error'),
                self.tr('An error occurred while reading your file.'))
Ejemplo n.º 12
0
    def execute(self):
        settings = QgsSettings()
        lastDir = settings.value('Processing/lastModelsDir', QDir.homePath())
        filename, selected_filter = QFileDialog.getOpenFileName(
            self.toolbox, self.tr('Open Model', 'AddModelFromFileAction'),
            lastDir,
            self.tr('Processing models (*.model3 *.MODEL3)',
                    'AddModelFromFileAction'))
        if filename:
            settings.setValue('Processing/lastModelsDir',
                              QFileInfo(filename).absoluteDir().absolutePath())

            dlg = ModelerDialog.create()
            dlg.loadModel(filename)
            dlg.show()
            dlg.activate()
Ejemplo n.º 13
0
    def _export_service(self):
        service_type = self.get_current_service_type()
        service_id = self.get_current_service_id(service_type)
        file, _ = QFileDialog.getSaveFileName(self, self.tr('Export Service'),
                                              QDir.homePath() + '/{}.json'.format(service_id), 'JSON Files (*.json)')
        if not file:
            return

        file = QgsFileUtils.ensureFileNameHasExtension(file, ['json'])

        if SERVICE_MANAGER.export_service(service_type, service_id, file):
            self.message_bar.pushMessage(
                self.tr("Service exported"), Qgis.Success, 5)
        else:
            self.message_bar.pushMessage(
                self.tr("An error occurred while exporting service"), Qgis.Critical, 5)
Ejemplo n.º 14
0
    def selectDirectory(self):
        lastDir = self.leText.text()
        settings = QgsSettings()
        if not lastDir:
            lastDir = settings.value("/Processing/LastOutputPath",
                                     QDir.homePath())

        dirName = QFileDialog.getExistingDirectory(self,
                                                   self.tr('Select Directory'),
                                                   lastDir,
                                                   QFileDialog.ShowDirsOnly)
        if dirName:
            self.leText.setText(QDir.toNativeSeparators(dirName))
            settings.setValue('/Processing/LastOutputPath', dirName)

        self.skipOutputChanged.emit(False)
Ejemplo n.º 15
0
    def _import_configuration(self):
        """
        Triggers importing a configuration
        """
        file, _ = QFileDialog.getOpenFileName(self, self.tr('Import Service'),
                                              QDir.homePath(),
                                              'JSON Files (*.json)')
        if not file:
            return

        res, err = SERVICE_MANAGER.import_service(file)
        if res:
            self.message_bar.pushMessage(self.tr("Service imported"),
                                         Qgis.Success, 5)
        else:
            self.message_bar.pushMessage(err, Qgis.Critical, 5)
Ejemplo n.º 16
0
    def execute(self):
        settings = QgsSettings()
        lastDir = settings.value('Processing/lastModelsDir', QDir.homePath())
        filename, selected_filter = QFileDialog.getOpenFileName(
            self.toolbox, self.tr('Open Model', 'AddModelFromFileAction'),
            lastDir,
            self.tr('Processing models (*.model3 *.MODEL3)',
                    'AddModelFromFileAction'))
        if filename:
            settings.setValue('Processing/lastModelsDir',
                              QFileInfo(filename).absoluteDir().absolutePath())

            alg = QgsProcessingModelAlgorithm()
            if not alg.fromFile(filename):
                QMessageBox.warning(
                    self.toolbox,
                    self.tr('Open Model', 'AddModelFromFileAction'),
                    self.tr('The selected file does not contain a valid model',
                            'AddModelFromFileAction'))
                return

            if QgsApplication.instance().processingRegistry().algorithmById(
                    'model:{}'.format(alg.id())):
                QMessageBox.warning(
                    self.toolbox,
                    self.tr('Open Model', 'AddModelFromFileAction'),
                    self.tr('Model with the same name already exists',
                            'AddModelFromFileAction'))
                return

            destFilename = os.path.join(ModelerUtils.modelsFolders()[0],
                                        os.path.basename(filename))
            if os.path.exists(destFilename):
                reply = QMessageBox.question(
                    self.toolbox,
                    self.tr('Open Model', 'AddModelFromFileAction'),
                    self.tr(
                        'There is already a model file with the same name. Overwrite?',
                        'AddModelFromFileAction'),
                    QMessageBox.Yes | QMessageBox.No, QMessageBox.No)

                if reply == QMessageBox.No:
                    return

            shutil.copyfile(filename, destFilename)
            QgsApplication.processingRegistry().providerById(
                'model').refreshAlgorithms()
Ejemplo n.º 17
0
    def load(self):
        context = dataobjects.createContext()
        settings = QgsSettings()
        last_path = settings.value("/Processing/LastBatchPath", QDir.homePath())
        filename, selected_filter = QFileDialog.getOpenFileName(self,
                                                                self.tr('Open Batch'), last_path,
                                                                self.tr('JSON files (*.json)'))
        if filename:
            last_path = QFileInfo(filename).path()
            settings.setValue('/Processing/LastBatchPath', last_path)
            with open(filename) as f:
                values = json.load(f)
        else:
            # If the user clicked on the cancel button.
            return

        self.tblParameters.setRowCount(0)
        try:
            for row, alg in enumerate(values):
                self.addRow()
                params = alg[self.PARAMETERS]
                outputs = alg[self.OUTPUTS]
                column = 0
                for param in self.alg.parameterDefinitions():
                    if param.flags() & QgsProcessingParameterDefinition.FlagHidden:
                        continue
                    if param.isDestination():
                        continue
                    if param.name() in params:
                        value = eval(params[param.name()])
                        wrapper = self.wrappers[row][column]
                        wrapper.setParameterValue(value, context)
                    column += 1

                for out in self.alg.destinationParameterDefinitions():
                    if out.flags() & QgsProcessingParameterDefinition.FlagHidden:
                        continue
                    if out.name() in outputs:
                        value = outputs[out.name()].strip("'")
                        widget = self.tblParameters.cellWidget(row, column)
                        widget.setValue(value)
                    column += 1
        except TypeError:
            QMessageBox.critical(
                self,
                self.tr('Error'),
                self.tr('An error occurred while reading your file.'))
Ejemplo n.º 18
0
    def showDirectorySelectionDialog(self):
        settings = QgsSettings()
        if settings.contains('/Processing/LastInputPath'):
            path = str(settings.value('/Processing/LastInputPath'))
        else:
            path = QDir.homePath()

        folder = QFileDialog.getExistingDirectory(self,
                                                  self.tr('Select Directory'),
                                                  path)
        if not folder:
            return

        settings.setValue('/Processing/LastInputPath', folder)

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

            p = pp.as_posix()

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

            files.append(p)

        if not files:
            return

        context = dataobjects.createContext()

        first_row = self.panel.batchRowCount(
        ) if self.panel.batchRowCount() > 1 else 0
        self.panel.addRow(len(files))
        self.panel.tblParameters.setUpdatesEnabled(False)
        for row, file in enumerate(files):
            self.setRowValue(first_row + row, file, context)
        self.panel.tblParameters.setUpdatesEnabled(True)
 def open_zonal_layer_dialog(self):
     """
     Open a file dialog to select the zonal layer to be loaded
     :returns: the zonal layer
     """
     text = self.tr('Select zonal layer to import')
     filters = self.tr('Vector shapefiles (*.shp);;SQLite (*.sqlite);;'
                       'All files (*.*)')
     default_dir = QSettings().value('irmt/select_layer_dir',
                                     QDir.homePath())
     file_name, file_type = QFileDialog.getOpenFileNameAndFilter(
         self, text, default_dir, filters)
     if not file_name:
         return None
     selected_dir = QFileInfo(file_name).dir().path()
     QSettings().setValue('irmt/select_layer_dir', selected_dir)
     zonal_layer_plus_stats = self.load_zonal_layer(file_name)
     return zonal_layer_plus_stats
 def open_file_dialog(self, dialog_type):
     """
     Open a file dialog to select the data file to be loaded
     :param string dialog_type: 'loss_layer' or 'zonal_layer'
     :returns: a layer
     """
     if dialog_type == 'loss_layer':
         text = self.tr('Select loss map to import')
         # FIXME: What should be the format of the raster maps?
         filters = self.tr('Loss curves from the OpenQuake-engine (*.csv);;'
                           'Shapefile vector loss curves (*.shp);;'
                           'Geojson vector loss curves (*.geojson);;'
                           'Raster loss curves (*.*)')
     elif dialog_type == 'zonal_layer':
         text = self.tr('Select zonal layer to import')
         filters = self.tr('Vector shapefiles (*.shp);;SQLite (*.sqlite);;'
                           'All files (*.*)')
     else:
         raise RuntimeError('Invalid dialog_type: {}'.format(dialog_type))
     default_dir = QSettings().value('irmt/select_layer_dir',
                                     QDir.homePath())
     file_name, file_type = QFileDialog.getOpenFileNameAndFilter(
         self, text, default_dir, filters)
     if dialog_type == 'zonal_layer':
         if not file_name:
             return None
         selected_dir = QFileInfo(file_name).dir().path()
         QSettings().setValue('irmt/select_layer_dir', selected_dir)
         layer = self.load_zonal_layer(file_name)
     elif dialog_type == 'loss_layer':
         if not file_name:
             return None
         selected_dir = QFileInfo(file_name).dir().path()
         QSettings().setValue('irmt/select_layer_dir', selected_dir)
         if file_type == 'Raster loss curves (*.*)':
             self.loss_layer_is_vector = False
         if file_type == 'Loss curves from the OpenQuake-engine (*.csv)':
             layer = self.import_loss_layer_from_csv(file_name)
         else:
             layer = self.load_loss_layer(file_name)
     else:
         raise RuntimeError
     return layer
 def open_file_dialog(self):
     """
     Open a file dialog to select the data file to be loaded
     """
     text = self.tr('Select the OQ-Engine output file to import')
     if self.output_type in OQ_CSV_TO_LAYER_TYPES:
         filters = self.tr('CSV files (*.csv)')
     else:
         raise NotImplementedError(self.output_type)
     default_dir = QSettings().value('irmt/load_as_layer_dir',
                                     QDir.homePath())
     path = QFileDialog.getOpenFileName(self, text, default_dir, filters)
     if not path:
         return
     selected_dir = QFileInfo(path).dir().path()
     QSettings().setValue('irmt/load_as_layer_dir', selected_dir)
     self.path = path
     self.path_le.setText(self.path)
     return path
Ejemplo n.º 22
0
    def openScriptFile(self):
        lastDirPath = self.settings.value("pythonConsole/lastDirPath", QDir.homePath())
        openFileTr = QCoreApplication.translate("PythonConsole", "Open File")
        fileList, selected_filter = QFileDialog.getOpenFileNames(
            self, openFileTr, lastDirPath, "Script file (*.py)")
        if fileList:
            for pyFile in fileList:
                for i in range(self.tabEditorWidget.count()):
                    tabWidget = self.tabEditorWidget.widget(i)
                    if tabWidget.path == pyFile:
                        self.tabEditorWidget.setCurrentWidget(tabWidget)
                        break
                else:
                    tabName = QFileInfo(pyFile).fileName()
                    self.tabEditorWidget.newTabEditor(tabName, pyFile)

                    lastDirPath = QFileInfo(pyFile).path()
                    self.settings.setValue("pythonConsole/lastDirPath", pyFile)
                    self.updateTabListScript(pyFile, action='append')
Ejemplo n.º 23
0
    def openScriptFile(self):
        lastDirPath = self.settings.value("pythonConsole/lastDirPath", QDir.homePath())
        openFileTr = QCoreApplication.translate("PythonConsole", "Open File")
        fileList, selected_filter = QFileDialog.getOpenFileNames(
            self, openFileTr, lastDirPath, "Script file (*.py)")
        if fileList:
            for pyFile in fileList:
                for i in range(self.tabEditorWidget.count()):
                    tabWidget = self.tabEditorWidget.widget(i)
                    if tabWidget.path == pyFile:
                        self.tabEditorWidget.setCurrentWidget(tabWidget)
                        break
                else:
                    tabName = QFileInfo(pyFile).fileName()
                    self.tabEditorWidget.newTabEditor(tabName, pyFile)

                    lastDirPath = QFileInfo(pyFile).path()
                    self.settings.setValue("pythonConsole/lastDirPath", pyFile)
                    self.updateTabListScript(pyFile, action='append')
Ejemplo n.º 24
0
    def _load_column_mapping(self):
        """
        Imports the current column mapping from a JSON definition file
        """
        config = RegistryConfig()
        prev_folder = config.read(["LastImportConfigFolder"]).get("LastImportConfigFolder")
        if not prev_folder:
            prev_folder = QDir.homePath()

        source_path, _ = QFileDialog.getOpenFileName(self, self.tr("Load Configuration"),
                                                     prev_folder,
                                                     "{0} (*.json)".format(self.tr('Configuration files')))

        if not source_path:
            return

        config.write({"LastImportConfigFolder": QFileInfo(source_path).path()})

        with open(source_path, 'rt') as f:
            imported_config = json.loads(''.join(f.readlines()))
            self._restore_column_config(imported_config)
Ejemplo n.º 25
0
Archivo: console.py Proyecto: t0b3/QGIS
    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).replace('*',
                                                                   '') + '.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:
            filename = QgsFileUtils.ensureFileNameHasExtension(
                filename, ['py'])

            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')
Ejemplo n.º 26
0
    def _save_column_mapping(self):
        """
        Exports the current column mapping to a JSON definition file
        """
        config = RegistryConfig()
        prev_folder = config.read(["LastImportConfigFolder"]).get("LastImportConfigFolder")
        if not prev_folder:
            prev_folder = QDir.homePath()

        dest_path, _ = QFileDialog.getSaveFileName(self, self.tr("Save Configuration"),
                                                   prev_folder,
                                                   "{0} (*.json)".format(self.tr('Configuration files')))

        if not dest_path:
            return

        dest_path = QgsFileUtils.ensureFileNameHasExtension(dest_path, ['.json'])

        config.write({"LastImportConfigFolder": QFileInfo(dest_path).path()})

        with open(dest_path, 'wt') as f:
            f.write(json.dumps(self._get_column_config(), indent=4))
Ejemplo n.º 27
0
    def showFileSelectionDialog(self):
        settings = QgsSettings()
        if settings.contains('/Processing/LastInputPath'):
            path = str(settings.value('/Processing/LastInputPath'))
        else:
            path = QDir.homePath()

        files, selected_filter = QFileDialog.getOpenFileNames(
            self, self.tr('Select Files'), path,
            self.parameterDefinition.createFileFilter())

        if not files:
            return

        settings.setValue('/Processing/LastInputPath',
                          os.path.dirname(str(files[0])))

        context = dataobjects.createContext()

        first_row = self.panel.batchRowCount(
        ) if self.panel.batchRowCount() > 1 else 0
        for row, file in enumerate(files):
            self.setRowValue(first_row + row, file, context)
Ejemplo n.º 28
0
 def select_and_copy_files_to_ipt_dir(self):
     """
     Open a file browser pointing to the most recently browsed directory,
     where multiple files can be selected. The selected files will be
     copied inside the ipt_dir
     """
     try:
         default_dir = QSettings().value('irmt/ipt_browsed_dir',
                                         QDir.homePath())
         text = 'The selected files will be copied to the ipt directory'
         file_paths, __ = QFileDialog.getOpenFileNames(
             self.parent().parent(), text, default_dir)
         if not file_paths:
             return {'ret': 1, 'reason': 'No file was selected'}
         selected_dir = QFileInfo(file_paths[0]).dir().path()
         QSettings().setValue('irmt/ipt_browsed_dir', selected_dir)
         ipt_dir = self.parent().ipt_dir
         for file_path in file_paths:
             basename = os.path.basename(file_path)
             copyfile(file_path, os.path.join(ipt_dir, basename))
     except Exception as exc:
         return {'ret': 2, 'reason': str(exc)}
     else:
         return {'ret': 0, 'reason': 'ok'}
Ejemplo n.º 29
0
    def load_aoi_from_file(self):
        path, _ = QFileDialog.getOpenFileName(self, "Open GeoJSON AOI file",
                                              QDir.homePath(),
                                              "JSON (*.json);;All Files (*)")
        file = QFile(path)
        if not file.open(QFile.ReadOnly | QFile.Text):
            return

        inf = QTextStream(file)
        json_txt = inf.readAll()

        try:
            json_obj = json.loads(json_txt)
        except ValueError:
            # noinspection PyUnresolvedReferences
            self._show_message('GeoJSON from file invalid',
                               level=Qgis.Warning,
                               duration=10)
            return

        json_geom = geometry_from_json(json_obj)

        if not json_geom:
            # noinspection PyUnresolvedReferences
            self._show_message('GeoJSON geometry from file invalid',
                               level=Qgis.Warning,
                               duration=10)
            return

        geom: QgsGeometry = qgsgeometry_from_geojson(json_geom)
        self._aoi_box.setToGeometry(geom,
                                    QgsCoordinateReferenceSystem("EPSG:4326"))

        self.leAOI.setText(json.dumps(json_geom))

        self.zoom_to_aoi()
Ejemplo n.º 30
0
    def save(self):
        toSave = []
        context = dataobjects.createContext()
        for row in range(self.batchRowCount()):
            algParams = {}
            algOutputs = {}
            alg = self.alg
            for param in alg.parameterDefinitions():
                if param.isDestination():
                    continue

                col = self.parameter_to_column[param.name()]
                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):
                    msg = self.tr(
                        'Wrong or missing parameter value: {0} (row {1})'
                    ).format(param.description(), row + 1)
                    self.parent.messageBar().pushMessage("",
                                                         msg,
                                                         level=Qgis.Warning,
                                                         duration=5)
                    return
                algParams[param.name()] = param.valueAsPythonString(
                    value, context)

            for out in alg.destinationParameterDefinitions():
                if out.flags() & QgsProcessingParameterDefinition.FlagHidden:
                    continue
                col = self.parameter_to_column[out.name()]
                widget = self.tblParameters.cellWidget(row + 1, col)
                text = widget.getValue()
                if text.strip() != '':
                    algOutputs[out.name()] = text.strip()
                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)
Ejemplo n.º 31
0
    def on_file_browse(self):
        settings = QSettings()

        # look for directory
        path = QgsProject.instance().homePath()
        if path == "":
            path = settings.value("mask/file_dir", "")
            if path == "":
                path = QDir.homePath()

        drivers = QgsVectorFileWriter.ogrDriverList()
        filterList = []
        filterMap = {}
        for driver in drivers:
            # grrr, driverMetadata is not really consistent
            if driver.driverName == "ESRI Shapefile":
                ext = "shp"
                glob = "*.shp"
            else:
                md = QgsVectorFileWriter.MetaData()
                if QgsVectorFileWriter.driverMetadata(driver.driverName, md):
                    ext = md.ext
                    glob = md.glob
                else:
                    continue

            fn = "%s (%s)" % (driver.longName, glob)
            filterMap[fn] = (driver.driverName, ext, glob)
            filterList += [fn]

        fileFilters = ";;".join(filterList)
        fd = QFileDialog(
            None,
            self.tr("Select a filename to save the mask layer to"),
            path,
            fileFilters,
        )
        save_format_name = self.parameters.file_format
        self.save_format = None
        for k, v in filterMap.items():
            if v[0] == save_format_name:
                self.save_format = v
                fd.selectNameFilter(k)
                break

        def on_filter_selected(ff):
            self.save_format = filterMap[ff]

        fd.filterSelected.connect(on_filter_selected)
        fd.setAcceptMode(QFileDialog.AcceptSave)
        r = fd.exec_()
        if r == 1:
            fn = fd.selectedFiles()[0]
            driver, ext, glob = self.save_format
            if not fn.endswith("." + ext):
                fn += "." + ext

            self.ui.filePath.setText(fn)
            self.ui.formatLbl.setText(self.save_format[0])
            self.parameters.file_format = self.save_format[0]
            self.parameters.file_path = fn
Ejemplo n.º 32
0
    def load_from_file(self):
        file, _ = QFileDialog.getOpenFileName(self, self.tr('Import Event IDs from File'), QDir.homePath(),
                                              'Text Files (*.*)')
        if not file:
            return

        with open(file, 'rt') as f:
            text = '\n'.join(f.readlines())
            self.event_ids_edit.setPlainText('\n'.join(self.parse_multi_input(text)))
 def last_icon_path(cls):
     return cls.get_settings().value('last_icon_path', QDir.homePath(), str)
Ejemplo n.º 34
0
 def outFile(self):
     of = QFileInfo(QFileDialog.getSaveFileName(self, 'Output map file', QDir.homePath(), 'PDF files (*.pdf)'))
     f = of.fileName()
     if f!='':
         self.lineEdit_3.setText(of.absoluteFilePath())
     return f
Ejemplo n.º 35
0
 def last_icon_path(cls):
     return cls.get_settings().value('last_icon_path', QDir.homePath(), str)
Ejemplo n.º 36
0
 def openfilepicker(self, widget):
     startpath = widget.text() or QDir.homePath()
     path = QFileDialog.getExistingDirectory(self.parent(), "", startpath)
     widget.setText(path)