def delete_map(self):
     name = self.ui.tabMaps.currentItem().text()
     map_id = self.ui.tabMaps.currentItem().data(Qt.UserRole)
     
     msgBox = QMessageBox()
     msgBox.setWindowTitle(self.tr("Delete QGIS Cloud map."))
     msgBox.setText(
         self.tr("Do you want to delete the map \"%s\"?") % name)
     msgBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
     msgBox.setDefaultButton(QMessageBox.Cancel)
     msgBox.setIcon(QMessageBox.Question)
     ret = msgBox.exec_()
     
     if ret == QMessageBox.Ok:
         self.ui.widgetServices.close()
         self.setCursor(Qt.WaitCursor)
         success = self.api.delete_map(map_id)
         
         if success:
             self.ui.btnMapDelete.setEnabled(False)
             self.refresh_maps()
         else:
             self.show_api_error(success)
             
         self.unsetCursor()
         self.ui.widgetServices.close()
     else:
         QMessageBox.warning(None,  self.tr('Warning'),  self.tr('Deletion of map "{name}" interrupted!').format(name=name))
Exemplo n.º 2
0
    def show_messagebox(self, **kwargs):
        """ Shows a message box with detail information """

        msg = kwargs['message'] if 'message' in kwargs else 'No message found'
        title = kwargs['title'] if 'title' in kwargs else 'New message'
        inf_text = kwargs['inf_text'] if 'inf_text' in kwargs else 'Info text'
        # color = "black"
        # bold = ''
        # if 'styleSheet' in kwargs:
        #     color = kwargs['styleSheet']['color'] if 'color' in kwargs['styleSheet'] else "black"
        #     if 'bold' in kwargs['styleSheet']:
        #         bold = 'b' if kwargs['styleSheet']['bold'] else ''
        #     else:
        #         bold = ''
        # msg = f'<font color="{color}"><{bold}>{msg}</font>'
        msg_box = QMessageBox()
        msg_box.setText(msg)
        if title:
            title = self.controller.tr(title)
            msg_box.setWindowTitle(title)
        if inf_text:
            inf_text = self.controller.tr(inf_text)
            msg_box.setInformativeText(inf_text)
        msg_box.setWindowFlags(Qt.WindowStaysOnTopHint)
        msg_box.setStandardButtons(QMessageBox.Ok)
        msg_box.setDefaultButton(QMessageBox.Ok)
        msg_box.open()
Exemplo n.º 3
0
 def showLoadingMsg(self, invalidRules=None, msgType=None):
     """
     Shows a message box to user if successfully loaded data or not.
     If not, shows to user a list of not loaded layers and allows user
     to choice between ignore and continue or cancel the importation.
     :param lyrList: (list) a list of not loaded layers.
     :param msgType: (str) type of message box - warning or information.
     :return: (signal) value returned from the clicked button.
     """
     msg = QMessageBox()
     msg.setWindowTitle(self.tr("DSGTools: importing spatial rules"))
     if invalidRules and msgType == "warning":
         msg.setIcon(QMessageBox.Warning)
         msg.setText(self.tr("Some rules have not been loaded"))
         msg.setInformativeText(
             self.tr("Do you want to ignore and continue or cancel?"))
         msgString = "\n".join((r.ruleName() for r in invalidRules))
         formatedMsgString = self.tr(
             "The following layers have not been loaded:\n{0}").format(
                 msgString)
         msg.setDetailedText(formatedMsgString)
         msg.setStandardButtons(QMessageBox.Ignore | QMessageBox.Cancel)
         msg.setDefaultButton(QMessageBox.Cancel)
     else:
         msg.setIcon(QMessageBox.Information)
         msg.setText(self.tr("Successfully loaded rules!"))
     choice = msg.exec_()
     return choice
Exemplo n.º 4
0
    def deLayer(self):
        if len(self.tableView_2.selectedIndexes())!=1:
            return

        msgBox = QMessageBox()
        msgBox.setInformativeText("Do you delete the layer?")
        msgBox.addButton(QMessageBox.Yes)
        msgBox.addButton(QMessageBox.No)
        msgBox.setDefaultButton(QMessageBox.No)
        msgBox.setWindowTitle("Confirmation")
        msgBox.setIcon(QMessageBox.Question)
        if msgBox.exec_() == QMessageBox.Yes:
            self.db.open()
            idx = self.tableView_2.selectionModel().selectedIndexes()[0]
            tname = str(self.model2.itemData(idx)[0])
            sql = "drop table %s" % tname
            q = self.db.exec_(sql)
            sql = "delete from geometry_columns where f_table_name='%s'" % tname
            q = self.db.exec_(sql)
            sql = "delete from geometry_columns_auth where f_table_name='%s'" % tname
            q = self.db.exec_(sql)
            sql = "delete from geometry_columns_field_infos where f_table_name='%s'" % tname
            q = self.db.exec_(sql)
            sql = "delete from geometry_columns_statistics where f_table_name='%s'" % tname
            q = self.db.exec_(sql)
            sql = "delete from geometry_columns_time where f_table_name='%s'" % tname
            q = self.db.exec_(sql)
            self.db.commit()
            self.db.close()
            self.loadLayers()
Exemplo n.º 5
0
    def runModel(self):
        valid, errors = self.model().validate()
        if not valid:
            message_box = QMessageBox()
            message_box.setWindowTitle(self.tr('Model is Invalid'))
            message_box.setIcon(QMessageBox.Warning)
            message_box.setText(self.tr('This model is not valid and contains one or more issues. Are you sure you want to run it in this state?'))
            message_box.setStandardButtons(QMessageBox.Yes | QMessageBox.Cancel)
            message_box.setDefaultButton(QMessageBox.Cancel)

            error_string = ''
            for e in errors:
                e = re.sub(r'<[^>]*>', '', e)
                error_string += '• {}\n'.format(e)

            message_box.setDetailedText(error_string)
            if message_box.exec_() == QMessageBox.Cancel:
                return

        def on_finished(successful, results):
            self.setLastRunChildAlgorithmResults(dlg.results().get('CHILD_RESULTS', {}))
            self.setLastRunChildAlgorithmInputs(dlg.results().get('CHILD_INPUTS', {}))

        dlg = AlgorithmDialog(self.model().create(), parent=self)
        dlg.setParameters(self.model().designerParameterValues())
        dlg.algorithmFinished.connect(on_finished)
        dlg.exec_()

        if dlg.wasExecuted():
            self.model().setDesignerParameterValues(dlg.createProcessingParameters(include_default=False))
 def delete_map(self):
     name = self.ui.tabMaps.currentItem().text()
     map_id = self.ui.tabMaps.currentItem().data(Qt.UserRole)
     
     msgBox = QMessageBox()
     msgBox.setWindowTitle(self.tr("Delete QGIS Cloud map."))
     msgBox.setText(
         self.tr("Do you want to delete the map \"%s\"?") % name)
     msgBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
     msgBox.setDefaultButton(QMessageBox.Cancel)
     msgBox.setIcon(QMessageBox.Question)
     ret = msgBox.exec_()
     
     if ret == QMessageBox.Ok:
         self.ui.widgetServices.close()
         self.setCursor(Qt.WaitCursor)
         success = self.api.delete_map(map_id)
         
         if success:
             self.ui.btnMapDelete.setEnabled(False)
             self.refresh_maps()
         else:
             self.show_api_error(success)
             
         self.unsetCursor()
         self.ui.widgetServices.close()
     else:
         QMessageBox.warning(None,  self.tr('Warning'),  self.tr('Deletion of map "{name}" interrupted!').format(name=name))
Exemplo n.º 7
0
    def showLoadingMsg(self, lyrList=None, msgType=None):
        """
        Shows a message box to user if successfully loaded data or not.
        If not, shows to user a list of not loaded layers and allows user
        to choice between ignore and continue or cancel the importation.
        :param lyrList: (list) a list of not loaded layers.
        :param msgType: (str) type of message box - warning or information.
        :return: (signal) value returned from the clicked button.
        """
        msg = QMessageBox()
        msg.setWindowTitle(self.tr("Information about importing rules"))

        if lyrList and msgType == "warning":
            msg.setIcon(QMessageBox.Warning)
            msg.setText(self.tr("Some rules have not been loaded"))
            msg.setInformativeText(
                self.tr("Do you want to ignore and continue or cancel?"))

            textLyrList = sorted(set(lyrList))
            formatedLyrList = ["{}" for item in textLyrList]
            msgString = ",".join(formatedLyrList).replace(",", "\n")
            formatedMsgString = self.tr(
                "The following layers have not been loaded:\n") + \
                msgString.format(*textLyrList)

            msg.setDetailedText(formatedMsgString)
            msg.setStandardButtons(QMessageBox.Ignore | QMessageBox.Cancel)
            msg.setDefaultButton(QMessageBox.Cancel)
        else:
            msg.setIcon(QMessageBox.Information)
            msg.setText(self.tr("Successfully loaded rules!"))

        choice = msg.exec_()
        return choice
Exemplo n.º 8
0
def show_info_box(text,
                  title=None,
                  inf_text=None,
                  context_name=None,
                  parameter=None):
    """ Show information box to the user """

    msg = ""
    if text:
        msg = tr(text, context_name)
        if parameter:
            msg += ": " + str(parameter)

    msg_box = QMessageBox()
    if len(msg) > 750:
        msg = msg[:750] + "\n[...]"
    msg_box.setText(msg)
    msg_box.setWindowFlags(Qt.WindowStaysOnTopHint)
    if title:
        title = tr(title, context_name)
        msg_box.setWindowTitle(title)
    if inf_text:
        inf_text = tr(inf_text, context_name)
        if len(inf_text) > 500:
            inf_text = inf_text[:500] + "\n[...]"
        msg_box.setInformativeText(inf_text)
    msg_box.setDefaultButton(QMessageBox.No)
    msg_box.exec_()
 def check_dir(self):
     if self.dlg.persistance_path_widget.filePath() != '' and \
             any(os.scandir(self.dlg.persistance_path_widget.filePath())):
         dialog = QMessageBox()
         dialog.setText(self.tr('The directory is not empty'))
         dialog.setInformativeText(
             self.tr('Do you want to overwrite the content?'))
         dialog.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
         dialog.setDefaultButton(QMessageBox.No)
         result = dialog.exec_()
         if result == QMessageBox.No:
             self.dlg.persistance_path_widget.setFilePath('')
Exemplo n.º 10
0
 def setLayer(self, layer):
     self.model.setLayer(layer)
     if self.model.rowCount() == 0:
         self.on_resetButton_clicked()
     else:
         dlg = QMessageBox(self)
         dlg.setText("Do you want to reset the field mapping?")
         dlg.setStandardButtons(
             QMessageBox.StandardButtons(QMessageBox.Yes | QMessageBox.No))
         dlg.setDefaultButton(QMessageBox.No)
         if dlg.exec_() == QMessageBox.Yes:
             self.on_resetButton_clicked()
Exemplo n.º 11
0
 def CustomMessage(title, msg, informative="", icon="Critical"):
     ''' Custom Informative Message '''
     d = QMessageBox()
     d.setWindowTitle(title)
     d.setText(msg)
     d.setInformativeText(informative)
     d.setIconPixmap(QgsUtils.GetIcon(icon))
     d.addButton(QMessageBox.Yes)
     d.addButton(QMessageBox.No)
     d.setDefaultButton(QMessageBox.No)
     ret = d.exec_()
     return ret
Exemplo n.º 12
0
 def setLayer(self, layer):
     self.model.setLayer(layer)
     if self.model.rowCount() == 0:
         self.on_resetButton_clicked()
     else:
         dlg = QMessageBox(self)
         dlg.setText("Do you want to reset the field mapping?")
         dlg.setStandardButtons(
             QMessageBox.StandardButtons(QMessageBox.Yes |
                                         QMessageBox.No))
         dlg.setDefaultButton(QMessageBox.No)
         if dlg.exec_() == QMessageBox.Yes:
             self.on_resetButton_clicked()
 def prepare_database(self):
     if self.check_connected():
         msgBox = QMessageBox()
         msgBox.setText(
             "DON'T USE THIS PARTWAY THROUGH THE JOB! because this will erase any data in tables used by this plugin."
         )
         msgBox.setInformativeText("Continue?")
         msgBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
         msgBox.setDefaultButton(QMessageBox.No)
         i = msgBox.exec_()
         if i == QMessageBox.Yes:
             self.dd.setup_database()
             iface.messageBar().pushMessage(
                 'fitting tool: prepared database')
Exemplo n.º 14
0
 def setLayer(self, layer):
     if layer is None or self.layer == layer:
         return
     self.layer = layer
     if self.model.rowCount(QModelIndex()) == 0:
         self.on_resetButton_clicked()
         return
     dlg = QMessageBox(self)
     dlg.setText(self.tr("Do you want to reset the field mapping?"))
     dlg.setStandardButtons(
         QMessageBox.StandardButtons(QMessageBox.Yes | QMessageBox.No))
     dlg.setDefaultButton(QMessageBox.No)
     if dlg.exec_() == QMessageBox.Yes:
         self.on_resetButton_clicked()
Exemplo n.º 15
0
 def ask(parent, title, question, box_icon=QMessageBox.Question):
     """Ask for operation confirmation."""
     msg_box = QMessageBox(parent)
     msg_box.setIcon(box_icon)
     msg_box.setWindowTitle(title)
     msg_box.setTextFormat(Qt.RichText)
     msg_box.setText(question)
     msg_box.setStandardButtons(QMessageBox.No | QMessageBox.Yes)
     msg_box.setDefaultButton(QMessageBox.No)
     res = msg_box.exec_()
     if res == QMessageBox.No:
         return False
     else:
         return True
Exemplo n.º 16
0
def show_details(detail_text, title=None, inf_text=None):
    """ Shows a message box with detail information """

    global_vars.iface.messageBar().clearWidgets()
    msg_box = QMessageBox()
    msg_box.setText(detail_text)
    if title:
        title = tr(title)
        msg_box.setWindowTitle(title)
    if inf_text:
        inf_text = tr(inf_text)
        msg_box.setInformativeText(inf_text)
    msg_box.setWindowFlags(Qt.WindowStaysOnTopHint)
    msg_box.setStandardButtons(QMessageBox.Ok)
    msg_box.setDefaultButton(QMessageBox.Ok)
    msg_box.exec_()
Exemplo n.º 17
0
 def setLayer(self, layer):
     if self.model.layer() == layer:
         return
     self.model.setLayer(layer)
     if layer is None:
         return
     if self.model.rowCount() == 0:
         self.on_resetButton_clicked()
         return
     dlg = QMessageBox(self)
     dlg.setText(self.tr("Do you want to reset the field mapping?"))
     dlg.setStandardButtons(
         QMessageBox.StandardButtons(QMessageBox.Yes |
                                     QMessageBox.No))
     dlg.setDefaultButton(QMessageBox.No)
     if dlg.exec_() == QMessageBox.Yes:
         self.on_resetButton_clicked()
 def check_project_saved(self):
     project = QgsProject.instance()
     fname = project.fileName()
     if project.isDirty() or fname == '':
         msgBox = QMessageBox()
         msgBox.setWindowTitle(self.tr("Project Modified"))
         msgBox.setText(self.tr("The project has been modified."))
         msgBox.setInformativeText(
             self.tr("The project needs to be saved before it can be published. Proceed?"))
         msgBox.setStandardButtons(QMessageBox.Save | QMessageBox.Cancel)
         msgBox.setDefaultButton(QMessageBox.Save)
         if msgBox.exec_() == QMessageBox.Save:
             self.iface.actionSaveProject().trigger()
             return not project.isDirty()
         else:
             return False
     return True
 def check_project_saved(self):
     project = QgsProject.instance()
     fname = project.fileName()
     if project.isDirty() or fname == '':
         msgBox = QMessageBox()
         msgBox.setWindowTitle(self.tr("Project Modified"))
         msgBox.setText(self.tr("The project has been modified."))
         msgBox.setInformativeText(
             self.tr("The project needs to be saved before it can be published. Proceed?"))
         msgBox.setStandardButtons(QMessageBox.Save | QMessageBox.Cancel)
         msgBox.setDefaultButton(QMessageBox.Save)
         if msgBox.exec_() == QMessageBox.Save:
             self.iface.actionSaveProject().trigger()
             return not project.isDirty()
         else:
             return False
     return True
Exemplo n.º 20
0
    def deLayer(self):
        if len(self.tableView_layers.selectedIndexes()) != 1:
            return

        msgBox = QMessageBox()
        msgBox.setInformativeText("Do you delete the layer?")
        msgBox.addButton(QMessageBox.Yes)
        msgBox.addButton(QMessageBox.No)
        msgBox.setDefaultButton(QMessageBox.No)
        msgBox.setWindowTitle("Confirmation")
        msgBox.setIcon(QMessageBox.Question)
        if msgBox.exec_() == QMessageBox.Yes:
            self.db.open()
            idx = self.tableView_layers.selectionModel().selectedIndexes()[0]
            tname = str(self.model2.itemData(idx)[0])

            #Check if layer is loaded on the TOC.
            #If layer is present will be removed and added from the TOC
            lyrs = [
                layer for layer in QgsProject.instance().mapLayers().values()
            ]

            for l in lyrs:
                if type(l).__name__ == 'QgsVectorLayer':
                    if tname == l.name():
                        #TODO: how get the self.db path or database name?
                        if l.providerType() == 'spatialite':
                            QgsProject.instance().removeMapLayer(l.id())

            sql = "drop table %s" % tname
            q = self.db.exec_(sql)
            sql = "delete from geometry_columns where f_table_name='%s'" % tname
            q = self.db.exec_(sql)
            sql = "delete from geometry_columns_auth where f_table_name='%s'" % tname
            q = self.db.exec_(sql)
            sql = "delete from geometry_columns_field_infos where f_table_name='%s'" % tname
            q = self.db.exec_(sql)
            sql = "delete from geometry_columns_statistics where f_table_name='%s'" % tname
            q = self.db.exec_(sql)
            sql = "delete from geometry_columns_time where f_table_name='%s'" % tname
            q = self.db.exec_(sql)
            self.db.commit()
            self.db.close()
            self.loadLayers()
Exemplo n.º 21
0
    def delete_database(self):
        name = self.ui.tabDatabases.currentItem().text()

        answer = False

        for layer in list(self.PROJECT_INSTANCE.mapLayers().values()):
            if QgsDataSourceUri(layer.publicSource()).database() == name:

                if not answer:
                    answer = QMessageBox.question(
                        self, self.tr("Warning"),
                        self.
                        tr('You have layers from database "{name}" loaded in your project! Do you want to remove them before you delete database "{name}"?'
                           ).format(name=name),
                        QMessageBox.StandardButtons(QMessageBox.Cancel
                                                    | QMessageBox.Yes))

                if answer == QMessageBox.Yes:
                    self.PROJECT_INSTANCE.removeMapLayer(layer.id())

        if answer == QMessageBox.Cancel:
            QMessageBox.warning(
                None, self.tr('Warning'),
                self.tr('Deletion of database "{name}" interrupted!').format(
                    name=name))
            return

        msgBox = QMessageBox()
        msgBox.setWindowTitle(self.tr("Delete QGIS Cloud database."))
        msgBox.setText(
            self.tr("Do you want to delete the database \"%s\"?") % name)
        msgBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
        msgBox.setDefaultButton(QMessageBox.Cancel)
        msgBox.setIcon(QMessageBox.Question)
        ret = msgBox.exec_()

        if ret == QMessageBox.Ok:
            self.setCursor(Qt.WaitCursor)
            result = self.api.delete_database(name)
            self.show_api_error(result)
            self.ui.btnDbDelete.setEnabled(False)
            time.sleep(2)
            self.refresh_databases()
            self.unsetCursor()
Exemplo n.º 22
0
 def veureInfo(self):
     if self.info is not None:
         box = QMessageBox(self)
         box.setWindowTitle('Info del mapa simbòlic')
         txt = '<table width="600">'
         params = self.info.split('\n')
         for param in params:
             linea = param.strip()
             if linea.endswith(':'):
                 linea += ' ---'
             txt += '<tr><td><nobr>&middot;&nbsp;{}</nobr></td></tr>'.format(linea)
         txt += '</table>'
         box.setTextFormat(Qt.RichText)
         box.setText("Paràmetres d'agregació de dades:")
         box.setInformativeText(txt)
         box.setIcon(QMessageBox.Information)
         box.setStandardButtons(QMessageBox.Ok)
         box.setDefaultButton(QMessageBox.Ok)
         box.exec()
    def delete_database(self):
        name = self.ui.tabDatabases.currentItem().text()
        
        answer = False
        
        for layer in list(self.PROJECT_INSTANCE.mapLayers().values()):            
            if QgsDataSourceUri(layer.publicSource()).database() == name:
                
                if not answer:
                    answer = QMessageBox.question(
                        self,
                        self.tr("Warning"),
                        self.tr('You have layers from database "{name}" loaded in your project! Do you want to remove them before you delete database "{name}"?').format(name=name),
                        QMessageBox.StandardButtons(
                            QMessageBox.Cancel |
                            QMessageBox.Yes))

                if answer == QMessageBox.Yes:
                     self.PROJECT_INSTANCE.removeMapLayer(layer.id())
                     
        if answer == QMessageBox.Cancel:
            QMessageBox.warning(None,  self.tr('Warning'),  self.tr('Deletion of database "{name}" interrupted!').format(name=name))
            return
            
        msgBox = QMessageBox()
        msgBox.setWindowTitle(self.tr("Delete QGIS Cloud database."))
        msgBox.setText(
            self.tr("Do you want to delete the database \"%s\"?") % name)
        msgBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
        msgBox.setDefaultButton(QMessageBox.Cancel)
        msgBox.setIcon(QMessageBox.Question)
        ret = msgBox.exec_()
        
        if ret == QMessageBox.Ok:
            self.setCursor(Qt.WaitCursor)
            result = self.api.delete_database(name)
            self.show_api_error(result)
            self.ui.btnDbDelete.setEnabled(False)
            time.sleep(2)
            self.refresh_databases()
            self.unsetCursor()
Exemplo n.º 24
0
 def createPullRequest(self):
     user2, repo2 = self.comboTarget.currentText().split(":")
     name = self.txtPrName.text()
     if name:
         conflicts = self.server.branchConflicts(self.user, self.repo,
                                                 "master", user2, repo2,
                                                 "master")
         if conflicts:
             ret = QMessageBox.warning(
                 self, "Conflicts with target repository",
                 "This Pull Request is in conflict with the target repo.\n"
                 "Please SYNC changes from target repo (and resolve conflicts) before making a PR!",
                 QMessageBox.Ok, QMessageBox.Ok)
             return
         # this assumes sending to parent
         commitsBehind, commitsAhead = self.server.compareHistories(
             self.user, self.repo, user2, repo2)
         if commitsBehind > 0:
             msgBox = QMessageBox()
             msgBox.setText("Target repo has changes")
             msgBox.setInformativeText(
                 "The target repo has changes not in this repo - we recommend SYNC those changes before creating a PR"
             )
             msgBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Abort)
             msgBox.setDefaultButton(QMessageBox.Abort)
             ret = msgBox.exec_()
             if ret == QMessageBox.Abort:
                 return
         self.server.createPullRequest(self.user,
                                       self.repo,
                                       user2,
                                       repo2,
                                       name,
                                       "master",
                                       "master",
                                       description=self.prDescription)
         self.close()
     else:
         self.bar.pushMessage("Error",
                              "Enter a valid pull request name",
                              level=Qgis.Warning)
Exemplo n.º 25
0
    def CustomMessage(title, msg, informative="", icon="Critical"):
        ''' Custom Informative Message '''
        d = QMessageBox()
        d.setTextFormat(Qt.RichText)
        d.setWindowTitle(title)
        d.setWindowIcon(QIcon(QPixmap(":/imgFMV/images/icon.png")))
        d.setText(msg)
        d.setInformativeText(informative)
        d.setIconPixmap(QgsUtils.GetIcon(icon))
        d.addButton(QMessageBox.Yes)
        d.addButton(QMessageBox.No)
        d.setDefaultButton(QMessageBox.No)

        # Trick resize QMessageBox
        horizontalSpacer = QSpacerItem(500, 0, QSizePolicy.Minimum,
                                       QSizePolicy.Expanding)
        layout = d.layout()
        layout.addItem(horizontalSpacer, layout.rowCount(), 0, 1,
                       layout.columnCount())

        ret = d.exec_()
        return ret
Exemplo n.º 26
0
def show_question(text,
                  title=None,
                  inf_text=None,
                  context_name=None,
                  parameter=None,
                  force_action=False):
    """ Ask question to the user """

    # Expert mode does not ask and accept all actions
    if global_vars.user_level['level'] not in (None,
                                               'None') and not force_action:
        if global_vars.user_level['level'] not in global_vars.user_level[
                'showquestion']:
            return True

    msg_box = QMessageBox()
    msg = tr(text, context_name)
    if parameter:
        msg += ": " + str(parameter)
    if len(msg) > 750:
        msg = msg[:750] + "\n[...]"
    msg_box.setText(msg)
    if title:
        title = tr(title, context_name)
        msg_box.setWindowTitle(title)
    if inf_text:
        inf_text = tr(inf_text, context_name)
        if len(inf_text) > 500:
            inf_text = inf_text[:500] + "\n[...]"
        msg_box.setInformativeText(inf_text)
    msg_box.setStandardButtons(QMessageBox.Cancel | QMessageBox.Ok)
    msg_box.setDefaultButton(QMessageBox.Ok)
    msg_box.setWindowFlags(Qt.WindowStaysOnTopHint)
    ret = msg_box.exec_()
    if ret == QMessageBox.Ok:
        return True
    elif ret == QMessageBox.Discard:
        return False
    def check(self, data_info: dict):
        logger.debug("Checking data access conditions and limitation")
        limitations = data_info.get("limitations", None)
        # if there are no limits, ok for adding the layer
        if len(limitations) == 0:
            logger.debug(
                "No limitations found, let's add this layer to the canvas !")
            self.layer_adder.adding(layer_info=data_info.get("layer"))
        else:
            li_lim = []
            for lim in limitations:
                lim = Limitation(**lim)
                if lim.directive:
                    directive = Directive(**lim.directive)
                else:
                    directive = Directive()
                # for 'legal' limitations, fill the list
                if lim.type == "legal":
                    # for this directive, no need to informe the user
                    if (lim.restriction == "other" and directive._id
                            == "6756c1875d06446982ed941555102c72"):
                        pass
                    # for other legal limitations, need to informe the user
                    else:
                        logger.debug(
                            "legal limitation detected : {}".format(lim))
                        li_lim.append(lim)
                # for any 'security' limitation, let's show the blocking popup and end the method
                elif lim.type == "security":
                    popup = QMessageBox()
                    popup.setWindowTitle("Limitations")

                    popup_txt = self.tr(
                        "This data is subject to a security limitation :",
                        __class__.__name__,
                    )
                    if lim.description != "":
                        popup_txt += "\n - {}".format(lim.description)
                    else:
                        popup_txt += self.tr("\n - No description provided",
                                             context=__class__.__name__)
                    popup.setText(popup_txt)

                    popup.setInformativeText(
                        self.tr(
                            "Do you want to add the layer to the canvas anyway ?",
                            context=__class__.__name__,
                        ))
                    popup.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
                    popup.setDefaultButton(QMessageBox.No)
                    popup.finished.connect(
                        partial(self.finished_slot, data_info.get("layer")))
                    popup.exec()
                    return
                else:
                    logger.info("Unexpected data limitation type : {}".format(
                        lim.to_str()))
                    pass
            # if all limitations are 'legal' type and 'No limit' INSPIRE directive, let's add the layer
            if len(li_lim) == 0:
                self.layer_adder.adding(layer_info=data_info.get("layer"))
                return
            # if there are other 'legal' type limitation, let's inform the user before adding the layer
            else:
                self.lim_sig.emit(li_lim)
                self.layer_adder.adding(layer_info=data_info.get("layer"))
                return
Exemplo n.º 28
0
    def search(self):
        try:
            # Current service
            service = self.tab.tabText(self.tab.currentIndex())

            # Params
            params = {'geometry': self.polygonInput.text()}

            # Set auth and add params according to service
            if service == 'BaseMap':
                # ! Auth
                self.bmSetAuth()

                # Set request attributes
                url = 'https://view.geoapi-airbusds.com/api/v1/images'
                auth = self.bmAuth
                headers = None

                # Update params
                params.update({
                    'size': self.maxResultsInput.value(),
                    'insertdtstart': '1970-01-01T00:00:00',
                    'insertdtend': self.now()
                })

                # Dates
                if self.bmFromCheck.isChecked():
                    params['insertdtstart'] = self.bmFromInput.dateTime(
                    ).toString(Qt.ISODate)
                if self.bmToCheck.isChecked():
                    params['insertdtend'] = self.bmToInput.dateTime().toString(
                        Qt.ISODate)

            else:
                # ! Auth
                self.dtSetAuth()

                url = 'https://search.oneatlas.geoapi-airbusds.com/api/v1/opensearch'
                auth = None
                headers = self.dtHeaders

                # Constellations (at least one)
                constellations = []
                if self.dtSpotCheck.isChecked():
                    constellations.append('SPOT')
                if self.dtPleiadesCheck.isChecked():
                    constellations.append('PHR')

                # Dates
                # MAYBE remove hours from dates
                dateFrom, dateTo = '1970-01-01T00:00:00', self.now()
                if self.dtFromCheck.isChecked():
                    dateFrom = self.dtFromInput.dateTime().toString(Qt.ISODate)
                if self.dtToCheck.isChecked():
                    dateTo = self.dtToInput.dateTime().toString(Qt.ISODate)

                # Angles
                angleMin, angleMax = 0, 30
                if self.dtAngleMinCheck.isChecked():
                    angleMin = self.dtAngleMinInput.value()
                if self.dtAngleMaxCheck.isChecked():
                    angleMax = self.dtAngleMaxInput.value()

                # Covers (directlly update params)
                if self.dtCloudCheck.isChecked():
                    params['cloudCover'] = f'[0,{self.dtCloudInput.value()}]'
                if self.dtSnowCheck.isChecked():
                    params['snowCover'] = f'[0,{self.dtSnowInput.value()}]'

                # Workspaces (at leat one)
                workspaces = []
                if self.dtPublicCheck.isChecked():
                    workspaces.append('0e33eb50-3404-48ad-b835-b0b4b72a5625')
                if self.dtPrivateCheck.isChecked():
                    workspaces.append(self.dtWorkspaceId)

                # Update all params with right format
                params.update({
                    'itemsPerPage': self.maxResultsInput.value(),
                    'constellation': ','.join(constellations),
                    'acquisitionDate': f'[{dateFrom},{dateTo}]',
                    'incidenceAngle': f'[{angleMin},{angleMax}]',
                    'workspace': ','.join(workspaces)
                })

            # Finally do the api call
            t = datetime.datetime.now()
            print(f'START {service} search')
            r = self.session.get(url,
                                 auth=auth,
                                 headers=headers,
                                 params=params)
            rSearch = r.json()

            # Exception request error
            if r.status_code != 200:
                self.error(
                    f'{service} search error {r.status_code}\n{rSearch["message"]}'
                )
                return

            # Create the search result layer with fields according to current service
            layer = QgsVectorLayer(
                f'Polygon?crs=epsg:4326&index=yes&{FIELDS[service]}',
                providerLib='memory',
                baseName=f'{service} search results')

            # Extract features
            features = []
            self.errorFeatures = []
            for rFeature in rSearch['features']:
                # Add a feature of the bbox on the new layer
                feature = QgsFeature(layer.fields())
                # Try to get each attributes
                feature['service'] = service
                feature['constellation'] = self.getPropertie(
                    rFeature, 'constellation')
                feature['incidenceAngle'] = self.getPropertie(
                    rFeature, 'incidenceAngle')
                feature['cloudCover'] = self.getPropertie(
                    rFeature, 'cloudCover')
                if service == 'BaseMap':
                    feature['id'] = rFeature['id']
                    feature['insertionDate'] = self.getPropertie(
                        rFeature, 'insertionDate')
                    feature['wmts'] = self.getPropertie(rFeature, 'wmts')
                    # Bbox
                    fBbox = rFeature['properties']['bbox']
                    rectangle = QgsRectangle(fBbox[0], fBbox[1], fBbox[2],
                                             fBbox[3])
                else:
                    feature['id'] = self.getPropertie(rFeature, 'id')
                    feature['acquisitionDate'] = self.getPropertie(
                        rFeature, 'acquisitionDate')
                    feature['snowCover'] = self.getPropertie(
                        rFeature, 'snowCover')
                    try:
                        for json in rFeature['_links']['imagesWmts']:
                            feature[f'wmts_{json["name"]}'] = json['href']
                        for json in rFeature['_links']['imagesWcs']:
                            if 'buffer' in rFeature['rights']:
                                feature[f'wcs_{json["name"]}'] = json['href']
                            else:
                                feature[f'wcs_{json["name"]}'] = None
                    except Exception as e:
                        print(
                            f'ERROR * eF = qgis.utils.plugins["OneAtlas"].mySearch.errorFeatures[{len(self.errorFeatures)}]'
                        )
                        print(str(e))
                        self.errorFeatures.append(rFeature)
                        continue
                    # Bbox
                    coordinates = rFeature['geometry']['coordinates'][0]
                    rectangle = QgsRectangle(coordinates[0][0],
                                             coordinates[0][1],
                                             coordinates[2][0],
                                             coordinates[2][1])
                # Add geometry from rectangle
                feature.setGeometry(
                    QgsGeometry.fromWkt(rectangle.asWktPolygon()))
                # Add feature to list
                features.append(feature)

            # Total
            if service == 'BaseMap':
                # Note : rSearch['totalResults'] is maybe the number of total element in bbox ?
                #   and numberOfElements is the true total result
                total = rSearch['numberOfElements']
                color = QColor.fromRgb(0, 250, 0)
            else:
                total = rSearch['totalResults']
                color = QColor.fromRgb(0, 250, 250)

            if len(self.errorFeatures) > 0:
                total -= len(self.errorFeatures)
                print(f'* {len(self.errorFeatures)} error feature')

            # Notification for number of total results
            msgBox = QMessageBox()
            msgBox.setWindowTitle(WINDOW_TITLE)
            msgBox.setText(f'There are {total} results')
            if total > len(features):
                msgBox.setIcon(QMessageBox.Warning)
                msgBox.setInformativeText(
                    f'The maximum is configured to {self.maxResultsInput.value()}\nPlease refine your criteria or your AOI'
                )
                msgBox.setStandardButtons(QMessageBox.Retry
                                          | QMessageBox.Ignore)
                msgBox.setDefaultButton(QMessageBox.Retry)
            else:
                msgBox.setIcon(QMessageBox.Information)
                msgBox.setStandardButtons(QMessageBox.Retry | QMessageBox.Ok)
                msgBox.setDefaultButton(QMessageBox.Ok)
            msgBox.button(QMessageBox.Retry).setText('Refine')
            msgBox.button(QMessageBox.Retry).setIcon(
                QIcon(os.path.dirname(__file__) + f'/search.png'))

            reply = msgBox.exec_()
            if reply == QMessageBox.Retry or len(features) == 0:
                return

            # Add result feature to the new layer
            (res, outFeats) = layer.dataProvider().addFeatures(features)

            # Change layer syle programmatically
            # Note : if we styling before save and add layer, we avoid to update legend style
            #   => self.iface.layerTreeView().refreshLayerSymbology(vlayer.id())
            symbol = layer.renderer().symbol()
            symbol.setOpacity(0.2)
            symbol.setColor(color)

            QgsProject.instance().addMapLayer(layer)
            # And refresh view
            layer.triggerRepaint()
            self.close()
        except:
            return
Exemplo n.º 29
0
    def accepted(self):
        """
        We start checking the document repository configuration and only allow to continue if we have a valid repo or
        if the repo won't be used.

        Then, check if connection to DB/schema is valid, if not, block the dialog.
        If valid, check it complies with LADM. If not, block the dialog. If it complies, we have two options: To emit
        db_connection changed or not. Finally, we store options in QSettings.
        """
        res_doc_repo, msg_doc_repo = self.check_document_repository_before_saving_settings(
        )
        if not res_doc_repo:
            self.show_message(msg_doc_repo, Qgis.Warning, 0)
            return  # Do not close the dialog

        ladm_col_schema = False

        db = self._get_db_connector_from_gui()

        test_level = EnumTestLevel.DB_SCHEMA

        if self._action_type == EnumDbActionType.SCHEMA_IMPORT:
            # Limit the validation (used in GeoPackage)
            test_level |= EnumTestLevel.SCHEMA_IMPORT

        res, code, msg = db.test_connection(
            test_level
        )  # No need to pass required_models, we don't test that much

        if res:
            if self._action_type != EnumDbActionType.SCHEMA_IMPORT:
                # Only check LADM-schema if we are not in an SCHEMA IMPORT.
                # We know in an SCHEMA IMPORT, at this point the schema is still not LADM.
                ladm_col_schema, code, msg = db.test_connection(
                    EnumTestLevel.LADM, required_models=self._required_models)

            if not ladm_col_schema and self._action_type != EnumDbActionType.SCHEMA_IMPORT:
                if self._blocking_mode:
                    self.show_message(msg, Qgis.Warning)
                    return  # Do not close the dialog

        else:
            if self._blocking_mode:
                self.show_message(msg, Qgis.Warning)
                return  # Do not close the dialog

        # Connection is valid and complies with LADM
        current_db_engine = self.cbo_db_engine.currentData()
        if self._lst_panel[current_db_engine].state_changed(
        ) or self.init_db_engine != current_db_engine:
            # Emit db_connection_changed
            if self._db is not None:
                self._db.close_connection()

            self._db = db

            # Update db connect with new db conn
            self.conn_manager.set_db_connector_for_source(
                self._db, self.db_source)

            # Emmit signal when db source changes
            self.db_connection_changed.emit(self._db, ladm_col_schema,
                                            self.db_source)
            self.logger.debug(
                __name__, "Settings dialog emitted a db_connection_changed.")

        if not ladm_col_schema and self._action_type == EnumDbActionType.CONFIG:
            msg_box = QMessageBox(self)
            msg_box.setIcon(QMessageBox.Question)
            msg_box.setText(
                QCoreApplication.translate(
                    "SettingsDialog",
                    "No LADM-COL DB has been configured! You'll continue with limited functionality until you configure a LADM-COL DB.\n\nDo you want to go to 'Create LADM-COL structure' dialog?"
                ))
            msg_box.setWindowTitle(
                QCoreApplication.translate("SettingsDialog", "Important"))
            msg_box.setStandardButtons(QMessageBox.Yes | QMessageBox.Ignore)
            msg_box.setDefaultButton(QMessageBox.Ignore)
            msg_box.button(QMessageBox.Yes).setText(
                QCoreApplication.translate("SettingsDialog",
                                           "Yes, go to create structure"))
            msg_box.button(QMessageBox.Ignore).setText(
                QCoreApplication.translate("SettingsDialog",
                                           "No, I'll do it later"))
            reply = msg_box.exec_()

            if reply == QMessageBox.Yes:
                self._open_dlg_import_schema = True  # We will open it when we've closed this Settings dialog

        # If active role is changed (a check and confirmation may be needed), refresh the GUI
        # Note: Better to leave this check as the last one in the accepted() method.
        selected_role = self.get_selected_role()
        if self.roles.get_active_role() != selected_role:
            b_change_role = True
            if STSession().is_user_logged():
                reply = QMessageBox.question(
                    self.parent,
                    QCoreApplication.translate("SettingsDialog", "Warning"),
                    QCoreApplication.translate(
                        "SettingsDialog",
                        "You have a ST connection opened and you want to change your role.\nIf you confirm that you want to change your role, you'll be logged out from the ST.\n\nDo you really want to change your role?"
                    ), QMessageBox.Yes | QMessageBox.Cancel,
                    QMessageBox.Cancel)
                if reply == QMessageBox.Yes:
                    STSession().logout()
                elif reply == QMessageBox.Cancel:
                    # No need to switch back selected role, the Settings Dialog gets it from role registry
                    b_change_role = False

            if b_change_role:
                self.logger.info(
                    __name__,
                    "The active role has changed from '{}' to '{}'.".format(
                        self.roles.get_active_role(), selected_role))
                self.roles.set_active_role(
                    selected_role
                )  # Emits signal that refreshed the plugin for this role

        self.save_settings(db)

        QDialog.accept(self)
        self.close()

        if self._open_dlg_import_schema:
            # After Settings dialog has been closed, we could call Import Schema depending on user's answer above
            self.open_dlg_import_schema.emit(Context())
            self.logger.debug(
                __name__,
                "Settings dialog emitted a show Import Schema dialog.")