Example #1
0
    def _addGeoGigServer(self, title, url):
        try:
            repos = addRepoEndpoint(url, title)
            if not repos:
                msg = "No repositories found at the specified server"
                QMessageBox.warning(
                    self, 'Add repositories',
                    "No repositories found at the specified server",
                    QMessageBox.Ok)
                groupItem = GroupItem(title)
            else:
                groupItem = GroupItem(title)
                for repo in repos:
                    item = RepoItem(self.repoTree, repo)
                    groupItem.addChild(item)

        except Exception as e:
            msg = "No geogig server found at the specified url. %s"
            QgsMessageLog.logMessage(msg % e, level=QgsMessageLog.CRITICAL)
            QMessageBox.warning(self, 'Add repositories',
                                msg % "See the logs for details.",
                                QMessageBox.Ok)
            groupItem = GroupItem(title)
        self.reposItem.addChild(groupItem)
        self.reposItem.setExpanded(True)
        self.repoTree.sortItems(0, Qt.AscendingOrder)
    def uninstall_collection(self):
        """Slot called when user clicks the uninstall button."""
        # get the QModelIndex for the item to be uninstalled
        uninstall_index = self.list_view_collections.currentIndex()
        coll_id = self._selected_collection_id
        try:
            self.collection_manager.uninstall(coll_id)
        except Exception as e:
            LOGGER.error('Could not uninstall collection ' +
                         config.COLLECTIONS[coll_id]['name'] + ':\n' + str(e))
        else:
            QMessageBox.information(
                self, 'Resource Sharing',
                'The collection was successfully uninstalled!')
            self.reload_collections_model()
            # Fix the GUI
            currentMenuRow = self.menu_list_widget.currentRow()
            self.set_current_tab(currentMenuRow)
            self.populate_repositories_widget()

            rowCount = self.collection_proxy.rowCount()
            if rowCount > 0:
                # Set the current (and selected) row in the listview
                newRow = uninstall_index.row()
                # Check if this was the last element
                rowCount = self.collection_proxy.rowCount()
                if newRow == rowCount:
                    newRow = newRow - 1
                # Select the new current element
                newIndex = self.collections_model.createIndex(newRow, 0)
                selection_model = self.list_view_collections.selectionModel()
                selection_model.setCurrentIndex(newIndex,
                                                selection_model.ClearAndSelect)
                # Get the id of the current collection
                proxyModel = self.list_view_collections.model()
                proxyIndex = proxyModel.index(newRow, 0)
                current_coll_id = proxyIndex.data(COLLECTION_ID_ROLE)
                self._selected_collection_id = current_coll_id
                # Update buttons
                status = config.COLLECTIONS[current_coll_id]['status']
                if status == COLLECTION_INSTALLED_STATUS:
                    self.button_install.setEnabled(True)
                    self.button_install.setText('Reinstall')
                    self.button_open.setEnabled(True)
                    self.button_uninstall.setEnabled(True)
                else:
                    self.button_install.setEnabled(True)
                    self.button_install.setText('Install')
                    self.button_open.setEnabled(False)
                    self.button_uninstall.setEnabled(False)
                # Update the web_view_details frame
                self.show_collection_metadata(current_coll_id)
            else:
                self.button_install.setEnabled(False)
                self.button_install.setText('Install')
                self.button_open.setEnabled(False)
                self.button_uninstall.setEnabled(False)
 def uninstall_collection(self):
     """Slot called when user clicks uninstall button."""
     try:
         self.collection_manager.uninstall(self._selected_collection_id)
     except Exception as e:
         raise
     self.reload_collections_model()
     QMessageBox.information(
         self,
         'Resource Sharing',
         'The collection is uninstalled succesfully!')
    def getPointTableFromSelectedLine(self, iface, tool, newPoints):
        closestFeatures = []
        layer = iface.activeLayer()
        if layer is None:
            QMessageBox.warning(iface.mainWindow(), "Closest Feature Finder",
                                "No vector layers selected")
            return None, closestFeatures

        # get the point coordinates in the layer's CRS
        point = tool.toLayerCoordinates(
            layer, QgsPoint(newPoints[0][0], newPoints[0][1]))
        closestFeatures = self.select_closest_feature(iface, layer, point)

        return layer, closestFeatures
Example #5
0
 def descriptionLinkClicked(self, url):
     url = url.toString()
     if url.startswith("checkout"):
         layernames = url[url.find(":") + 1:].split(",")
         for layername in layernames:
             if layername:
                 try:
                     self._checkoutLayer(layername, None)
                 except HasLocalChangesError:
                     QMessageBox.warning(
                         config.iface.mainWindow(), 'Cannot change version',
                         "There are local changes that would be overwritten.\n"
                         "Revert them before changing version.",
                         QMessageBox.Ok)
 def install_finished(self):
     # Process the result
     self.progress_dialog.hide()
     if self.installer_worker.install_status:
         self.reload_collections_model()
         message = '%s is installed successfully' % (
             config.COLLECTIONS[self._selected_collection_id]['name'])
     else:
         message = self.installer_worker.error_message
     QMessageBox.information(self, 'Resource Sharing', message)
     # Clean up the worker and thread
     self.installer_worker.deleteLater()
     self.installer_thread.quit()
     self.installer_thread.wait()
     self.installer_thread.deleteLater()
Example #7
0
 def on_restore_default_settings_btn_clicked(self):
     msg = ("All current settings will be deleted and replaced by defaults."
            " Are you sure?")
     reply = QMessageBox.question(self, 'Warning', msg, QMessageBox.Yes,
                                  QMessageBox.No)
     if reply == QMessageBox.Yes:
         self.restore_state(restore_defaults=True)
Example #8
0
 def delete(self):
     ret = QMessageBox.question(self.tree, 'Delete layer',
             'Are you sure you want to delete this layer from this branch?',
             QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
     if ret == QMessageBox.No:
         return
     execute(lambda: self._removeLayer())
    def delete_repository(self):
        """Delete a repository in the tree widget."""
        selected_item = self.tree_repositories.currentItem()
        if selected_item:
            repo_name = selected_item.text(0)
        if not repo_name:
            return
        # Check if it is among the offical repositories
        repo_url = self.repository_manager.directories[repo_name]['url']
        if repo_url in self.repository_manager._online_directories.values():
            self.message_bar.pushMessage(
                self.tr('You can not remove official repositories!'),
                Qgis.Warning, 5)
            return
        warning = self.tr('Are you sure you want to remove the following '
                          'repository?') + '\n' + repo_name
        if QMessageBox.warning(self, self.tr('QGIS Resource Sharing'), warning,
                               QMessageBox.Yes,
                               QMessageBox.No) == QMessageBox.No:
            return

        # Remove repository
        installed_collections = \
            self.collection_manager.get_installed_collections(repo_url)
        if installed_collections:
            message = ('You have installed collections from this '
                       'repository. Please uninstall them first!')
            self.message_bar.pushMessage(message, Qgis.Warning, 5)
        else:
            self.repository_manager.remove_directory(repo_name)
            # Reload data and widget
            self.reload_data_and_widget()
            # Deactivate the edit and delete buttons
            self.button_edit.setEnabled(False)
            self.button_delete.setEnabled(False)
 def on_calc_action_btn_clicked(self, calc_id, action):
     # NOTE: while scrolling through the list of calculations, the tool
     # keeps polling and refreshing the list, without losing the current
     # scrolling.  But if you click on any button, at the next refresh, the
     # view is scrolled to the top. Therefore we need to keep track of which
     # line was selected, in order to scroll to that line.
     self.current_calc_id = self.pointed_calc_id = calc_id
     self._set_show_calc_params_btn()
     self.highlight_and_scroll_to_calc_id(calc_id)
     if action == 'Console':
         self.update_output_list(calc_id)
         self.console_dlg = ShowConsoleDialog(self, calc_id)
         self.console_dlg.setWindowTitle(
             'Console log of calculation %s' % calc_id)
         self.console_dlg.show()
     elif action == 'Remove':
         confirmed = QMessageBox.question(
             self,
             'Remove calculation?',
             'The calculation will be removed permanently. Are you sure?',
             QMessageBox.Yes | QMessageBox.No)
         if confirmed == QMessageBox.Yes:
             self.remove_calc(calc_id)
             if self.current_calc_id == calc_id:
                 self.clear_output_list()
     elif action == 'Outputs':
         self.update_output_list(calc_id)
     elif action == 'Continue':
         self.update_output_list(calc_id)
         self.run_calc(calc_id)
     else:
         raise NotImplementedError(action)
Example #11
0
 def delete(self):
     ret = QMessageBox.question(self.tree, '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(self.branch)
     repoWatcher.repoChanged.emit(self.repo)
 def on_reload_homepage_btn_clicked(self):
     msg = ("Reloading the homepage, all current changes will be discarded."
            " Are you sure?")
     reply = QMessageBox.question(self, 'Warning', msg, QMessageBox.Yes,
                                  QMessageBox.No)
     if reply == QMessageBox.Yes:
         self.set_host()
         self.load_homepage()
 def on_purge_chk_stateChanged(self, state):
     if state:
         reply = QMessageBox.question(
             self, 'Warning!',
             "Are you sure to delete the empty zones from the zonal layer?",
             QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
         if reply == QMessageBox.No:
             self.purge_chk.setCheckState(0)
Example #14
0
def confirm_overwrite(parent, files):
    """
    Open a dialog to ask for user's confirmation on file overwriting
    """
    return QMessageBox.question(
        parent, 'Overwrite existing files?',
        'If you continue the following files will be '
        'overwritten: %s\n\n'
        'Continue?' % '\n'.join(files), QMessageBox.Yes | QMessageBox.No)
Example #15
0
    def _addGeoGigServer(self, title, url):
        try:
            repos = addRepoEndpoint(url, title)
            if not repos:
                msg = "No repositories found at the specified server"
                QMessageBox.warning(self, 'Add repositories',
                                "No repositories found at the specified server",
                                QMessageBox.Ok)


        except Exception as e:
            msg = "No geogig server found at the specified url. %s"
            QgsMessageLog.logMessage(msg % e, level=QgsMessageLog.CRITICAL)
            QMessageBox.warning(self, 'Add repositories',
                                msg % "See the logs for details.",
                                QMessageBox.Ok)

        self.comboEndpoint.addItem(title)
        self.comboEndpoint.setCurrentIndex(self.comboEndpoint.count() - 1)
Example #16
0
 def addLayer(self):
     layers = [
         layer for layer in getVectorLayers()
         if layer.source().lower().split("|")[0].split(".")[-1] in
         ["gpkg", "geopkg"] and not isRepoLayer(layer)
     ]
     if layers:
         dlg = ImportDialog(self, repo=self.currentRepo)
         dlg.exec_()
         if dlg.ok:
             #self.versionsTree.updateCurrentBranchItem()
             setAsRepoLayer(dlg.layer)
             repoWatcher.repoChanged.emit(self.currentRepo)
     else:
         QMessageBox.warning(
             self, 'Cannot add layer',
             "No suitable layers can be found in your current QGIS project.\n"
             "Only Geopackage layers that do not already belong to a repository can be added.",
             QMessageBox.Ok)
Example #17
0
    def deleteCurrentElement(self):
        if len(self.repoTree.selectedItems()) == 0:
            return

        item = self.repoTree.selectedItems()[0]
        if isinstance(item, RepoItem):
            ret = QMessageBox.warning(
                config.iface.mainWindow(), "Remove repository",
                "Are you sure you want to remove this repository and all the data in it?",
                QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
            if ret == QMessageBox.No:
                return
            tracked = getTrackedPathsForRepo(item.repo)
            item.repo.delete()
            removeRepo(item.repo)
            removeTrackedForRepo(item.repo)
            layers = getVectorLayers()
            for layer in layers:
                if formatSource(layer) in tracked:
                    setAsNonRepoLayer(layer)
            parent = item.parent()
            parent.removeChild(item)
            self.updateCurrentRepo(None)
        elif isinstance(item, GroupItem):
            self._removeRepoEndpoint(item)
        elif isinstance(item, BranchItem):
            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
            item.repo.deletebranch(item.branch)
            repoWatcher.repoChanged.emit(item.repo)

        elif isinstance(item, LayerItem):
            ret = QMessageBox.question(
                self, 'Delete layer',
                'Are you sure you want to delete this layer from the selected branch?',
                QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            if ret == QMessageBox.No:
                return
            execute(lambda: self._removeLayer(item))
 def deleteGeoGigServer(self):
     group = self.comboEndpoint.currentText()
     res = QMessageBox.question(
         None, "Delete server?", "Are you sure you want to remove the "
         "'{}' GeoGig server from the list?".format(group),
         QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
     if res == QMessageBox.Yes:
         removeRepoEndpoint(group)
         self.comboEndpoint.removeItem(self.comboEndpoint.currentIndex())
         self.fillTree()
         self._enableOrDisableButtons()
 def install_finished(self):
     # Process the result
     self.progress_dialog.hide()
     installStatus = self.installer_worker.install_status
     if not installStatus:
         message = self.installer_worker.error_message
     # Clean up the worker and thread
     self.installer_worker.deleteLater()
     self.installer_thread.quit()
     self.installer_thread.wait()
     self.installer_thread.deleteLater()
     if installStatus:
         self.reload_collections_model()
         # Report what has been installed
         message = ('<b>%s</b> was successfully installed, '
                    'containing:\n<ul>' %
                    (config.COLLECTIONS[self._sel_coll_id]['name']))
         number = 0
         for type_, description in SUPPORTED_RESOURCES_MAP.items():
             if type_ in config.COLLECTIONS[self._sel_coll_id].keys():
                 number = config.COLLECTIONS[self._sel_coll_id][type_]
                 message += (f'\n<li>{number} {description}'
                             f'{"s" if number > 1 else ""}'
                             f'</li>')
         message += '\n</ul>'
     QMessageBox.information(self, 'Resource Sharing', message)
     self.populate_repositories_widget()
     # Set the selection
     oldRow = self.current_index.row()
     newIndex = self.collections_model.createIndex(oldRow, 0)
     selection_model = self.list_view_collections.selectionModel()
     selection_model.setCurrentIndex(newIndex,
                                     selection_model.ClearAndSelect)
     selection_model.select(newIndex, selection_model.ClearAndSelect)
     # Update the buttons
     self.button_install.setEnabled(True)
     self.button_install.setText('Reinstall')
     self.button_open.setEnabled(True)
     self.button_uninstall.setEnabled(True)
     self.show_collection_metadata(self._sel_coll_id)
Example #20
0
    def credentials_uploader(self):
        """Get file selected by the user and loads API credentials into plugin.
        If the selected is compliant, credentials are loaded from then it's
        moved inside plugin/_auth subfolder.
        """
        # test file structure
        try:
            selected_file = path.normpath(self.ui_auth_form.btn_browse_credentials.filePath())
            api_credentials = plg_tools.credentials_loader(selected_file)
        except Exception as e:
            logger.error(e)
            QMessageBox.critical(self.ui_auth_form,
                                 self.tr("Alert", "IsogeoPlgApiMngr"),
                                 self.tr("The selected credentials file is not correct.",
                                         "IsogeoPlgApiMngr"))
        # move credentials file into the plugin file structure
        if path.isfile(path.join(self.auth_folder, "client_secrets.json")):
            rename(path.join(self.auth_folder, "client_secrets.json"),
                   path.join(self.auth_folder, "old_client_secrets_{}.json"
                                               .format(int(time.time())))
                   )
            logger.debug("client_secrets.json already existed. "
                         "Previous file has been renamed.")
        else:
            pass
        rename(selected_file,
               path.join(self.auth_folder, "client_secrets.json"))
        logger.debug("Selected credentials file has been moved into plugin"
                     "_auth subfolder")

        # set form
        self.ui_auth_form.ent_app_id.setText(api_credentials.get("client_id"))
        self.ui_auth_form.ent_app_secret.setText(api_credentials.get("client_secret"))
        self.ui_auth_form.lbl_api_url_value.setText(api_credentials.get("uri_auth"))

        # update class attributes from file
        self.credentials_update(credentials_source="oAuth2_file")

        # store into QSettings if existing
        self.credentials_storer(store_location="QSettings")
 def deleteGeoGigServer(self):
     group = self.comboEndpoint.currentText()
     res = QMessageBox.question(None,
                               "Delete server?",
                               "Are you sure you want to remove the "
                               "'{}' GeoGig server from the list?".format(group),
                               QMessageBox.Yes | QMessageBox.No,
                               QMessageBox.No)
     if res == QMessageBox.Yes:
         removeRepoEndpoint(group)
         self.comboEndpoint.removeItem(self.comboEndpoint.currentIndex())
         self.fillTree()
         self._enableOrDisableButtons()
Example #22
0
    def genReport(self):
        tec = self.tecItemList.currentItem()

        projFolder = self.settings.value('projFolder')
        saveFile = QFileDialog.getSaveFileName(filter=self.tr('*.txt;; *.csv'),
                                               directory=projFolder)
        if saveFile.endswith('.txt'):
            self.reportAsTxt(tec, saveFile)
        elif saveFile.endswith('.csv'):
            self.reportAsCsv(tec, saveFile)
        else:
            QMessageBox(QMessageBox.Critical,
                        title=toUnicode(MSG['msg26']),
                        text=toUnicode(MSG['msg25']))
Example #23
0
    def selectionChanged(self):
        self.checkButtons()
        items = self.repoTree.selectedItems()
        if items:
            item = items[0]
            try:
                if isinstance(item, (GroupItem, RepositoriesItem)):
                    self.updateCurrentRepo(None)
                    url = QUrl.fromLocalFile(
                        resourceFile("localrepos_offline.html"))
                    self.repoDescription.setSource(url)
                else:
                    if item.repo != self.currentRepo:
                        self.updateCurrentRepo(item.repo)

            except Exception as e:
                msg = "An error occurred while fetching repository data! %s"
                QgsMessageLog.logMessage(msg % e, level=QgsMessageLog.CRITICAL)
                QMessageBox.warning(self, 'Add repositories',
                                    msg % "See the logs for details.",
                                    QMessageBox.Ok)
        else:
            self.updateCurrentRepo(None)
Example #24
0
    def pull(self):
        dlg = RemoteRefDialog(self.currentRepo)
        dlg.exec_()
        if dlg.remote is not None:
            conflicts = execute(
                lambda: self.currentRepo.pull(dlg.remote, dlg.branch))
            if conflicts:
                ret = QMessageBox.warning(
                    iface.mainWindow(), "Error while syncing",
                    "There are conflicts between local and remote changes.\n"
                    "Do you want to continue and fix them?",
                    QMessageBox.Yes | QMessageBox.No)
                if ret == QMessageBox.No:
                    self.currentRepo.closeTransaction(
                        conflicts[0].transactionId)
                    return

                dlg = ConflictDialog(conflicts)
                dlg.exec_()
                solved, resolvedConflicts = dlg.solved, dlg.resolvedConflicts
                if not solved:
                    self.repo.closeTransaction(conflicts[0].transactionId)
                    return
                for conflict, resolution in zip(
                        conflicts, list(resolvedConflicts.values())):
                    if resolution == ConflictDialog.LOCAL:
                        conflict.resolveWithLocalVersion()
                    elif resolution == ConflictDialog.REMOTE:
                        conflict.resolveWithRemoteVersion()
                    elif resolution == ConflictDialog.DELETE:
                        conflict.resolveDeletingFeature()
                    else:
                        conflict.resolveWithNewFeature(resolution)
                user, email = config.getUserInfo()
                if user is None:
                    return
                self.currentRepo.commitAndCloseMergeAndTransaction(
                    user, email, "Resolved merge conflicts",
                    conflicts[0].transactionId)
                config.iface.messageBar().pushMessage(
                    "Changes have been correctly pulled from remote",
                    level=QgsMessageBar.INFO,
                    duration=5)
                repoWatcher.repoChanged.emit(self.currentRepo)
            else:
                config.iface.messageBar().pushMessage(
                    "Changes have been correctly pulled from remote",
                    level=QgsMessageBar.INFO,
                    duration=5)
                repoWatcher.repoChanged.emit(self.currentRepo)
Example #25
0
    def handle_token(self, answer):
        """Handle the API answer when asked for a token.

        This handles the API answer. If it has sent an access token, it calls
        the initialization function. If not, it raises an error, and ask
        for new IDs
        """
        logger.info("Asked a token and got a reply from the API.")
        bytarray = answer.readAll()
        content = str(bytarray)
        parsed_content = json.loads(content)
        if "access_token" in parsed_content:
            logger.info("The API reply is an access token : "
                        "the request worked as expected.")
            # TO DO : Appeler la fonction d'initialisation
            self.token = "Bearer " + parsed_content["access_token"]
            if self.savedSearch == "first":
                self.requestStatusClear = True
                self.set_widget_status()
            else:
                self.requestStatusClear = True
                self.send_request_to_isogeo_api(self.token)
        # TO DO : Distinguer plusieurs cas d"erreur
        elif "error" in parsed_content:
            logger.error("The API reply is an error. Id and secret must be "
                         "invalid. Asking for them again.")
            QMessageBox.information(
                iface.mainWindow(), self.tr("Error"), parsed_content["error"])
            self.requestStatusClear = True
            self.auth_prompt_form.show()
        else:
            self.requestStatusClear = True
            logger.error("The API reply has an unexpected form : "
                         "{0}".format(parsed_content))
            QMessageBox.information(
                iface.mainWindow(), self.tr("Error"), self.tr("Unknown error"))
Example #26
0
 def displayBboxOnMap(self, dstLayer, crs, bboxString, formatInstance):
     bboxGeom = formatInstance.format(bboxString)
     if dstLayer is None:
         dstLayer = self.createTemporaryLayer(crs)
     if dstLayer.readOnly():
         errorMessage = QCoreApplication.translate(
             B_BOX_TOOLBOX, "Selected layer is readonly")
         QMessageBox.Critical(self.iface.mainWindow(), B_BOX_TOOLBOX,
                              errorMessage)
         return
     f = self.createFeature(bboxGeom)
     dstLayer.dataProvider().addFeature(f)
     dstLayer.updateExtents()
     dstLayer.reload()
     self.canvas.refreshAllLayers()
Example #27
0
 def delete(self):
     ret = QMessageBox.warning(config.iface.mainWindow(), "Remove repository",
                         "Are you sure you want to remove this repository and all the data in it?",
                         QMessageBox.Yes | QMessageBox.No,
                         QMessageBox.Yes);
     if ret == QMessageBox.No:
         return
     tracked = getTrackedPathsForRepo(self.repo)
     self.repo.delete()
     removeRepo(self.repo)
     removeTrackedForRepo(self.repo)
     layers = vectorLayers()
     for layer in layers:
         if formatSource(layer) in tracked:
             setAsNonRepoLayer(layer)
     self.tree.takeTopLevelItem(self.tree.indexOfTopLevelItem(self))
     repoWatcher.repoChanged.emit(self.repo)
Example #28
0
def confirmation_on_close(parent, event=None):
    """
    Open a QMessageBox to confirm closing a dialog discarding changes

    :param parent: the parent dialog that is being closed
    :param event: event that triggered this dialog (e.g. reject or closeEvent)
    """
    msg = tr("WARNING: all unsaved changes will be lost. Are you sure?")
    reply = QMessageBox.question(parent, 'Message', msg, QMessageBox.Yes,
                                 QMessageBox.No)
    if event is not None:
        if reply == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()
    else:
        if reply == QMessageBox.Yes:
            parent.__class__.__base__.reject(parent)
Example #29
0
 def remove_selected_profile(self, platform_or_engine):
     assert platform_or_engine in ('platform', 'engine'), platform_or_engine
     if QMessageBox.question(
             self, 'Remove connection profile',
         ('If you continue, the selected profile will be permanently'
          ' deleted. Are you sure?'),
             QMessageBox.Yes | QMessageBox.No) != QMessageBox.Yes:
         return
     profiles = json.loads(QSettings().value('irmt/%s_profiles' %
                                             platform_or_engine))
     if platform_or_engine == 'platform':
         cur_profile = self.platform_profile_cbx.currentText()
     else:  # engine
         cur_profile = self.engine_profile_cbx.currentText()
     del profiles[cur_profile]
     QSettings().remove('irmt/current_%s_profile' % platform_or_engine)
     self.save_profiles(platform_or_engine, profiles)
     self.refresh_profile_cbxs(platform_or_engine)
    def delete_repository(self):
        """Delete a repository in the tree widget."""
        selected_item = self.tree_repositories.currentItem()
        if selected_item:
            repo_name = selected_item.text(0)

        if not repo_name:
            return
        # Check if it's the approved online dir repository
        repo_url = self.repository_manager.directories[repo_name]['url']
        if repo_url in self.repository_manager._online_directories.values():
            self.message_bar.pushMessage(
                self.tr(
                    'You can not remove the official repositories!'),
                Qgis.Warning, 5)
            return

        warning = self.tr('Are you sure you want to remove the following '
                          'repository?') + '\n' + repo_name
        if QMessageBox.warning(
                self,
                self.tr('QGIS Resource Sharing'),
                warning,
                QMessageBox.Yes,
                QMessageBox.No) == QMessageBox.No:
            return

        # Remove repository
        installed_collections = \
            self.collection_manager.get_installed_collections(repo_url)
        if installed_collections:
            message = ('You have some installed collections from this '
                       'repository. Please uninstall them first!')
            self.message_bar.pushMessage(message, Qgis.Warning, 5)
        else:
            self.repository_manager.remove_directory(repo_name)
            # Reload data and widget
            self.reload_data_and_widget()
            # Deactivate edit and delete button
            self.button_edit.setEnabled(False)
            self.button_delete.setEnabled(False)
    def pull(self):
        dlg = RemoteRefDialog(self.repo)
        dlg.exec_()
        if dlg.remote is not None:
            conflicts = execute(lambda: self.repo.pull(dlg.remote, dlg.branch))
            if conflicts:
                ret = QMessageBox.warning(iface.mainWindow(), "Conflict(s) found while syncing",
                                          "There are conflicts between local repository and connection.\n"
                                          "Do you want to continue and fix them?",
                                          QMessageBox.Yes | QMessageBox.No)
                if ret == QMessageBox.No:
                    self.repo.closeTransaction(conflicts[0].transactionId)
                    return

                dlg = ConflictDialog(conflicts)
                dlg.exec_()
                solved, resolvedConflicts = dlg.solved, dlg.resolvedConflicts
                if not solved:
                    self.repo.closeTransaction(conflicts[0].transactionId)
                    return
                for conflict, resolution in zip(conflicts, list(resolvedConflicts.values())):
                    if resolution == ConflictDialog.LOCAL:
                        conflict.resolveWithLocalVersion()
                    elif resolution == ConflictDialog.REMOTE:
                        conflict.resolveWithRemoteVersion()
                    elif resolution == ConflictDialog.DELETE:
                        conflict.resolveDeletingFeature()
                    else:
                        conflict.resolveWithNewFeature(resolution)
                user, email = config.getUserInfo()
                if user is None:
                    return
                self.repo.commitAndCloseMergeAndTransaction(user, email, "Resolved merge conflicts", conflicts[0].transactionId)
                config.iface.messageBar().pushMessage("Changes have been correctly pulled from the connection",
                                               level = QgsMessageBar.INFO, duration = 5)
                repoWatcher.repoChanged.emit(self.repo)
            else:
                config.iface.messageBar().pushMessage("Changes have been correctly pulled from the connection",
                                               level = QgsMessageBar.INFO, duration = 5)
                repoWatcher.repoChanged.emit(self.repo)
Example #32
0
    def addLayer(self , iface, mdl, layer1 = None):
        if layer1 == None:
            templist=[]
            j=0
            # Ask the layer by a input dialog 
            for i in range(0, iface.mapCanvas().layerCount()):
                donothing = False
                layer = iface.mapCanvas().layer(i)
                if isProfilable(layer):
                    for j in range(0, mdl.rowCount()):
                        if str(mdl.item(j,2).data(QtCore.Qt.EditRole)) == str(layer.name()):
                            donothing = True
                else:
                    donothing = True
                    
                if donothing == False:
                    templist +=  [[layer, layer.name()]]
                        
            if len(templist) == 0:
                QMessageBox.warning(iface.mainWindow(), "Profile tool", "No raster to add")
                return
            else:    
                testqt, ok = QInputDialog.getItem(iface.mainWindow(), "Layer selector", "Choose layer", [templist[k][1] for k in range( len(templist) )], False)
                if ok:
                    for i in range (0,len(templist)):
                        if templist[i][1] == testqt:
                            layer2 = templist[i][0]
                else:
                    return
        else : 
            if isProfilable(layer1):
                layer2 = layer1
            else:
                QMessageBox.warning(iface.mainWindow(), "Profile tool", "Active layer is not a profilable layer")
                return

        # Ask the Band by a input dialog
        #First, if isProfilable, considerate the real band number (instead of band + 1 for raster)
        if layer2.type() == layer2.PluginLayer and  isProfilable(layer2):
            self.bandoffset = 0
            typename = 'parameter'
        elif layer2.type() == layer2.RasterLayer:
            self.bandoffset = 1
            typename = 'band'
        elif layer2.type() == layer2.VectorLayer:
            self.bandoffset = 0
            typename = 'field'

            
        if layer2.type() == layer2.RasterLayer and layer2.bandCount() != 1:
            listband = []
            for i in range(0,layer2.bandCount()):
                listband.append(str(i+self.bandoffset))
            testqt, ok = QInputDialog.getItem(iface.mainWindow(), typename + " selector", "Choose the " + typename, listband, False)
            if ok :
                choosenBand = int(testqt) - self.bandoffset
            else:
                return 2
        elif layer2.type() == layer2.VectorLayer :
            fieldstemp = [field.name() for field in layer2.fields() ]
            if int(QtCore.QT_VERSION_STR[0]) == 4 :    #qgis2
                fields = [field.name() for field in layer2.fields() if field.type() in [2,3,4,5,6]]
            
            elif int(QtCore.QT_VERSION_STR[0]) == 5 :    #qgis3
                fields = [field.name() for field in layer2.fields() if field.isNumeric()]
            if len(fields)==0:
                QMessageBox.warning(iface.mainWindow(), "Profile tool", "Active layer is not a profilable layer")
                return
            elif len(fields) == 1 :
                choosenBand = fieldstemp.index(fields[0])
                
            else:
                testqt, ok = QInputDialog.getItem(iface.mainWindow(), typename + " selector", "Choose the " + typename, fields, False)
                if ok :
                    choosenBand = fieldstemp.index(testqt)
                else:
                    return 2
            
        else:
            choosenBand = 0

        #Complete the tableview
        row = mdl.rowCount()
        mdl.insertRow(row)
        mdl.setData( mdl.index(row, 0, QModelIndex())  ,True, QtCore.Qt.CheckStateRole)
        mdl.item(row,0).setFlags(QtCore.Qt.ItemIsSelectable) 
        lineColour = QtCore.Qt.red
        if layer2.type() == layer2.PluginLayer and layer2.LAYER_TYPE == 'crayfish_viewer':
            lineColour = QtCore.Qt.blue
        mdl.setData( mdl.index(row, 1, QModelIndex())  ,QColor(lineColour) , QtCore.Qt.BackgroundRole)
        mdl.item(row,1).setFlags(QtCore.Qt.NoItemFlags) 
        mdl.setData( mdl.index(row, 2, QModelIndex())  ,layer2.name())
        mdl.item(row,2).setFlags(QtCore.Qt.NoItemFlags) 
        mdl.setData( mdl.index(row, 3, QModelIndex())  ,choosenBand + self.bandoffset)
        mdl.item(row,3).setFlags(QtCore.Qt.NoItemFlags) 

        if layer2.type() == layer2.VectorLayer :
            #mdl.setData( mdl.index(row, 4, QModelIndex())  ,QVariant(100.0))
            mdl.setData( mdl.index(row, 4, QModelIndex())  ,100.0)
            #mdl.item(row,3).setFlags(Qt.NoItemFlags) 
        else:
            mdl.setData( mdl.index(row, 4, QModelIndex())  ,'')
            mdl.item(row,4).setFlags(QtCore.Qt.NoItemFlags) 
            
            
        mdl.setData( mdl.index(row, 5, QModelIndex())  ,layer2)
        mdl.item(row,5).setFlags(QtCore.Qt.NoItemFlags)
        self.layerAddedOrRemoved.emit()
    def install_finished(self):
        # Process the result
        self.progress_dialog.hide()
        installStatus = self.installer_worker.install_status
        if not installStatus:
            message = self.installer_worker.error_message
        # Clean up the worker and thread
        self.installer_worker.deleteLater()
        self.installer_thread.quit()
        self.installer_thread.wait()
        self.installer_thread.deleteLater()

        if installStatus:
            self.reload_collections_model()
            # Report what has been installed
            message = '<b>%s</b> was successfully installed, containing:\n<ul>' % (
                config.COLLECTIONS[self._selected_collection_id]['name'])
            number = 0
            if 'style' in config.COLLECTIONS[
                    self._selected_collection_id].keys():
                number = config.COLLECTIONS[
                    self._selected_collection_id]['style']
                message = message + '\n<li> ' + str(
                    number) + ' Layer style (QML) file'
                if number > 1:
                    message = message + 's'
            if 'symbol' in config.COLLECTIONS[
                    self._selected_collection_id].keys():
                number = config.COLLECTIONS[
                    self._selected_collection_id]['symbol']
                message = message + '\n<li> ' + str(
                    number) + ' XML symbol file'
                if number > 1:
                    message = message + 's'
            if 'svg' in config.COLLECTIONS[
                    self._selected_collection_id].keys():
                number = config.COLLECTIONS[
                    self._selected_collection_id]['svg']
                message = message + '\n<li> ' + str(number) + ' SVG file'
                if number > 1:
                    message = message + 's'
            if 'models' in config.COLLECTIONS[
                    self._selected_collection_id].keys():
                number = config.COLLECTIONS[
                    self._selected_collection_id]['models']
                message = message + '\n<li> ' + str(number) + ' model'
                if number > 1:
                    message = message + 's'
            if 'expressions' in config.COLLECTIONS[
                    self._selected_collection_id].keys():
                number = config.COLLECTIONS[
                    self._selected_collection_id]['expressions']
                message = message + '\n<li> ' + str(
                    number) + ' expression file'
                if number > 1:
                    message = message + 's'
            if 'processing' in config.COLLECTIONS[
                    self._selected_collection_id].keys():
                number = config.COLLECTIONS[
                    self._selected_collection_id]['processing']
                message = message + '\n<li> ' + str(
                    number) + ' processing script'
                if number > 1:
                    message = message + 's'
            if 'rscripts' in config.COLLECTIONS[
                    self._selected_collection_id].keys():
                number = config.COLLECTIONS[
                    self._selected_collection_id]['rscripts']
                message = message + '\n<li> ' + str(number) + ' R script'
                if number > 1:
                    message = message + 's'
            message = message + '\n</ul>'
        QMessageBox.information(self, 'Resource Sharing', message)
        self.populate_repositories_widget()
        # Set the selection
        oldRow = self.current_index.row()
        newIndex = self.collections_model.createIndex(oldRow, 0)
        selection_model = self.list_view_collections.selectionModel()
        selection_model.setCurrentIndex(newIndex,
                                        selection_model.ClearAndSelect)
        selection_model.select(newIndex, selection_model.ClearAndSelect)
        # Update the buttons
        self.button_install.setEnabled(True)
        self.button_install.setText('Reinstall')
        self.button_open.setEnabled(True)
        self.button_uninstall.setEnabled(True)

        self.show_collection_metadata(self._selected_collection_id)
Example #34
0
 def exceptionOccurred(self, message):
     QMessageBox.critical(self, self.tr("OQ-Consolidate: Error"), message)
     self.stopProcessing()
     self.restoreGui()
     return
Example #35
0
 def processError(self, message):
     QMessageBox.critical(self, self.tr("OQ-Consolidate: Error"), message)
     self.stopProcessing()
     self.restoreGui()
     return
Example #36
0
 def processFinished(self):
     self.stopProcessing()
     QMessageBox.information(self, self.tr("OQ-Consolidate: Info"),
                             'Consolidation complete.')
     self.restoreGui()
 def add(self):
     if self.status == self.NOT_IN_SYNC:
         msgBox = QMessageBox()
         msgBox.setWindowTitle("Layer was already exported")
         msgBox.setText("This layer was exported already at a different commit.\n"
                        "Which one would you like to add to your QGIS project?")
         msgBox.addButton(QPushButton('Use previously exported commit'), QMessageBox.YesRole)
         msgBox.addButton(QPushButton('Use latest commit from this branch'), QMessageBox.NoRole)
         msgBox.addButton(QPushButton('Cancel'), QMessageBox.RejectRole)
         QApplication.restoreOverrideCursor()
         ret = msgBox.exec_()
         if ret == 0:
             checkoutLayer(self.repo, self.layer, None, self.currentCommitId)
         elif ret == 1:
             try:
                 layer = checkoutLayer(self.repo, self.layer, None, self.branchCommitId)
                 repoWatcher.layerUpdated.emit(layer)
             except HasLocalChangesError:
                 QMessageBox.warning(config.iface.mainWindow(), 'Cannot export this commit',
                                     "The layer has local changes that would be overwritten.\n"
                                     "Either sync layer with branch or revert local changes "
                                     "before changing commit",QMessageBox.Ok)
     else:
         checkoutLayer(self.repo, self.layer, None, self.branchCommitId)
Example #38
0
    def test_proxy_configuration(self):
        """Check adequation between system and QGIS proxy configuration.

        If a proxy configuration is set up for the computer, and for QGIS.
        If none or both is set up, pass. But if there is a proxy config for the
        computer but not in QGIS, pops an alert message.
        """
        system_proxy_config = getproxies()
        if system_proxy_config == {}:
            logger.info("No proxy found on the OS: OK.")
            return 0
        else:
            qgis_proxy = qsettings.value("proxy/proxyEnabled", "")
            if str(qgis_proxy) == "true":
                http = system_proxy_config.get('http')
                if http is None:
                    pass
                else:
                    elements = http.split(':')
                    if len(elements) == 2:
                        host = elements[0]
                        port = elements[1]
                        qgis_host = qsettings.value("proxy/proxyHost", "")
                        qgis_port = qsettings.value("proxy/proxyPort", "")
                        if qgis_host == host:
                            if qgis_port == port:
                                logger.info("A proxy is set up both in QGIS "
                                            "and the OS and they match => "
                                            "Proxy config : OK")
                                pass
                            else:
                                QMessageBox.information(iface.mainWindow(
                                ), self.tr("Alert", "Tools"),
                                    self.tr("Proxy issue : \nQGIS and your OS "
                                            "have different proxy set up.", "Tools"))
                        else:
                            QMessageBox.information(iface.mainWindow(
                            ), self.tr("Alert", "Tools"),
                                self.tr("Proxy issue : \nQGIS and your OS have"
                                        " different proxy set ups.", "Tools"))
                    elif len(elements) == 3 and elements[0] == 'http':
                        host_short = elements[1][2:]
                        host_long = elements[0] + ':' + elements[1]
                        port = elements[2]
                        qgis_host = qsettings.value("proxy/proxyHost", "")
                        qgis_port = qsettings.value("proxy/proxyPort", "")
                        if qgis_host == host_short or qgis_host == host_long:
                            if qgis_port == port:
                                logger.info("A proxy is set up both in QGIS"
                                            " and the OS and they match "
                                            "=> Proxy config : OK")
                                pass
                            else:
                                logger.error("OS and QGIS proxy ports do not "
                                             "match. => Proxy config: not OK")
                                QMessageBox.information(iface.mainWindow(
                                ), self.tr("Alert", "Tools"),
                                    self.tr("Proxy issue : \nQGIS and your OS"
                                            " have different proxy set ups.", "Tools"))
                        else:
                            logger.error("OS and QGIS proxy hosts do not "
                                         "match. => Proxy config: not OK")
                            QMessageBox.information(iface.mainWindow(
                            ), self.tr("Alert", "Tools"),
                                self.tr("Proxy issue : \nQGIS and your OS have"
                                        " different proxy set ups.", "Tools"))
            else:
                logger.error("OS uses a proxy but it isn't set up in QGIS."
                             " => Proxy config: not OK")
                QMessageBox.information(iface.mainWindow(
                ), self.tr("Alert", "Tools"),
                    self.tr("Proxy issue : \nYou have a proxy set up on your"
                            " OS but none in QGIS.\nPlease set it up in "
                            "'Preferences/Options/Network'.", "Tools"))