コード例 #1
0
ファイル: ScriptEditorDialog.py プロジェクト: ravirbdgtc/QGIS
    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()
コード例 #2
0
 def showSnippets(self, evt):
     popupmenu = QMenu()
     for name, snippet in self.snippets.iteritems():
         action = QAction(self.tr(name), self.btnSnippets)
         action.triggered[()].connect(lambda snippet=snippet: self.editor.insert(snippet))
         popupmenu.addAction(action)
     popupmenu.exec_(QCursor.pos())
コード例 #3
0
ファイル: ScriptEditorDialog.py プロジェクト: ravirbdgtc/QGIS
 def showSnippets(self, evt):
     popupmenu = QMenu()
     for name, snippet in self.snippets.iteritems():
         action = QAction(self.tr(name), self.btnSnippets)
         action.triggered[(
         )].connect(lambda snippet=snippet: self.editor.insert(snippet))
         popupmenu.addAction(action)
     popupmenu.exec_(QCursor.pos())
コード例 #4
0
 def updateAlgsList():
     """Call this method when there has been any change that
     requires the list of algorithms to be created again from
     algorithm providers.
     """
     QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
     Processing.loadFromProviders()
     Processing.fireAlgsListHasChanged()
     QApplication.restoreOverrideCursor()
コード例 #5
0
    def navigate(self):
        """manage navigation / paging"""

        caller = self.sender().objectName()

        if caller == 'btnFirst':
            self.startfrom = 0
        elif caller == 'btnLast':
            self.startfrom = self.catalog.results['matches'] - self.maxrecords
        elif caller == 'btnNext':
            self.startfrom += self.maxrecords
            if self.startfrom >= self.catalog.results["matches"]:
                msg = self.tr('End of results. Go to start?')
                res = QMessageBox.information(self, self.tr('Navigation'),
                                              msg,
                                              (QMessageBox.Ok |
                                               QMessageBox.Cancel))
                if res == QMessageBox.Ok:
                    self.startfrom = 0
                else:
                    return
        elif caller == "btnPrev":
            self.startfrom -= self.maxrecords
            if self.startfrom <= 0:
                msg = self.tr('Start of results. Go to end?')
                res = QMessageBox.information(self, self.tr('Navigation'),
                                              msg,
                                              (QMessageBox.Ok |
                                               QMessageBox.Cancel))
                if res == QMessageBox.Ok:
                    self.startfrom = (self.catalog.results['matches'] -
                                      self.maxrecords)
                else:
                    return

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

        try:
            self.catalog.getrecords2(constraints=self.constraints,
                                     maxrecords=self.maxrecords,
                                     startposition=self.startfrom, esn='full')
        except ExceptionReport as err:
            QApplication.restoreOverrideCursor()
            QMessageBox.warning(self, self.tr('Search error'),
                                self.tr('Search error: %s') % err)
            return
        except Exception as err:
            QApplication.restoreOverrideCursor()
            QMessageBox.warning(self, self.tr('Connection error'),
                                self.tr('Connection error: %s') % err)
            return

        QApplication.restoreOverrideCursor()

        self.display_results()
コード例 #6
0
ファイル: dlg_sql_window.py プロジェクト: ravirbdgtc/QGIS
    def loadSqlLayer(self):
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        try:
            layer = self._getSqlLayer(self.filter)
            if layer is None:
                return

            from qgis.core import QgsMapLayerRegistry
            QgsMapLayerRegistry.instance().addMapLayers([layer], True)
        finally:
            QApplication.restoreOverrideCursor()
コード例 #7
0
    def grabHTTP(self, url, loadFunction, arguments=None):
        """Grab distant content via QGIS internal classes and QtNetwork."""
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        request = QUrl(url)
        reply = self.manager.get(QNetworkRequest(request))
        if arguments:
            reply.finished.connect(partial(loadFunction, reply, arguments))
        else:
            reply.finished.connect(partial(loadFunction, reply))

        while not reply.isFinished():
            QCoreApplication.processEvents()
コード例 #8
0
ファイル: dlg_sql_window.py プロジェクト: ravirbdgtc/QGIS
    def fillColumnCombos(self):
        query = self._getSqlQuery()
        if query == "":
            return

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

        # remove a trailing ';' from query if present
        if query.strip().endswith(';'):
            query = query.strip()[:-1]

        # get all the columns
        cols = []
        quotedCols = []
        connector = self.db.connector
        if self.aliasSubQuery:
            # get a new alias
            aliasIndex = 0
            while True:
                alias = "_subQuery__%d" % aliasIndex
                escaped = re.compile('\\b("?)' + re.escape(alias) + '\\1\\b')
                if not escaped.search(query):
                    break
                aliasIndex += 1

            sql = u"SELECT * FROM (%s\n) AS %s LIMIT 0" % (
                unicode(query), connector.quoteId(alias))
        else:
            sql = u"SELECT * FROM (%s\n) WHERE 1=0" % unicode(query)

        c = None
        try:
            c = connector._execute(None, sql)
            cols = connector._get_cursor_columns(c)
            for col in cols:
                quotedCols.append(connector.quoteId(col))

        except BaseError as e:
            QApplication.restoreOverrideCursor()
            DlgDbError.showError(e, self)
            self.uniqueModel.clear()
            self.geomCombo.clear()
            return

        finally:
            if c:
                c.close()
                del c

        self.setColumnCombos(cols, quotedCols)

        QApplication.restoreOverrideCursor()
コード例 #9
0
ファイル: layer_preview.py プロジェクト: ravirbdgtc/QGIS
    def _loadTablePreview(self, table, limit=False):
        """ if has geometry column load to map canvas """
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        self.setRenderFlag(False)
        vl = None

        if table and table.geomType:
            # limit the query result if required
            if limit and table.rowCount > 1000:
                uniqueField = table.getValidQGisUniqueFields(True)
                if uniqueField is None:
                    self.parent.tabs.setCurrentWidget(self.parent.info)
                    self.parent.infoBar.pushMessage(
                        QApplication.translate(
                            "DBManagerPlugin",
                            "Unable to find a valid unique field"),
                        QgsMessageBar.WARNING,
                        self.parent.iface.messageTimeout())
                    return

                uri = table.database().uri()
                uri.setDataSource(
                    "", u"(SELECT * FROM %s LIMIT 1000)" % table.quotedName(),
                    table.geomColumn, "", uniqueField.name)
                provider = table.database().dbplugin().providerName()
                vl = QgsVectorLayer(uri.uri(False), table.name, provider)
            else:
                vl = table.toMapLayer()

            if not vl.isValid():
                vl.deleteLater()
                vl = None

        # remove old layer (if any) and set new
        if self.currentLayer:
            QgsMapLayerRegistry.instance().removeMapLayers(
                [self.currentLayer.id()])

        if vl:
            self.setLayerSet([QgsMapCanvasLayer(vl)])
            QgsMapLayerRegistry.instance().addMapLayers([vl], False)
            self.zoomToFullExtent()
        else:
            self.setLayerSet([])

        self.currentLayer = vl

        self.setRenderFlag(True)
        QApplication.restoreOverrideCursor()
コード例 #10
0
ファイル: table_viewer.py プロジェクト: ravirbdgtc/QGIS
    def _loadTableData(self, table):
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        try:
            # set the new model
            self.setModel(table.tableDataModel(self))

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

        else:
            self.update()

        finally:
            QApplication.restoreOverrideCursor()
コード例 #11
0
    def showPopupMenu(self):
        popupmenu = QMenu()

        if not (isinstance(self.param, ParameterMultipleInput) and
                self.param.datatype == ParameterMultipleInput.TYPE_FILE):
            selectLayerAction = QAction(
                self.tr('Select from open layers'), self.pushButton)
            selectLayerAction.triggered.connect(self.showLayerSelectionDialog)
            popupmenu.addAction(selectLayerAction)

        selectFileAction = QAction(
            self.tr('Select from filesystem'), self.pushButton)
        selectFileAction.triggered.connect(self.showFileSelectionDialog)
        popupmenu.addAction(selectFileAction)

        popupmenu.exec_(QCursor.pos())
コード例 #12
0
    def accept(self):
        keepOpen = ProcessingConfig.getSetting(
            ProcessingConfig.KEEP_DIALOG_OPEN)
        try:
            if self.setParamValues():
                QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
                ProcessingLog.addToLog(ProcessingLog.LOG_ALGORITHM,
                                       self.alg.getAsCommand())

                self.executed = runalg(self.alg, self)
                if self.executed:
                    handleAlgorithmResults(self.alg, self, not keepOpen)
                if not keepOpen:
                    QDialog.reject(self)
        finally:
            QApplication.restoreOverrideCursor()
コード例 #13
0
    def showPopupMenu(self):
        popupmenu = QMenu()

        if not (isinstance(self.param, ParameterMultipleInput)
                and self.param.datatype == ParameterMultipleInput.TYPE_FILE):
            selectLayerAction = QAction(self.tr('Select from open layers'),
                                        self.pushButton)
            selectLayerAction.triggered.connect(self.showLayerSelectionDialog)
            popupmenu.addAction(selectLayerAction)

        selectFileAction = QAction(self.tr('Select from filesystem'),
                                   self.pushButton)
        selectFileAction.triggered.connect(self.showFileSelectionDialog)
        popupmenu.addAction(selectFileAction)

        popupmenu.exec_(QCursor.pos())
コード例 #14
0
    def _get_csw(self):
        """convenience function to init owslib.csw.CatalogueServiceWeb"""

        # connect to the server
        try:
            QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
            self.catalog = CatalogueServiceWeb(self.catalog_url,
                                               timeout=self.timeout)
            return True
        except ExceptionReport as err:
            msg = self.tr('Error connecting to service: %s') % err
        except ValueError as err:
            msg = self.tr('Value Error: %s') % err
        except Exception as err:
            msg = self.tr('Unknown Error: %s') % err

        QMessageBox.warning(self, self.tr('CSW Connection error'), msg)
        QApplication.restoreOverrideCursor()
        return False
コード例 #15
0
    def show_metadata(self):
        """show record metadata"""

        if not self.treeRecords.selectedItems():
            return

        item = self.treeRecords.currentItem()
        if not item:
            return

        identifier = get_item_data(item, 'identifier')

        try:
            QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
            cat = CatalogueServiceWeb(self.catalog_url, timeout=self.timeout)
            cat.getrecordbyid(
                [self.catalog.records[identifier].identifier])
        except ExceptionReport as err:
            QApplication.restoreOverrideCursor()
            QMessageBox.warning(self, self.tr('GetRecords error'),
                                self.tr('Error getting response: %s') % err)
            return
        except KeyError as err:
            QMessageBox.warning(self,
                                self.tr('Record parsing error'),
                                'Unable to locate record identifier')
            QApplication.restoreOverrideCursor()
            return

        QApplication.restoreOverrideCursor()

        record = cat.records[identifier]
        record.xml_url = cat.request

        crd = RecordDialog()
        metadata = render_template('en', self.context,
                                   record, 'record_metadata_dc.html')

        style = QgsApplication.reportStyleSheet()
        crd.textMetadata.document().setDefaultStyleSheet(style)
        crd.textMetadata.setHtml(metadata)
        crd.exec_()
コード例 #16
0
ファイル: doExtractProj.py プロジェクト: ravirbdgtc/QGIS
    def accept(self):
        self.inFiles = None
        if self.batchCheck.isChecked():
            self.inFiles = Utils.getRasterFiles(self.inSelector.filename(), self.recurseCheck.isChecked())
        else:
            self.inFiles = [self.inSelector.filename()]

        self.progressBar.setRange(0, len(self.inFiles))

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        self.okButton.setEnabled(False)

        self.extractor = ExtractThread(self.inFiles, self.prjCheck.isChecked())
        self.extractor.fileProcessed.connect(self.updateProgress)
        self.extractor.processFinished.connect(self.processingFinished)
        self.extractor.processInterrupted.connect(self.processingInterrupted)

        self.buttonBox.rejected.disconnect(self.reject)
        self.buttonBox.rejected.connect(self.stopProcessing)

        self.extractor.start()
コード例 #17
0
    def selectExtent(self):
        popupmenu = QMenu()
        useLayerExtentAction = QAction(self.tr('Use layer/canvas extent'),
                                       self.btnSelect)
        selectOnCanvasAction = QAction(self.tr('Select extent on canvas'),
                                       self.btnSelect)

        popupmenu.addAction(useLayerExtentAction)
        popupmenu.addAction(selectOnCanvasAction)

        selectOnCanvasAction.triggered.connect(self.selectOnCanvas)
        useLayerExtentAction.triggered.connect(self.useLayerExtent)

        if self.canUseAutoExtent():
            useMincoveringExtentAction = QAction(
                self.tr('Use min covering extent from input layers'),
                self.btnSelect)
            useMincoveringExtentAction.triggered.connect(
                self.useMinCoveringExtent)
            popupmenu.addAction(useMincoveringExtentAction)

        popupmenu.exec_(QCursor.pos())
コード例 #18
0
    def selectExtent(self):
        popupmenu = QMenu()
        useLayerExtentAction = QAction(
            self.tr('Use layer/canvas extent'), self.btnSelect)
        selectOnCanvasAction = QAction(
            self.tr('Select extent on canvas'), self.btnSelect)

        popupmenu.addAction(useLayerExtentAction)
        popupmenu.addAction(selectOnCanvasAction)

        selectOnCanvasAction.triggered.connect(self.selectOnCanvas)
        useLayerExtentAction.triggered.connect(self.useLayerExtent)

        if self.canUseAutoExtent():
            useMincoveringExtentAction = QAction(
                self.tr('Use min covering extent from input layers'),
                self.btnSelect)
            useMincoveringExtentAction.triggered.connect(
                self.useMinCoveringExtent)
            popupmenu.addAction(useMincoveringExtentAction)

        popupmenu.exec_(QCursor.pos())
コード例 #19
0
ファイル: dlg_sql_window.py プロジェクト: ravirbdgtc/QGIS
    def executeSql(self):

        sql = self._getSqlQuery()
        if sql == "":
            return

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

        # delete the old model
        old_model = self.viewResult.model()
        self.viewResult.setModel(None)
        if old_model:
            old_model.deleteLater()

        cols = []
        quotedCols = []

        try:
            # set the new model
            model = self.db.sqlResultModel(sql, self)
            self.viewResult.setModel(model)
            self.lblResult.setText(
                self.tr("%d rows, %.1f seconds") %
                (model.affectedRows(), model.secs()))
            cols = self.viewResult.model().columnNames()
            for col in cols:
                quotedCols.append(self.db.connector.quoteId(col))

        except BaseError as e:
            QApplication.restoreOverrideCursor()
            DlgDbError.showError(e, self)
            self.uniqueModel.clear()
            self.geomCombo.clear()
            return

        self.setColumnCombos(cols, quotedCols)

        self.update()
        QApplication.restoreOverrideCursor()
コード例 #20
0
    def selectOutput(self):
        if isinstance(self.output, OutputDirectory):
            self.selectDirectory()
        else:
            popupMenu = QMenu()

            actionSaveToTempFile = QAction(
                self.tr('Save to a temporary file'), self.btnSelect)
            actionSaveToTempFile.triggered.connect(self.saveToTemporaryFile)
            popupMenu.addAction(actionSaveToTempFile)

            actionSaveToFile = QAction(
                self.tr('Save to file...'), self.btnSelect)
            actionSaveToFile.triggered.connect(self.selectFile)
            popupMenu.addAction(actionSaveToFile)

            if isinstance(self.output, OutputVector) \
                    and self.alg.provider.supportsNonFileBasedOutput():
                actionSaveToMemory = QAction(
                    self.tr('Save to memory layer'), self.btnSelect)
                actionSaveToMemory.triggered.connect(self.saveToMemory)
                popupMenu.addAction(actionSaveToMemory)
                actionSaveToSpatialite = QAction(
                    self.tr('Save to Spatialite table...'), self.btnSelect)
                actionSaveToSpatialite.triggered.connect(self.saveToSpatialite)
                popupMenu.addAction(actionSaveToSpatialite)
                actionSaveToPostGIS = QAction(
                    self.tr('Save to PostGIS table...'), self.btnSelect)
                actionSaveToPostGIS.triggered.connect(self.saveToPostGIS)
                settings = QSettings()
                settings.beginGroup('/PostgreSQL/connections/')
                names = settings.childGroups()
                settings.endGroup()
                actionSaveToPostGIS.setEnabled(bool(names))
                popupMenu.addAction(actionSaveToPostGIS)

            popupMenu.exec_(QCursor.pos())
コード例 #21
0
    def selectOutput(self):
        if isinstance(self.output, OutputDirectory):
            self.selectDirectory()
        else:
            popupMenu = QMenu()

            actionSaveToTempFile = QAction(self.tr('Save to a temporary file'),
                                           self.btnSelect)
            actionSaveToTempFile.triggered.connect(self.saveToTemporaryFile)
            popupMenu.addAction(actionSaveToTempFile)

            actionSaveToFile = QAction(self.tr('Save to file...'),
                                       self.btnSelect)
            actionSaveToFile.triggered.connect(self.selectFile)
            popupMenu.addAction(actionSaveToFile)

            if isinstance(self.output, OutputVector) \
                    and self.alg.provider.supportsNonFileBasedOutput():
                actionSaveToMemory = QAction(self.tr('Save to memory layer'),
                                             self.btnSelect)
                actionSaveToMemory.triggered.connect(self.saveToMemory)
                popupMenu.addAction(actionSaveToMemory)
                actionSaveToSpatialite = QAction(
                    self.tr('Save to Spatialite table...'), self.btnSelect)
                actionSaveToSpatialite.triggered.connect(self.saveToSpatialite)
                popupMenu.addAction(actionSaveToSpatialite)
                actionSaveToPostGIS = QAction(
                    self.tr('Save to PostGIS table...'), self.btnSelect)
                actionSaveToPostGIS.triggered.connect(self.saveToPostGIS)
                settings = QSettings()
                settings.beginGroup('/PostgreSQL/connections/')
                names = settings.childGroups()
                settings.endGroup()
                actionSaveToPostGIS.setEnabled(bool(names))
                popupMenu.addAction(actionSaveToPostGIS)

            popupMenu.exec_(QCursor.pos())
コード例 #22
0
ファイル: dlg_export_vector.py プロジェクト: ravirbdgtc/QGIS
    def accept(self):
        # sanity checks
        if self.editOutputFile.text() == "":
            QMessageBox.information(self, self.tr("Export to file"),
                                    self.tr("Output file name is required"))
            return

        if self.chkSourceSrid.isEnabled() and self.chkSourceSrid.isChecked():
            try:
                sourceSrid = int(self.editSourceSrid.text())
            except ValueError:
                QMessageBox.information(
                    self, self.tr("Export to file"),
                    self.tr("Invalid source srid: must be an integer"))
                return

        if self.chkTargetSrid.isEnabled() and self.chkTargetSrid.isChecked():
            try:
                targetSrid = int(self.editTargetSrid.text())
            except ValueError:
                QMessageBox.information(
                    self, self.tr("Export to file"),
                    self.tr("Invalid target srid: must be an integer"))
                return

        # override cursor
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        # store current input layer crs, so I can restore it later
        prevInCrs = self.inLayer.crs()
        try:
            uri = self.editOutputFile.text()
            providerName = "ogr"

            options = {}

            # set the OGR driver will be used
            driverName = self.cboFileFormat.itemData(
                self.cboFileFormat.currentIndex())
            options['driverName'] = driverName

            # set the output file encoding
            if self.chkEncoding.isEnabled() and self.chkEncoding.isChecked():
                enc = self.cboEncoding.currentText()
                options['fileEncoding'] = enc

            if self.chkDropTable.isChecked():
                options['overwrite'] = True

            outCrs = None
            if self.chkTargetSrid.isEnabled() and self.chkTargetSrid.isChecked(
            ):
                targetSrid = int(self.editTargetSrid.text())
                outCrs = qgis.core.QgsCoordinateReferenceSystem(targetSrid)

            # update input layer crs
            if self.chkSourceSrid.isEnabled() and self.chkSourceSrid.isChecked(
            ):
                sourceSrid = int(self.editSourceSrid.text())
                inCrs = qgis.core.QgsCoordinateReferenceSystem(sourceSrid)
                self.inLayer.setCrs(inCrs)

            # do the export!
            ret, errMsg = qgis.core.QgsVectorLayerImport.importLayer(
                self.inLayer, uri, providerName, outCrs, False, False, options)
        except Exception as e:
            ret = -1
            errMsg = unicode(e)

        finally:
            # restore input layer crs and encoding
            self.inLayer.setCrs(prevInCrs)
            # restore cursor
            QApplication.restoreOverrideCursor()

        if ret != 0:
            QMessageBox.warning(self, self.tr("Export to file"),
                                self.tr("Error %d\n%s") % (ret, errMsg))
            return

        # create spatial index
        # if self.chkSpatialIndex.isEnabled() and self.chkSpatialIndex.isChecked():
        #       self.db.connector.createSpatialIndex( (schema, table), geom )

        QMessageBox.information(self, self.tr("Export to file"),
                                self.tr("Export finished."))
        return QDialog.accept(self)
コード例 #23
0
ファイル: AlgorithmDialog.py プロジェクト: ravirbdgtc/QGIS
    def accept(self):
        self.settings.setValue("/Processing/dialogBase", self.saveGeometry())

        checkCRS = ProcessingConfig.getSetting(ProcessingConfig.WARN_UNMATCHING_CRS)
        try:
            self.setParamValues()
            if checkCRS and not self.alg.checkInputCRS():
                reply = QMessageBox.question(self, self.tr("Unmatching CRS's"),
                                             self.tr('Layers do not all use the same CRS. This can '
                                                     'cause unexpected results.\nDo you want to '
                                                     'continue?'),
                                             QMessageBox.Yes | QMessageBox.No,
                                             QMessageBox.No)
                if reply == QMessageBox.No:
                    return
            msg = self.alg._checkParameterValuesBeforeExecuting()
            if msg:
                QMessageBox.warning(
                    self, self.tr('Unable to execute algorithm'), msg)
                return
            self.btnRun.setEnabled(False)
            self.btnClose.setEnabled(False)
            buttons = self.mainWidget.iterateButtons
            self.iterateParam = None

            for i in range(len(buttons.values())):
                button = buttons.values()[i]
                if button.isChecked():
                    self.iterateParam = buttons.keys()[i]
                    break

            self.progressBar.setMaximum(0)
            self.lblProgress.setText(self.tr('Processing algorithm...'))
            # Make sure the Log tab is visible before executing the algorithm
            try:
                self.tabWidget.setCurrentIndex(1)
                self.repaint()
            except:
                pass

            QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

            self.setInfo(
                self.tr('<b>Algorithm %s starting...</b>') % self.alg.name)

            if self.iterateParam:
                if runalgIterating(self.alg, self.iterateParam, self):
                    self.finish()
                else:
                    QApplication.restoreOverrideCursor()
                    self.resetGUI()
            else:
                command = self.alg.getAsCommand()
                if command:
                    ProcessingLog.addToLog(
                        ProcessingLog.LOG_ALGORITHM, command)
                if runalg(self.alg, self):
                    self.finish()
                else:
                    QApplication.restoreOverrideCursor()
                    self.resetGUI()
        except AlgorithmDialogBase.InvalidParameterValue as e:
            try:
                self.buttonBox.accepted.connect(lambda:
                                                e.widget.setPalette(QPalette()))
                palette = e.widget.palette()
                palette.setColor(QPalette.Base, QColor(255, 255, 0))
                e.widget.setPalette(palette)
                self.lblProgress.setText(
                    self.tr('<b>Missing parameter value: %s</b>') % e.parameter.description)
                return
            except:
                QMessageBox.critical(self,
                                     self.tr('Unable to execute algorithm'),
                                     self.tr('Wrong or missing parameter values'))
コード例 #24
0
    def accept(self):
        if self.mode == self.ASK_FOR_INPUT_MODE:
            # create the input layer (if not already done) and
            # update available options
            self.reloadInputLayer()

        # sanity checks
        if self.inLayer is None:
            QMessageBox.information(
                self, self.tr("Import to database"),
                self.tr("Input layer missing or not valid"))
            return

        if self.cboTable.currentText() == "":
            QMessageBox.information(self, self.tr("Import to database"),
                                    self.tr("Output table name is required"))
            return

        if self.chkSourceSrid.isEnabled() and self.chkSourceSrid.isChecked():
            try:
                sourceSrid = self.editSourceSrid.text()
            except ValueError:
                QMessageBox.information(
                    self, self.tr("Import to database"),
                    self.tr("Invalid source srid: must be an integer"))
                return

        if self.chkTargetSrid.isEnabled() and self.chkTargetSrid.isChecked():
            try:
                targetSrid = self.editTargetSrid.text()
            except ValueError:
                QMessageBox.information(
                    self, self.tr("Import to database"),
                    self.tr("Invalid target srid: must be an integer"))
                return

        # override cursor
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        # store current input layer crs and encoding, so I can restore it
        prevInCrs = self.inLayer.crs()
        prevInEncoding = self.inLayer.dataProvider().encoding()

        try:
            schema = self.outUri.schema() if not self.cboSchema.isEnabled(
            ) else self.cboSchema.currentText()
            table = self.cboTable.currentText()

            # get pk and geom field names from the source layer or use the
            # ones defined by the user
            srcUri = qgis.core.QgsDataSourceURI(self.inLayer.source())

            pk = srcUri.keyColumn() if not self.chkPrimaryKey.isChecked(
            ) else self.editPrimaryKey.text()
            if not pk:
                pk = self.default_pk

            if self.inLayer.hasGeometryType() and self.chkGeomColumn.isEnabled(
            ):
                geom = srcUri.geometryColumn(
                ) if not self.chkGeomColumn.isChecked(
                ) else self.editGeomColumn.text()
                if not geom:
                    geom = self.default_geom
            else:
                geom = None

            # get output params, update output URI
            self.outUri.setDataSource(schema, table, geom, "", pk)
            uri = self.outUri.uri(False)

            providerName = self.db.dbplugin().providerName()

            options = {}
            if self.chkDropTable.isChecked():
                options['overwrite'] = True

            if self.chkSinglePart.isEnabled() and self.chkSinglePart.isChecked(
            ):
                options['forceSinglePartGeometryType'] = True

            outCrs = None
            if self.chkTargetSrid.isEnabled() and self.chkTargetSrid.isChecked(
            ):
                targetSrid = int(self.editTargetSrid.text())
                outCrs = qgis.core.QgsCoordinateReferenceSystem(targetSrid)

            # update input layer crs and encoding
            if self.chkSourceSrid.isEnabled() and self.chkSourceSrid.isChecked(
            ):
                sourceSrid = int(self.editSourceSrid.text())
                inCrs = qgis.core.QgsCoordinateReferenceSystem(sourceSrid)
                self.inLayer.setCrs(inCrs)

            if self.chkEncoding.isEnabled() and self.chkEncoding.isChecked():
                enc = self.cboEncoding.currentText()
                self.inLayer.setProviderEncoding(enc)

            onlySelected = self.chkSelectedFeatures.isChecked()

            # do the import!
            ret, errMsg = qgis.core.QgsVectorLayerImport.importLayer(
                self.inLayer, uri, providerName, outCrs, onlySelected, False,
                options)
        except Exception as e:
            ret = -1
            errMsg = unicode(e)

        finally:
            # restore input layer crs and encoding
            self.inLayer.setCrs(prevInCrs)
            self.inLayer.setProviderEncoding(prevInEncoding)
            # restore cursor
            QApplication.restoreOverrideCursor()

        if ret != 0:
            output = qgis.gui.QgsMessageViewer()
            output.setTitle(self.tr("Import to database"))
            output.setMessageAsPlainText(
                self.tr("Error %d\n%s") % (ret, errMsg))
            output.showMessage()
            return

        # create spatial index
        if self.chkSpatialIndex.isEnabled() and self.chkSpatialIndex.isChecked(
        ):
            self.db.connector.createSpatialIndex((schema, table), geom)

        QMessageBox.information(self, self.tr("Import to database"),
                                self.tr("Import was successful."))
        return QDialog.accept(self)
コード例 #25
0
    def runAlgorithm(algOrName, onFinish, *args, **kwargs):
        if isinstance(algOrName, GeoAlgorithm):
            alg = algOrName
        else:
            alg = Processing.getAlgorithm(algOrName)
        if alg is None:
            print 'Error: Algorithm not found\n'
            QgsMessageLog.logMessage(
                Processing.tr('Error: Algorithm {0} not found\n').format(
                    algOrName), Processing.tr("Processing"))
            return
        alg = alg.getCopy()

        if len(args) == 1 and isinstance(args[0], dict):
            # Set params by name and try to run the alg even if not all parameter values are provided,
            # by using the default values instead.
            setParams = []
            for (name, value) in args[0].items():
                param = alg.getParameterFromName(name)
                if param and param.setValue(value):
                    setParams.append(name)
                    continue
                output = alg.getOutputFromName(name)
                if output and output.setValue(value):
                    continue
                print 'Error: Wrong parameter value %s for parameter %s.' % (
                    value, name)
                QgsMessageLog.logMessage(
                    Processing.tr(
                        'Error: Wrong parameter value {0} for parameter {1}.').
                    format(value, name), Processing.tr("Processing"))
                ProcessingLog.addToLog(
                    ProcessingLog.LOG_ERROR,
                    Processing.
                    tr('Error in %s. Wrong parameter value %s for parameter %s.'
                       ) % (alg.name, value, name))
                return
            # fill any missing parameters with default values if allowed
            for param in alg.parameters:
                if param.name not in setParams:
                    if not param.setDefaultValue():
                        print 'Error: Missing parameter value for parameter %s.' % param.name
                        QgsMessageLog.logMessage(
                            Processing.
                            tr('Error: Missing parameter value for parameter {0}.'
                               ).format(param.name),
                            Processing.tr("Processing"))
                        ProcessingLog.addToLog(
                            ProcessingLog.LOG_ERROR,
                            Processing.
                            tr('Error in %s. Missing parameter value for parameter %s.'
                               ) % (alg.name, param.name))
                        return
        else:
            if len(args) != alg.getVisibleParametersCount(
            ) + alg.getVisibleOutputsCount():
                print 'Error: Wrong number of parameters'
                QgsMessageLog.logMessage(
                    Processing.tr('Error: Wrong number of parameters'),
                    Processing.tr("Processing"))
                processing.alghelp(algOrName)
                return
            i = 0
            for param in alg.parameters:
                if not param.hidden:
                    if not param.setValue(args[i]):
                        print 'Error: Wrong parameter value: ' + unicode(
                            args[i])
                        QgsMessageLog.logMessage(
                            Processing.tr('Error: Wrong parameter value: ') +
                            unicode(args[i]), Processing.tr("Processing"))
                        return
                    i = i + 1

            for output in alg.outputs:
                if not output.hidden:
                    if not output.setValue(args[i]):
                        print 'Error: Wrong output value: ' + unicode(args[i])
                        QgsMessageLog.logMessage(
                            Processing.tr('Error: Wrong output value: ') +
                            unicode(args[i]), Processing.tr("Processing"))
                        return
                    i = i + 1

        msg = alg._checkParameterValuesBeforeExecuting()
        if msg:
            print 'Unable to execute algorithm\n' + unicode(msg)
            QgsMessageLog.logMessage(
                Processing.tr('Unable to execute algorithm\n{0}').format(msg),
                Processing.tr("Processing"))
            return

        if not alg.checkInputCRS():
            print('Warning: Not all input layers use the same CRS.\n' +
                  'This can cause unexpected results.')
            QgsMessageLog.logMessage(
                Processing.
                tr('Warning: Not all input layers use the same CRS.\nThis can cause unexpected results.'
                   ), Processing.tr("Processing"))

        # Don't set the wait cursor twice, because then when you
        # restore it, it will still be a wait cursor.
        overrideCursor = False
        if iface is not None:
            cursor = QApplication.overrideCursor()
            if cursor is None or cursor == 0:
                QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
                overrideCursor = True
            elif cursor.shape() != Qt.WaitCursor:
                QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
                overrideCursor = True

        progress = None
        if kwargs is not None and "progress" in kwargs.keys():
            progress = kwargs["progress"]
        elif iface is not None:
            progress = MessageBarProgress()

        ret = runalg(alg, progress)
        if ret:
            if onFinish is not None:
                onFinish(alg, progress)
        else:
            QgsMessageLog.logMessage(
                Processing.tr("There were errors executing the algorithm."),
                Processing.tr("Processing"))

        if overrideCursor:
            QApplication.restoreOverrideCursor()
        if isinstance(progress, MessageBarProgress):
            progress.close()
        return alg
コード例 #26
0
    def accept(self):
        self.algs = []
        self.load = []
        self.canceled = False

        for row in range(self.mainWidget.tblParameters.rowCount()):
            alg = self.alg.getCopy()
            col = 0
            for param in alg.parameters:
                if param.hidden:
                    continue
                if isinstance(param, ParameterExtent):
                    col += 1
                    continue
                widget = self.mainWidget.tblParameters.cellWidget(row, col)
                if not self.mainWidget.setParamValue(param, widget, alg):
                    self.lblProgress.setText(
                        self.tr('<b>Missing parameter value: %s (row %d)</b>')
                        % (param.description, row + 1))
                    self.algs = None
                    return
                col += 1
            col = 0
            for param in alg.parameters:
                if param.hidden:
                    continue
                if isinstance(param, ParameterExtent):
                    widget = self.mainWidget.tblParameters.cellWidget(row, col)
                    if not self.mainWidget.setParamValue(param, widget, alg):
                        self.lblProgress.setText(
                            self.
                            tr('<b>Missing parameter value: %s (row %d)</b>') %
                            (param.description, row + 1))
                        self.algs = None
                        return
                col += 1
            for out in alg.outputs:
                if out.hidden:
                    continue

                widget = self.mainWidget.tblParameters.cellWidget(row, col)
                text = widget.getValue()
                if text.strip() != '':
                    out.value = text
                    col += 1
                else:
                    self.lblProgress.setText(
                        self.
                        tr('<b>Wrong or missing parameter value: %s (row %d)</b>'
                           ) % (out.description, row + 1))
                    self.algs = None
                    return

            self.algs.append(alg)
            if self.alg.getVisibleOutputsCount():
                widget = self.mainWidget.tblParameters.cellWidget(row, col)
                self.load.append(widget.currentIndex() == 0)
            else:
                self.load.append(False)

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        self.mainWidget.setEnabled(False)

        self.progressBar.setMaximum(len(self.algs))
        # Make sure the Log tab is visible before executing the algorithm
        try:
            self.tabWidget.setCurrentIndex(1)
            self.repaint()
        except:
            pass

        for count, alg in enumerate(self.algs):
            self.setText(
                self.tr('\nProcessing algorithm %d/%d...') %
                (count + 1, len(self.algs)))
            self.setInfo(self.tr('<b>Algorithm %s starting...</b>' % alg.name))
            if runalg(alg, self) and not self.canceled:
                if self.load[count]:
                    handleAlgorithmResults(alg, self, False)
                self.setInfo(
                    self.tr('Algorithm %s correctly executed...') % alg.name)
            else:
                QApplication.restoreOverrideCursor()
                return

        self.finish()