示例#1
0
    def createSpatialIndex(self):
        """ create spatial index for the geometry column """
        if self.table.type != self.table.VectorType:
            QMessageBox.information(
                self, self.tr("DB Manager"),
                self.tr("The selected table has no geometry"))
            return

        res = QMessageBox.question(
            self, self.tr("Create?"),
            self.tr("Create spatial index for field %s?") %
            self.table.geomColumn, QMessageBox.Yes | QMessageBox.No)
        if res != QMessageBox.Yes:
            return

        # TODO: first check whether the index doesn't exist already
        QApplication.setOverrideCursor(Qt.WaitCursor)
        self.aboutToChangeTable.emit()

        try:
            self.table.createSpatialIndex()
            self.populateViews()
        except BaseError as e:
            DlgDbError.showError(e, self)
            return
        finally:
            QApplication.restoreOverrideCursor()
 def okPressed(self):
     self.alg = self.createAlgorithm()
     if self.alg is not None:
         self.close()
     else:
         QMessageBox.warning(self, self.tr('Unable to add algorithm'),
                             self.tr('Wrong or missing parameter values'))
示例#3
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.'))
    def execute(self):
        settings = QSettings()
        lastDir = settings.value('Processing/lastModelsDir', '')
        filename = 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.modelsFolder(), os.path.basename(filename))
            shutil.copyfile(filename, destFilename)
            self.toolbox.updateProvider('model')
示例#5
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.'))
 def execute(self):
     settings = QSettings()
     lastDir = settings.value('Processing/lastScriptsDir', '')
     filename = QFileDialog.getOpenFileName(
         self.toolbox, self.tr('Script files', 'AddScriptFromFileAction'),
         lastDir,
         self.tr('Script files (*.py *.PY)', 'AddScriptFromFileAction'))
     if filename:
         try:
             settings.setValue(
                 'Processing/lastScriptsDir',
                 QFileInfo(filename).absoluteDir().absolutePath())
             script = ScriptAlgorithm(filename)
         except WrongScriptException:
             QMessageBox.warning(
                 self.toolbox,
                 self.tr('Error reading script', 'AddScriptFromFileAction'),
                 self.tr(
                     'The selected file does not contain a valid script',
                     'AddScriptFromFileAction'))
             return
         destFilename = os.path.join(ScriptUtils.scriptsFolder(),
                                     os.path.basename(filename))
         with open(destFilename, 'w') as f:
             f.write(script.script)
         self.toolbox.updateProvider('script')
示例#7
0
    def batchFinished(self):
        self.base.stop()

        if len(self.errors) > 0:
            msg = u"Processing of the following files ended with error: <br><br>" + "<br><br>".join(self.errors)
            QErrorMessage(self).showMessage(msg)

        inDir = self.getInputFileName()
        outDir = self.getOutputFileName()
        if outDir is None or inDir == outDir:
            self.outFiles = self.inFiles

        # load layers managing the render flag to avoid waste of time
        canvas = self.iface.mapCanvas()
        previousRenderFlag = canvas.renderFlag()
        canvas.setRenderFlag(False)
        notCreatedList = []
        for item in self.outFiles:
            fileInfo = QFileInfo(item)
            if fileInfo.exists():
                if self.base.loadCheckBox.isChecked():
                    self.addLayerIntoCanvas(fileInfo)
            else:
                notCreatedList.append(item)
        canvas.setRenderFlag(previousRenderFlag)

        if len(notCreatedList) == 0:
            QMessageBox.information(self, self.tr("Finished"), self.tr("Operation completed."))
        else:
            QMessageBox.warning(self, self.tr("Warning"), self.tr("The following files were not created: \n{0}").format(', '.join(notCreatedList)))
示例#8
0
    def refreshExtent(self):
        files = self.getInputFileNames()
        self.intersectCheck.setEnabled(len(files) > 1)

        if not self.intersectCheck.isChecked():
            self.someValueChanged()
            return

        if len(files) < 2:
            self.intersectCheck.setChecked(False)
            return

        self.extent = self.getIntersectedExtent(files)

        if self.extent is None:
            QMessageBox.warning(
                self, self.tr("Error retrieving the extent"),
                self.
                tr('GDAL was unable to retrieve the extent from any file. \nThe "Use intersected extent" option will be unchecked.'
                   ))
            self.intersectCheck.setChecked(False)
            return

        elif self.extent.isEmpty():
            QMessageBox.warning(
                self, self.tr("Empty extent"),
                self.
                tr('The computed extent is empty. \nDisable the "Use intersected extent" option to have a nonempty output.'
                   ))

        self.someValueChanged()
示例#9
0
    def setParamValues(self):
        if self.mUpdateExistingGroupBox.isChecked():
            fieldName = self.mExistingFieldComboBox.currentText()
        else:
            fieldName = self.mOutputFieldNameLineEdit.text()

        layer = dataobjects.getObjectFromName(self.cmbInputLayer.currentText())

        self.alg.setParameterValue('INPUT_LAYER', layer)
        self.alg.setParameterValue('FIELD_NAME', fieldName)
        self.alg.setParameterValue(
            'FIELD_TYPE', self.mOutputFieldTypeComboBox.currentIndex())
        self.alg.setParameterValue('FIELD_LENGTH',
                                   self.mOutputFieldWidthSpinBox.value())
        self.alg.setParameterValue('FIELD_PRECISION',
                                   self.mOutputFieldPrecisionSpinBox.value())
        self.alg.setParameterValue('NEW_FIELD',
                                   self.mNewFieldGroupBox.isChecked())
        self.alg.setParameterValue('FORMULA', self.builder.expressionText())
        self.alg.setOutputValue('OUTPUT_LAYER',
                                self.leOutputFile.text().strip() or None)

        msg = self.alg.checkParameterValuesBeforeExecuting()
        if msg:
            QMessageBox.warning(self, self.tr('Unable to execute algorithm'),
                                msg)
            return False
        return True
示例#10
0
 def activateAlgorithm(self):
     if self.model.activateAlgorithm(self.element.name):
         self.model.updateModelerView()
     else:
         QMessageBox.warning(None, 'Could not activate Algorithm',
                             'The selected algorithm depends on other currently non-active algorithms.\n'
                             'Activate them them before trying to activate it.')
示例#11
0
    def execute(self):
        settings = QSettings()
        lastDir = settings.value('Processing/lastModelsDir', '')
        filename = 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.modelsFolder(),
                                        os.path.basename(filename))
            shutil.copyfile(filename, destFilename)
            self.toolbox.updateProvider('model')
示例#12
0
    def fetchAvailablePlugins(self, reloadMode):
        """ Fetch plugins from all enabled repositories."""
        """  reloadMode = true:  Fully refresh data from QSettings to mRepositories  """
        """  reloadMode = false: Fetch unready repositories only """
        QApplication.setOverrideCursor(Qt.WaitCursor)

        if reloadMode:
            repositories.load()
            plugins.clearRepoCache()
            plugins.getAllInstalled()

        for key in repositories.allEnabled():
            if reloadMode or repositories.all()[key]["state"] == 3:  # if state = 3 (error or not fetched yet), try to fetch once again
                repositories.requestFetching(key)

        if repositories.fetchingInProgress():
            fetchDlg = QgsPluginInstallerFetchingDialog(iface.mainWindow())
            fetchDlg.exec_()
            del fetchDlg
            for key in repositories.all():
                repositories.killConnection(key)

        QApplication.restoreOverrideCursor()

        # display error messages for every unavailable reposioty, unless Shift pressed nor all repositories are unavailable
        keepQuiet = QgsApplication.keyboardModifiers() == Qt.KeyboardModifiers(Qt.ShiftModifier)
        if repositories.allUnavailable() and repositories.allUnavailable() != repositories.allEnabled():
            for key in repositories.allUnavailable():
                if not keepQuiet:
                    QMessageBox.warning(iface.mainWindow(), self.tr("QGIS Python Plugin Installer"), self.tr("Error reading repository:") + " " + key + "\n\n" + repositories.all()[key]["error"])
                if QgsApplication.keyboardModifiers() == Qt.KeyboardModifiers(Qt.ShiftModifier):
                    keepQuiet = True
        # finally, rebuild plugins from the caches
        plugins.rebuild()
示例#13
0
 def okPressed(self):
     self.alg = self.createAlgorithm()
     if self.alg is not None:
         self.close()
     else:
         QMessageBox.warning(self, self.tr('Unable to add algorithm'),
                             self.tr('Wrong or missing parameter values'))
示例#14
0
    def add_columns(self):
        if self.ui.columns.currentIndex() <= 0:
            return
        ag = self.ui.columns.currentText()
        if self.evt.focus == "where":  # in where section
            if ag in self.col_where:  # column already called in where section
                response = QMessageBox.question(self, "Column already used in WHERE clause", "Do you want to add column %s again?" % ag, QMessageBox.Yes | QMessageBox.No)
                if response == QMessageBox.No:
                    self.ui.columns.setCurrentIndex(0)
                    return
            self.ui.where.insertPlainText(ag)
            self.col_where.append(ag)
        elif self.evt.focus == "col":
            if ag in self.col_col:  # column already called in col section
                response = QMessageBox.question(self, "Column already used in COLUMNS section", "Do you want to add column %s again?" % ag, QMessageBox.Yes | QMessageBox.No)
                if response == QMessageBox.No:
                    self.ui.columns.setCurrentIndex(0)
                    return
            if len(self.ui.col.toPlainText().strip()) > 0:
                self.ui.col.insertPlainText(",\n" + ag)
            else:
                self.ui.col.insertPlainText(ag)
            self.col_col.append(ag)
        elif self.evt.focus == "group":
            if len(self.ui.group.toPlainText().strip()) > 0:
                self.ui.group.insertPlainText(", " + ag)
            else:
                self.ui.group.insertPlainText(ag)
        elif self.evt.focus == "order":
            if len(self.ui.order.toPlainText().strip()) > 0:
                self.ui.order.insertPlainText(", " + ag)
            else:
                self.ui.order.insertPlainText(ag)

        self.ui.columns.setCurrentIndex(0)
示例#15
0
    def setParamValues(self):
        if self.mUpdateExistingGroupBox.isChecked():
            fieldName = self.mExistingFieldComboBox.currentText()
        else:
            fieldName = self.mOutputFieldNameLineEdit.text()

        layer = dataobjects.getObjectFromName(self.cmbInputLayer.currentText())

        self.alg.setParameterValue('INPUT_LAYER', layer)
        self.alg.setParameterValue('FIELD_NAME', fieldName)
        self.alg.setParameterValue('FIELD_TYPE',
                                   self.mOutputFieldTypeComboBox.currentIndex())
        self.alg.setParameterValue('FIELD_LENGTH',
                                   self.mOutputFieldWidthSpinBox.value())
        self.alg.setParameterValue('FIELD_PRECISION',
                                   self.mOutputFieldPrecisionSpinBox.value())
        self.alg.setParameterValue('NEW_FIELD',
                                   self.mNewFieldGroupBox.isChecked())
        self.alg.setParameterValue('FORMULA', self.builder.expressionText())
        self.alg.setOutputValue('OUTPUT_LAYER', self.leOutputFile.text().strip() or None)

        msg = self.alg.checkParameterValuesBeforeExecuting()
        if msg:
            QMessageBox.warning(
                self, self.tr('Unable to execute algorithm'), msg)
            return False
        return True
示例#16
0
    def createGeomColumn(self):
        """ first check whether everything's fine """
        if self.editName.text() == "":
            QMessageBox.critical(self, self.tr("DB Manager"),
                                 self.tr("field name must not be empty"))
            return

        name = self.editName.text()
        geom_type = self.GEOM_TYPES[self.cboType.currentIndex()]
        dim = self.spinDim.value()
        try:
            srid = int(self.editSrid.text())
        except ValueError:
            srid = -1
        createSpatialIndex = False

        # now create the geometry column
        QApplication.setOverrideCursor(Qt.WaitCursor)
        try:
            self.table.addGeometryColumn(name, geom_type, srid, dim,
                                         createSpatialIndex)
        except DbError as e:
            DlgDbError.showError(e, self)
            return
        finally:
            QApplication.restoreOverrideCursor()

        self.accept()
示例#17
0
    def createGeomColumn(self):
        """ first check whether everything's fine """
        if self.editName.text() == "":
            QMessageBox.critical(self, self.tr("DB Manager"), self.tr("field name must not be empty"))
            return

        name = self.editName.text()
        geom_type = self.GEOM_TYPES[self.cboType.currentIndex()]
        dim = self.spinDim.value()
        try:
            srid = int(self.editSrid.text())
        except ValueError:
            srid = -1
        createSpatialIndex = False

        # now create the geometry column
        QApplication.setOverrideCursor(Qt.WaitCursor)
        try:
            self.table.addGeometryColumn(name, geom_type, srid, dim, createSpatialIndex)
        except DbError as e:
            DlgDbError.showError(e, self)
            return
        finally:
            QApplication.restoreOverrideCursor()

        self.accept()
示例#18
0
 def currentColumn(self):
     """ returns row index of selected column """
     sel = self.viewFields.selectionModel()
     indexes = sel.selectedRows()
     if len(indexes) == 0:
         QMessageBox.information(self, self.tr("DB Manager"), self.tr("nothing selected"))
         return -1
     return indexes[0].row()
示例#19
0
 def activateAlgorithm(self):
     if self.model.activateAlgorithm(self.element.name):
         self.model.updateModelerView()
     else:
         QMessageBox.warning(
             None, 'Could not activate Algorithm',
             'The selected algorithm depends on other currently non-active algorithms.\n'
             'Activate them them before trying to activate it.')
示例#20
0
文件: plugin.py 项目: boggins/QGIS
    def runAction(self, action):
        action = unicode(action)

        if action.startswith("rows/"):
            if action == "rows/count":
                self.refreshRowCount()
                return True

        elif action.startswith("triggers/"):
            parts = action.split('/')
            trigger_action = parts[1]

            msg = QApplication.translate("DBManagerPlugin", "Do you want to %s all triggers?") % trigger_action
            QApplication.restoreOverrideCursor()
            try:
                if QMessageBox.question(None, QApplication.translate("DBManagerPlugin", "Table triggers"), msg,
                                        QMessageBox.Yes | QMessageBox.No) == QMessageBox.No:
                    return False
            finally:
                QApplication.setOverrideCursor(Qt.WaitCursor)

            if trigger_action == "enable" or trigger_action == "disable":
                enable = trigger_action == "enable"
                self.emitAboutToChange()
                self.database().connector.enableAllTableTriggers(enable, (self.schemaName(), self.name))
                self.refreshTriggers()
                return True

        elif action.startswith("trigger/"):
            parts = action.split('/')
            trigger_name = parts[1]
            trigger_action = parts[2]

            msg = QApplication.translate("DBManagerPlugin", "Do you want to %s trigger %s?") % (
                trigger_action, trigger_name)
            QApplication.restoreOverrideCursor()
            try:
                if QMessageBox.question(None, QApplication.translate("DBManagerPlugin", "Table trigger"), msg,
                                        QMessageBox.Yes | QMessageBox.No) == QMessageBox.No:
                    return False
            finally:
                QApplication.setOverrideCursor(Qt.WaitCursor)

            if trigger_action == "delete":
                self.emitAboutToChange()
                self.database().connector.deleteTableTrigger(trigger_name, (self.schemaName(), self.name))
                self.refreshTriggers()
                return True

            elif trigger_action == "enable" or trigger_action == "disable":
                enable = trigger_action == "enable"
                self.emitAboutToChange()
                self.database().connector.enableTableTrigger(trigger_name, enable, (self.schemaName(), self.name))
                self.refreshTriggers()
                return True

        return False
示例#21
0
 def currentColumn(self):
     """ returns row index of selected column """
     sel = self.viewFields.selectionModel()
     indexes = sel.selectedRows()
     if len(indexes) == 0:
         QMessageBox.information(self, self.tr("DB Manager"),
                                 self.tr("nothing selected"))
         return -1
     return indexes[0].row()
示例#22
0
文件: plugin.py 项目: ravirbdgtc/QGIS
    def runAction(self, action):
        action = unicode(action)

        if action.startswith("rows/"):
            if action == "rows/count":
                self.refreshRowCount()
                return True

        elif action.startswith("triggers/"):
            parts = action.split('/')
            trigger_action = parts[1]

            msg = QApplication.translate("DBManagerPlugin", "Do you want to %s all triggers?") % trigger_action
            QApplication.restoreOverrideCursor()
            try:
                if QMessageBox.question(None, QApplication.translate("DBManagerPlugin", "Table triggers"), msg,
                                        QMessageBox.Yes | QMessageBox.No) == QMessageBox.No:
                    return False
            finally:
                QApplication.setOverrideCursor(Qt.WaitCursor)

            if trigger_action == "enable" or trigger_action == "disable":
                enable = trigger_action == "enable"
                self.aboutToChange.emit()
                self.database().connector.enableAllTableTriggers(enable, (self.schemaName(), self.name))
                self.refreshTriggers()
                return True

        elif action.startswith("trigger/"):
            parts = action.split('/')
            trigger_name = parts[1]
            trigger_action = parts[2]

            msg = QApplication.translate("DBManagerPlugin", "Do you want to %s trigger %s?") % (
                trigger_action, trigger_name)
            QApplication.restoreOverrideCursor()
            try:
                if QMessageBox.question(None, QApplication.translate("DBManagerPlugin", "Table trigger"), msg,
                                        QMessageBox.Yes | QMessageBox.No) == QMessageBox.No:
                    return False
            finally:
                QApplication.setOverrideCursor(Qt.WaitCursor)

            if trigger_action == "delete":
                self.aboutToChange.emit()
                self.database().connector.deleteTableTrigger(trigger_name, (self.schemaName(), self.name))
                self.refreshTriggers()
                return True

            elif trigger_action == "enable" or trigger_action == "disable":
                enable = trigger_action == "enable"
                self.aboutToChange.emit()
                self.database().connector.enableTableTrigger(trigger_name, enable, (self.schemaName(), self.name))
                self.refreshTriggers()
                return True

        return False
示例#23
0
    def deleteField(self):
        """ delete selected field """
        row = self.selectedField()
        if row is None:
            QMessageBox.information(self, self.tr("DB Manager"), self.tr("no field selected"))
        else:
            self.fields.model().removeRows(row, 1)

        self.updatePkeyCombo()
示例#24
0
 def accept(self):
     try:
         self.value = float(eval(unicode(self.leFormula.text())))
         if self.isInteger:
             self.value = int(round(self.value))
         QDialog.accept(self)
     except:
         QMessageBox.critical(self, self.tr('Wrong expression'),
                              self.tr('The expression entered is not correct'))
示例#25
0
    def createTable(self):
        """ create table with chosen fields, optionally add a geometry column """
        if not self.hasSchemas:
            schema = None
        else:
            schema = unicode(self.cboSchema.currentText())
            if len(schema) == 0:
                QMessageBox.information(self, self.tr("DB Manager"), self.tr("select schema!"))
                return

        table = unicode(self.editName.text())
        if len(table) == 0:
            QMessageBox.information(self, self.tr("DB Manager"), self.tr("enter table name!"))
            return

        m = self.fields.model()
        if m.rowCount() == 0:
            QMessageBox.information(self, self.tr("DB Manager"), self.tr("add some fields!"))
            return

        useGeomColumn = self.chkGeomColumn.isChecked()
        if useGeomColumn:
            geomColumn = unicode(self.editGeomColumn.text())
            if len(geomColumn) == 0:
                QMessageBox.information(self, self.tr("DB Manager"), self.tr("set geometry column name"))
                return

            geomType = self.GEOM_TYPES[self.cboGeomType.currentIndex()]
            geomDim = self.spinGeomDim.value()
            try:
                geomSrid = int(self.editGeomSrid.text())
            except ValueError:
                geomSrid = 0
            useSpatialIndex = self.chkSpatialIndex.isChecked()

        flds = m.getFields()
        pk_index = self.cboPrimaryKey.currentIndex()
        if pk_index >= 0:
            flds[pk_index].primaryKey = True

        # commit to DB
        QApplication.setOverrideCursor(Qt.WaitCursor)
        try:
            if not useGeomColumn:
                self.db.createTable(table, flds, schema)
            else:
                geom = geomColumn, geomType, geomSrid, geomDim, useSpatialIndex
                self.db.createVectorTable(table, flds, geom, schema)

        except (ConnectionError, DbError) as e:
            DlgDbError.showError(e, self)
            return

        finally:
            QApplication.restoreOverrideCursor()

        QMessageBox.information(self, self.tr("Good"), self.tr("everything went fine"))
示例#26
0
 def execute(self):
     f = os.path.join(FusionUtils.FusionPath(), 'pdq.exe')
     if os.path.exists(f):
         subprocess.Popen(f)
     else:
         QMessageBox.critical(None,
                              self.tr('Unable to open viewer'),
                              self.tr('The current Fusion folder does not contain the '
                                      'viewer executable.\nPlease check the configuration '
                                      'in the Processing settings dialog.'))
示例#27
0
 def execute(self):
     f = os.path.join(FusionUtils.FusionPath(), 'pdq.exe')
     if os.path.exists(f):
         subprocess.Popen(f)
     else:
         QMessageBox.critical(
             None, self.tr('Unable to open viewer'),
             self.tr('The current Fusion folder does not contain the '
                     'viewer executable.\nPlease check the configuration '
                     'in the Processing settings dialog.'))
示例#28
0
    def finish(self):
        for count, alg in enumerate(self.algs):
            self.loadHTMLResults(alg, count)

        self.createSummaryTable()
        QApplication.restoreOverrideCursor()

        self.mainWidget.setEnabled(True)
        QMessageBox.information(self, self.tr('Batch processing'),
                                self.tr('Batch processing completed'))
示例#29
0
 def accept(self):
     try:
         self.value = float(eval(unicode(self.leFormula.text())))
         if self.isInteger:
             self.value = int(round(self.value))
         QDialog.accept(self)
     except:
         QMessageBox.critical(
             self, self.tr('Wrong expression'),
             self.tr('The expression entered is not correct'))
示例#30
0
    def finish(self):
        for count, alg in enumerate(self.algs):
            self.loadHTMLResults(alg, count)

        self.createSummaryTable()
        QApplication.restoreOverrideCursor()

        self.mainWidget.setEnabled(True)
        QMessageBox.information(self, self.tr('Batch processing'),
                                self.tr('Batch processing completed'))
示例#31
0
 def activateProvider(self, providerName):
     name = 'ACTIVATE_' + providerName.upper().replace(' ', '_')
     ProcessingConfig.setSettingValue(name, True)
     self.fillTree()
     self.textChanged()
     self.showDisabled()
     provider = Processing.getProviderFromName(providerName)
     if not provider.canBeActivated():
         QMessageBox.warning(self, "Activate provider",
                             "The provider has been activated, but it might need additional configuration.")
示例#32
0
    def deleteField(self):
        """ delete selected field """
        row = self.selectedField()
        if row is None:
            QMessageBox.information(self, self.tr("DB Manager"),
                                    self.tr("no field selected"))
        else:
            self.fields.model().removeRows(row, 1)

        self.updatePkeyCombo()
示例#33
0
    def onOK(self):
        """ first check whether everything's fine """
        fld = self.getField(True)  # don't change the original copy
        if fld.name == "":
            QMessageBox.critical(self, self.tr("DB Manager"), self.tr("field name must not be empty"))
            return
        if fld.dataType == "":
            QMessageBox.critical(self, self.tr("DB Manager"), self.tr("field type must not be empty"))
            return

        self.accept()
示例#34
0
    def importLayer(self, layerType, providerKey, layerName, uriString,
                    parent):
        global isImportVectorAvail

        if not isImportVectorAvail:
            return False

        if layerType == 'raster':
            return False  # not implemented yet
            inLayer = QgsRasterLayer(uriString, layerName, providerKey)
        else:
            inLayer = QgsVectorLayer(uriString, layerName, providerKey)

        if not inLayer.isValid():
            # invalid layer
            QMessageBox.warning(
                None, self.tr("Invalid layer"),
                self.tr("Unable to load the layer %s") % inLayer.name())
            return False

        # retrieve information about the new table's db and schema
        outItem = parent.internalPointer()
        outObj = outItem.getItemData()
        outDb = outObj.database()
        outSchema = None
        if isinstance(outItem, SchemaItem):
            outSchema = outObj
        elif isinstance(outItem, TableItem):
            outSchema = outObj.schema()

        # toIndex will point to the parent item of the new table
        toIndex = parent
        if isinstance(toIndex.internalPointer(), TableItem):
            toIndex = toIndex.parent()

        if inLayer.type() == inLayer.VectorLayer:
            # create the output uri
            schema = outSchema.name if outDb.schemas(
            ) is not None and outSchema is not None else ""
            pkCol = geomCol = ""

            # default pk and geom field name value
            if providerKey in ['postgres', 'spatialite']:
                inUri = QgsDataSourceURI(inLayer.source())
                pkCol = inUri.keyColumn()
                geomCol = inUri.geometryColumn()

            outUri = outDb.uri()
            outUri.setDataSource(schema, layerName, geomCol, "", pkCol)

            self.importVector.emit(inLayer, outDb, outUri, toIndex)
            return True

        return False
示例#35
0
 def setLayer(self, layer):
     self.model.setLayer(layer)
     if self.model.rowCount() == 0:
         self.on_resetButton_clicked()
     else:
         dlg = QMessageBox(self)
         dlg.setText("Do you want to reset the field mapping?")
         dlg.setStandardButtons(
             QMessageBox.StandardButtons(QMessageBox.Yes + QMessageBox.No))
         dlg.setDefaultButton(QMessageBox.No)
         if dlg.exec_() == QMessageBox.Yes:
             self.on_resetButton_clicked()
示例#36
0
 def okPressed(self):
     if self.textTableName.text().strip() == "":
         self.textTableName.setStyleSheet("QLineEdit{background: yellow}")
         return
     item = self.treeConnections.currentItem()
     if isinstance(item, ConnectionItem):
         QMessageBox.warning(self, "Wrong selection", "Select a schema item in the tree")
         return
     self.schema = item.text(0)
     self.table = self.textTableName.text().strip()
     self.connection = item.parent().text(0)
     self.close()
示例#37
0
    def runModel(self):
        if len(self.alg.algs) == 0:
            QMessageBox.warning(self, self.tr('Empty model'),
                                self.tr("Model doesn't contains any algorithms and/or "
                                        "parameters and can't be executed"))
            return

        if self.alg.provider is None:
            # Might happen if model is opened from modeler dialog
            self.alg.provider = ModelerUtils.providers['model']
        alg = self.alg.getCopy()
        dlg = AlgorithmDialog(alg)
        dlg.exec_()
示例#38
0
 def okPressed(self):
     if self.textTableName.text().strip() == "":
         self.textTableName.setStyleSheet("QLineEdit{background: yellow}")
         return
     item = self.treeConnections.currentItem()
     if isinstance(item, ConnectionItem):
         QMessageBox.warning(self, "Wrong selection",
                             "Select a schema item in the tree")
         return
     self.schema = item.text(0)
     self.table = self.textTableName.text().strip()
     self.connection = item.parent().text(0)
     self.close()
示例#39
0
    def checkLayer(self):
        layerList = []

        layerMap = QgsMapLayerRegistry.instance().mapLayers()
        for name, layer in layerMap.iteritems():
            if layer.type() == QgsMapLayer.RasterLayer:
                layerList.append(unicode(layer.source()))

        if unicode(self.inputFileEdit.text()) in layerList:
            QMessageBox.warning(self, self.tr("Assign projection"), self.tr("This raster already found in map canvas"))
            return

        self.onRun()
示例#40
0
    def onOK(self):
        """ first check whether everything's fine """
        fld = self.getField(True)  # don't change the original copy
        if fld.name == "":
            QMessageBox.critical(self, self.tr("DB Manager"),
                                 self.tr("field name must not be empty"))
            return
        if fld.dataType == "":
            QMessageBox.critical(self, self.tr("DB Manager"),
                                 self.tr("field type must not be empty"))
            return

        self.accept()
示例#41
0
    def runModel(self):
        if len(self.alg.algs) == 0:
            QMessageBox.warning(
                self, self.tr('Empty model'),
                self.tr("Model doesn't contains any algorithms and/or "
                        "parameters and can't be executed"))
            return

        if self.alg.provider is None:
            # Might happen if model is opened from modeler dialog
            self.alg.provider = ModelerUtils.providers['model']
        alg = self.alg.getCopy()
        dlg = AlgorithmDialog(alg)
        dlg.exec_()
示例#42
0
    def importLayer(self, layerType, providerKey, layerName, uriString, parent):
        global isImportVectorAvail

        if not isImportVectorAvail:
            return False

        if layerType == 'raster':
            return False  # not implemented yet
            inLayer = QgsRasterLayer(uriString, layerName, providerKey)
        else:
            inLayer = QgsVectorLayer(uriString, layerName, providerKey)

        if not inLayer.isValid():
            # invalid layer
            QMessageBox.warning(None, self.tr("Invalid layer"), self.tr("Unable to load the layer %s") % inLayer.name())
            return False

        # retrieve information about the new table's db and schema
        outItem = parent.internalPointer()
        outObj = outItem.getItemData()
        outDb = outObj.database()
        outSchema = None
        if isinstance(outItem, SchemaItem):
            outSchema = outObj
        elif isinstance(outItem, TableItem):
            outSchema = outObj.schema()

        # toIndex will point to the parent item of the new table
        toIndex = parent
        if isinstance(toIndex.internalPointer(), TableItem):
            toIndex = toIndex.parent()

        if inLayer.type() == inLayer.VectorLayer:
            # create the output uri
            schema = outSchema.name if outDb.schemas() is not None and outSchema is not None else ""
            pkCol = geomCol = ""

            # default pk and geom field name value
            if providerKey in ['postgres', 'spatialite']:
                inUri = QgsDataSourceURI(inLayer.source())
                pkCol = inUri.keyColumn()
                geomCol = inUri.geometryColumn()

            outUri = outDb.uri()
            outUri.setDataSource(schema, layerName, geomCol, "", pkCol)

            self.importVector.emit(inLayer, outDb, outUri, toIndex)
            return True

        return False
示例#43
0
    def finished(self):
        outFn = self.getOutputFileName()
        if self.needOverwrite:
            oldFile = QFile(outFn)
            newFile = QFile(self.tempFile)
            if oldFile.remove():
                newFile.rename(outFn)

        fileInfo = QFileInfo(outFn)
        if fileInfo.exists():
            if self.base.loadCheckBox.isChecked():
                self.addLayerIntoCanvas(fileInfo)
            QMessageBox.information(self, self.tr("Finished"), self.tr("Processing completed."))
        else:
            QMessageBox.warning(self, self.tr("Warning"), self.tr("{0} not created.").format(outFn))
示例#44
0
    def exportAsPython(self):
        filename = unicode(QFileDialog.getSaveFileName(self,
                                                       self.tr('Save Model As Python Script'), '',
                                                       self.tr('Python files (*.py *.PY)')))
        if not filename:
            return

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

        text = self.alg.toPython()
        with codecs.open(filename, 'w', encoding='utf-8') as fout:
            fout.write(text)
        QMessageBox.information(self, self.tr('Model exported'),
                                self.tr('Model was correctly exported.'))
示例#45
0
 def removeElement(self):
     if isinstance(self.element, ModelerParameter):
         if not self.model.removeParameter(self.element.param.name):
             QMessageBox.warning(None, 'Could not remove element',
                                 'Other elements depend on the selected one.\n'
                                 'Remove them before trying to remove it.')
         else:
             self.model.updateModelerView()
     elif isinstance(self.element, Algorithm):
         if not self.model.removeAlgorithm(self.element.name):
             QMessageBox.warning(None, 'Could not remove element',
                                 'Other elements depend on the selected one.\n'
                                 'Remove them before trying to remove it.')
         else:
             self.model.updateModelerView()
示例#46
0
 def accept(self):
     if not self.preloadAPI.isChecked() and \
        not self.groupBoxPreparedAPI.isChecked():
         if self.tableWidget.rowCount() == 0:
             QMessageBox.information(self, self.tr("Warning!"),
                                     self.tr('Please specify API file or check "Use preloaded API files"'))
             return
     if self.groupBoxPreparedAPI.isChecked() and \
        not self.lineEdit.text():
         QMessageBox.information(self, self.tr("Warning!"),
                                 self.tr('The APIs file was not compiled, click on "Compile APIs..."'))
         return
     self.saveSettings()
     self.listPath = []
     QDialog.accept(self)
示例#47
0
    def runAction(self, action):
        action = unicode(action)

        if action.startswith("vacuumanalyze/"):
            if action == "vacuumanalyze/run":
                self.runVacuumAnalyze()
                return True

        elif action.startswith("rule/"):
            parts = action.split('/')
            rule_name = parts[1]
            rule_action = parts[2]

            msg = u"Do you want to %s rule %s?" % (rule_action, rule_name)

            QApplication.restoreOverrideCursor()

            try:
                if QMessageBox.question(None, self.tr("Table rule"), msg,
                                        QMessageBox.Yes | QMessageBox.No) == QMessageBox.No:
                    return False
            finally:
                QApplication.setOverrideCursor(Qt.WaitCursor)

            if rule_action == "delete":
                self.aboutToChange.emit()
                self.database().connector.deleteTableRule(rule_name, (self.schemaName(), self.name))
                self.refreshRules()
                return True

        return Table.runAction(self, action)
示例#48
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.scriptsFolder()
            filterName = self.tr('Python scripts (*.py)')
        elif self.algType == self.SCRIPT_R:
            scriptDir = RUtils.RScriptsFolder()
            filterName = self.tr('Processing R script (*.rsx)')

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

        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()
示例#49
0
文件: plugin.py 项目: boggins/QGIS
    def runAction(self, action):
        action = unicode(action)

        if action.startswith("spatialindex/"):
            parts = action.split('/')
            spatialIndex_action = parts[1]

            msg = QApplication.translate("DBManagerPlugin", "Do you want to %s spatial index for field %s?") % (
                spatialIndex_action, self.geomColumn)
            QApplication.restoreOverrideCursor()
            try:
                if QMessageBox.question(None, QApplication.translate("DBManagerPlugin", "Spatial Index"), msg,
                                        QMessageBox.Yes | QMessageBox.No) == QMessageBox.No:
                    return False
            finally:
                QApplication.setOverrideCursor(Qt.WaitCursor)

            if spatialIndex_action == "create":
                self.createSpatialIndex()
                return True
            elif spatialIndex_action == "delete":
                self.deleteSpatialIndex()
                return True

        if action.startswith("extent/"):
            if action == "extent/get":
                self.refreshTableExtent()
                return True

            if action == "extent/estimated/get":
                self.refreshTableEstimatedExtent()
                return True

        return Table.runAction(self, action)
示例#50
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.scriptsFolder()
            filterName = self.tr('Python scripts (*.py)')
        elif self.algType == self.SCRIPT_R:
            scriptDir = RUtils.RScriptsFolder()
            filterName = self.tr('Processing R script (*.rsx)')

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

        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()
示例#51
0
    def onOK(self):
        # execute and commit the code
        QApplication.setOverrideCursor(Qt.WaitCursor)
        try:
            sql = u"\n".join(self.updateSql())
            self.db.connector._execute_and_commit(sql)

        except BaseError as e:
            DlgDbError.showError(e, self)
            return

        finally:
            QApplication.restoreOverrideCursor()

        QMessageBox.information(self, "good!", "everything went fine!")
        self.accept()
示例#52
0
    def accept(self):
        for setting in self.items.keys():
            if isinstance(setting.value, bool):
                setting.setValue(self.items[setting].checkState() == Qt.Checked)
            else:
                try:
                    setting.setValue(unicode(self.items[setting].text()))
                except ValueError as e:
                    QMessageBox.warning(self, self.tr('Wrong value'),
                                        self.tr('Wrong value for parameter "%s":\n\n%s' % (setting.description, unicode(e))))
                    return
            setting.save()
        Processing.updateAlgsList()
        updateMenus()

        QDialog.accept(self)
示例#53
0
    def load(self, items):
        """load connections"""

        self.settings.beginGroup('/MetaSearch/')
        keys = self.settings.childGroups()
        self.settings.endGroup()

        exml = etree.parse(self.filename).getroot()

        for csw in exml.findall('csw'):
            conn_name = csw.attrib.get('name')

            # process only selected connections
            if conn_name not in items:
                continue

            # check for duplicates
            if conn_name in keys:
                label = self.tr('File %s exists. Overwrite?') % conn_name
                res = QMessageBox.warning(self, self.tr('Loading Connections'),
                                          label,
                                          QMessageBox.Yes | QMessageBox.No)
                if res != QMessageBox.Yes:
                    continue

            # no dups detected or overwrite is allowed
            url = '/MetaSearch/%s/url' % conn_name
            self.settings.setValue(url, csw.attrib.get('url'))