Exemplo n.º 1
0
    def _open(self):
        if self.plugin["status"] == "upgradeable":
            reply = QMessageBox.question(
                iface.mainWindow(),
                "Plugin",
                "An older version of the plugin is already installed. Do you want to upgrade it?",
                QMessageBox.Yes | QMessageBox.No)
            if reply != QMessageBox.Yes:
                return
        elif self.plugin["status"] in ["not installed", "new"]:
            pass
        else:
            reply = QMessageBox.question(
                iface.mainWindow(),
                "Plugin",
                "The plugin is already installed. Do you want to reinstall it?",
                QMessageBox.Yes | QMessageBox.No)
            if reply != QMessageBox.Yes:
                return

        def _install():
            installer = pyplugin_installer.instance()
            installer.installPlugin(self.plugin["id"])
            self.plugin["status"] = "installed"

        execute(_install)
Exemplo n.º 2
0
 def remove(self):
     item = self.lessonsTree.currentItem()
     if hasattr(item, "lesson"):
         reply = QMessageBox.question(None,
                                  "Confirmation",
                                  "Are you sure you want to uninstall this lesson?",
                                  QMessageBox.Yes | QMessageBox.No,
                                  QMessageBox.No)
         if reply == QMessageBox.Yes:
             _removeLesson(item.lesson)
             item = self.lessonsTree.currentItem()
             parent = item.parent()
             parent.takeChild(parent.indexOfChild(item))
             if parent.childCount() == 0:
                 self.lessonsTree.takeTopLevelItem(self.lessonsTree.indexOfTopLevelItem(parent))
             item.lesson.uninstall()
     else:
         reply = QMessageBox.question(None,
                      "Confirmation",
                      "Are you sure you want to uninstall this group of lessons?",
                      QMessageBox.Yes | QMessageBox.No,
                      QMessageBox.No)
         if reply == QMessageBox.Yes:
             for i in range(item.childCount()):
                 child = item.child(i)
                 _removeLesson(child.lesson)
                 child.lesson.uninstall()
             self.lessonsTree.takeTopLevelItem(self.lessonsTree.indexOfTopLevelItem(item))
Exemplo n.º 3
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)
Exemplo n.º 4
0
    def runAction(self, action):
        action = str(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
Exemplo n.º 5
0
    def execute(self):
        model = self.itemData
        if model is None:
            return # shouldn't happen, but let's be safe

        project_provider = model.provider().id() == PROJECT_PROVIDER_ID

        if project_provider:
            msg = self.tr('Are you sure you want to delete this model from the current project?', 'DeleteModelAction')
        else:
            msg = self.tr('Are you sure you want to delete this model?', 'DeleteModelAction')

        reply = QMessageBox.question(
            None,
            self.tr('Delete Model', 'DeleteModelAction'),
            msg,
            QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No)

        if reply == QMessageBox.Yes:
            if project_provider:
                provider = QgsApplication.processingRegistry().providerById(PROJECT_PROVIDER_ID)
                provider.remove_model(model)
                QgsProject.instance().setDirty(True)
            else:
                os.remove(model.sourceFilePath())
                QgsApplication.processingRegistry().providerById('model').refreshAlgorithms()
Exemplo n.º 6
0
    def require_directory(self):
        """Ensure directory path entered in dialog exist.

        When the path does not exist, this function will ask the user if he
        want to create it or not.

        TODO: This is cut & paste from OSM - refactor to have one method

        :raises: CanceledImportDialogError - when user choose 'No' in
            the question dialog for creating directory.
        """
        path = self.output_directory.text()

        if os.path.exists(path):
            return

        title = self.tr('Directory %s not exist') % path
        question = self.tr(
            'Directory %s not exist. Do you want to create it?') % path
        # noinspection PyCallByClass,PyTypeChecker
        answer = QMessageBox.question(
            self, title, question, QMessageBox.Yes | QMessageBox.No)

        if answer == QMessageBox.Yes:
            if len(path) != 0:
                os.makedirs(path)
            else:
                # noinspection PyCallByClass,PyTypeChecker,PyArgumentList
                display_warning_message_box(
                    self,
                    self.tr('InaSAFE error'),
                    self.tr('Output directory can not be empty.'))
                raise CanceledImportDialogError()
        else:
            raise CanceledImportDialogError()
Exemplo n.º 7
0
    def deleteConstraint(self):
        """ delete a constraint """

        index = self.currentConstraint()
        if index == -1:
            return

        m = self.viewConstraints.model()
        constr = m.getObject(index)

        res = QMessageBox.question(self, self.tr("Are you sure"),
                                   self.tr("really delete constraint '%s'?") % constr.name,
                                   QMessageBox.Yes | QMessageBox.No)
        if res != QMessageBox.Yes:
            return

        QApplication.setOverrideCursor(Qt.WaitCursor)
        self.aboutToChangeTable.emit()
        try:
            constr.delete()
            self.populateViews()
        except BaseError as e:
            DlgDbError.showError(e, self)
            return
        finally:
            QApplication.restoreOverrideCursor()
Exemplo n.º 8
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)
Exemplo n.º 9
0
    def runAction(self, action):
        action = str(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)
    def removeTableRows(self):
        '''Remove selected entries from the coordinate table.'''
        indices = [x.row() for x in self.resultsTable.selectionModel().selectedRows()]
        if len(indices) == 0:
            return
        # We need to remove the rows from the bottom to the top so that the indices
        # don't change.
        reply = QMessageBox.question(self, 'Message',
            'Are your sure you want to delete the selected locations?',
            QMessageBox.Yes, QMessageBox.No)

        if reply == QMessageBox.Yes:
            # Blocking the signals is necessary to prevent the signals replacing
            # the marker before it is completely removed.
            self.resultsTable.blockSignals(True)
            for row in sorted(indices, reverse=True):
                # Remove the marker from the map
                item = self.resultsTable.item(row, 0).data(Qt.UserRole)
                if item.marker is not None:
                    self.canvas.scene().removeItem(item.marker)
                    item.marker = None
                # Then remove the location from the table
                self.resultsTable.removeRow(row)
            
            self.resultsTable.blockSignals(False)
            self.resultsTable.clearSelection()
 def execute(self):
     reply = QMessageBox.question(None,
                                  self.tr('Confirmation', 'DeletePreconfiguredAlgorithmAction'),
                                  self.tr('Are you sure you want to delete this algorithm?',
                                          'DeletePreconfiguredAlgorithmAction'),
                                  QMessageBox.Yes | QMessageBox.No,
                                  QMessageBox.No)
     if reply == QMessageBox.Yes:
         os.remove(self.itemData.descriptionFile)
         QgsApplication.processingRegistry().providerById('preconfigured').refreshAlgorithms()
Exemplo n.º 12
0
 def execute(self):
     reply = QMessageBox.question(
         None,
         self.tr('Confirmation', 'DeleteModelAction'),
         self.tr('Are you sure you want to delete this model?', 'DeleteModelAction'),
         QMessageBox.Yes | QMessageBox.No,
         QMessageBox.No)
     if reply == QMessageBox.Yes:
         os.remove(self.itemData.sourceFilePath())
         QgsApplication.processingRegistry().providerById('model').refreshAlgorithms()
Exemplo n.º 13
0
 def clearLog(self):
     reply = QMessageBox.question(self,
                                  self.tr('Confirmation'),
                                  self.tr('Are you sure you want to clear the history?'),
                                  QMessageBox.Yes | QMessageBox.No,
                                  QMessageBox.No
                                  )
     if reply == QMessageBox.Yes:
         ProcessingLog.clearLog()
         self.fillTree()
    def clearAll(self):
        reply = QMessageBox.question(self, 'Message',
            'Are your sure you want to delete all locations?',
            QMessageBox.Yes, QMessageBox.No)

        if reply == QMessageBox.Yes:
            self.resultsTable.blockSignals(True)
            self.removeMarkers()
            self.resultsTable.setRowCount(0)
            self.resultsTable.blockSignals(False)
Exemplo n.º 15
0
 def execute(self):
     reply = QMessageBox.question(
         None,
         self.tr('Confirmation', 'DeleteModelAction'),
         self.tr('Are you sure you want to delete this model?', 'DeleteModelAction'),
         QMessageBox.Yes | QMessageBox.No,
         QMessageBox.No)
     if reply == QMessageBox.Yes:
         os.remove(self.itemData.descriptionFile)
         algList.reloadProvider('model')
    def deleteBranch(self, branch):
        ret = QMessageBox.question(self, 'Delete Branch',
                    'Are you sure you want to delete this branch?',
                    QMessageBox.Yes | QMessageBox.No,
                    QMessageBox.No)
        if ret == QMessageBox.No:
            return

        self.repo.deletebranch(branch)
        repoWatcher.repoChanged.emit(self.repo)
Exemplo n.º 17
0
    def run_all_clicked(self):
        """Run all scenario when pbRunAll is clicked."""
        self.reset_status()

        self.enable_busy_cursor()
        report = []
        fail_count = 0
        pass_count = 0

        index = 0
        for row in range(self.table.rowCount()):
            item = self.table.item(row, 0)
            status_item = self.table.item(row, 1)
            name_item = item.text()

            try:
                index += 1
                result = self.run_task(item, status_item, index=index)
                if result:
                    # P for passed
                    report.append('P: %s\n' % name_item)
                    pass_count += 1
                else:
                    report.append('F: %s\n' % name_item)
                    fail_count += 1
            except Exception as e:  # pylint: disable=W0703
                LOGGER.exception(
                    'Batch execution failed. The exception: ' + str(e))
                report.append('F: %s\n' % name_item)
                fail_count += 1
                self.disable_busy_cursor()

        try:
            report_path = self.write_report(
                report, pass_count, fail_count)
            self.show_report(report_path)
        except IOError:
            # noinspection PyArgumentList,PyCallByClass,PyTypeChecker
            QMessageBox.question(self, 'Error',
                                       'Failed to write report file.')
            self.disable_busy_cursor()
        self.disable_busy_cursor()
Exemplo n.º 18
0
 def on_delete(self):
     res = QMessageBox.question(None,
                                self.tr('Delete group'),
                                self.tr('Delete selected group?'),
                                QMessageBox.Yes, QMessageBox.No)
     if res == QMessageBox.Yes:
         group_info = self.lstGroups.currentItem().data(Qt.UserRole)
         dir_path = os.path.abspath(os.path.join(group_info.file_path, os.path.pardir))
         shutil.rmtree(dir_path, True)
         self.feel_list()
         self.ds_model.resetModel()
Exemplo n.º 19
0
 def removeItems(self, removeAll=False):
     if removeAll:
         res = QMessageBox.question(self, self.tr('Clear?'), self.tr('Are you sure you want to delete all items?'))
         if res == QMessageBox.Yes:
             self.lstItems.model().clear()
     else:
         self.lstItems.setUpdatesEnabled(False)
         indexes = sorted(self.lstItems.selectionModel().selectedIndexes())
         for i in reversed(indexes):
             self.lstItems.model().removeRow(i.row())
         self.lstItems.setUpdatesEnabled(True)
Exemplo n.º 20
0
 def execute(self):
     reply = QMessageBox.question(None,
                                  self.tr('Confirmation', 'DeleteScriptAction'),
                                  self.tr('Are you sure you want to delete this script?',
                                          'DeleteScriptAction'),
                                  QMessageBox.Yes | QMessageBox.No,
                                  QMessageBox.No)
     if reply == QMessageBox.Yes:
         os.remove(self.itemData.descriptionFile)
         if self.scriptType == self.SCRIPT_PYTHON:
             QgsApplication.processingRegistry().providerById('script').refreshAlgorithms()
Exemplo n.º 21
0
 def execute(self):
     reply = QMessageBox.question(
         None,
         self.tr("Confirmation", "DeletePreconfiguredAlgorithmAction"),
         self.tr("Are you sure you want to delete this algorithm?", "DeletePreconfiguredAlgorithmAction"),
         QMessageBox.Yes | QMessageBox.No,
         QMessageBox.No,
     )
     if reply == QMessageBox.Yes:
         os.remove(self.itemData.descriptionFile)
         algList.reloadProvider("preconfigured")
Exemplo n.º 22
0
 def set_tms_scales(self):
     res = QMessageBox.question(
         self.iface.mainWindow(),
         self.tr('QuickMapServices'),
         self.tr('Set SlippyMap scales for current project? \nThe previous settings will be overwritten!'),
         QMessageBox.Yes | QMessageBox.No)
     if res == QMessageBox.Yes:
         # set scales
         QgsProject.instance().writeEntry('Scales', '/ScalesList', self.scales_list)
         # activate
         QgsProject.instance().writeEntry('Scales', '/useProjectScales', True)
Exemplo n.º 23
0
 def closeEvent(self, evt):
     if self.hasChanged:
         ret = QMessageBox.question(self, self.tr('Unsaved changes'),
                                    self.tr('There are unsaved changes in script. Continue?'),
                                    QMessageBox.Yes | QMessageBox.No, QMessageBox.No
                                    )
         if ret == QMessageBox.Yes:
             evt.accept()
         else:
             evt.ignore()
     else:
         evt.accept()
 def removeLayer(self):
     """Remove currently selected layer (= row) from options"""
     currentRow = self.optionsDialog.tableWidget.currentRow()
     try:
         layerName = self.optionsDialog.tableWidget.item(currentRow, 0).text()
     except AttributeError:  # if no row is selected
         return
     if QMessageBox.question(self.optionsDialog,
                             QCoreApplication.translate("TimeManagerGuiControl", "Remove Layer"),
                             QCoreApplication.translate("TimeManagerGuiControl", "Do you really want to remove layer {}?").format(layerName),
                             QMessageBox.Ok, QMessageBox.Cancel) == QMessageBox.Ok:
         self.optionsDialog.tableWidget.removeRow(self.optionsDialog.tableWidget.currentRow())
    def requestFinished(self):
        QApplication.restoreOverrideCursor()
        reply = self.sender()
        visible = True
        if reply.error() != QNetworkReply.NoError:
            if reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) == 401:
                msg = 'Your credentials seem invalid.\n' \
                      'You will not be able to access any content.\n' \
                      'Please enter valid Connect credentials to use plugin.'
            else:
                msg = 'An error occurred when validating your ' \
                      'credentials. Server responded:\n{}.\n' \
                      'You will not be able to access any content.\n' \
                      'Please enter valid Connect credentials to use plugin'.format(reply.errorString())
            QMessageBox.warning(self, 'Error!', msg)
            return
        else:
            self.btnSignOut.setText("Logout")
            self.saveOrUpdateAuthId()
            self.roles = json.loads(str(reply.readAll()))

            # if this is first login ask if user wants to have basemap
            settings = QSettings()
            firstLogin = settings.value('boundlessconnect/firstLogin', True, bool)
            if firstLogin:
                settings.setValue('boundlessconnect/firstLogin', False)
                if oauth2_supported() and basemaputils.canAccessBasemap(self.roles):
                    ret = QMessageBox.question(self,
                                               self.tr('Base Maps'),
                                               self.tr('Would you like to add Boundless basemap '
                                                       'to your default project? This option can '
                                                       'be disabled at any time in the settings.'),
                                               QMessageBox.Yes | QMessageBox.No,
                                               QMessageBox.No)
                    if ret == QMessageBox.Yes:
                        if self.token is None:
                            self._showMessage("Seems you have no Connect token. Login with valid Connect credentials and try again.",
                                              QgsMessageBar.WARNING)
                            return

                        if self.installBaseMap():
                            pass

        execute(connect.loadPlugins)
        self.stackedWidget.setCurrentIndex(1)
        self.labelLevel.setVisible(visible)
        self.labelLevel.setText("Logged in as: <b>%s</b>" % self.connectWidget.login())

        self.loggedIn = True

        cat = ",".join(list(connect.categories.keys()))
        self._findContent(cat)
Exemplo n.º 26
0
 def execute(self):
     reply = QMessageBox.question(None,
                                  self.tr('Confirmation', 'DeleteScriptAction'),
                                  self.tr('Are you sure you want to delete this script?',
                                          'DeleteScriptAction'),
                                  QMessageBox.Yes | QMessageBox.No,
                                  QMessageBox.No)
     if reply == QMessageBox.Yes:
         os.remove(self.itemData.descriptionFile)
         if self.scriptType == self.SCRIPT_PYTHON:
             algList.reloadProvider('script')
         elif self.scriptType == self.SCRIPT_R:
             algList.reloadProvider('r')
Exemplo n.º 27
0
    def removeActionSlot(self, item, action, parent):
        QApplication.restoreOverrideCursor()
        try:
            res = QMessageBox.question(parent, QApplication.translate("DBManagerPlugin", "hey!"),
                                       QApplication.translate("DBManagerPlugin",
                                                              "Really remove connection to %s?") % item.connectionName(),
                                       QMessageBox.Yes | QMessageBox.No)
            if res != QMessageBox.Yes:
                return
        finally:
            QApplication.setOverrideCursor(Qt.WaitCursor)

        item.remove()
Exemplo n.º 28
0
    def confirm(self):
        # runs when OK button is pressed
        # initialise input parameters
        self.BASE_LAYER = self.dlg.ui.comboBase.currentItemData()
        self.SECONDARY_LAYER = self.dlg.ui.comboSecondary.currentItemData()
        self.SURFACE_LAYER = self.dlg.ui.comboSurface.currentItemData()
        self.LOCALITIES_LAYER = self.dlg.ui.comboLocalities.currentItemData()
        self.TAXON_FIELD_INDEX = self.dlg.ui.comboTaxonField.currentItemData()[0]
        self.GRID_LAYER = self.dlg.ui.comboGrid.currentItemData()
        self.X_MIN = float(self.dlg.ui.leMinX.text())
        self.Y_MIN = float(self.dlg.ui.leMinY.text())
        self.X_MAX = float(self.dlg.ui.leMaxX.text())
        self.Y_MAX = float(self.dlg.ui.leMaxY.text())
        self.OUT_WIDTH = self.dlg.ui.spnOutWidth.value()
        self.OUT_HEIGHT = self.dlg.ui.spnOutHeight.value()
        self.OUT_DIR = self.dlg.ui.leOutDir.text()

        try:
            self.getUniqueValues()
        except:
            message =  "Could not get unique values from localities layer. "
            message += "Check that the localities layer and taxon identifier "
            message += "field are properly specified."
            QMessageBox.information(self.dlg,"Distribution Map Generator",
                message)
            return

        question =  "This will generate " + str(self.UNIQUE_COUNT)
        question += " maps. Are you sure you want to continue?"
        reply = QMessageBox.question(self.dlg,'Distribution Map Generator',
            question,
            QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)

        self.GRID_INDEX = QgsSpatialIndex()
        for feat in getLayerFromId(self.GRID_LAYER).getFeatures():
            self.GRID_INDEX.insertFeature(feat)

        if reply == QMessageBox.Yes:
            try:
                self.process()
            except QgsCsException:
                return
            except Exception as ex:
                log(ex)
                return
            QMessageBox.information(self.dlg,"Distribution Map Generator",
                "Map processing complete.")
            self.dlg.ui.progressBar.setValue(0)
            QDialog.accept(self.dlg)
        else:
            return
Exemplo n.º 29
0
 def loadVectorFile(self, fileName):
     fileSaved = QApplication.translate("code", "Datei gespeichert.")
     load =QApplication.translate("code", "Laden?")
     reply = QMessageBox.question(self.iface.mainWindow(),
                                  "VoGIS-Profiltool",
                                  #fileSaved + os.linesep + os.linesep + os.linesep + load,
                                  fileSaved + "\n\n\n" + load,
                                  QMessageBox.Yes | QMessageBox.No,
                                  QMessageBox.Yes
                                  )
     if reply == QMessageBox.Yes:
         self.iface.addVectorLayer(fileName,
                                   os.path.basename(fileName),
                                   "ogr"
                                   )
Exemplo n.º 30
0
 def execute(self):
     reply = QMessageBox.question(None,
                                  self.tr("Delete Script"),
                                  self.tr("Are you sure you want to delete this script?"),
                                  QMessageBox.Yes | QMessageBox.No,
                                  QMessageBox.No)
     if reply == QMessageBox.Yes:
         filePath = ScriptUtils.findAlgorithmSource(self.itemData.__class__.__name__)
         if filePath is not None:
             os.remove(filePath)
             QgsApplication.processingRegistry().providerById("script").refreshAlgorithms()
         else:
             QMessageBox.warning(None,
                                 self.tr("Delete Script"),
                                 self.tr("Can not find corresponding script file.")
                                 )
Exemplo n.º 31
0
    def closeEvent(self, evt):
        settings = QgsSettings()
        settings.setValue("/Processing/stateModeler", self.saveState())
        settings.setValue("/Processing/geometryModeler", self.saveGeometry())

        if self.hasChanged:
            ret = QMessageBox.question(
                self, self.tr('Save Model?'),
                self.
                tr('There are unsaved changes in this model. Do you want to keep those?'
                   ),
                QMessageBox.Save | QMessageBox.Cancel | QMessageBox.Discard,
                QMessageBox.Cancel)

            if ret == QMessageBox.Save:
                self.saveModel(False)
                evt.accept()
            elif ret == QMessageBox.Discard:
                evt.accept()
            else:
                evt.ignore()
        else:
            evt.accept()
Exemplo n.º 32
0
    def deleteTableActionSlot(self, item, action, parent):
        QApplication.restoreOverrideCursor()
        try:
            if not isinstance(item, Table):
                parent.infoBar.pushMessage(
                    QApplication.translate(
                        "DBManagerPlugin",
                        "Select a table/view for deletion."), Qgis.Info,
                    parent.iface.messageTimeout())
                return
            res = QMessageBox.question(
                parent, QApplication.translate("DBManagerPlugin",
                                               "DB Manager"),
                QApplication.translate("DBManagerPlugin",
                                       "Really delete table/view {0}?").format(
                                           item.name),
                QMessageBox.Yes | QMessageBox.No)
            if res != QMessageBox.Yes:
                return
        finally:
            QApplication.setOverrideCursor(Qt.WaitCursor)

        item.delete()
Exemplo n.º 33
0
    def require_directory(self):
        """Ensure directory path entered in dialog exist.

        When the path does not exist, this function will ask the user if he
        want to create it or not.

        :raises: CanceledImportDialogError - when user choose 'No' in
            the question dialog for creating directory.
        """
        path = self.output_directory.text()

        if path == '':
            # If let empty, we create an temporary directory
            return

        if os.path.exists(path):
            return

        title = self.tr('Directory %s not exist') % path
        question = self.tr(
            'Directory %s not exist. Do you want to create it?') % path
        # noinspection PyCallByClass,PyTypeChecker
        answer = QMessageBox.question(
            self, title, question, QMessageBox.Yes | QMessageBox.No)

        if answer == QMessageBox.Yes:
            if len(path) != 0:
                os.makedirs(path)
            else:
                # noinspection PyCallByClass,PyTypeChecker,PyArgumentList
                display_warning_message_box(
                    self,
                    self.tr('InaSAFE error'),
                    self.tr('Output directory can not be empty.'))
                raise CanceledImportDialogError()
        else:
            raise CanceledImportDialogError()
    def showRestrictionDetails(self, closestLayer, closestFeature):

        TOMsMessageLog.logMessage(
            "In showRestrictionDetails ... Layer: " + str(closestLayer.name()),
            level=Qgis.Info)

        self.showRestrictionMapTool.notifyFeatureFound.disconnect(self.showRestrictionDetails)

        # TODO: could improve ... basically check to see if transaction in progress ...
        if closestLayer.isEditable() == True:
            reply = QMessageBox.question(None, "Information",
                                            "There is a transaction in progress on this layer. This action will rollback back any changes. Do you want to continue?",
                                            QMessageBox.Yes, QMessageBox.No)
            if reply == QMessageBox.No:
                return
            if closestLayer.commitChanges() == False:
                reply = QMessageBox.information(None, "Information",
                                                "Problem committing changes" + str(closestLayer.commitErrors()),
                                                QMessageBox.Ok)
            else:
                TOMsMessageLog.logMessage("In showRestrictionDetails: changes committed", level=Qgis.Info)

        """if self.iface.activeLayer().readOnly() == True:
            TOMsMessageLog.logMessage("In showSignDetails - Not able to start transaction ...",
                                     level=Qgis.Info)
        else:
            if self.iface.activeLayer().startEditing() == False:
                reply = QMessageBox.information(None, "Information",
                                                "Could not start transaction on " + self.currLayer.name(),
                                                QMessageBox.Ok)
                return"""

        self.dialog = self.iface.getFeatureForm(closestLayer, closestFeature)
        #self.TOMsUtils.setupRestrictionDialog(self.dialog, closestLayer, closestFeature)
        self.setupFieldRestrictionDialog(self.dialog, closestLayer, closestFeature)

        self.dialog.show()
Exemplo n.º 35
0
    def do_export(self):

        def export():
            stl_file = QFileDialog.getSaveFileName(self, self.tr('Export to STL'), self.lastSavingPath + layer_name, filter=".stl")
            if stl_file[0] != '':
                self.lastSavingPath = os.path.dirname(stl_file[0]) + '//'
                Export_dialog.Export(self, parameters, stl_file[0])

        parameters = self.get_parameters()
        layer_name = self.layer.name() + '_model.stl'
        if parameters != 0:
            row_stl = int(math.ceil(self.height / parameters["spacing_mm"]) + 1)
            col_stl = int(math.ceil(self.width / parameters["spacing_mm"]) + 1)
            tooMuchPoints = row_stl * col_stl > 500000
            if tooMuchPoints:
                reply = QMessageBox.question(self, self.tr('Export to STL'),
                                             self.tr('The construction of the STL file could takes several minutes. Do you want to continue?'),
                                             QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
                if reply == QMessageBox.Yes:
                    export()
            else:
                export()
        else:
            QMessageBox.warning(self, self.tr("Attention"), self.tr("Fill the data correctly"))
    def reallocate_clicked(self):
        if not self.__selected_items:
            self.logger.warning_msg(__name__, QCoreApplication.translate("AllocateParcelsFieldDataCapturePanelWidget",
                                                                         "First select some parcels."), 5)
            return

        # Get selected parcels that are already allocated
        already_allocated = list()  # [parcel_fid1, ...]
        for parcel_fid, parcel_number in self.__selected_items.items():
            if parcel_fid in self._parcel_data():
                if self._parcel_data()[parcel_fid][1]:  # surveyor_name
                    already_allocated.append(parcel_fid)

        if already_allocated:
            # Ask for confirmation
            reply = QMessageBox.question(self,
                                         QCoreApplication.translate("AllocateParcelsFieldDataCapturePanelWidget", "Do you confirm?"),
                                         QCoreApplication.translate("AllocateParcelsFieldDataCapturePanelWidget",
                                                                    "Are you sure you want to remove the allocation of selected parcels?"),
                                         QMessageBox.Yes, QMessageBox.No)
            if reply == QMessageBox.Yes:
                self.discard_parcel_allocation(already_allocated)
        else:
            self.logger.info_msg(__name__, QCoreApplication.translate("AllocateParcelsFieldDataCapturePanelWidget", "Selected parcels are not yet allocated, so we cannot reallocate them."))
Exemplo n.º 37
0
    def return_to_main_dialog(self):
        # first prompt
        quit_msg = "Are you sure you want to return to the main dialog? you will lose all the products generated"
        reply = QMessageBox.question(None, 'Return to Compute the Principal Components',
                                     quit_msg, QMessageBox.Yes, QMessageBox.No)
        if reply == QMessageBox.No:
            return

        # clear/close components analysis
        for view_widget in MainAnalysisDialog.view_widgets:
            if view_widget.component_analysis_dialog and view_widget.component_analysis_dialog.is_opened:
                view_widget.component_analysis_dialog.deleteLater()
            # clean view widget and its component analysis
            view_widget.clean()

        # clear and recover
        from pca4cd.pca4cd import PCA4CD as pca4cd
        self.reject(is_ok_to_close=True)
        self.deleteLater()
        pca4cd.removes_temporary_files()
        pca4cd.tmp_dir = Path(tempfile.mkdtemp())
        iface.mapCanvas().clearCache()
        # recover the main dialog
        pca4cd.dialog.show()
Exemplo n.º 38
0
 def makeModel(self):
     if self.common.PegaQWaterLayer('PIPES') == False:
         return
     dlg = self.dlg  #GHydraulicsSettingsDialog()
     template = dlg.getTemplate()
     maker = GHydraulicsModelMaker(template)
     self.iface.mainWindow().statusBar().showMessage(
         'Checking EPANET model')
     self.checkModel(maker)
     question = 'Overwrite the fields NODE1 and NODE2 in all line tables?'
     self.iface.mainWindow().statusBar().showMessage("Making EPANET model")
     autolength = dlg.getAutoLength()
     if autolength:
         question = 'Overwrite the fields NODE1, NODE2 and LENGTH in all line tables?'
     if self.explainOnce('makeModelExplanation', 'Make EPANET Model',
                         question):
         vcount = maker.make()
         if 0 < vcount:
             reply = QMessageBox.question(
                 self.iface.mainWindow(), GHydraulicsModelChecker.TITLE,
                 'Your model is missing ' + str(vcount) +
                 ' junctions. Would you like to add them now?',
                 QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
             if QMessageBox.Yes == reply:
                 self.iface.mainWindow().statusBar().showMessage(
                     'Adding missing junctions to EPANET model')
                 maker.addMissingJunctions()
                 lyrJunctions = self.common.PegaQWaterLayer('JUNCTIONS')
                 lyrJunctions.triggerRepaint()
         #dlg = GHydraulicsSettingsDialog()
         if autolength:
             self.iface.mainWindow().statusBar().showMessage(
                 'Pipe length calculation')
             maker.calculateLength()
         maker.cleanup()
     self.iface.mainWindow().statusBar().showMessage('')
Exemplo n.º 39
0
 def CheckPolylines(self, layer):
     for feature in layer.getFeatures():
         geom = feature.geometry()
         if geom.isMultipart():
             NroParts = len(list(geom.parts()))
             if NroParts > 1:
                 layer.removeSelection()
                 layer.select(feature.id())
                 self.iface.mapCanvas().zoomToSelected(layer)
                 msgTxt = QCoreApplication.translate(
                     'QWater',
                     u'Multipart feature with {:d} parts found!').format(
                         NroParts)
                 resp = QMessageBox.question(
                     None, 'QWater', msgTxt + QCoreApplication.translate(
                         'QWater',
                         u' Convert all features to single parts?'),
                     QMessageBox.Yes, QMessageBox.No)
                 if resp == QMessageBox.Yes:
                     nSplitted, nCreated = self.convertToSinglePart(layer)
                     return True, nSplitted, nCreated
                 else:
                     return False, 0, 0
     return True, 0, 0
Exemplo n.º 40
0
    def deleteConstraint(self):
        """ delete a constraint """

        index = self.currentConstraint()
        if index == -1:
            return

        m = self.viewConstraints.model()
        constr = m.getObject(index)

        res = QMessageBox.question(
            self, self.tr("Are you sure"),
            self.tr("Really delete constraint '{0}'?").format(constr.name),
            QMessageBox.Yes | QMessageBox.No)
        if res != QMessageBox.Yes:
            return

        with OverrideCursor(Qt.WaitCursor):
            self.aboutToChangeTable.emit()
            try:
                constr.delete()
                self.refresh()
            except BaseError as e:
                DlgDbError.showError(e, self)
Exemplo n.º 41
0
    def createFeature(self, geom):
        # pydevd.settrace()
        layer = self.canvas.currentLayer()
        provider = layer.dataProvider()
        f = QgsFeature()

        # if (geom.validateGeometry()):
        if (geom.isGeosValid()):
            f.setGeometry(geom)
        else:
            reply = QMessageBox.question(self.iface.mainWindow(), 'Feature not valid',
                                         "The geometry of the feature you just added isn't valid. Do you want to use it anyway?",
                                         QMessageBox.Yes, QMessageBox.No)
            if reply == QMessageBox.Yes:
                f.setGeometry(geom)
            else:
                return False

        ## Add attributefields to feature.
        fields = layer.pendingFields()

        try:  # API-Break 1.8 vs. 2.0 handling
            attr = f.initAttributes(len(fields))
            for i in range(len(fields)):
                f.setAttribute(i, provider.defaultValue(i))

        except AttributeError:  # <=1.8
            ## Add attributefields to feature.
            for i in fields:
                f.addAttribute(i, provider.defaultValue(i))

        layer.beginEditCommand("Feature added")
        layer.addFeature(f)
        layer.endEditCommand()

        self.canvas.refresh()
Exemplo n.º 42
0
    def runAction(self, action):
        action = str(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 = self.tr(u"Do you want to {0} rule {1}?").format(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

        elif action.startswith("refreshmaterializedview/"):
            if action == "refreshmaterializedview/run":
                self.runRefreshMaterializedView()
                return True

        return Table.runAction(self, action)
Exemplo n.º 43
0
    def closeEvent(self, evnt):
        """
        """

        if self.need_save:
            reply = QMessageBox.question(
                self, u"Sauvegarder ?",
                u"Voulez-vous appliquer les changements avant de fermer la fenêtre de paramétrage de l'extension ?",
                QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel,
                QMessageBox.Yes)

            if reply == QMessageBox.No:
                evnt.accept()
                super(ParamBox, self).closeEvent(evnt)
            elif reply == QMessageBox.Yes:
                self.save_settings()
                evnt.accept()
                super(ParamBox, self).closeEvent(evnt)

        else:
            evnt.accept()
            super(ParamBox, self).closeEvent(evnt)

        evnt.ignore()
Exemplo n.º 44
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 Spatial Index"),
            self.tr("Create spatial index for field {0}?").format(
                self.table.geomColumn), QMessageBox.Yes | QMessageBox.No)
        if res != QMessageBox.Yes:
            return

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

            try:
                self.table.createSpatialIndex()
                self.refresh()
            except BaseError as e:
                DlgDbError.showError(e, self)
Exemplo n.º 45
0
# -*- coding: utf-8 -*-
Exemplo n.º 46
0
    def checkModel(self, maker):
        checker = maker.checker
        if 0 == checker.getLayerCount(
                EpanetModel.JUNCTIONS) or 0 == checker.getLayerCount(
                    EpanetModel.PIPES):
            question = 'Your junction and/or pipe layer configuration is incomplete. Do you want configure the layers now?'
            reply = QMessageBox.question(self.iface.mainWindow(),
                                         GHydraulicsModelChecker.TITLE,
                                         question,
                                         QMessageBox.Yes | QMessageBox.No,
                                         QMessageBox.Yes)
            if reply == QMessageBox.Yes:
                self.showSettings()
            if 0 == checker.getLayerCount(
                    EpanetModel.JUNCTIONS) or 0 == checker.getLayerCount(
                        EpanetModel.PIPES):
                return False
        self.checkForModifications(checker)
        missing = checker.checkFields()
        if 0 < len(missing):
            fieldlist = []
            for name in list(missing.keys()):
                fieldlist.append('<br/>Layer "' + name + '": ' +
                                 ', '.join(missing[name]))
            message = 'Your model is missing some fields.' + ''.join(
                fieldlist) + '<br/>Would you like to add them?'
            reply = QMessageBox.question(self.iface.mainWindow(),
                                         GHydraulicsModelChecker.TITLE,
                                         message,
                                         QMessageBox.Yes | QMessageBox.No,
                                         QMessageBox.Yes)
            if QMessageBox.Yes != reply:
                return False
            if not checker.addFields(missing):
                QMessageBox.critical(self.iface.mainWindow(),
                                     GHydraulicsModelChecker.TITLE,
                                     'Not all fields could be added.',
                                     QMessageBox.Ok)
                return False
        crss = checker.getCrsDictionary()
        if 1 != len(crss):
            message = 'Your model uses more than one coordinate reference system. Please use only one.'
            QMessageBox.critical(self.iface.mainWindow(),
                                 GHydraulicsModelChecker.TITLE, message,
                                 QMessageBox.Ok, QMessageBox.Ok)
            return False

        missing = checker.checkIds()
        if 0 < len(missing):
            question = 'There are ' + str(
                len(missing)
            ) + ' duplicate ' + GHydraulicsModel.ID_FIELD + ' values. Do want to fix this automatically now?'
            reply = QMessageBox.question(self.iface.mainWindow(),
                                         GHydraulicsModelChecker.TITLE,
                                         question,
                                         QMessageBox.Yes | QMessageBox.No,
                                         QMessageBox.Yes)
            if QMessageBox.Yes != reply:
                return False
            if not maker.enforceUniqueIds():
                return False
        multis = checker.getMultipartCount()
        if 0 < multis:
            question = 'There are ' + str(
                multis
            ) + ' pipes with multipart geometries possibly causing problems. Do you want to explode them now?'
            reply = QMessageBox.question(self.iface.mainWindow(),
                                         GHydraulicsModelChecker.TITLE,
                                         question,
                                         QMessageBox.Yes | QMessageBox.No,
                                         QMessageBox.Yes)
            if QMessageBox.Yes == reply:
                maker.explodeMultipartPipes()
Exemplo n.º 47
0
    def accept(self):
        feedback = self.createFeedback()
        context = dataobjects.createContext(feedback)

        checkCRS = ProcessingConfig.getSetting(ProcessingConfig.WARN_UNMATCHING_CRS)
        try:
            parameters = self.getParameterValues()

            if checkCRS and not self.algorithm().validateInputCrs(parameters, context):
                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
            checkExtentCRS = ProcessingConfig.getSetting(ProcessingConfig.WARN_UNMATCHING_EXTENT_CRS)
            # TODO
            if False and checkExtentCRS and self.checkExtentCRS():
                reply = QMessageBox.question(self, self.tr("Extent CRS"),
                                             self.tr('Extent parameters must use the same CRS as the input layers.\n'
                                                     'Your input layers do not have the same extent as the project, '
                                                     'so the extent might be in a wrong CRS if you have selected it from the canvas.\n'
                                                     'Do you want to continue?'),
                                             QMessageBox.Yes | QMessageBox.No,
                                             QMessageBox.No)
                if reply == QMessageBox.No:
                    return
            ok, msg = self.algorithm().checkParameterValues(parameters, context)
            if msg:
                QMessageBox.warning(
                    self, self.tr('Unable to execute algorithm'), msg)
                return
            self.runButton().setEnabled(False)
            self.cancelButton().setEnabled(False)
            buttons = self.mainWidget().iterateButtons
            self.iterateParam = None

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

            self.clearProgress()
            self.setProgressText(self.tr('Processing algorithm...'))

            self.setInfo(
                self.tr('<b>Algorithm \'{0}\' starting...</b>').format(self.algorithm().displayName()), escapeHtml=False)

            feedback.pushInfo(self.tr('Input parameters:'))
            display_params = []
            for k, v in parameters.items():
                display_params.append("'" + k + "' : " + self.algorithm().parameterDefinition(k).valueAsPythonString(v, context))
            feedback.pushCommandInfo('{ ' + ', '.join(display_params) + ' }')
            feedback.pushInfo('')
            start_time = time.time()

            if self.iterateParam:
                # Make sure the Log tab is visible before executing the algorithm
                try:
                    self.showLog()
                    self.repaint()
                except:
                    pass

                self.cancelButton().setEnabled(self.algorithm().flags() & QgsProcessingAlgorithm.FlagCanCancel)
                if executeIterating(self.algorithm(), parameters, self.iterateParam, context, feedback):
                    feedback.pushInfo(
                        self.tr('Execution completed in {0:0.2f} seconds'.format(time.time() - start_time)))
                    self.cancelButton().setEnabled(False)
                    self.finish(True, parameters, context, feedback)
                else:
                    self.cancelButton().setEnabled(False)
                    self.resetGui()
            else:
                command = self.algorithm().asPythonCommand(parameters, context)
                if command:
                    ProcessingLog.addToLog(command)
                self.cancelButton().setEnabled(self.algorithm().flags() & QgsProcessingAlgorithm.FlagCanCancel)

                def on_complete(ok, results):
                    if ok:
                        feedback.pushInfo(self.tr('Execution completed in {0:0.2f} seconds'.format(time.time() - start_time)))
                        feedback.pushInfo(self.tr('Results:'))
                        feedback.pushCommandInfo(pformat(results))
                    else:
                        feedback.reportError(
                            self.tr('Execution failed after {0:0.2f} seconds'.format(time.time() - start_time)))
                    feedback.pushInfo('')

                    if self.feedback_dialog is not None:
                        self.feedback_dialog.close()
                        self.feedback_dialog.deleteLater()
                        self.feedback_dialog = None

                    self.cancelButton().setEnabled(False)

                    self.finish(ok, results, context, feedback)

                if self.algorithm().flags() & QgsProcessingAlgorithm.FlagCanRunInBackground:
                    # Make sure the Log tab is visible before executing the algorithm
                    self.showLog()

                    task = QgsProcessingAlgRunnerTask(self.algorithm(), parameters, context, feedback)
                    task.executed.connect(on_complete)
                    self.setCurrentTask(task)
                else:
                    self.feedback_dialog = self.createProgressDialog()
                    self.feedback_dialog.show()
                    ok, results = execute(self.algorithm(), parameters, context, feedback)
                    on_complete(ok, results)

        except AlgorithmDialogBase.InvalidParameterValue as e:
            try:
                self.buttonBox().accepted.connect(lambda e=e:
                                                  e.widget.setPalette(QPalette()))
                palette = e.widget.palette()
                palette.setColor(QPalette.Base, QColor(255, 255, 0))
                e.widget.setPalette(palette)
            except:
                pass
            self.messageBar().clearWidgets()
            self.messageBar().pushMessage("", self.tr("Wrong or missing parameter value: {0}").format(e.parameter.description()),
                                          level=QgsMessageBar.WARNING, duration=5)
Exemplo n.º 48
0
 def clearTable(self, removeAll=False):
     res = QMessageBox.question(
         self, self.tr('Clear?'),
         self.tr('Are you sure you want to clear table?'))
     if res == QMessageBox.Yes:
         self.tblView.model().clear()
Exemplo n.º 49
0
    def runAction(self, action):
        action = str(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 {0} all triggers?").format(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 {0} trigger {1}?").format(
                    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
Exemplo n.º 50
0
    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
            checkExtentCRS = ProcessingConfig.getSetting(
                ProcessingConfig.WARN_UNMATCHING_EXTENT_CRS)
            if checkExtentCRS and self.checkExtentCRS():
                reply = QMessageBox.question(
                    self, self.tr("Extent CRS"),
                    self.
                    tr('Extent parameters must use the same CRS as the input layers.\n'
                       'Your input layers do not have the same extent as the project, '
                       'so the extent might be in a wrong CRS if you have selected it from the canvas.\n'
                       'Do 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(list(buttons.values()))):
                button = list(buttons.values())[i]
                if button.isChecked():
                    self.iterateParam = list(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.feedback):
                    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.feedback):
                    self.finish()
                else:
                    QApplication.restoreOverrideCursor()
                    self.resetGUI()
        except AlgorithmDialogBase.InvalidParameterValue as e:
            try:
                self.buttonBox.accepted.connect(
                    lambda e=e: e.widget.setPalette(QPalette()))
                palette = e.widget.palette()
                palette.setColor(QPalette.Base, QColor(255, 255, 0))
                e.widget.setPalette(palette)
            except:
                pass
            self.bar.clearWidgets()
            self.bar.pushMessage("",
                                 "Wrong or missing parameter value: %s" %
                                 e.parameter.description,
                                 level=QgsMessageBar.WARNING,
                                 duration=5)
Exemplo n.º 51
0
    def commitEconomicDiametersForLayer(self, vlayer):
        feature = QgsFeature()
        provider = vlayer.dataProvider()
        allAttrs = provider.attributeIndexes()

        # Locate fields
        diafieldidx = provider.fieldNameIndex(self.diafieldname)
        flowfieldidx = provider.fieldNameIndex(self.flofieldname)
        roufieldidx = provider.fieldNameIndex(self.roufieldname)

        if -1 == diafieldidx:
            raise GHydraulicsException('ERROR: Unable to locate the "' +
                                       self.diafieldname + '" field')
        if -1 == flowfieldidx:
            raise GHydraulicsException('ERROR: Unable to locate the "' +
                                       self.flofieldname + '" field')
        if -1 == roufieldidx:
            raise GHydraulicsException('ERROR: Unable to locate the "' +
                                       self.roufieldname + '" field')

        #Carrega Tubos
        proj = QgsProject.instance()
        tubosMat = proj.readEntry(self.SETTINGS, "TUBOS_MAT", "0")[0]
        if tubosMat == '0':
            raise GHydraulicsException(
                'ERROR: Please, Define Pipes on settings dialog First!')
            #tubos=QWaterModel.TUBOS_MAT
        else:
            tubos = eval(tubosMat)
            if not isinstance(tubos[0][0], str):
                raise GHydraulicsException(
                    'ERROR: Incorrect Pipes definition!. Please, Define Pipes on settings dialog First!'
                )

        tubosFlow, tubosRough = self.getFlows(tubos)
        #raise GHydraulicsException('TESTE: Interrommpido!')

        self.diceconomic = tubosFlow
        economicflows = list(self.diceconomic.keys())
        economicflows.sort()

        dicattributechanges = {}

        if vlayer.selectedFeatureCount() == 0:
            iter = vlayer.getFeatures()
        else:
            '''
            msgBox = QMessageBox()
            msgBox.setWindowTitle('QWater')
            msgBox.setInformativeText('Diameter size only for selected features?')
            msgBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel)
            msgBox.setDefaultButton(QMessageBox.Yes)
            resp=msgBox.exec_()
            '''
            resp = QMessageBox.question(
                None, 'QWater',
                QCoreApplication.translate(
                    'QWater', 'Size Diameters only for selected features?'),
                QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel
            )  #QMessageBox.Yes, QMessageBox.No, QMessageBox.Cancel)
            if resp == QMessageBox.Cancel:
                raise GHydraulicsException(
                    'QWater: Operation cancelled. Nothing done!')
            else:
                if resp == QMessageBox.Yes:
                    iter = vlayer.selectedFeatures()
                else:
                    iter = vlayer.getFeatures()

        # Loop over selected or all features depend on last user option
        LowDiam = False
        for feature in iter:
            # Fetch result_flow attribute
            attrs = feature.attributes()
            flow = abs(
                attrs[flowfieldidx]
            )  #Almerio: acrescentei a funcao 'abs' aqui para trazer o valor absoluto da vazao
            # Look up the economic diameter from the dictionary
            biggerflow = economicflows[-1]  #pega o ultimo/maior valor
            for economicflow in economicflows:
                if economicflow > flow:
                    biggerflow = economicflow
                    break
            economicdiameter = self.diceconomic[biggerflow]
            # Indicate when dictionary is not valid any more
            if flow > biggerflow:
                #economicdiameter = 9999
                LowDiam = True
            vlayer.changeAttributeValue(
                feature.id(), diafieldidx,
                economicdiameter)  # modifica o diametro
            vlayer.changeAttributeValue(
                feature.id(), roufieldidx,
                tubosRough[economicdiameter])  #modifica a rugosidade
        iface.mapCanvas().refreshAllLayers()
        if LowDiam:
            MsgTxt = 'Pipes with insufficient diameter found! Please, insert bigger diameters Pipes on settings dialog!'
            iface.messageBar().pushMessage(self.SETTINGS,
                                           MsgTxt,
                                           level=Qgis.Warning,
                                           duration=0)
Exemplo n.º 52
0
    def divide(self):
        """ Divide the selected polygon.

            :param area: area to divide (float)
            :param rotate: rotate/offset True/False (bool)
        """
        selection = self.layer.selectedFeatures()
        if len(selection) != 1:
            QMessageBox.warning(
                self.iface.mainWindow(), tr("Warning"),
                tr("Not a single polygon is selected in active layer"))
            return
        feat = selection[0]  # feature to divide
        geom = feat.geometry()
        if geom is None:
            return
        save_geom = QgsGeometry(geom)  # save original geometry
        # change to layer coordinates
        point1 = self.toLayerCoordinates(
            self.layer, QgsPointXY(self.startPoint.x(), self.startPoint.y()))
        point2 = self.toLayerCoordinates(
            self.layer, QgsPointXY(self.endPoint.x(), self.endPoint.y()))
        # show coordinates to change
        coord_dlg = CoordDialog(point1, point2)
        if not coord_dlg.exec_():
            return

        point1 = QgsPointXY(float(coord_dlg.ui.StartEast.text()),
                            float(coord_dlg.ui.StartNorth.text()))
        point2 = QgsPointXY(float(coord_dlg.ui.EndEast.text()),
                            float(coord_dlg.ui.EndNorth.text()))
        # center of rotation
        point0 = point1
        rotate = True
        while geom.contains(point1):
            # extend line outside polygon
            point1 = QgsPointXY(point1.x() - (point2.x() - point1.x()) * 10,
                                point1.y() - (point2.y() - point1.y()) * 10)
        while geom.contains(point2):
            # extend line outside polygon
            point2 = QgsPointXY(point2.x() + (point2.x() - point1.x()) * 10,
                                point2.y() + (point2.y() - point1.y()) * 10)
        geom_line = QgsGeometry.fromPolyline([point1, point2])  # divider
        if not geom.intersects(geom_line):
            if QMessageBox.question(
                    self.iface.mainWindow(), tr("Question"),
                    tr("Line does not intersects polygon, line will be shifted into the polygon. Do you want to continue?"
                       ), QMessageBox.Yes, QMessageBox.No) == QMessageBox.No:
                return
            # find an internal point
            if Qgis.QGIS_VERSION > '2.4':
                cp = geom.pointOnSurface().vertexAt(0)
            else:
                cp = geom.centroid().vertexAt(0)
            # offset line to go through cp
            dx = point2.x() - point1.x()
            dy = point2.y() - point1.y()
            point0 = QgsPointXY(cp.x(), cp.y())
            point1 = QgsPointXY(cp.x() - 1000.0 * dx, cp.y() - 1000.0 * dy)
            point2 = QgsPointXY(cp.x() + 1000.0 * dx, cp.y() + 1000.0 * dy)
            rotate = False
        # divide polygon
        result, new_geoms, test_points = geom.splitGeometry([point1, point2],
                                                            True)
        if result != 0:
            QMessageBox.warning(self.iface.mainWindow(), tr("Warning"),
                                tr("Area division failed ") + str(result))
            return
        # open modal dialog
        area_dlg = AreaDialog(save_geom.area(), geom.area(), rotate)
        if not area_dlg.exec_():
            return
        area = float(area_dlg.ui.AreaLineEdit.text())
        rotate = area_dlg.ui.OnePointRadio.isChecked()
        if save_geom.area() <= area:
            QMessageBox.warning(
                self.iface.mainWindow(), tr("Warning"),
                tr("Area of polygon is smaller then requested area"))
            return

        i = 0
        # l = ((point2.x() - point1.x())**2 + (point2.y() - point1.y())**2)**0.5
        while True:
            da = geom.area() - area
            if fabs(da) <= config.area_tolerance:
                break
                # area OK exit loop
            # length of intersection
            geom_line = QgsGeometry.fromPolyline([point1, point2])
            section = save_geom.intersection(geom_line)
            l = section.length()  # section length
            dir = atan2(point2.x() - point0.x(), point2.y() - point0.y())
            if rotate:  # change line direction
                b = da * 2.0 / l
                dir += atan(b / l)
                point1 = QgsPointXY(point0.x() + sin(dir + pi) * 1000.0,
                                    point0.y() + cos(dir + pi) * 1000.0)
                point2 = QgsPointXY(point0.x() + sin(dir) * 1000.0,
                                    point0.y() + cos(dir) * 1000.0)
            else:  # offset line
                # perpendicular direction to line
                b = da / l  # approximate offset
                dir += pi / 2.0  # perpendicular dir
                point1 = QgsPointXY(point1.x() + sin(dir) * b,
                                    point1.y() + cos(dir) * b)
                point2 = QgsPointXY(point2.x() + sin(dir) * b,
                                    point2.y() + cos(dir) * b)
            i += 1
            if i > config.max_iteration:
                QMessageBox.warning(
                    self.iface.mainWindow(), tr("Warning"),
                    tr("Area division not finished after max iteration") +
                    str(result))
                return
            geom = QgsGeometry(save_geom)  # continue from original geomerty
            while geom.contains(point1):
                # extend line outside polygon
                point1 = QgsPointXY(
                    point1.x() - (point2.x() - point1.x()) * 10,
                    point1.y() - (point2.y() - point1.y()) * 10)
            while geom.contains(point2):
                # extend line outside polygon
                point2 = QgsPointXY(
                    point2.x() + (point2.x() - point1.x()) * 10,
                    point2.y() + (point2.y() - point1.y()) * 10)
            result, new_geoms, test_points = geom.splitGeometry(
                [point1, point2], True)
        # refresh old geometry
        fid = feat.id()
        self.layer.dataProvider().changeGeometryValues({fid: geom})
        # add new feature
        feat_new = QgsFeature()
        fields = self.layer.dataProvider().fields()
        feat_new.setFields(fields, True)
        # combine new_geoms to single geometry
        new_geom = QgsGeometry(new_geoms[0])
        for new_g in new_geoms[1:]:
            new_geom = QgsGeometry(new_geom.combine(new_g))
        feat_new.setGeometry(new_geom)
        self.layer.dataProvider().addFeatures([feat_new])
        # refresh canvas
        self.canvas.refresh()
from qgis.PyQt.QtWidgets import QMessageBox

reply = QMessageBox.question(None, 
            "Pregunta",
            "¿Quieres abrir la página de Wikipedia del aeropuerto '[%name%]'?",
            QMessageBox.Yes, QMessageBox.No)

if reply == QMessageBox.Yes:
    import webbrowser
    webbrowser.open("[%wikipedia%]")
Exemplo n.º 54
0
    def runAlgorithm(self):
        self.feedback = self.createFeedback()
        self.context = dataobjects.createContext(self.feedback)
        self.context.setLogLevel(self.logLevel())

        checkCRS = ProcessingConfig.getSetting(
            ProcessingConfig.WARN_UNMATCHING_CRS)
        try:
            # messy as all heck, but we don't want to call the dialog's implementation of
            # createProcessingParameters as we want to catch the exceptions raised by the
            # parameter panel instead...
            parameters = {} if self.mainWidget() is None else self.mainWidget(
            ).createProcessingParameters()

            if checkCRS and not self.algorithm().validateInputCrs(
                    parameters, self.context):
                reply = QMessageBox.question(
                    self, self.tr("Unmatching CRS's"),
                    self.tr('Parameters 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
            ok, msg = self.algorithm().checkParameterValues(
                parameters, self.context)
            if not ok:
                QMessageBox.warning(self,
                                    self.tr('Unable to execute algorithm'),
                                    msg)
                return

            self.blockControlsWhileRunning()
            self.setExecutedAnyResult(True)
            self.cancelButton().setEnabled(False)

            self.iterateParam = None

            for param in self.algorithm().parameterDefinitions():
                if isinstance(
                        parameters.get(param.name(), None),
                        QgsProcessingFeatureSourceDefinition
                ) and parameters[param.name(
                )].flags & QgsProcessingFeatureSourceDefinition.FlagCreateIndividualOutputPerInputFeature:
                    self.iterateParam = param.name()
                    break

            self.clearProgress()
            self.feedback.pushVersionInfo(self.algorithm().provider())
            if self.algorithm().provider().warningMessage():
                self.feedback.reportError(
                    self.algorithm().provider().warningMessage())

            self.feedback.pushInfo(
                QCoreApplication.translate('AlgorithmDialog',
                                           'Algorithm started at: {}').format(
                                               datetime.datetime.now().replace(
                                                   microsecond=0).isoformat()))

            self.setInfo(QCoreApplication.translate(
                'AlgorithmDialog',
                '<b>Algorithm \'{0}\' starting&hellip;</b>').format(
                    self.algorithm().displayName()),
                         escapeHtml=False)

            self.feedback.pushInfo(self.tr('Input parameters:'))
            display_params = []
            for k, v in parameters.items():
                display_params.append("'" + k + "' : " + self.algorithm(
                ).parameterDefinition(k).valueAsPythonString(v, self.context))
            self.feedback.pushCommandInfo('{ ' + ', '.join(display_params) +
                                          ' }')
            self.feedback.pushInfo('')
            start_time = time.time()

            def elapsed_time(start_time, result):
                delta_t = time.time() - start_time
                hours = int(delta_t / 3600)
                minutes = int((delta_t % 3600) / 60)
                seconds = delta_t - hours * 3600 - minutes * 60

                str_hours = [self.tr("hour"), self.tr("hours")][hours > 1]
                str_minutes = [self.tr("minute"),
                               self.tr("minutes")][minutes > 1]
                str_seconds = [self.tr("second"),
                               self.tr("seconds")][seconds != 1]

                if hours > 0:
                    elapsed = '{0} {1:0.2f} {2} ({3} {4} {5} {6} {7:0.0f} {2})'.format(
                        result, delta_t, str_seconds, hours, str_hours,
                        minutes, str_minutes, seconds)
                elif minutes > 0:
                    elapsed = '{0} {1:0.2f} {2} ({3} {4} {5:0.0f} {2})'.format(
                        result, delta_t, str_seconds, minutes, str_minutes,
                        seconds)
                else:
                    elapsed = '{0} {1:0.2f} {2}'.format(
                        result, delta_t, str_seconds)

                return (elapsed)

            if self.iterateParam:
                # Make sure the Log tab is visible before executing the algorithm
                try:
                    self.showLog()
                    self.repaint()
                except:
                    pass

                self.cancelButton().setEnabled(
                    self.algorithm().flags()
                    & QgsProcessingAlgorithm.FlagCanCancel)
                if executeIterating(self.algorithm(), parameters,
                                    self.iterateParam, self.context,
                                    self.feedback):
                    self.feedback.pushInfo(
                        self.tr(
                            elapsed_time(start_time,
                                         'Execution completed in')))
                    self.cancelButton().setEnabled(False)
                    self.finish(True, parameters, self.context, self.feedback)
                else:
                    self.cancelButton().setEnabled(False)
                    self.resetGui()
            else:
                self.history_details = {
                    'python_command':
                    self.algorithm().asPythonCommand(parameters, self.context),
                    'algorithm_id':
                    self.algorithm().id(),
                    'parameters':
                    self.algorithm().asMap(parameters, self.context)
                }
                process_command, command_ok = self.algorithm(
                ).asQgisProcessCommand(parameters, self.context)
                if command_ok:
                    self.history_details['process_command'] = process_command
                self.history_log_id, _ = QgsGui.historyProviderRegistry(
                ).addEntry('processing', self.history_details)

                QgsGui.instance().processingRecentAlgorithmLog().push(
                    self.algorithm().id())
                self.cancelButton().setEnabled(
                    self.algorithm().flags()
                    & QgsProcessingAlgorithm.FlagCanCancel)

                def on_complete(ok, results):
                    if ok:
                        self.feedback.pushInfo(
                            self.tr(
                                elapsed_time(start_time,
                                             'Execution completed in')))
                        self.feedback.pushInfo(self.tr('Results:'))
                        r = {
                            k: v
                            for k, v in results.items()
                            if k not in ('CHILD_RESULTS', 'CHILD_INPUTS')
                        }
                        self.feedback.pushCommandInfo(pformat(r))
                    else:
                        self.feedback.reportError(
                            self.tr(
                                elapsed_time(start_time,
                                             'Execution failed after')))
                    self.feedback.pushInfo('')

                    if self.history_log_id is not None:
                        self.history_details['results'] = results
                        QgsGui.historyProviderRegistry().updateEntry(
                            self.history_log_id, self.history_details)

                    if self.feedback_dialog is not None:
                        self.feedback_dialog.close()
                        self.feedback_dialog.deleteLater()
                        self.feedback_dialog = None

                    self.cancelButton().setEnabled(False)

                    self.finish(ok,
                                results,
                                self.context,
                                self.feedback,
                                in_place=self.in_place)

                    self.feedback = None
                    self.context = None

                if not self.in_place and not (
                        self.algorithm().flags()
                        & QgsProcessingAlgorithm.FlagNoThreading):
                    # Make sure the Log tab is visible before executing the algorithm
                    self.showLog()

                    task = QgsProcessingAlgRunnerTask(self.algorithm(),
                                                      parameters, self.context,
                                                      self.feedback)
                    if task.isCanceled():
                        on_complete(False, {})
                    else:
                        task.executed.connect(on_complete)
                        self.setCurrentTask(task)
                else:
                    self.proxy_progress = QgsProxyProgressTask(
                        QCoreApplication.translate(
                            "AlgorithmDialog", "Executing “{}”").format(
                                self.algorithm().displayName()))
                    QgsApplication.taskManager().addTask(self.proxy_progress)
                    self.feedback.progressChanged.connect(
                        self.proxy_progress.setProxyProgress)
                    self.feedback_dialog = self.createProgressDialog()
                    self.feedback_dialog.show()
                    if self.in_place:
                        ok, results = execute_in_place(self.algorithm(),
                                                       parameters,
                                                       self.context,
                                                       self.feedback)
                    else:
                        ok, results = execute(self.algorithm(), parameters,
                                              self.context, self.feedback)
                    self.feedback.progressChanged.disconnect()
                    self.proxy_progress.finalize(ok)
                    on_complete(ok, results)

        except AlgorithmDialogBase.InvalidParameterValue as e:
            self.flag_invalid_parameter_value(e.parameter.description(),
                                              e.widget)
        except AlgorithmDialogBase.InvalidOutputExtension as e:
            self.flag_invalid_output_extension(e.message, e.widget)
Exemplo n.º 55
0
    def check(self):

        # TAB Geometry
        if self.receivers_layer_comboBox.currentText() == "":
            QMessageBox.information(
                self, self.tr("opeNoise - Calculate Noise Levels"),
                self.tr("Please specify the receivers point layer."))
            return False

        if self.sources_pts_layer_checkBox.isChecked(
        ) is False and self.sources_roads_layer_checkBox.isChecked() is False:
            QMessageBox.information(
                self, self.tr("opeNoise - Calculate Noise Levels"),
                self.tr("Please specify at least one source layer."))
            return False

        if self.sources_pts_layer_checkBox.isChecked(
        ) and self.sources_pts_layer_comboBox.currentText() == "":
            QMessageBox.information(
                self, self.tr("opeNoise - Calculate Noise Levels"),
                self.tr("Please specify the points sources layer."))
            return False

        if self.sources_roads_layer_checkBox.isChecked(
        ) and self.sources_roads_layer_comboBox.currentText() == "":
            QMessageBox.information(
                self, self.tr("opeNoise - Calculate Noise Levels"),
                self.tr("Please specify the roads sources layer."))
            return False

        if self.buildings_layer_checkBox.isChecked(
        ) == True and self.buildings_layer_comboBox.currentText() == "":
            QMessageBox.information(
                self, self.tr("opeNoise - Calculate Noise Levels"),
                self.tr("Please specify the buildings layer."))
            return False

        #TAB Geometry -- field data already present
        receiver_layer = self.receivers_layer_comboBox.currentLayer()
        receiver_fields = receiver_layer.fields()
        fields = [x.name() for x in receiver_fields.toList()]

        personal_fields = ['gen', 'day', 'eve', 'nig', 'den']
        fields_already_present = list(set(personal_fields) & set(fields))
        if fields_already_present:
            overwrite_begin = self.tr(
                "In receiver layer you already have the fields:")
            overwrite_end = self.tr(
                " present. Do you want to overwrite data in attribute table and delete all results from your previous calculation?"
            )
            reply = QMessageBox.question(
                self, self.tr("opeNoise - Calculate Noise Levels"),
                overwrite_begin + '\n' + str(fields_already_present) +
                overwrite_end, QMessageBox.Yes, QMessageBox.No)
            fList = []
            for field_to_delete in fields_already_present:
                idx_field = receiver_layer.dataProvider().fieldNameIndex(
                    field_to_delete)
                fList.append(idx_field)

            receiver_layer.dataProvider().deleteAttributes(fList)
            receiver_layer.updateFields()

            if reply == QMessageBox.No:
                return False

        # TAB Option
        if self.save_settings_checkBox.isChecked(
        ) and self.save_settings_lineEdit.text() == "":
            QMessageBox.information(
                self, self.tr("opeNoise - Calculate Noise Levels"),
                self.tr("Please specify a file to save Settings."))
            return False

        if self.L_den_checkBox.isChecked() and int(
                self.L_day_hours_spinBox.value()) + int(
                    self.L_eve_hours_spinBox.value()) + int(
                        self.L_nig_hours_spinBox.value()) != 24:
            QMessageBox.information(
                self, self.tr("opeNoise - Calculate Noise Levels"),
                self.
                tr("The amount of the hours of Lday, Leve and Lnig must be 24."
                   ))
            return False

        if self.rays_layer_checkBox.isChecked(
        ) == True and self.rays_layer_lineEdit.text() == "":
            QMessageBox.information(
                self, self.tr("opeNoise - Calculate Noise Levels"),
                self.tr("Please specify the direct sound rays layer."))
            return False

        if self.diff_rays_layer_checkBox.isChecked(
        ) == True and self.diff_rays_layer_lineEdit.text() == "":
            QMessageBox.information(
                self, self.tr("opeNoise - Calculate Noise Levels"),
                self.tr("Please specify the diffraction sound rays layer."))
            return False

        return True
Exemplo n.º 56
0
    def accept(self):
        super(AlgorithmDialog, self)._saveGeometry()

        context = dataobjects.createContext()

        checkCRS = ProcessingConfig.getSetting(
            ProcessingConfig.WARN_UNMATCHING_CRS)
        try:
            parameters = self.getParamValues()

            QgsMessageLog.logMessage(str(parameters), 'Processing',
                                     QgsMessageLog.CRITICAL)

            # TODO
            if False and 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
            checkExtentCRS = ProcessingConfig.getSetting(
                ProcessingConfig.WARN_UNMATCHING_EXTENT_CRS)
            #TODO
            if False and checkExtentCRS and self.checkExtentCRS():
                reply = QMessageBox.question(
                    self, self.tr("Extent CRS"),
                    self.
                    tr('Extent parameters must use the same CRS as the input layers.\n'
                       'Your input layers do not have the same extent as the project, '
                       'so the extent might be in a wrong CRS if you have selected it from the canvas.\n'
                       'Do you want to continue?'),
                    QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
                if reply == QMessageBox.No:
                    return
            ok, msg = self.alg.checkParameterValues(parameters, context)
            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(list(buttons.values()))):
                button = list(buttons.values())[i]
                if button.isChecked():
                    self.iterateParam = list(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 {0} starting...</b>').format(
                    self.alg.displayName()))

            if self.iterateParam:
                if executeIterating(self.alg, parameters, self.iterateParam,
                                    context, self.feedback):
                    self.finish(parameters, context)
                else:
                    QApplication.restoreOverrideCursor()
                    self.resetGUI()
            else:
                # TODO
                #command = self.alg.getAsCommand()
                #if command:
                #    ProcessingLog.addToLog(command)
                self.buttonCancel.setEnabled(
                    self.alg.flags() & QgsProcessingAlgorithm.FlagCanCancel)
                result = executeAlgorithm(self.alg, parameters, context,
                                          self.feedback)
                self.buttonCancel.setEnabled(False)
                self.finish(result, context)
                #TODO
                #else:
                #    QApplication.restoreOverrideCursor()
                #    self.resetGUI()
        except AlgorithmDialogBase.InvalidParameterValue as e:
            try:
                self.buttonBox.accepted.connect(
                    lambda e=e: e.widget.setPalette(QPalette()))
                palette = e.widget.palette()
                palette.setColor(QPalette.Base, QColor(255, 255, 0))
                e.widget.setPalette(palette)
            except:
                pass
            self.bar.clearWidgets()
            self.bar.pushMessage(
                "",
                self.tr("Wrong or missing parameter value: {0}").format(
                    e.parameter.description()),
                level=QgsMessageBar.WARNING,
                duration=5)
Exemplo n.º 57
0
    def runAlgorithm(self):
        self.feedback = self.createFeedback()
        self.context = dataobjects.createContext(self.feedback)

        checkCRS = ProcessingConfig.getSetting(
            ProcessingConfig.WARN_UNMATCHING_CRS)
        try:
            parameters = self.getParameterValues()

            if checkCRS and not self.algorithm().validateInputCrs(
                    parameters, self.context):
                reply = QMessageBox.question(
                    self, self.tr("Unmatching CRS's"),
                    self.tr('Parameters 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
            ok, msg = self.algorithm().checkParameterValues(
                parameters, self.context)
            if not ok:
                QMessageBox.warning(self,
                                    self.tr('Unable to execute algorithm'),
                                    msg)
                return
            self.runButton().setEnabled(False)
            self.cancelButton().setEnabled(False)
            buttons = self.mainWidget().iterateButtons
            self.iterateParam = None

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

            self.clearProgress()
            self.setProgressText(
                QCoreApplication.translate('AlgorithmDialog',
                                           'Processing algorithm…'))

            self.setInfo(QCoreApplication.translate(
                'AlgorithmDialog',
                '<b>Algorithm \'{0}\' starting&hellip;</b>').format(
                    self.algorithm().displayName()),
                         escapeHtml=False)

            self.feedback.pushInfo(self.tr('Input parameters:'))
            display_params = []
            for k, v in parameters.items():
                display_params.append("'" + k + "' : " + self.algorithm(
                ).parameterDefinition(k).valueAsPythonString(v, self.context))
            self.feedback.pushCommandInfo('{ ' + ', '.join(display_params) +
                                          ' }')
            self.feedback.pushInfo('')
            start_time = time.time()

            if self.iterateParam:
                # Make sure the Log tab is visible before executing the algorithm
                try:
                    self.showLog()
                    self.repaint()
                except:
                    pass

                self.cancelButton().setEnabled(
                    self.algorithm().flags()
                    & QgsProcessingAlgorithm.FlagCanCancel)
                if executeIterating(self.algorithm(), parameters,
                                    self.iterateParam, self.context,
                                    self.feedback):
                    self.feedback.pushInfo(
                        self.tr('Execution completed in {0:0.2f} seconds').
                        format(time.time() - start_time))
                    self.cancelButton().setEnabled(False)
                    self.finish(True, parameters, self.context, self.feedback)
                else:
                    self.cancelButton().setEnabled(False)
                    self.resetGui()
            else:
                command = self.algorithm().asPythonCommand(
                    parameters, self.context)
                if command:
                    ProcessingLog.addToLog(command)
                QgsGui.instance().processingRecentAlgorithmLog().push(
                    self.algorithm().id())
                self.cancelButton().setEnabled(
                    self.algorithm().flags()
                    & QgsProcessingAlgorithm.FlagCanCancel)

                def on_complete(ok, results):
                    if ok:
                        self.feedback.pushInfo(
                            self.tr('Execution completed in {0:0.2f} seconds').
                            format(time.time() - start_time))
                        self.feedback.pushInfo(self.tr('Results:'))
                        self.feedback.pushCommandInfo(pformat(results))
                    else:
                        self.feedback.reportError(
                            self.tr('Execution failed after {0:0.2f} seconds').
                            format(time.time() - start_time))
                    self.feedback.pushInfo('')

                    if self.feedback_dialog is not None:
                        self.feedback_dialog.close()
                        self.feedback_dialog.deleteLater()
                        self.feedback_dialog = None

                    self.cancelButton().setEnabled(False)

                    if not self.in_place:
                        self.finish(ok, results, self.context, self.feedback)
                    elif ok:
                        self.close()

                    self.feedback = None
                    self.context = None

                if not self.in_place and not (
                        self.algorithm().flags()
                        & QgsProcessingAlgorithm.FlagNoThreading):
                    # Make sure the Log tab is visible before executing the algorithm
                    self.showLog()

                    task = QgsProcessingAlgRunnerTask(self.algorithm(),
                                                      parameters, self.context,
                                                      self.feedback)
                    if task.isCanceled():
                        on_complete(False, {})
                    else:
                        task.executed.connect(on_complete)
                        self.setCurrentTask(task)
                else:
                    self.proxy_progress = QgsProxyProgressTask(
                        QCoreApplication.translate(
                            "AlgorithmDialog", "Executing “{}”").format(
                                self.algorithm().displayName()))
                    QgsApplication.taskManager().addTask(self.proxy_progress)
                    self.feedback.progressChanged.connect(
                        self.proxy_progress.setProxyProgress)
                    self.feedback_dialog = self.createProgressDialog()
                    self.feedback_dialog.show()
                    if self.in_place:
                        ok, results = execute_in_place(self.algorithm(),
                                                       parameters,
                                                       self.context,
                                                       self.feedback)
                    else:
                        ok, results = execute(self.algorithm(), parameters,
                                              self.context, self.feedback)
                    self.feedback.progressChanged.disconnect()
                    self.proxy_progress.finalize(ok)
                    on_complete(ok, results)

        except AlgorithmDialogBase.InvalidParameterValue as e:
            try:
                self.buttonBox().accepted.connect(
                    lambda e=e: e.widget.setPalette(QPalette()))
                palette = e.widget.palette()
                palette.setColor(QPalette.Base, QColor(255, 255, 0))
                e.widget.setPalette(palette)
            except:
                pass
            self.messageBar().clearWidgets()
            self.messageBar().pushMessage(
                "",
                self.tr("Wrong or missing parameter value: {0}").format(
                    e.parameter.description()),
                level=Qgis.Warning,
                duration=5)
        except AlgorithmDialogBase.InvalidOutputExtension as e:
            try:
                self.buttonBox().accepted.connect(
                    lambda e=e: e.widget.setPalette(QPalette()))
                palette = e.widget.palette()
                palette.setColor(QPalette.Base, QColor(255, 255, 0))
                e.widget.setPalette(palette)
            except:
                pass
            self.messageBar().clearWidgets()
            self.messageBar().pushMessage("",
                                          e.message,
                                          level=Qgis.Warning,
                                          duration=5)
Exemplo n.º 58
0
    def accept(self):
        super(AlgorithmDialog, self)._saveGeometry()

        feedback = self.createFeedback()
        context = dataobjects.createContext(feedback)

        checkCRS = ProcessingConfig.getSetting(
            ProcessingConfig.WARN_UNMATCHING_CRS)
        try:
            parameters = self.getParamValues()

            if checkCRS and not self.alg.validateInputCrs(parameters, context):
                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
            checkExtentCRS = ProcessingConfig.getSetting(
                ProcessingConfig.WARN_UNMATCHING_EXTENT_CRS)
            # TODO
            if False and checkExtentCRS and self.checkExtentCRS():
                reply = QMessageBox.question(
                    self, self.tr("Extent CRS"),
                    self.
                    tr('Extent parameters must use the same CRS as the input layers.\n'
                       'Your input layers do not have the same extent as the project, '
                       'so the extent might be in a wrong CRS if you have selected it from the canvas.\n'
                       'Do you want to continue?'),
                    QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
                if reply == QMessageBox.No:
                    return
            ok, msg = self.alg.checkParameterValues(parameters, context)
            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(list(buttons.values()))):
                button = list(buttons.values())[i]
                if button.isChecked():
                    self.iterateParam = list(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

            self.setInfo(
                self.tr('<b>Algorithm \'{0}\' starting...</b>').format(
                    self.alg.displayName()),
                escape_html=False)

            feedback.pushInfo(self.tr('Input parameters:'))
            feedback.pushCommandInfo(pformat(parameters))
            feedback.pushInfo('')
            start_time = time.time()

            if self.iterateParam:
                self.buttonCancel.setEnabled(
                    self.alg.flags() & QgsProcessingAlgorithm.FlagCanCancel)
                if executeIterating(self.alg, parameters, self.iterateParam,
                                    context, feedback):
                    feedback.pushInfo(
                        self.tr(
                            'Execution completed in {0:0.2f} seconds'.format(
                                time.time() - start_time)))
                    self.buttonCancel.setEnabled(False)
                    self.finish(True, parameters, context, feedback)
                else:
                    self.buttonCancel.setEnabled(False)
                    self.resetGUI()
            else:
                command = self.alg.asPythonCommand(parameters, context)
                if command:
                    ProcessingLog.addToLog(command)
                self.buttonCancel.setEnabled(
                    self.alg.flags() & QgsProcessingAlgorithm.FlagCanCancel)

                def on_complete(ok, results):
                    if ok:
                        feedback.pushInfo(
                            self.tr('Execution completed in {0:0.2f} seconds'.
                                    format(time.time() - start_time)))
                        feedback.pushInfo(self.tr('Results:'))
                        feedback.pushCommandInfo(pformat(results))
                    else:
                        feedback.reportError(
                            self.tr('Execution failed after {0:0.2f} seconds'.
                                    format(time.time() - start_time)))
                    feedback.pushInfo('')

                    self.buttonCancel.setEnabled(False)
                    self.finish(ok, results, context, feedback)

                task = QgsProcessingAlgRunnerTask(self.alg, parameters,
                                                  context, feedback)
                task.executed.connect(on_complete)
                QgsApplication.taskManager().addTask(task)

        except AlgorithmDialogBase.InvalidParameterValue as e:
            try:
                self.buttonBox.accepted.connect(
                    lambda e=e: e.widget.setPalette(QPalette()))
                palette = e.widget.palette()
                palette.setColor(QPalette.Base, QColor(255, 255, 0))
                e.widget.setPalette(palette)
            except:
                pass
            self.bar.clearWidgets()
            self.bar.pushMessage(
                "",
                self.tr("Wrong or missing parameter value: {0}").format(
                    e.parameter.description()),
                level=QgsMessageBar.WARNING,
                duration=5)
    def discard_parcels(self):
        # Take 2 cases into account:
        # 1) an already allocated parcel is being discarded --> fill_table()
        # 2) a 'to be allocated' parcel is being discarded --> fill_table(refresh_allocated_parcels=False)
        already_allocated = list()
        to_be_allocated = list()

        selected_gui_items = [
            item.data(Qt.UserRole)
            for item in self.tbl_parcels.selectedItems()
        ]
        for row in range(self.tbl_parcels.rowCount()):
            item = self.tbl_parcels.item(row, 0)
            fid = item.data(Qt.UserRole)
            if fid in selected_gui_items:
                item2 = self.tbl_parcels.item(row, 1)
                if item2.data(Qt.UserRole):  # Allocated?
                    already_allocated.append(fid)
                else:
                    to_be_allocated.append(fid)

        if not already_allocated and not to_be_allocated:
            self.logger.warning_msg(
                __name__,
                QCoreApplication.translate(
                    "BaseAllocateParcelsToReceiverPanelWidget",
                    "First select some parcels in the list."))
            return

        reply = QMessageBox.question(
            self,
            QCoreApplication.translate(
                "BaseAllocateParcelsToReceiverPanelWidget", "Do you confirm?"),
            QCoreApplication.translate(
                "BaseAllocateParcelsToReceiverPanelWidget",
                "Are you sure you want to remove the allocation of selected parcels in the list?"
            ), QMessageBox.Yes, QMessageBox.No)

        if reply == QMessageBox.Yes:
            res = False
            # 1)
            if already_allocated:
                res = self._controller.discard_parcel_allocation(
                    already_allocated)

            # 2)
            for parcel_fid in to_be_allocated:
                del self.__parcels_to_be_allocated[parcel_fid]
                res = True

            if res:
                self.logger.success_msg(
                    __name__,
                    QCoreApplication.translate(
                        "BaseAllocateParcelsToReceiverPanelWidget",
                        "Selected parcels were successfully discarded!"))
            else:
                self.logger.warning_msg(
                    __name__,
                    QCoreApplication.translate(
                        "BaseAllocateParcelsToReceiverPanelWidget",
                        "There were troubles discarding parcels!"))

            # Finally, reload the table, refreshing from data source only when already-allocated parcels were discarded
            # For safety, we reload even if not res, just to make sure our data is totally in sync
            self.fill_table(bool(already_allocated))
Exemplo n.º 60
0
    def import_button_clicked(self):
        self.bar.clearWidgets()
        self.save_settings()
        etl_result = False

        if self.rad_snc_data.isChecked():
            etl = ETLSNC(self.names, self._data_source_widget)
        else:  # Cobol
            etl = ETLCobol(self.names, self._data_source_widget)

        if self._db.test_connection()[0]:
            reply = QMessageBox.question(
                self, QCoreApplication.translate("SuppliesETLWizard",
                                                 "Warning"),
                QCoreApplication.translate(
                    "SuppliesETLWizard",
                    "The database <i>{}</i> already has a valid LADM-COL structure.<br/><br/>If such database has any data, loading data into it might cause invalid data.<br/><br/>Do you still want to continue?"
                ).format(self._db.get_description_conn_string()),
                QMessageBox.Yes, QMessageBox.No)

            if reply == QMessageBox.Yes:
                self.set_gui_controls_enabled(False)
                self.button(self.BackButton).setEnabled(False)
                self.button(self.CustomButton1).setEnabled(False)
                self.button(self.CancelButton).setText(
                    QCoreApplication.translate("SuppliesETLWizard", "Cancel"))

                with OverrideCursor(Qt.WaitCursor):
                    res_alpha, msg_alpha = etl.load_alphanumeric_layers()

                    if res_alpha:
                        res_spatial, msg_spatial = etl.load_spatial_layers()

                        if res_spatial:
                            res_model, msg_model = self.load_model_layers(
                                etl.layers)

                            if res_model:
                                layers_feature_count_before = {
                                    name: layer.featureCount()
                                    for name, layer in etl.layers.items()
                                }
                                self._running_tool = True
                                self.progress.setVisible(True)
                                res_etl_model = etl.run_etl_model(
                                    self.custom_feedback)
                                if not self.custom_feedback.isCanceled(
                                ) and res_etl_model:
                                    self.progress.setValue(100)

                                    self.button(
                                        self.NextButton).setVisible(True)
                                    self.button(
                                        self.CustomButton1).setVisible(False)
                                    self.button(self.CancelButton).setText(
                                        QCoreApplication.translate(
                                            "SuppliesETLWizard", "Close"))
                                    self.show_message(
                                        QCoreApplication.translate(
                                            "SuppliesETLWizard",
                                            "The {} has finished successfully!"
                                        ).format(self.tool_name), Qgis.Success,
                                        0)

                                    self.logger.clear_status()
                                    self.fill_summary(
                                        layers_feature_count_before,
                                        etl.layers)
                                    etl_result = True
                                else:
                                    self.initialize_feedback(
                                    )  # Get ready for an eventual new execution
                                    self.logger.clear_status()
                                self._running_tool = False
                            else:
                                self.show_message(msg_model, Qgis.Warning)
                        else:
                            self.show_message(msg_spatial, Qgis.Warning)
                    else:
                        self.show_message(msg_alpha, Qgis.Warning)
        else:
            with OverrideCursor(Qt.WaitCursor):
                # TODO: if an empty schema was selected, do the magic under the hood
                # self.create_model_into_database()
                # Now execute "accepted()"
                msg = QCoreApplication.translate(
                    "SuppliesETLWizard",
                    "To run the ETL, the database (schema) should have the Supplies LADM-COL structure. Choose a proper database (schema) and try again."
                )
                self.show_message(msg, Qgis.Warning)
                self.logger.warning(__name__, msg)

        self.on_result.emit(
            etl_result)  # Inform other classes if the execution was successful