Beispiel #1
0
    def __init__(self, parent, tablename):
        super(PostgisTableSelector, self).__init__(parent)
        self.connection = None
        self.table = None
        self.schema = None
        self.setupUi(self)
        settings = QSettings()
        settings.beginGroup('/PostgreSQL/connections/')
        names = settings.childGroups()
        settings.endGroup()
        for n in names:
            item = ConnectionItem(n)
            self.treeConnections.addTopLevelItem(item)

        def itemExpanded(item):
            try:
                item.populateSchemas()
            except:
                pass

        self.treeConnections.itemExpanded.connect(itemExpanded)

        self.textTableName.setText(tablename)

        self.buttonBox.accepted.connect(self.okPressed)
        self.buttonBox.rejected.connect(self.cancelPressed)
    def __init__(self, iface):
        self.iface = iface
        QDialog.__init__(self)
        # Set up the user interface from Designer.
        self.ui = uic.loadUi(ui_file, self)

        self.configFilePath = os.path.join(os.path.dirname(__file__), 'config.cfg')
        self.defFlags = Qt.NoItemFlags | Qt.ItemIsEnabled | Qt.ItemIsEditable | Qt.ItemIsSelectable
        
        # Populate the PostGIS connection combo with the available connections
        
        # Determine our current preference
        s = QSettings()
        selectedConnection = str(s.value("constraintchecker/postgisConnection", ''))
        
        s.beginGroup('PostgreSQL/connections')
        i = 0
        for connectionName in s.childGroups():
            self.postgisConnectionComboBox.addItem(connectionName)
            if connectionName == selectedConnection:
                # Select this preference in the combo if exists
                self.postgisConnectionComboBox.setCurrentIndex(i)
            i += 1
        s.endGroup()
        
        # Now read the configuration file (if it exists) into the table widget
        try:
            self.readConfiguration()
        except:
            pass
Beispiel #3
0
 def deleteRepository(self, reposName):
     """ delete repository connection """
     if not reposName:
         return
     reposName = reposName.decode("utf-8")
     settings = QSettings()
     settings.beginGroup(reposGroup)
     if settings.value(reposName + "/url", "", type=unicode) == officialRepo[1]:
         iface.pluginManagerInterface().pushMessage(
             self.tr("You can't remove the official QGIS Plugin Repository. You can disable it if needed."),
             QgsMessageBar.WARNING,
         )
         return
     warning = self.tr("Are you sure you want to remove the following repository?") + "\n" + reposName
     if (
         QMessageBox.warning(
             iface.mainWindow(), self.tr("QGIS Python Plugin Installer"), warning, QMessageBox.Yes, QMessageBox.No
         )
         == QMessageBox.No
     ):
         return
     # delete from the settings, refresh data and repopulate all the widgets
     settings.remove(reposName)
     repositories.remove(reposName)
     plugins.removeRepository(reposName)
     self.reloadAndExportData()
    def load_directories(self):
        """Load directories of repository registered in settings."""
        self._directories = {}
        settings = QSettings()
        settings.beginGroup(repo_settings_group())

        # Write online directory first to QSettings if needed
        for online_dir_name in self._online_directories:
            repo_present = False
            for repo_name in settings.childGroups():
                url = settings.value(repo_name + '/url', '', type=unicode)
                if url == self._online_directories[online_dir_name]:
                    repo_present = True
                    break
            if not repo_present:
                self.add_directory(
                    online_dir_name, self._online_directories[online_dir_name])

        for repo_name in settings.childGroups():
            self._directories[repo_name] = {}
            url = settings.value(
                repo_name + '/url', '', type=unicode)
            self._directories[repo_name]['url'] = url
            auth_cfg = settings.value(
                repo_name + '/auth_cfg', '', type=unicode).strip()
            self._directories[repo_name]['auth_cfg'] = auth_cfg
        settings.endGroup()
Beispiel #5
0
 def addRepository(self):
     """ add new repository connection """
     dlg = QgsPluginInstallerRepositoryDialog(iface.mainWindow())
     dlg.editParams.setText(repositories.urlParams())
     dlg.checkBoxEnabled.setCheckState(Qt.Checked)
     if not dlg.exec_():
         return
     for i in repositories.all().values():
         if dlg.editURL.text().strip() == i["url"]:
             iface.pluginManagerInterface().pushMessage(
                 self.tr("Unable to add another repository with the same URL!"), QgsMessageBar.WARNING
             )
             return
     settings = QSettings()
     settings.beginGroup(reposGroup)
     reposName = dlg.editName.text()
     reposURL = dlg.editURL.text().strip()
     if reposName in repositories.all():
         reposName = reposName + "(2)"
     # add to settings
     settings.setValue(reposName + "/url", reposURL)
     settings.setValue(reposName + "/authcfg", dlg.editAuthCfg.text().strip())
     settings.setValue(reposName + "/enabled", bool(dlg.checkBoxEnabled.checkState()))
     # refresh lists and populate widgets
     plugins.removeRepository(reposName)
     self.reloadAndExportData()
Beispiel #6
0
    def connect(self, parent=None):
        conn_name = self.connectionName()
        settings = QSettings()
        settings.beginGroup(u"/%s/%s" % (self.connectionSettingsKey(), conn_name))

        if not settings.contains("database"):  # non-existent entry?
            raise InvalidDataException(self.tr('There is no defined database connection "%s".') % conn_name)

        from qgis.core import QgsDataSourceUri

        uri = QgsDataSourceUri()

        settingsList = ["service", "host", "port", "database", "username", "password", "authcfg"]
        service, host, port, database, username, password, authcfg = [settings.value(x, "", type=str) for x in settingsList]

        useEstimatedMetadata = settings.value("estimatedMetadata", False, type=bool)
        sslmode = settings.value("sslmode", QgsDataSourceUri.SslPrefer, type=int)

        settings.endGroup()

        if service:
            uri.setConnection(service, database, username, password, sslmode, authcfg)
        else:
            uri.setConnection(host, port, database, username, password, sslmode, authcfg)

        uri.setUseEstimatedMetadata(useEstimatedMetadata)

        try:
            return self.connectToUri(uri)
        except ConnectionError:
            return False
Beispiel #7
0
def uri_from_name(conn_name):
    settings = QSettings()
    settings.beginGroup(u"/PostgreSQL/connections/%s" % conn_name)

    if not settings.contains("database"):  # non-existent entry?
        raise DbError('There is no defined database connection "%s".' % conn_name)

    uri = QgsDataSourceUri()

    settingsList = ["service", "host", "port", "database", "username", "password", "authcfg"]
    service, host, port, database, username, password, authcfg = [settings.value(x, "", type=str) for x in settingsList]

    useEstimatedMetadata = settings.value("estimatedMetadata", False, type=bool)
    sslmode = settings.value("sslmode", QgsDataSourceUri.SslPrefer, type=int)

    settings.endGroup()

    if hasattr(authcfg, 'isNull') and authcfg.isNull():
        authcfg = ''

    if service:
        uri.setConnection(service, database, username, password, sslmode, authcfg)
    else:
        uri.setConnection(host, port, database, username, password, sslmode, authcfg)

    uri.setUseEstimatedMetadata(useEstimatedMetadata)

    return uri
Beispiel #8
0
def import_setting(file_path, qsettings=None):
    """Import InaSAFE's setting from a file.

    :param file_path: The file to read the imported setting.
    :type file_path: basestring

    :param qsettings: A custom QSettings to use. If it's not defined, it will
        use the default one.
    :type qsettings: qgis.PyQt.QtCore.QSettings

    :returns: A dictionary of the imported settings.
    :rtype: dict
    """
    with open(file_path, 'r') as f:
        inasafe_settings = json.load(f)

    if not qsettings:
        qsettings = QSettings()

    # Clear the previous setting
    qsettings.beginGroup('inasafe')
    qsettings.remove('')
    qsettings.endGroup()

    for key, value in list(inasafe_settings.items()):
        set_setting(key, value, qsettings=qsettings)

    return inasafe_settings
Beispiel #9
0
    def connect(self, selected, parent=None):
        settings = QSettings()
        settings.beginGroup(u"/%s/connections/%s" % (self.getSettingsKey(), selected))

        if not settings.contains("database"):  # non-existent entry?
            raise DbError('there is no defined database connection "%s".' % selected)

        get_value_str = lambda x: str(settings.value(x) if Utils.isSIPv2() else settings.value(x).toString())
        service, host, port, database, username, password = list(map(get_value_str, ["service", "host", "port", "database", "username", "password"]))

        # qgis1.5 use 'savePassword' instead of 'save' setting
        isSave = settings.value("save") if Utils.isSIPv2() else settings.value("save").toBool()
        isSavePassword = settings.value("savePassword") if Utils.isSIPv2() else settings.value("savePassword").toBool()
        if not (isSave or isSavePassword):
            (password, ok) = QInputDialog.getText(parent, "Enter password", 'Enter password for connection "%s":' % selected, QLineEdit.Password)
            if not ok: return

        settings.endGroup()

        uri = QgsDataSourceUri()
        if service:
            uri.setConnection(service, database, username, password)
        else:
            uri.setConnection(host, port, database, username, password)

        return Connection(uri)
    def fetch_online_directories(self):
        """Fetch online directory of repositories."""
        downloader = NetworkManager(self.DIRECTORY_URL)
        status, _ = downloader.fetch()
        if status:
            directory_file = QTemporaryFile()
            if directory_file.open():
                directory_file.write(downloader.content)
                directory_file.close()

            with open(directory_file.fileName()) as csv_file:
                reader = csv.DictReader(csv_file, fieldnames=('name', 'url'))
                for row in reader:
                    self._online_directories[row['name']] = row['url'].strip()
            # Save it to cache
            settings = QSettings()
            settings.beginGroup(repo_settings_group())
            settings.setValue('online_directories', self._online_directories)
            settings.endGroup()
        else:
            # Just use cache from previous use
            settings = QSettings()
            settings.beginGroup(repo_settings_group())
            self._online_directories = settings.value('online_directories', {})
            settings.endGroup()
Beispiel #11
0
    def load(self):
        """ populate the mRepositories dict"""
        self.mRepositories = {}
        settings = QSettings()
        settings.beginGroup(reposGroup)
        # first, update repositories in QSettings if needed
        officialRepoPresent = False
        for key in settings.childGroups():
            url = settings.value(key + "/url", "", type=unicode)
            if url == officialRepo[1]:
                officialRepoPresent = True
            if url == officialRepo[2]:
                settings.setValue(key + "/url", officialRepo[1])  # correct a depreciated url
                officialRepoPresent = True
        if not officialRepoPresent:
            settings.setValue(officialRepo[0] + "/url", officialRepo[1])

        for key in settings.childGroups():
            self.mRepositories[key] = {}
            self.mRepositories[key]["url"] = settings.value(key + "/url", "", type=unicode)
            self.mRepositories[key]["authcfg"] = settings.value(key + "/authcfg", "", type=unicode)
            self.mRepositories[key]["enabled"] = settings.value(key + "/enabled", True, type=bool)
            self.mRepositories[key]["valid"] = settings.value(key + "/valid", True, type=bool)
            self.mRepositories[key]["Relay"] = Relay(key)
            self.mRepositories[key]["xmlData"] = None
            self.mRepositories[key]["state"] = 0
            self.mRepositories[key]["error"] = ""
        settings.endGroup()
Beispiel #12
0
def export_setting(file_path, qsettings=None):
    """Export InaSAFE's setting to a file.

    :param file_path: The file to write the exported setting.
    :type file_path: basestring

    :param qsettings: A custom QSettings to use. If it's not defined, it will
        use the default one.
    :type qsettings: qgis.PyQt.QtCore.QSettings

    :returns: A dictionary of the exported settings.
    :rtype: dict
    """
    inasafe_settings = {}

    if not qsettings:
        qsettings = QSettings()

    qsettings.beginGroup('inasafe')
    all_keys = qsettings.allKeys()
    qsettings.endGroup()

    for key in all_keys:
        inasafe_settings[key] = setting(key, qsettings=qsettings)

    def custom_default(obj):
        if obj is None or (hasattr(obj, 'isNull') and obj.isNull()):
            return ''
        raise TypeError

    with open(file_path, 'w') as json_file:
        json.dump(
            inasafe_settings, json_file, indent=2, default=custom_default)

    return inasafe_settings
Beispiel #13
0
 def connections(self):
     # get the list of connections
     conn_list = []
     settings = QSettings()
     settings.beginGroup(self.connectionSettingsKey())
     for name in settings.childGroups():
         conn_list.append(createDbPlugin(self.typeName(), name))
     settings.endGroup()
     return conn_list
    def getAvailableConnections(self):
        connections = []

        settings = QSettings()
        settings.beginGroup("/%s/connections" % self.getSettingsKey())
        keys = settings.childGroups()
        for name in keys:
            connections.append(Connection.ConnectionAction(name, self.getTypeName()))
        settings.endGroup()

        return connections
 def getProxyConfiguration(self):
     settings = QSettings('QGIS', 'QGIS2')
     settings.beginGroup('proxy')
     enabled = str(settings.value('proxyEnable'))
     host = str(settings.value('proxyHost'))
     port = str(settings.value('proxyPort'))
     user = str(settings.value('proxyUser'))
     password = str(settings.value('proxyPassword'))
     type = str(settings.value('proxyType'))
     settings.endGroup()
     return (enabled, host, port, user, password, type)
Beispiel #16
0
    def connect(self, parent=None):
        conn_name = self.connectionName()
        settings = QSettings()
        settings.beginGroup(u"/%s/%s" % (self.connectionSettingsKey(), conn_name))

        if not settings.contains("sqlitepath"):  # non-existent entry?
            raise InvalidDataException(u'there is no defined database connection "%s".' % conn_name)

        database = settings.value("sqlitepath")

        uri = QgsDataSourceUri()
        uri.setDatabase(database)
        return self.connectToUri(uri)
Beispiel #17
0
 def editRepository(self, reposName):
     """ edit repository connection """
     if not reposName:
         return
     reposName = reposName.decode("utf-8")
     checkState = {False: Qt.Unchecked, True: Qt.Checked}
     dlg = QgsPluginInstallerRepositoryDialog(iface.mainWindow())
     dlg.editName.setText(reposName)
     dlg.editURL.setText(repositories.all()[reposName]["url"])
     dlg.editAuthCfg.setText(repositories.all()[reposName]["authcfg"])
     dlg.editParams.setText(repositories.urlParams())
     dlg.checkBoxEnabled.setCheckState(checkState[repositories.all()[reposName]["enabled"]])
     if repositories.all()[reposName]["valid"]:
         dlg.checkBoxEnabled.setEnabled(True)
         dlg.labelInfo.setText("")
     else:
         dlg.checkBoxEnabled.setEnabled(False)
         dlg.labelInfo.setText(self.tr("This repository is blocked due to incompatibility with your QGIS version"))
         dlg.labelInfo.setFrameShape(QFrame.Box)
     if not dlg.exec_():
         return  # nothing to do if cancelled
     for i in repositories.all().values():
         if (
             dlg.editURL.text().strip() == i["url"]
             and dlg.editURL.text().strip() != repositories.all()[reposName]["url"]
         ):
             iface.pluginManagerInterface().pushMessage(
                 self.tr("Unable to add another repository with the same URL!"), QgsMessageBar.WARNING
             )
             return
     # delete old repo from QSettings and create new one
     settings = QSettings()
     settings.beginGroup(reposGroup)
     settings.remove(reposName)
     newName = dlg.editName.text()
     if newName in repositories.all() and newName != reposName:
         newName = newName + "(2)"
     settings.setValue(newName + "/url", dlg.editURL.text().strip())
     settings.setValue(newName + "/authcfg", dlg.editAuthCfg.text().strip())
     settings.setValue(newName + "/enabled", bool(dlg.checkBoxEnabled.checkState()))
     if dlg.editAuthCfg.text().strip() != repositories.all()[reposName]["authcfg"]:
         repositories.all()[reposName]["authcfg"] = dlg.editAuthCfg.text().strip()
     if (
         dlg.editURL.text().strip() == repositories.all()[reposName]["url"]
         and dlg.checkBoxEnabled.checkState() == checkState[repositories.all()[reposName]["enabled"]]
     ):
         repositories.rename(reposName, newName)
         self.exportRepositoriesToManager()
         return  # nothing else to do if only repository name was changed
     plugins.removeRepository(reposName)
     self.reloadAndExportData()
    def remove_directory(self, repo_name):
        """Remove a directory and all the collections of that repository.

        :param repo_name: The old name of the repository
        :type repo_name: str
        """
        self._repositories.pop(repo_name, None)
        self.rebuild_collections()
        # Remove repo from QSettings
        settings = QSettings()
        settings.beginGroup(repo_settings_group())
        settings.remove(repo_name)
        settings.endGroup()
        # Serialize repositories every time successfully removed a repo
        self.serialize_repositories()
    def from_settings(cls, conn_name):
        settings = QSettings()
        key = DbConnectionCfg.connection_key(conn_name)
        settings.beginGroup(key)
        host = settings.value("host")
        port = settings.value("port")
        database = settings.value("database")
        username = settings.value("username")
        password = settings.value("password")
#        sslmode = settings.value("sslmode", type=int)
        sslmode = settings.value("sslmode")
#        QMessageBox.information(None,'',sslmode)
        estimatedMetadata = settings.value("estimatedMetadata", type=bool)
        return cls(
            host, port, database, username, password,
            sslmode, estimatedMetadata)
 def get_cloud_db_connections(db_name):
     connection_names = []
     settings = QSettings()
     settings.beginGroup(u"/PostgreSQL/connections")
     for name in settings.childGroups():
         settings.beginGroup(name)
         # host might be NoneType, which causes str conversion to fail
         try:
             db = settings.value("database")
             host = settings.value("host")
             if db == db_name and host in DbConnectionCfg.CLOUD_DB_HOSTS:
                 connection_names.append(name)
         except:
             pass
         settings.endGroup()
     settings.endGroup()
     return connection_names
Beispiel #21
0
    def selectOutput(self):
        if isinstance(self.output, OutputDirectory):
            self.selectDirectory()
        else:
            popupMenu = QMenu()

            if isinstance(self.output, OutputVector) \
                    and self.alg.provider.supportsNonFileBasedOutput():
                # use memory layers for temporary layers if supported
                actionSaveToTemp = QAction(
                    self.tr('Create temporary layer'), self.btnSelect)
            else:
                actionSaveToTemp = QAction(
                    self.tr('Save to a temporary file'), self.btnSelect)
            actionSaveToTemp.triggered.connect(self.saveToTemporary)
            popupMenu.addAction(actionSaveToTemp)

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

            actionShowExpressionsBuilder = QAction(
                self.tr('Use expression...'), self.btnSelect)
            actionShowExpressionsBuilder.triggered.connect(self.showExpressionsBuilder)
            popupMenu.addAction(actionShowExpressionsBuilder)

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

            popupMenu.exec_(QCursor.pos())
    def addLayer(self, layerType):
        if layerType.hasXYZUrl():
            # create XYZ layer
            layer, url = self.createXYZLayer(layerType,
                                             layerType.displayName)
        else:
            # create OpenlayersLayer
            layer = OpenlayersLayer(self.iface, self._olLayerTypeRegistry)
            layer.setName(layerType.displayName)
            layer.setLayerType(layerType)

        if layer.isValid():
            coordRefSys = layerType.coordRefSys(self.canvasCrs())
            self.setMapCrs(coordRefSys)
            QgsProject.instance().addMapLayer(layer)

            # store xyz config into qgis settings
            if layerType.hasXYZUrl():
                settings = QSettings()
                settings.beginGroup('qgis/connections-xyz')
                settings.setValue("%s/authcfg" % (layer.name()), '')
                settings.setValue("%s/password" % (layer.name()), '')
                settings.setValue("%s/referer" % (layer.name()), '')
                settings.setValue("%s/url" % (layer.name()), url)
                settings.setValue("%s/username" % (layer.name()), '')
                # specify max/min or else only a picture of the map is saved
                # in settings
                settings.setValue("%s/zmax" % (layer.name()), '18')
                settings.setValue("%s/zmin" % (layer.name()), '0')
                settings.endGroup()
                # reload connections to update Browser Panel content
                self.iface.reloadConnections()

            self._ol_layers += [layer]

            # last added layer is new reference
            self.setReferenceLayer(layer)

            if not layerType.hasXYZUrl():
                msg = "Printing and rotating of Javascript API " \
                      "based layers is currently not supported!"
                self.iface.messageBar().pushMessage(
                    "OpenLayers Plugin", msg, level=Qgis.MessageLevel(1),
                    duration=5)
    def add_directory(self, repo_name, url, auth_cfg=None):
        """Add a directory to settings and add the collections from that repo.

        :param repo_name: The name of the repository
        :type repo_name: str

        :param url: The URL of the repository
        :type url: str
        """
        repo_handler = BaseRepositoryHandler.get_handler(url)
        if repo_handler is None:
            raise Exception('There is no handler available for the given URL!')

        if auth_cfg:
            repo_handler.auth_cfg = auth_cfg

        # Fetch metadata
        status, description = repo_handler.fetch_metadata()
        if status:
            # Parse metadata
            try:
                collections = repo_handler.parse_metadata()
            except MetadataError:
                raise
            # Add the repo and the collections
            self._repositories[repo_name] = collections
            self.rebuild_collections()
            # Add to QSettings
            settings = QSettings()
            settings.beginGroup(repo_settings_group())
            settings.setValue(repo_name + '/url', url)
            if auth_cfg:
                settings.setValue(repo_name + '/auth_cfg', auth_cfg)
            settings.endGroup()
            # Serialize repositories every time we successfully added a repo
            self.serialize_repositories()

        return status, description
Beispiel #24
0
# -*- coding: utf-8 -*-
#! python3  # noqa: E265

# PyQT
from qgis.PyQt.QtCore import QSettings

# QGIS Qt Application settings
qsettings = QSettings()
# list subgroups
print(qsettings.childGroups())

# get Isogeo settings
qsettings.beginGroup("isogeo")
print(qsettings.childGroups())
print(qsettings.allKeys())

# exit Isogeo settings
qsettings.endGroup()
Beispiel #25
0
 def remove(self):
     settings = QSettings()
     settings.beginGroup(u"/%s/%s" % (self.connectionSettingsKey(), self.connectionName()))
     settings.remove("")
     self.deleted.emit()
     return True
Beispiel #26
0
    def connect(self, parent=None):
        conn_name = self.connectionName()
        settings = QSettings()
        settings.beginGroup(u"/{0}/{1}".format(self.connectionSettingsKey(),
                                               conn_name))

        if not settings.contains("database"):  # non-existent entry?
            raise InvalidDataException(
                self.tr('There is no defined database connection "{}".'.format(
                    conn_name)))

        from qgis.core import QgsDataSourceURI
        uri = QgsDataSourceURI()

        settingsList = ["host", "port", "database", "username", "password"]
        host, port, database, username, password = [
            settings.value(x, "", type=str) for x in settingsList
        ]

        # get all of the connexion options

        useEstimatedMetadata = settings.value("estimatedMetadata",
                                              False,
                                              type=bool)
        uri.setParam(
            'userTablesOnly',
            unicode(settings.value("userTablesOnly", False, type=bool)))
        uri.setParam(
            'geometryColumnsOnly',
            unicode(settings.value("geometryColumnsOnly", False, type=bool)))
        uri.setParam(
            'allowGeometrylessTables',
            unicode(settings.value("allowGeometrylessTables", False,
                                   type=bool)))
        uri.setParam(
            'onlyExistingTypes',
            unicode(settings.value("onlyExistingTypes", False, type=bool)))
        uri.setParam(
            'includeGeoAttributes',
            unicode(settings.value("includeGeoAttributes", False, type=bool)))

        settings.endGroup()

        uri.setConnection(host, port, database, username, password)

        uri.setUseEstimatedMetadata(useEstimatedMetadata)

        err = u""
        try:
            return self.connectToUri(uri)
        except ConnectionError as e:
            err = unicode(e)

        # ask for valid credentials
        max_attempts = 3
        for i in range(max_attempts):
            (ok, username, password) = QgsCredentials.instance().get(
                uri.connectionInfo(False), username, password, err)

            if not ok:
                return False

            uri.setConnection(host, port, database, username, password)

            try:
                self.connectToUri(uri)
            except ConnectionError as e:
                if i == max_attempts - 1:  # failed the last attempt
                    raise e
                err = unicode(e)
                continue

            QgsCredentials.instance().put(uri.connectionInfo(False), username,
                                          password)

            return True

        return False
Beispiel #27
0
 def remove(self):
     settings = QSettings()
     settings.beginGroup(u"/%s/%s" % (self.connectionSettingsKey(), self.connectionName()))
     settings.remove("")
     self.deleted.emit()
     return True
Beispiel #28
0
class TestQgsSettings(unittest.TestCase):

    cnt = 0

    def setUp(self):
        self.cnt += 1
        h, path = tempfile.mkstemp('.ini')
        assert QgsSettings.setGlobalSettingsPath(path)
        self.settings = QgsSettings('testqgissettings', 'testqgissettings%s' % self.cnt)
        self.globalsettings = QSettings(self.settings.globalSettingsPath(), QSettings.IniFormat)

    def tearDown(self):
        settings_file = self.settings.fileName()
        settings_default_file = self.settings.globalSettingsPath()
        del(self.settings)
        try:
            os.unlink(settings_file)
        except:
            pass
        try:
            os.unlink(settings_default_file)
        except:
            pass

    def addToDefaults(self, key, value):
        self.globalsettings.setValue(key, value)
        self.globalsettings.sync()

    def addArrayToDefaults(self, prefix, key, values):
        defaults = QSettings(self.settings.globalSettingsPath(), QSettings.IniFormat)  # NOQA
        self.globalsettings.beginWriteArray(prefix)
        i = 0
        for v in values:
            self.globalsettings.setArrayIndex(i)
            self.globalsettings.setValue(key, v)
            i += 1
        self.globalsettings.endArray()
        self.globalsettings.sync()

    def addGroupToDefaults(self, prefix, kvp):
        defaults = QSettings(self.settings.globalSettingsPath(), QSettings.IniFormat)  # NOQA
        self.globalsettings.beginGroup(prefix)
        for k, v in kvp.items():
            self.globalsettings.setValue(k, v)
        self.globalsettings.endGroup()
        self.globalsettings.sync()

    def test_basic_functionality(self):
        self.assertEqual(self.settings.value('testqgissettings/doesnotexists', 'notexist'), 'notexist')
        self.settings.setValue('testqgissettings/name', 'qgisrocks')
        self.settings.sync()
        self.assertEqual(self.settings.value('testqgissettings/name'), 'qgisrocks')

    def test_defaults(self):
        self.assertIsNone(self.settings.value('testqgissettings/name'))
        self.addToDefaults('testqgissettings/name', 'qgisrocks')
        self.assertEqual(self.settings.value('testqgissettings/name'), 'qgisrocks')

    def test_allkeys(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addToDefaults('testqgissettings/name', 'qgisrocks')
        self.addToDefaults('testqgissettings/name2', 'qgisrocks2')
        self.settings.setValue('nepoti/eman', 'osaple')

        self.assertEqual(3, len(self.settings.allKeys()))
        self.assertIn('testqgissettings/name', self.settings.allKeys())
        self.assertIn('nepoti/eman', self.settings.allKeys())
        self.assertEqual('qgisrocks', self.settings.value('testqgissettings/name'))
        self.assertEqual('qgisrocks2', self.settings.value('testqgissettings/name2'))
        self.assertEqual('qgisrocks', self.globalsettings.value('testqgissettings/name'))
        self.assertEqual('osaple', self.settings.value('nepoti/eman'))
        self.assertEqual(3, len(self.settings.allKeys()))
        self.assertEqual(2, len(self.globalsettings.allKeys()))

    def test_precedence_simple(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addToDefaults('testqgissettings/names/name1', 'qgisrocks1')
        self.settings.setValue('testqgissettings/names/name1', 'qgisrocks-1')

        self.assertEqual(self.settings.value('testqgissettings/names/name1'), 'qgisrocks-1')

    def test_precedence_group(self):
        """Test if user can override a group value"""
        self.assertEqual(self.settings.allKeys(), [])
        self.addGroupToDefaults('connections-xyz', {
            'OSM': 'http://a.tile.openstreetmap.org/{z}/{x}/{y}.png',
            'OSM-b': 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png',
        })
        self.settings.beginGroup('connections-xyz')
        self.assertEqual(self.settings.value('OSM'), 'http://a.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.assertEqual(self.settings.value('OSM-b'), 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.settings.endGroup()

        # Override edit
        self.settings.beginGroup('connections-xyz')
        self.settings.setValue('OSM', 'http://c.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.settings.endGroup()

        # Check it again!
        self.settings.beginGroup('connections-xyz')
        self.assertEqual(self.settings.value('OSM'), 'http://c.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.assertEqual(self.settings.value('OSM-b'), 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.settings.endGroup()

        # Override remove: the global value will be resumed!!!
        self.settings.beginGroup('connections-xyz')
        self.settings.remove('OSM')
        self.settings.endGroup()

        # Check it again!
        self.settings.beginGroup('connections-xyz')
        self.assertEqual(self.settings.value('OSM'), 'http://a.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.assertEqual(self.settings.value('OSM-b'), 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.settings.endGroup()

        # Override remove: store a blank!
        self.settings.beginGroup('connections-xyz')
        self.settings.setValue('OSM', '')
        self.settings.endGroup()

        # Check it again!
        self.settings.beginGroup('connections-xyz')
        self.assertEqual(self.settings.value('OSM'), '')
        self.assertEqual(self.settings.value('OSM-b'), 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.settings.endGroup()

        # Override remove: store a None: will resume the global setting!
        self.settings.beginGroup('connections-xyz')
        self.settings.setValue('OSM', None)
        self.settings.endGroup()

        # Check it again!
        self.settings.beginGroup('connections-xyz')
        self.assertEqual(self.settings.value('OSM'), 'http://a.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.assertEqual(self.settings.value('OSM-b'), 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.settings.endGroup()

    def test_uft8(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addToDefaults('testqgissettings/names/namèé↓1', 'qgisrocks↓1')
        self.assertEqual(self.settings.value('testqgissettings/names/namèé↓1'), 'qgisrocks↓1')

        self.settings.setValue('testqgissettings/names/namèé↓2', 'qgisrocks↓2')
        self.assertEqual(self.settings.value('testqgissettings/names/namèé↓2'), 'qgisrocks↓2')
        self.settings.setValue('testqgissettings/names/namèé↓1', 'qgisrocks↓-1')
        self.assertEqual(self.settings.value('testqgissettings/names/namèé↓1'), 'qgisrocks↓-1')

    def test_groups(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addToDefaults('testqgissettings/names/name1', 'qgisrocks1')
        self.addToDefaults('testqgissettings/names/name2', 'qgisrocks2')
        self.addToDefaults('testqgissettings/names/name3', 'qgisrocks3')
        self.addToDefaults('testqgissettings/name', 'qgisrocks')

        self.settings.beginGroup('testqgissettings')
        self.assertEqual(['names'], self.settings.childGroups())

        self.settings.setValue('surnames/name1', 'qgisrocks-1')
        self.assertEqual(['surnames', 'names'], self.settings.childGroups())

        self.settings.setValue('names/name1', 'qgisrocks-1')
        self.assertEqual('qgisrocks-1', self.settings.value('names/name1'))
        self.settings.endGroup()
        self.settings.beginGroup('testqgissettings/names')
        self.settings.setValue('name4', 'qgisrocks-4')
        keys = sorted(self.settings.childKeys())
        self.assertEqual(keys, ['name1', 'name2', 'name3', 'name4'])
        self.settings.endGroup()
        self.assertEqual('qgisrocks-1', self.settings.value('testqgissettings/names/name1'))
        self.assertEqual('qgisrocks-4', self.settings.value('testqgissettings/names/name4'))

    def test_array(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addArrayToDefaults('testqgissettings', 'key', ['qgisrocks1', 'qgisrocks2', 'qgisrocks3'])
        self.assertEqual(self.settings.allKeys(), ['testqgissettings/1/key', 'testqgissettings/2/key', 'testqgissettings/3/key', 'testqgissettings/size'])
        self.assertEqual(self.globalsettings.allKeys(), ['testqgissettings/1/key', 'testqgissettings/2/key', 'testqgissettings/3/key', 'testqgissettings/size'])

        self.assertEqual(3, self.globalsettings.beginReadArray('testqgissettings'))
        self.globalsettings.endArray()
        self.assertEqual(3, self.settings.beginReadArray('testqgissettings'))

        values = []
        for i in range(3):
            self.settings.setArrayIndex(i)
            values.append(self.settings.value("key"))

        self.assertEqual(values, ['qgisrocks1', 'qgisrocks2', 'qgisrocks3'])

    def test_array_overrides(self):
        """Test if an array completely shadows the global one"""
        self.assertEqual(self.settings.allKeys(), [])
        self.addArrayToDefaults('testqgissettings', 'key', ['qgisrocks1', 'qgisrocks2', 'qgisrocks3'])
        self.assertEqual(self.settings.allKeys(), ['testqgissettings/1/key', 'testqgissettings/2/key', 'testqgissettings/3/key', 'testqgissettings/size'])
        self.assertEqual(self.globalsettings.allKeys(), ['testqgissettings/1/key', 'testqgissettings/2/key', 'testqgissettings/3/key', 'testqgissettings/size'])

        self.assertEqual(3, self.globalsettings.beginReadArray('testqgissettings'))
        self.globalsettings.endArray()
        self.assertEqual(3, self.settings.beginReadArray('testqgissettings'))

        # Now override!
        self.settings.beginWriteArray('testqgissettings')
        self.settings.setArrayIndex(0)
        self.settings.setValue('key', 'myqgisrocksmore1')
        self.settings.setArrayIndex(1)
        self.settings.setValue('key', 'myqgisrocksmore2')
        self.settings.endArray()

        # Check it!
        self.assertEqual(2, self.settings.beginReadArray('testqgissettings'))

        values = []
        for i in range(2):
            self.settings.setArrayIndex(i)
            values.append(self.settings.value("key"))

        self.assertEqual(values, ['myqgisrocksmore1', 'myqgisrocksmore2'])

    def test_section_getters_setters(self):
        self.assertEqual(self.settings.allKeys(), [])

        self.settings.setValue('key1', 'core1', section=QgsSettings.Core)
        self.settings.setValue('key2', 'core2', section=QgsSettings.Core)

        self.settings.setValue('key1', 'server1', section=QgsSettings.Server)
        self.settings.setValue('key2', 'server2', section=QgsSettings.Server)

        self.settings.setValue('key1', 'gui1', section=QgsSettings.Gui)
        self.settings.setValue('key2', 'gui2', QgsSettings.Gui)

        self.settings.setValue('key1', 'plugins1', section=QgsSettings.Plugins)
        self.settings.setValue('key2', 'plugins2', section=QgsSettings.Plugins)

        self.settings.setValue('key1', 'misc1', section=QgsSettings.Misc)
        self.settings.setValue('key2', 'misc2', section=QgsSettings.Misc)

        self.settings.setValue('key1', 'auth1', section=QgsSettings.Auth)
        self.settings.setValue('key2', 'auth2', section=QgsSettings.Auth)

        self.settings.setValue('key1', 'app1', section=QgsSettings.App)
        self.settings.setValue('key2', 'app2', section=QgsSettings.App)

        self.settings.setValue('key1', 'provider1', section=QgsSettings.Providers)
        self.settings.setValue('key2', 'provider2', section=QgsSettings.Providers)

        self.settings.setValue('key1', 'auth1', section=QgsSettings.Auth)
        self.settings.setValue('key2', 'auth2', section=QgsSettings.Auth)

        # Test that the values are namespaced
        self.assertEqual(self.settings.value('core/key1'), 'core1')
        self.assertEqual(self.settings.value('core/key2'), 'core2')

        self.assertEqual(self.settings.value('server/key1'), 'server1')
        self.assertEqual(self.settings.value('server/key2'), 'server2')

        self.assertEqual(self.settings.value('gui/key1'), 'gui1')
        self.assertEqual(self.settings.value('gui/key2'), 'gui2')

        self.assertEqual(self.settings.value('plugins/key1'), 'plugins1')
        self.assertEqual(self.settings.value('plugins/key2'), 'plugins2')

        self.assertEqual(self.settings.value('misc/key1'), 'misc1')
        self.assertEqual(self.settings.value('misc/key2'), 'misc2')

        # Test getters
        self.assertEqual(self.settings.value('key1', None, section=QgsSettings.Core), 'core1')
        self.assertEqual(self.settings.value('key2', None, section=QgsSettings.Core), 'core2')

        self.assertEqual(self.settings.value('key1', None, section=QgsSettings.Server), 'server1')
        self.assertEqual(self.settings.value('key2', None, section=QgsSettings.Server), 'server2')

        self.assertEqual(self.settings.value('key1', None, section=QgsSettings.Gui), 'gui1')
        self.assertEqual(self.settings.value('key2', None, section=QgsSettings.Gui), 'gui2')

        self.assertEqual(self.settings.value('key1', None, section=QgsSettings.Plugins), 'plugins1')
        self.assertEqual(self.settings.value('key2', None, section=QgsSettings.Plugins), 'plugins2')

        self.assertEqual(self.settings.value('key1', None, section=QgsSettings.Misc), 'misc1')
        self.assertEqual(self.settings.value('key2', None, section=QgsSettings.Misc), 'misc2')

        self.assertEqual(self.settings.value('key1', None, section=QgsSettings.Auth), 'auth1')
        self.assertEqual(self.settings.value('key2', None, section=QgsSettings.Auth), 'auth2')

        self.assertEqual(self.settings.value('key1', None, section=QgsSettings.App), 'app1')
        self.assertEqual(self.settings.value('key2', None, section=QgsSettings.App), 'app2')

        self.assertEqual(self.settings.value('key1', None, section=QgsSettings.Providers), 'provider1')
        self.assertEqual(self.settings.value('key2', None, section=QgsSettings.Providers), 'provider2')

        # Test default values on Section getter
        self.assertEqual(self.settings.value('key_not_exist', 'misc_not_exist', section=QgsSettings.Misc), 'misc_not_exist')

    def test_contains(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addToDefaults('testqgissettings/name', 'qgisrocks1')
        self.addToDefaults('testqgissettings/name2', 'qgisrocks2')

        self.assertTrue(self.settings.contains('testqgissettings/name'))
        self.assertTrue(self.settings.contains('testqgissettings/name2'))

        self.settings.setValue('testqgissettings/name3', 'qgisrocks3')
        self.assertTrue(self.settings.contains('testqgissettings/name3'))

    def test_remove(self):
        self.settings.setValue('testQgisSettings/temp', True)
        self.assertEqual(self.settings.value('testQgisSettings/temp'), True)
        self.settings.remove('testQgisSettings/temp')
        self.assertEqual(self.settings.value('testqQgisSettings/temp'), None)
def get_databases():
    d = {}
    qs = QSettings()

    # spatialite
    qs.beginGroup("SpatiaLite/connections")

    for db_entry in qs.allKeys():
        db_name, _ = os.path.split(db_entry)

        settings = {
            "key": os.path.basename(db_entry),
            "db_name": db_name,
            "combo_key":
            "spatialite: {0}".format(os.path.splitext(db_name)[0]),
            "db_type": "spatialite",
            "db_settings": {
                "db_path": qs.value(db_entry)
            },
        }

        d[settings["combo_key"]] = settings
    qs.endGroup()

    qs.beginGroup("PostgreSQL/connections")
    for db_entry in qs.allKeys():
        prefix, attribute = os.path.split(db_entry)
        db_name = qs.value(prefix + "/database")
        settings = {
            "key": db_entry,
            "db_name": db_name,
            "combo_key": "postgres: {0}".format(db_name),
            "db_type": "postgres",
            "db_settings": {
                "host": qs.value(prefix + "/host"),
                "port": qs.value(prefix + "/port"),
                "database": qs.value(prefix + "/database"),
                "username": qs.value(prefix + "/username"),
                "password": qs.value(prefix + "/password"),
            },
        }

        if qs.value(prefix + "/saveUsername") == u"true":
            settings["saveUsername"] = True
            settings["db_settings"]["username"] = qs.value(prefix +
                                                           "/username")
        else:
            settings["saveUsername"] = False

        if qs.value(prefix + "/savePassword") == u"true":
            settings["savePassword"] = True
            settings["db_settings"]["password"] = qs.value(prefix +
                                                           "/password")
        else:
            settings["savePassword"] = False

        d[settings["combo_key"]] = settings
    qs.endGroup()
    available_dbs = collections.OrderedDict(sorted(d.items()))

    return available_dbs
Beispiel #30
0
# -*- coding: utf-8 -*-

import os
from qgis.PyQt.QtCore import QSettings
from gml_application_schema_toolbox import name as plugin_name

DEFAULT_GMLAS_CONFIG = os.path.realpath(
    os.path.join(os.path.dirname(__file__), "..", "conf", "gmlasconf.xml"))

defaults = {
    "default_maxfeatures": 100,
    "wfs2_services": [],
    "default_wfs2_service": None,
    "default_import_method": "gmlas",
    "default_gmlas_config": DEFAULT_GMLAS_CONFIG,
    "default_language": "en",
    "default_db_type": "SQLite",
    "default_access_mode": None
}

settings = QSettings()
settings.beginGroup(plugin_name())
for key, value in defaults.items():
    if not settings.contains(key):
        settings.setValue(key, value)
Beispiel #31
0
 def addConnection(self, conn_name, uri):
     settings = QSettings()
     settings.beginGroup(u"/%s/%s" % (self.connectionSettingsKey(), conn_name))
     settings.setValue("sqlitepath", uri.database())
     return True
Beispiel #32
0
 def addConnection(self, conn_name, uri):
     settings = QSettings()
     settings.beginGroup(u"/%s/%s" %
                         (self.connectionSettingsKey(), conn_name))
     settings.setValue("sqlitepath", uri.database())
     return True
Beispiel #33
0
    def connChanged(self, conn_name='', schema_name=''):
        # close any existing connection to a river database
        if self.rdb:
            self.addInfo(
                "Closing existing connection to {0}@{1} river database".format(
                    self.rdb.dbname, self.rdb.host))
            self.rdb.disconnect_pg()
            self.rdb = None
        else:
            pass
        s = QSettings()
        s.beginGroup('/PostgreSQL/connections')
        connsNames = s.childGroups()

        if conn_name in connsNames:
            self.curConnName = conn_name
        else:
            self.curConnName = self.ui.connsCbo.currentText()

        self.ui.connsCbo.clear()
        self.ui.connsCbo.addItem('')
        for conn in connsNames:
            self.ui.connsCbo.addItem(conn)
        try:
            i = connsNames.index(self.curConnName) + 1
        except ValueError:
            i = 0
        self.ui.connsCbo.setCurrentIndex(i)
        if self.ui.connsCbo.currentIndex() == 0:
            self.ui.schemasCbo.clear()
            self.ui.schemasCbo.addItem('')
            self.disableActions()
            return
        connName = self.ui.connsCbo.currentText()
        s.endGroup()
        s.beginGroup('/PostgreSQL/connections/{0}'.format(connName))

        # first try to get the credentials from AuthManager, then from the basic settings
        authconf = s.value('authcfg', None)
        if authconf:
            auth_manager = QgsApplication.authManager()
            conf = QgsAuthMethodConfig()
            auth_manager.loadAuthenticationConfig(authconf, conf, True)
            if conf.id():
                self.user = conf.config('username', '')
                self.passwd = conf.config('password', '')
        else:
            self.user = s.value('username')
            self.passwd = s.value('password')

        self.host = s.value('host')
        self.port = s.value('port')
        self.database = s.value('database')

        s.endGroup()

        # create a new connection to river database
        self.rdb = rivdb.RiverDatabase(self, self.database, self.host,
                                       self.port, self.user, self.passwd)
        self.rdb.SRID = int(self.crs.postgisSrid())
        if self.rdb.connect_pg():
            self.addInfo(
                'Created connection to river database: {0}@{1}'.format(
                    self.rdb.dbname, self.rdb.host))
            self.rdb.last_conn = connName
        else:
            info = 'Couldn\'t connect to river database: {0}@{1}'.format(
                self.rdb.dbname, self.rdb.host)
            info += '\nPlease, check you database connection settings!'
            self.addInfo(info)
            self.ui.schemasCbo.clear()
            return

        # refresh schemas combo
        schemaName = self.ui.schemasCbo.currentText()
        qry = "SELECT nspname FROM pg_namespace WHERE nspname !~ '^pg_' AND nspname != 'information_schema' ORDER BY nspname"
        schemas = self.rdb.run_query(qry, fetch=True)
        self.ui.schemasCbo.clear()
        self.ui.schemasCbo.addItem('')
        if not schemas:
            schemas = []
        for schema in schemas:
            self.ui.schemasCbo.addItem(schema[0])
        if schema_name:
            schemaExists = self.ui.schemasCbo.findText(schema_name)
        else:
            schemaExists = self.ui.schemasCbo.findText(schemaName)
        if schemaExists:
            self.ui.schemasCbo.setCurrentIndex(schemaExists)
        self.enableDBActions()
        self.schemaChanged()
 def show_options_dialog(self):
     dlg = OptionsDialog(self.ili2db_configuration)
     if dlg.exec_():
         settings = QSettings()
         settings.beginGroup("QgisModelBaker/ili2db")
         self.ili2db_configuration.save(settings)
Beispiel #35
0
 def dbConnectionNames(self):
     settings = QSettings()
     settings.beginGroup('/PostgreSQL/connections/')
     return settings.childGroups()
Beispiel #36
0
class TestQgsSettings(unittest.TestCase):

    cnt = 0

    def setUp(self):
        self.cnt += 1
        h, path = tempfile.mkstemp('.ini')
        assert QgsSettings.setGlobalSettingsPath(path)
        self.settings = QgsSettings('testqgissettings',
                                    'testqgissettings%s' % self.cnt)
        self.globalsettings = QSettings(self.settings.globalSettingsPath(),
                                        QSettings.IniFormat)

    def tearDown(self):
        settings_file = self.settings.fileName()
        settings_default_file = self.settings.globalSettingsPath()
        del (self.settings)
        try:
            os.unlink(settings_file)
        except:
            pass
        try:
            os.unlink(settings_default_file)
        except:
            pass

    def addToDefaults(self, key, value):
        self.globalsettings.setValue(key, value)
        self.globalsettings.sync()

    def addArrayToDefaults(self, prefix, key, values):
        defaults = QSettings(self.settings.globalSettingsPath(),
                             QSettings.IniFormat)  # NOQA
        self.globalsettings.beginWriteArray(prefix)
        i = 0
        for v in values:
            self.globalsettings.setArrayIndex(i)
            self.globalsettings.setValue(key, v)
            i += 1
        self.globalsettings.endArray()
        self.globalsettings.sync()

    def addGroupToDefaults(self, prefix, kvp):
        defaults = QSettings(self.settings.globalSettingsPath(),
                             QSettings.IniFormat)  # NOQA
        self.globalsettings.beginGroup(prefix)
        for k, v in kvp.items():
            self.globalsettings.setValue(k, v)
        self.globalsettings.endGroup()
        self.globalsettings.sync()

    def test_basic_functionality(self):
        self.assertEqual(
            self.settings.value('testqgissettings/doesnotexists', 'notexist'),
            'notexist')
        self.settings.setValue('testqgissettings/name', 'qgisrocks')
        self.settings.sync()
        self.assertEqual(self.settings.value('testqgissettings/name'),
                         'qgisrocks')

    def test_defaults(self):
        self.assertIsNone(self.settings.value('testqgissettings/name'))
        self.addToDefaults('testqgissettings/name', 'qgisrocks')
        self.assertEqual(self.settings.value('testqgissettings/name'),
                         'qgisrocks')

    def test_allkeys(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addToDefaults('testqgissettings/name', 'qgisrocks')
        self.addToDefaults('testqgissettings/name2', 'qgisrocks2')
        self.settings.setValue('nepoti/eman', 'osaple')

        self.assertEqual(3, len(self.settings.allKeys()))
        self.assertIn('testqgissettings/name', self.settings.allKeys())
        self.assertIn('nepoti/eman', self.settings.allKeys())
        self.assertEqual('qgisrocks',
                         self.settings.value('testqgissettings/name'))
        self.assertEqual('qgisrocks2',
                         self.settings.value('testqgissettings/name2'))
        self.assertEqual('qgisrocks',
                         self.globalsettings.value('testqgissettings/name'))
        self.assertEqual('osaple', self.settings.value('nepoti/eman'))
        self.assertEqual(3, len(self.settings.allKeys()))
        self.assertEqual(2, len(self.globalsettings.allKeys()))

    def test_precedence_simple(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addToDefaults('testqgissettings/names/name1', 'qgisrocks1')
        self.settings.setValue('testqgissettings/names/name1', 'qgisrocks-1')

        self.assertEqual(self.settings.value('testqgissettings/names/name1'),
                         'qgisrocks-1')

    def test_precedence_group(self):
        """Test if user can override a group value"""
        self.assertEqual(self.settings.allKeys(), [])
        self.addGroupToDefaults(
            'connections-xyz', {
                'OSM': 'http://a.tile.openstreetmap.org/{z}/{x}/{y}.png',
                'OSM-b': 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png',
            })
        self.settings.beginGroup('connections-xyz')
        self.assertEqual(self.settings.value('OSM'),
                         'http://a.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.assertEqual(self.settings.value('OSM-b'),
                         'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.settings.endGroup()

        # Override edit
        self.settings.beginGroup('connections-xyz')
        self.settings.setValue(
            'OSM', 'http://c.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.settings.endGroup()

        # Check it again!
        self.settings.beginGroup('connections-xyz')
        self.assertEqual(self.settings.value('OSM'),
                         'http://c.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.assertEqual(self.settings.value('OSM-b'),
                         'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.settings.endGroup()

        # Override remove: the global value will be resumed!!!
        self.settings.beginGroup('connections-xyz')
        self.settings.remove('OSM')
        self.settings.endGroup()

        # Check it again!
        self.settings.beginGroup('connections-xyz')
        self.assertEqual(self.settings.value('OSM'),
                         'http://a.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.assertEqual(self.settings.value('OSM-b'),
                         'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.settings.endGroup()

        # Override remove: store a blank!
        self.settings.beginGroup('connections-xyz')
        self.settings.setValue('OSM', '')
        self.settings.endGroup()

        # Check it again!
        self.settings.beginGroup('connections-xyz')
        self.assertEqual(self.settings.value('OSM'), '')
        self.assertEqual(self.settings.value('OSM-b'),
                         'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.settings.endGroup()

        # Override remove: store a None: will resume the global setting!
        self.settings.beginGroup('connections-xyz')
        self.settings.setValue('OSM', None)
        self.settings.endGroup()

        # Check it again!
        self.settings.beginGroup('connections-xyz')
        self.assertEqual(self.settings.value('OSM'),
                         'http://a.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.assertEqual(self.settings.value('OSM-b'),
                         'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.settings.endGroup()

    def test_uft8(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addToDefaults('testqgissettings/names/namèé↓1', 'qgisrocks↓1')
        self.assertEqual(self.settings.value('testqgissettings/names/namèé↓1'),
                         'qgisrocks↓1')

        self.settings.setValue('testqgissettings/names/namèé↓2', 'qgisrocks↓2')
        self.assertEqual(self.settings.value('testqgissettings/names/namèé↓2'),
                         'qgisrocks↓2')
        self.settings.setValue('testqgissettings/names/namèé↓1',
                               'qgisrocks↓-1')
        self.assertEqual(self.settings.value('testqgissettings/names/namèé↓1'),
                         'qgisrocks↓-1')

    def test_groups(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addToDefaults('testqgissettings/names/name1', 'qgisrocks1')
        self.addToDefaults('testqgissettings/names/name2', 'qgisrocks2')
        self.addToDefaults('testqgissettings/names/name3', 'qgisrocks3')
        self.addToDefaults('testqgissettings/name', 'qgisrocks')

        self.settings.beginGroup('testqgissettings')
        self.assertEqual(['names'], self.settings.childGroups())

        self.settings.setValue('surnames/name1', 'qgisrocks-1')
        self.assertEqual(['surnames', 'names'], self.settings.childGroups())

        self.settings.setValue('names/name1', 'qgisrocks-1')
        self.assertEqual('qgisrocks-1', self.settings.value('names/name1'))
        self.settings.endGroup()
        self.settings.beginGroup('testqgissettings/names')
        self.settings.setValue('name4', 'qgisrocks-4')
        keys = sorted(self.settings.childKeys())
        self.assertEqual(keys, ['name1', 'name2', 'name3', 'name4'])
        self.settings.endGroup()
        self.assertEqual('qgisrocks-1',
                         self.settings.value('testqgissettings/names/name1'))
        self.assertEqual('qgisrocks-4',
                         self.settings.value('testqgissettings/names/name4'))

    def test_global_groups(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.assertEqual(self.globalsettings.allKeys(), [])

        self.addToDefaults('testqgissettings/foo/first', 'qgis')
        self.addToDefaults('testqgissettings/foo/last', 'rocks')

        self.settings.beginGroup('testqgissettings')
        self.assertEqual(['foo'], self.settings.childGroups())
        self.assertEqual(['foo'], self.settings.globalChildGroups())
        self.settings.endGroup()

        self.settings.setValue('testqgissettings/bar/first', 'qgis')
        self.settings.setValue('testqgissettings/bar/last', 'rocks')

        self.settings.beginGroup('testqgissettings')
        self.assertEqual(sorted(['bar', 'foo']),
                         sorted(self.settings.childGroups()))
        self.assertEqual(['foo'], self.settings.globalChildGroups())
        self.settings.endGroup()

        self.globalsettings.remove('testqgissettings/foo')

        self.settings.beginGroup('testqgissettings')
        self.assertEqual(['bar'], self.settings.childGroups())
        self.assertEqual([], self.settings.globalChildGroups())
        self.settings.endGroup()

    def test_group_section(self):
        # Test group by using Section
        self.settings.beginGroup('firstgroup', section=QgsSettings.Core)
        self.assertEqual([], self.settings.childGroups())
        self.settings.setValue('key', 'value')
        self.settings.setValue('key2/subkey1', 'subvalue1')
        self.settings.setValue('key2/subkey2', 'subvalue2')
        self.settings.setValue('key3', 'value3')

        self.assertEqual(['key', 'key2/subkey1', 'key2/subkey2', 'key3'],
                         self.settings.allKeys())
        self.assertEqual(['key', 'key3'], self.settings.childKeys())
        self.assertEqual(['key2'], self.settings.childGroups())
        self.settings.endGroup()
        # Set value by writing the group manually
        self.settings.setValue('firstgroup/key4',
                               'value4',
                               section=QgsSettings.Core)
        # Checking the value that have been set
        self.assertEqual(
            self.settings.value('firstgroup/key', section=QgsSettings.Core),
            'value')
        self.assertEqual(
            self.settings.value('firstgroup/key2/subkey1',
                                section=QgsSettings.Core), 'subvalue1')
        self.assertEqual(
            self.settings.value('firstgroup/key2/subkey2',
                                section=QgsSettings.Core), 'subvalue2')
        self.assertEqual(
            self.settings.value('firstgroup/key3', section=QgsSettings.Core),
            'value3')
        self.assertEqual(
            self.settings.value('firstgroup/key4', section=QgsSettings.Core),
            'value4')
        # Clean up firstgroup
        self.settings.remove('firstgroup', section=QgsSettings.Core)

    def test_array(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addArrayToDefaults('testqgissettings', 'key',
                                ['qgisrocks1', 'qgisrocks2', 'qgisrocks3'])
        self.assertEqual(self.settings.allKeys(), [
            'testqgissettings/1/key', 'testqgissettings/2/key',
            'testqgissettings/3/key', 'testqgissettings/size'
        ])
        self.assertEqual(self.globalsettings.allKeys(), [
            'testqgissettings/1/key', 'testqgissettings/2/key',
            'testqgissettings/3/key', 'testqgissettings/size'
        ])

        self.assertEqual(
            3, self.globalsettings.beginReadArray('testqgissettings'))
        self.globalsettings.endArray()
        self.assertEqual(3, self.settings.beginReadArray('testqgissettings'))

        values = []
        for i in range(3):
            self.settings.setArrayIndex(i)
            values.append(self.settings.value("key"))

        self.assertEqual(values, ['qgisrocks1', 'qgisrocks2', 'qgisrocks3'])

    def test_array_overrides(self):
        """Test if an array completely shadows the global one"""
        self.assertEqual(self.settings.allKeys(), [])
        self.addArrayToDefaults('testqgissettings', 'key',
                                ['qgisrocks1', 'qgisrocks2', 'qgisrocks3'])
        self.assertEqual(self.settings.allKeys(), [
            'testqgissettings/1/key', 'testqgissettings/2/key',
            'testqgissettings/3/key', 'testqgissettings/size'
        ])
        self.assertEqual(self.globalsettings.allKeys(), [
            'testqgissettings/1/key', 'testqgissettings/2/key',
            'testqgissettings/3/key', 'testqgissettings/size'
        ])

        self.assertEqual(
            3, self.globalsettings.beginReadArray('testqgissettings'))
        self.globalsettings.endArray()
        self.assertEqual(3, self.settings.beginReadArray('testqgissettings'))

        # Now override!
        self.settings.beginWriteArray('testqgissettings')
        self.settings.setArrayIndex(0)
        self.settings.setValue('key', 'myqgisrocksmore1')
        self.settings.setArrayIndex(1)
        self.settings.setValue('key', 'myqgisrocksmore2')
        self.settings.endArray()

        # Check it!
        self.assertEqual(2, self.settings.beginReadArray('testqgissettings'))

        values = []
        for i in range(2):
            self.settings.setArrayIndex(i)
            values.append(self.settings.value("key"))

        self.assertEqual(values, ['myqgisrocksmore1', 'myqgisrocksmore2'])

    def test_section_getters_setters(self):
        self.assertEqual(self.settings.allKeys(), [])

        self.settings.setValue('key1', 'core1', section=QgsSettings.Core)
        self.settings.setValue('key2', 'core2', section=QgsSettings.Core)

        self.settings.setValue('key1', 'server1', section=QgsSettings.Server)
        self.settings.setValue('key2', 'server2', section=QgsSettings.Server)

        self.settings.setValue('key1', 'gui1', section=QgsSettings.Gui)
        self.settings.setValue('key2', 'gui2', QgsSettings.Gui)

        self.settings.setValue('key1', 'plugins1', section=QgsSettings.Plugins)
        self.settings.setValue('key2', 'plugins2', section=QgsSettings.Plugins)

        self.settings.setValue('key1', 'misc1', section=QgsSettings.Misc)
        self.settings.setValue('key2', 'misc2', section=QgsSettings.Misc)

        self.settings.setValue('key1', 'auth1', section=QgsSettings.Auth)
        self.settings.setValue('key2', 'auth2', section=QgsSettings.Auth)

        self.settings.setValue('key1', 'app1', section=QgsSettings.App)
        self.settings.setValue('key2', 'app2', section=QgsSettings.App)

        self.settings.setValue('key1',
                               'provider1',
                               section=QgsSettings.Providers)
        self.settings.setValue('key2',
                               'provider2',
                               section=QgsSettings.Providers)

        self.settings.setValue('key1', 'auth1', section=QgsSettings.Auth)
        self.settings.setValue('key2', 'auth2', section=QgsSettings.Auth)

        # Test that the values are namespaced
        self.assertEqual(self.settings.value('core/key1'), 'core1')
        self.assertEqual(self.settings.value('core/key2'), 'core2')

        self.assertEqual(self.settings.value('server/key1'), 'server1')
        self.assertEqual(self.settings.value('server/key2'), 'server2')

        self.assertEqual(self.settings.value('gui/key1'), 'gui1')
        self.assertEqual(self.settings.value('gui/key2'), 'gui2')

        self.assertEqual(self.settings.value('plugins/key1'), 'plugins1')
        self.assertEqual(self.settings.value('plugins/key2'), 'plugins2')

        self.assertEqual(self.settings.value('misc/key1'), 'misc1')
        self.assertEqual(self.settings.value('misc/key2'), 'misc2')

        # Test getters
        self.assertEqual(
            self.settings.value('key1', None, section=QgsSettings.Core),
            'core1')
        self.assertEqual(
            self.settings.value('key2', None, section=QgsSettings.Core),
            'core2')

        self.assertEqual(
            self.settings.value('key1', None, section=QgsSettings.Server),
            'server1')
        self.assertEqual(
            self.settings.value('key2', None, section=QgsSettings.Server),
            'server2')

        self.assertEqual(
            self.settings.value('key1', None, section=QgsSettings.Gui), 'gui1')
        self.assertEqual(
            self.settings.value('key2', None, section=QgsSettings.Gui), 'gui2')

        self.assertEqual(
            self.settings.value('key1', None, section=QgsSettings.Plugins),
            'plugins1')
        self.assertEqual(
            self.settings.value('key2', None, section=QgsSettings.Plugins),
            'plugins2')

        self.assertEqual(
            self.settings.value('key1', None, section=QgsSettings.Misc),
            'misc1')
        self.assertEqual(
            self.settings.value('key2', None, section=QgsSettings.Misc),
            'misc2')

        self.assertEqual(
            self.settings.value('key1', None, section=QgsSettings.Auth),
            'auth1')
        self.assertEqual(
            self.settings.value('key2', None, section=QgsSettings.Auth),
            'auth2')

        self.assertEqual(
            self.settings.value('key1', None, section=QgsSettings.App), 'app1')
        self.assertEqual(
            self.settings.value('key2', None, section=QgsSettings.App), 'app2')

        self.assertEqual(
            self.settings.value('key1', None, section=QgsSettings.Providers),
            'provider1')
        self.assertEqual(
            self.settings.value('key2', None, section=QgsSettings.Providers),
            'provider2')

        # Test default values on Section getter
        self.assertEqual(
            self.settings.value('key_not_exist',
                                'misc_not_exist',
                                section=QgsSettings.Misc), 'misc_not_exist')

    def test_contains(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addToDefaults('testqgissettings/name', 'qgisrocks1')
        self.addToDefaults('testqgissettings/name2', 'qgisrocks2')

        self.assertTrue(self.settings.contains('testqgissettings/name'))
        self.assertTrue(self.settings.contains('testqgissettings/name2'))

        self.settings.setValue('testqgissettings/name3', 'qgisrocks3')
        self.assertTrue(self.settings.contains('testqgissettings/name3'))

    def test_remove(self):
        self.settings.setValue('testQgisSettings/temp', True)
        self.assertEqual(self.settings.value('testQgisSettings/temp'), True)
        self.settings.remove('testQgisSettings/temp')
        self.assertEqual(self.settings.value('testqQgisSettings/temp'), None)

        # Test remove by using Section
        self.settings.setValue('testQgisSettings/tempSection',
                               True,
                               section=QgsSettings.Core)
        self.assertEqual(
            self.settings.value('testQgisSettings/tempSection',
                                section=QgsSettings.Core), True)
        self.settings.remove('testQgisSettings/temp', section=QgsSettings.Core)
        self.assertEqual(
            self.settings.value('testqQgisSettings/temp',
                                section=QgsSettings.Core), None)
Beispiel #37
0
    def connect(self, parent=None):
        conn_name = self.connectionName()
        settings = QSettings()
        settings.beginGroup(u"/{0}/{1}".format(
                            self.connectionSettingsKey(), conn_name))

        if not settings.contains("database"):  # non-existent entry?
            raise InvalidDataException(
                self.tr('There is no defined database connection "{}".'.format(
                    conn_name)))

        from qgis.core import QgsDataSourceURI
        uri = QgsDataSourceURI()

        settingsList = ["host", "port", "database", "username", "password"]
        host, port, database, username, password = [settings.value(x, "", type=str) for x in settingsList]

        # get all of the connexion options

        useEstimatedMetadata = settings.value(
            "estimatedMetadata", False, type=bool)
        uri.setParam('userTablesOnly', unicode(
            settings.value("userTablesOnly", False, type=bool)))
        uri.setParam('geometryColumnsOnly', unicode(
            settings.value("geometryColumnsOnly", False, type=bool)))
        uri.setParam('allowGeometrylessTables', unicode(
            settings.value("allowGeometrylessTables", False, type=bool)))
        uri.setParam('onlyExistingTypes', unicode(
            settings.value("onlyExistingTypes", False, type=bool)))

        settings.endGroup()

        uri.setConnection(host, port, database, username, password)

        uri.setUseEstimatedMetadata(useEstimatedMetadata)

        err = u""
        try:
            return self.connectToUri(uri)
        except ConnectionError as e:
            err = unicode(e)

        # ask for valid credentials
        max_attempts = 3
        for i in range(max_attempts):
            (ok, username, password) = QgsCredentials.instance().get(
                uri.connectionInfo(False), username, password, err)

            if not ok:
                return False

            uri.setConnection(host, port, database, username, password)

            try:
                self.connectToUri(uri)
            except ConnectionError as e:
                if i == max_attempts - 1:  # failed the last attempt
                    raise e
                err = unicode(e)
                continue

            QgsCredentials.instance().put(
                uri.connectionInfo(False), username, password)

            return True

        return False
Beispiel #38
0
def get_postgres_connections():
    settings = QSettings()
    settings.beginGroup('/PostgreSQL/connections/')
    connections = settings.childGroups()
    settings.endGroup()
    return connections
Beispiel #39
0
 def getSuppressOptions(self):
     qgisSettigns = QSettings()
     qgisSettigns.beginGroup('qgis/digitizing')
     setting = qgisSettigns.value('disable_enter_attribute_values_dialog')
     qgisSettigns.endGroup()
     return setting
 def show_options_dialog(self):
     dlg = OptionsDialog(self.ili2db_configuration)
     if dlg.exec_():
         settings = QSettings()
         settings.beginGroup('QgsProjectGenerator/ili2db')
         self.ili2db_configuration.save(settings)
Beispiel #41
0
class TestQgsSettings(unittest.TestCase):

    cnt = 0

    def setUp(self):
        self.cnt += 1
        h, path = tempfile.mkstemp('.ini')
        Path(path).touch()
        assert QgsSettings.setGlobalSettingsPath(path)
        self.settings = QgsSettings('testqgissettings', 'testqgissettings%s' % self.cnt)
        self.globalsettings = QSettings(self.settings.globalSettingsPath(), QSettings.IniFormat)
        self.globalsettings.sync()
        assert os.path.exists(self.globalsettings.fileName())

    def tearDown(self):
        settings_file = self.settings.fileName()
        settings_default_file = self.settings.globalSettingsPath()
        del(self.settings)
        try:
            os.unlink(settings_file)
        except:
            pass
        try:
            os.unlink(settings_default_file)
        except:
            pass

    def addToDefaults(self, key, value):
        self.globalsettings.setValue(key, value)
        self.globalsettings.sync()

    def addArrayToDefaults(self, prefix, key, values):
        defaults = QSettings(self.settings.globalSettingsPath(), QSettings.IniFormat)  # NOQA
        self.globalsettings.beginWriteArray(prefix)
        i = 0
        for v in values:
            self.globalsettings.setArrayIndex(i)
            self.globalsettings.setValue(key, v)
            i += 1
        self.globalsettings.endArray()
        self.globalsettings.sync()

    def addGroupToDefaults(self, prefix, kvp):
        defaults = QSettings(self.settings.globalSettingsPath(), QSettings.IniFormat)  # NOQA
        self.globalsettings.beginGroup(prefix)
        for k, v in kvp.items():
            self.globalsettings.setValue(k, v)
        self.globalsettings.endGroup()
        self.globalsettings.sync()

    def test_basic_functionality(self):
        self.assertEqual(self.settings.value('testqgissettings/doesnotexists', 'notexist'), 'notexist')
        self.settings.setValue('testqgissettings/name', 'qgisrocks')
        self.settings.sync()
        self.assertEqual(self.settings.value('testqgissettings/name'), 'qgisrocks')

    def test_defaults(self):
        self.assertIsNone(self.settings.value('testqgissettings/name'))
        self.addToDefaults('testqgissettings/name', 'qgisrocks')
        self.assertEqual(self.settings.value('testqgissettings/name'), 'qgisrocks')

    def test_allkeys(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addToDefaults('testqgissettings/name', 'qgisrocks')
        self.addToDefaults('testqgissettings/name2', 'qgisrocks2')
        self.settings.setValue('nepoti/eman', 'osaple')

        self.assertEqual(3, len(self.settings.allKeys()))
        self.assertIn('testqgissettings/name', self.settings.allKeys())
        self.assertIn('nepoti/eman', self.settings.allKeys())
        self.assertEqual('qgisrocks', self.settings.value('testqgissettings/name'))
        self.assertEqual('qgisrocks2', self.settings.value('testqgissettings/name2'))
        self.assertEqual('qgisrocks', self.globalsettings.value('testqgissettings/name'))
        self.assertEqual('osaple', self.settings.value('nepoti/eman'))
        self.assertEqual(3, len(self.settings.allKeys()))
        self.assertEqual(2, len(self.globalsettings.allKeys()))

    def test_precedence_simple(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addToDefaults('testqgissettings/names/name1', 'qgisrocks1')
        self.settings.setValue('testqgissettings/names/name1', 'qgisrocks-1')

        self.assertEqual(self.settings.value('testqgissettings/names/name1'), 'qgisrocks-1')

    def test_precedence_group(self):
        """Test if user can override a group value"""
        self.assertEqual(self.settings.allKeys(), [])
        self.addGroupToDefaults('connections-xyz', {
            'OSM': 'http://a.tile.openstreetmap.org/{z}/{x}/{y}.png',
            'OSM-b': 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png',
        })
        self.settings.beginGroup('connections-xyz')
        self.assertEqual(self.settings.value('OSM'), 'http://a.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.assertEqual(self.settings.value('OSM-b'), 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.settings.endGroup()

        # Override edit
        self.settings.beginGroup('connections-xyz')
        self.settings.setValue('OSM', 'http://c.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.settings.endGroup()

        # Check it again!
        self.settings.beginGroup('connections-xyz')
        self.assertEqual(self.settings.value('OSM'), 'http://c.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.assertEqual(self.settings.value('OSM-b'), 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.settings.endGroup()

        # Override remove: the global value will be resumed!!!
        self.settings.beginGroup('connections-xyz')
        self.settings.remove('OSM')
        self.settings.endGroup()

        # Check it again!
        self.settings.beginGroup('connections-xyz')
        self.assertEqual(self.settings.value('OSM'), 'http://a.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.assertEqual(self.settings.value('OSM-b'), 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.settings.endGroup()

        # Override remove: store a blank!
        self.settings.beginGroup('connections-xyz')
        self.settings.setValue('OSM', '')
        self.settings.endGroup()

        # Check it again!
        self.settings.beginGroup('connections-xyz')
        self.assertEqual(self.settings.value('OSM'), '')
        self.assertEqual(self.settings.value('OSM-b'), 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.settings.endGroup()

        # Override remove: store a None: will resume the global setting!
        self.settings.beginGroup('connections-xyz')
        self.settings.setValue('OSM', None)
        self.settings.endGroup()

        # Check it again!
        self.settings.beginGroup('connections-xyz')
        self.assertEqual(self.settings.value('OSM'), 'http://a.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.assertEqual(self.settings.value('OSM-b'), 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.settings.endGroup()

    def test_uft8(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addToDefaults('testqgissettings/names/namèé↓1', 'qgisrocks↓1')
        self.assertEqual(self.settings.value('testqgissettings/names/namèé↓1'), 'qgisrocks↓1')

        self.settings.setValue('testqgissettings/names/namèé↓2', 'qgisrocks↓2')
        self.assertEqual(self.settings.value('testqgissettings/names/namèé↓2'), 'qgisrocks↓2')
        self.settings.setValue('testqgissettings/names/namèé↓1', 'qgisrocks↓-1')
        self.assertEqual(self.settings.value('testqgissettings/names/namèé↓1'), 'qgisrocks↓-1')

    def test_groups(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addToDefaults('testqgissettings/names/name1', 'qgisrocks1')
        self.addToDefaults('testqgissettings/names/name2', 'qgisrocks2')
        self.addToDefaults('testqgissettings/names/name3', 'qgisrocks3')
        self.addToDefaults('testqgissettings/name', 'qgisrocks')

        self.settings.beginGroup('testqgissettings')
        self.assertEqual(self.settings.group(), 'testqgissettings')
        self.assertEqual(['names'], self.settings.childGroups())

        self.settings.setValue('surnames/name1', 'qgisrocks-1')
        self.assertEqual(['surnames', 'names'], self.settings.childGroups())

        self.settings.setValue('names/name1', 'qgisrocks-1')
        self.assertEqual('qgisrocks-1', self.settings.value('names/name1'))
        self.settings.endGroup()
        self.assertEqual(self.settings.group(), '')
        self.settings.beginGroup('testqgissettings/names')
        self.assertEqual(self.settings.group(), 'testqgissettings/names')
        self.settings.setValue('name4', 'qgisrocks-4')
        keys = sorted(self.settings.childKeys())
        self.assertEqual(keys, ['name1', 'name2', 'name3', 'name4'])
        self.settings.endGroup()
        self.assertEqual(self.settings.group(), '')
        self.assertEqual('qgisrocks-1', self.settings.value('testqgissettings/names/name1'))
        self.assertEqual('qgisrocks-4', self.settings.value('testqgissettings/names/name4'))

    def test_global_groups(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.assertEqual(self.globalsettings.allKeys(), [])

        self.addToDefaults('testqgissettings/foo/first', 'qgis')
        self.addToDefaults('testqgissettings/foo/last', 'rocks')

        self.settings.beginGroup('testqgissettings')
        self.assertEqual(self.settings.group(), 'testqgissettings')
        self.assertEqual(['foo'], self.settings.childGroups())
        self.assertEqual(['foo'], self.settings.globalChildGroups())
        self.settings.endGroup()
        self.assertEqual(self.settings.group(), '')

        self.settings.setValue('testqgissettings/bar/first', 'qgis')
        self.settings.setValue('testqgissettings/bar/last', 'rocks')

        self.settings.beginGroup('testqgissettings')
        self.assertEqual(sorted(['bar', 'foo']), sorted(self.settings.childGroups()))
        self.assertEqual(['foo'], self.settings.globalChildGroups())
        self.settings.endGroup()

        self.globalsettings.remove('testqgissettings/foo')

        self.settings.beginGroup('testqgissettings')
        self.assertEqual(['bar'], self.settings.childGroups())
        self.assertEqual([], self.settings.globalChildGroups())
        self.settings.endGroup()

    def test_group_section(self):
        # Test group by using Section
        self.settings.beginGroup('firstgroup', section=QgsSettings.Core)
        self.assertEqual(self.settings.group(), 'core/firstgroup')
        self.assertEqual([], self.settings.childGroups())
        self.settings.setValue('key', 'value')
        self.settings.setValue('key2/subkey1', 'subvalue1')
        self.settings.setValue('key2/subkey2', 'subvalue2')
        self.settings.setValue('key3', 'value3')

        self.assertEqual(['key', 'key2/subkey1', 'key2/subkey2', 'key3'], self.settings.allKeys())
        self.assertEqual(['key', 'key3'], self.settings.childKeys())
        self.assertEqual(['key2'], self.settings.childGroups())
        self.settings.endGroup()
        self.assertEqual(self.settings.group(), '')
        # Set value by writing the group manually
        self.settings.setValue('firstgroup/key4', 'value4', section=QgsSettings.Core)
        # Checking the value that have been set
        self.assertEqual(self.settings.value('firstgroup/key', section=QgsSettings.Core), 'value')
        self.assertEqual(self.settings.value('firstgroup/key2/subkey1', section=QgsSettings.Core), 'subvalue1')
        self.assertEqual(self.settings.value('firstgroup/key2/subkey2', section=QgsSettings.Core), 'subvalue2')
        self.assertEqual(self.settings.value('firstgroup/key3', section=QgsSettings.Core), 'value3')
        self.assertEqual(self.settings.value('firstgroup/key4', section=QgsSettings.Core), 'value4')
        # Clean up firstgroup
        self.settings.remove('firstgroup', section=QgsSettings.Core)

    def test_array(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addArrayToDefaults('testqgissettings', 'key', ['qgisrocks1', 'qgisrocks2', 'qgisrocks3'])
        self.assertEqual(self.settings.allKeys(), ['testqgissettings/1/key', 'testqgissettings/2/key', 'testqgissettings/3/key', 'testqgissettings/size'])
        self.assertEqual(self.globalsettings.allKeys(), ['testqgissettings/1/key', 'testqgissettings/2/key', 'testqgissettings/3/key', 'testqgissettings/size'])

        self.assertEqual(3, self.globalsettings.beginReadArray('testqgissettings'))
        self.globalsettings.endArray()
        self.assertEqual(3, self.settings.beginReadArray('testqgissettings'))

        values = []
        for i in range(3):
            self.settings.setArrayIndex(i)
            values.append(self.settings.value("key"))

        self.assertEqual(values, ['qgisrocks1', 'qgisrocks2', 'qgisrocks3'])

    def test_array_overrides(self):
        """Test if an array completely shadows the global one"""
        self.assertEqual(self.settings.allKeys(), [])
        self.addArrayToDefaults('testqgissettings', 'key', ['qgisrocks1', 'qgisrocks2', 'qgisrocks3'])
        self.assertEqual(self.settings.allKeys(), ['testqgissettings/1/key', 'testqgissettings/2/key', 'testqgissettings/3/key', 'testqgissettings/size'])
        self.assertEqual(self.globalsettings.allKeys(), ['testqgissettings/1/key', 'testqgissettings/2/key', 'testqgissettings/3/key', 'testqgissettings/size'])

        self.assertEqual(3, self.globalsettings.beginReadArray('testqgissettings'))
        self.globalsettings.endArray()
        self.assertEqual(3, self.settings.beginReadArray('testqgissettings'))

        # Now override!
        self.settings.beginWriteArray('testqgissettings')
        self.settings.setArrayIndex(0)
        self.settings.setValue('key', 'myqgisrocksmore1')
        self.settings.setArrayIndex(1)
        self.settings.setValue('key', 'myqgisrocksmore2')
        self.settings.endArray()

        # Check it!
        self.assertEqual(2, self.settings.beginReadArray('testqgissettings'))

        values = []
        for i in range(2):
            self.settings.setArrayIndex(i)
            values.append(self.settings.value("key"))

        self.assertEqual(values, ['myqgisrocksmore1', 'myqgisrocksmore2'])

    def test_section_getters_setters(self):
        self.assertEqual(self.settings.allKeys(), [])

        self.settings.setValue('key1', 'core1', section=QgsSettings.Core)
        self.settings.setValue('key2', 'core2', section=QgsSettings.Core)

        self.settings.setValue('key1', 'server1', section=QgsSettings.Server)
        self.settings.setValue('key2', 'server2', section=QgsSettings.Server)

        self.settings.setValue('key1', 'gui1', section=QgsSettings.Gui)
        self.settings.setValue('key2', 'gui2', QgsSettings.Gui)

        self.settings.setValue('key1', 'plugins1', section=QgsSettings.Plugins)
        self.settings.setValue('key2', 'plugins2', section=QgsSettings.Plugins)

        self.settings.setValue('key1', 'misc1', section=QgsSettings.Misc)
        self.settings.setValue('key2', 'misc2', section=QgsSettings.Misc)

        self.settings.setValue('key1', 'auth1', section=QgsSettings.Auth)
        self.settings.setValue('key2', 'auth2', section=QgsSettings.Auth)

        self.settings.setValue('key1', 'app1', section=QgsSettings.App)
        self.settings.setValue('key2', 'app2', section=QgsSettings.App)

        self.settings.setValue('key1', 'provider1', section=QgsSettings.Providers)
        self.settings.setValue('key2', 'provider2', section=QgsSettings.Providers)

        # This is an overwrite of previous setting and it is intentional
        self.settings.setValue('key1', 'auth1', section=QgsSettings.Auth)
        self.settings.setValue('key2', 'auth2', section=QgsSettings.Auth)

        # Test that the values are namespaced
        self.assertEqual(self.settings.value('core/key1'), 'core1')
        self.assertEqual(self.settings.value('core/key2'), 'core2')

        self.assertEqual(self.settings.value('server/key1'), 'server1')
        self.assertEqual(self.settings.value('server/key2'), 'server2')

        self.assertEqual(self.settings.value('gui/key1'), 'gui1')
        self.assertEqual(self.settings.value('gui/key2'), 'gui2')

        self.assertEqual(self.settings.value('plugins/key1'), 'plugins1')
        self.assertEqual(self.settings.value('plugins/key2'), 'plugins2')

        self.assertEqual(self.settings.value('misc/key1'), 'misc1')
        self.assertEqual(self.settings.value('misc/key2'), 'misc2')

        # Test getters
        self.assertEqual(self.settings.value('key1', None, section=QgsSettings.Core), 'core1')
        self.assertEqual(self.settings.value('key2', None, section=QgsSettings.Core), 'core2')

        self.assertEqual(self.settings.value('key1', None, section=QgsSettings.Server), 'server1')
        self.assertEqual(self.settings.value('key2', None, section=QgsSettings.Server), 'server2')

        self.assertEqual(self.settings.value('key1', None, section=QgsSettings.Gui), 'gui1')
        self.assertEqual(self.settings.value('key2', None, section=QgsSettings.Gui), 'gui2')

        self.assertEqual(self.settings.value('key1', None, section=QgsSettings.Plugins), 'plugins1')
        self.assertEqual(self.settings.value('key2', None, section=QgsSettings.Plugins), 'plugins2')

        self.assertEqual(self.settings.value('key1', None, section=QgsSettings.Misc), 'misc1')
        self.assertEqual(self.settings.value('key2', None, section=QgsSettings.Misc), 'misc2')

        self.assertEqual(self.settings.value('key1', None, section=QgsSettings.Auth), 'auth1')
        self.assertEqual(self.settings.value('key2', None, section=QgsSettings.Auth), 'auth2')

        self.assertEqual(self.settings.value('key1', None, section=QgsSettings.App), 'app1')
        self.assertEqual(self.settings.value('key2', None, section=QgsSettings.App), 'app2')

        self.assertEqual(self.settings.value('key1', None, section=QgsSettings.Providers), 'provider1')
        self.assertEqual(self.settings.value('key2', None, section=QgsSettings.Providers), 'provider2')

        # Test default values on Section getter
        self.assertEqual(self.settings.value('key_not_exist', 'misc_not_exist', section=QgsSettings.Misc), 'misc_not_exist')

    def test_contains(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addToDefaults('testqgissettings/name', 'qgisrocks1')
        self.addToDefaults('testqgissettings/name2', 'qgisrocks2')

        self.assertTrue(self.settings.contains('testqgissettings/name'))
        self.assertTrue(self.settings.contains('testqgissettings/name2'))

        self.settings.setValue('testqgissettings/name3', 'qgisrocks3')
        self.assertTrue(self.settings.contains('testqgissettings/name3'))

    def test_remove(self):
        self.settings.setValue('testQgisSettings/temp', True)
        self.assertEqual(self.settings.value('testQgisSettings/temp'), True)
        self.settings.remove('testQgisSettings/temp')
        self.assertEqual(self.settings.value('testqQgisSettings/temp'), None)

        # Test remove by using Section
        self.settings.setValue('testQgisSettings/tempSection', True, section=QgsSettings.Core)
        self.assertEqual(self.settings.value('testQgisSettings/tempSection', section=QgsSettings.Core), True)
        self.settings.remove('testQgisSettings/temp', section=QgsSettings.Core)
        self.assertEqual(self.settings.value('testqQgisSettings/temp', section=QgsSettings.Core), None)

    def test_enumValue(self):
        self.settings.setValue('enum', 'LayerUnits')
        self.assertEqual(self.settings.enumValue('enum', QgsTolerance.Pixels), QgsTolerance.LayerUnits)
        self.settings.setValue('enum', 'dummy_setting')
        self.assertEqual(self.settings.enumValue('enum', QgsTolerance.Pixels), QgsTolerance.Pixels)
        self.assertEqual(type(self.settings.enumValue('enum', QgsTolerance.Pixels)), QgsTolerance.UnitType)

    def test_setEnumValue(self):
        self.settings.setValue('enum', 'LayerUnits')
        self.assertEqual(self.settings.enumValue('enum', QgsTolerance.Pixels), QgsTolerance.LayerUnits)
        self.settings.setEnumValue('enum', QgsTolerance.Pixels)
        self.assertEqual(self.settings.enumValue('enum', QgsTolerance.Pixels), QgsTolerance.Pixels)

    def test_flagValue(self):
        pointAndLine = QgsMapLayerProxyModel.Filters(QgsMapLayerProxyModel.PointLayer | QgsMapLayerProxyModel.LineLayer)
        pointAndPolygon = QgsMapLayerProxyModel.Filters(QgsMapLayerProxyModel.PointLayer | QgsMapLayerProxyModel.PolygonLayer)

        self.settings.setValue('flag', 'PointLayer|PolygonLayer')
        self.assertEqual(self.settings.flagValue('flag', pointAndLine), pointAndPolygon)
        self.settings.setValue('flag', 'dummy_setting')
        self.assertEqual(self.settings.flagValue('flag', pointAndLine), pointAndLine)
        self.assertEqual(type(self.settings.flagValue('enum', pointAndLine)), QgsMapLayerProxyModel.Filters)

    def test_overwriteDefaultValues(self):
        """Test that unchanged values are not stored"""
        self.globalsettings.setValue('a_value_with_default', 'a value')
        self.globalsettings.setValue('an_invalid_value', QVariant())

        self.assertEqual(self.settings.value('a_value_with_default'), 'a value')
        self.assertEqual(self.settings.value('an_invalid_value'), QVariant())

        # Now, set them with the same current value
        self.settings.setValue('a_value_with_default', 'a value')
        self.settings.setValue('an_invalid_value', QVariant())

        # Check
        pure_settings = QSettings(self.settings.fileName(), QSettings.IniFormat)
        self.assertFalse('a_value_with_default' in pure_settings.allKeys())
        self.assertFalse('an_invalid_value' in pure_settings.allKeys())

        # Set a changed value
        self.settings.setValue('a_value_with_default', 'a new value')
        self.settings.setValue('an_invalid_value', 'valid value')

        # Check
        self.assertTrue('a_value_with_default' in pure_settings.allKeys())
        self.assertTrue('an_invalid_value' in pure_settings.allKeys())

        self.assertEqual(self.settings.value('a_value_with_default'), 'a new value')
        self.assertEqual(self.settings.value('an_invalid_value'), 'valid value')

        # Re-set to original values
        self.settings.setValue('a_value_with_default', 'a value')
        self.settings.setValue('an_invalid_value', QVariant())

        self.assertEqual(self.settings.value('a_value_with_default'), 'a value')
        self.assertEqual(self.settings.value('an_invalid_value'), QVariant())

        # Check if they are gone
        pure_settings = QSettings(self.settings.fileName(), QSettings.IniFormat)
        self.assertFalse('a_value_with_default' not in pure_settings.allKeys())
        self.assertFalse('an_invalid_value' not in pure_settings.allKeys())
Beispiel #42
0
class PathfinderSettingsDialog(QDialog, FORM_CLASS):
    def __init__(self, parent=None):
        super(PathfinderSettingsDialog, self).__init__(parent)
        self.setupUi(self)

        self.settings = QSettings()
        self.settings.beginGroup('pathfinder')

        self.create_bindings()
        self.restore_settings()
        self.update_preview()

    def create_bindings(self) -> None:
        """Create bindings for the all elements."""
        # comboboxes https://doc.qt.io/qtforpython-5/PySide2/QtWidgets/QComboBox.html
        self.quote_cbox.currentTextChanged.connect(
            lambda v: self.on_curr_changed('quote_char', v))
        self.separ_cbox.currentTextChanged.connect(
            lambda v: self.on_curr_changed('separ_char', v))

        # lineedits https://doc.qt.io/qtforpython-5/PySide2/QtWidgets/QLineEdit.html
        self.quote_char_custom.textChanged.connect(
            lambda v: self.on_changed('quote_char_custom', v))
        self.separ_char_custom.textChanged.connect(
            lambda v: self.on_changed('separ_char_custom', v))
        self.prefix.textChanged.connect(lambda v: self.on_changed('prefix', v))
        self.postfix.textChanged.connect(
            lambda v: self.on_changed('postfix', v))

        # checkboxes https://doc.qt.io/qtforpython-5/PySide2/QtWidgets/QCheckBox.html
        self.incl_file_name.stateChanged.connect(
            lambda v: self.on_changed('incl_file_name', v))
        self.incl_layer_name.stateChanged.connect(
            lambda v: self.on_changed('incl_layer_name', v))
        self.incl_subset_str.stateChanged.connect(
            lambda v: self.on_changed('incl_subset_str', v))
        self.single_path_quote.stateChanged.connect(
            lambda v: self.on_changed('single_path_quote', v))
        self.single_path_affix.stateChanged.connect(
            lambda v: self.on_changed('single_path_affix', v))
        self.paths_on_new_line.stateChanged.connect(
            lambda v: self.on_changed('paths_on_new_line', v))
        self.show_notification.stateChanged.connect(
            lambda v: self.on_changed('show_notification', v))
        self.original_vrt_ds.stateChanged.connect(
            lambda v: self.on_changed('original_vrt_ds', v))

        # buttons https://doc.qt.io/qtforpython-5/PySide2/QtWidgets/QDialogButtonBox.html
        self.buttonBox.button(
            QDialogButtonBox.RestoreDefaults).clicked.connect(
                self.restore_defaults)

    def restore_settings(self) -> None:
        defs = PathfinderMaps.DEFAULTS
        """Reflect pathfinder's current settings inside the settings dialog."""
        self.quote_cbox.setCurrentText(
            self.settings.value('quote_char', defs['quote_char']))
        self.separ_cbox.setCurrentText(
            self.settings.value('separ_char', defs['separ_char']))

        self.quote_char_custom.setText(
            self.settings.value('quote_char_custom',
                                defs['quote_char_custom']))
        self.separ_char_custom.setText(
            self.settings.value('separ_char_custom',
                                defs['separ_char_custom']))
        self.prefix.setText(self.settings.value('prefix', defs['prefix']))
        self.postfix.setText(self.settings.value('postfix', defs['postfix']))

        # cast state to int because the value is returned as string from persistent storage
        self.incl_file_name.setCheckState(
            self.settings.value('incl_file_name', defs['incl_file_name'], int))
        self.incl_layer_name.setCheckState(
            self.settings.value('incl_layer_name', defs['incl_layer_name'],
                                int))
        self.incl_subset_str.setCheckState(
            self.settings.value('incl_subset_str', defs['incl_subset_str'],
                                int))
        self.single_path_quote.setCheckState(
            self.settings.value('single_path_quote', defs['single_path_quote'],
                                int))
        self.single_path_affix.setCheckState(
            self.settings.value('single_path_affix', defs['single_path_affix'],
                                int))
        self.paths_on_new_line.setCheckState(
            self.settings.value('paths_on_new_line', defs['paths_on_new_line'],
                                int))
        self.show_notification.setCheckState(
            self.settings.value('show_notification', defs['show_notification'],
                                int))
        self.original_vrt_ds.setCheckState(
            self.settings.value('original_vrt_ds', defs['original_vrt_ds'],
                                int))

    def on_curr_changed(self, key: str, value: str) -> None:
        """Enable/Disable corresponding custom character lineedit if necessary and forward
        key and value to on_changed().

        :param key: The name of the setting.
        :param value: The new value of the setting.
        """
        getattr(self, f'{key}_custom').setEnabled(value == tr('Other'))
        self.on_changed(key, value)

    def on_changed(self, key: str, value: str) -> None:
        """Change the setting ``key`` to ``value`` and update the preview.

        :param key: The name of the setting.
        :param value: The new value of the setting.
        """
        self.settings.setValue(key, value)
        self.update_preview()

    def update_preview(self, n: int = 2) -> None:
        """Construct a string of ``n`` mock paths using the current settings and display it in the
        paths_preview QLabel.

        :param n: The number of mock paths to be displayed in the preview. Optional. [default: 2]
        """
        pf = Pathfinder()
        # TODO: allow user to manipulate n
        paths = n * ['dir/subdir/file.ext|layername=lyr|subset=id > 0']
        parsed = [pf.parse_path(path, must_exist=False) for path in paths]
        out = pf.build_string(parsed)
        self.paths_preview.setText(out)

    def restore_defaults(self) -> None:
        """Reset settings to their default values."""
        for k, v in PathfinderMaps().DEFAULTS.items():
            self.settings.setValue(k, v)

        self.restore_settings()
        self.show()

    def keyPressEvent(self, event: QKeyEvent) -> None:
        """Modify key press events.

        :param event:
        """
        # gobble Enter
        if event.key() == Qt.Key_Enter:
            pass

        # close dialog on Escape
        if event.key() == Qt.Key_Escape:
            self.close()
Beispiel #43
0
 def dbConnectionNames(self):
     settings = QSettings()
     settings.beginGroup('/PostgreSQL/connections/')
     return settings.childGroups()
Beispiel #44
0
class MetaSearchDialog(QDialog, BASE_CLASS):

    """main dialogue"""

    def __init__(self, iface):
        """init window"""

        QDialog.__init__(self)
        self.setupUi(self)

        self.iface = iface
        self.map = iface.mapCanvas()
        self.settings = QSettings()
        self.catalog = None
        self.catalog_url = None
        self.context = StaticContext()

        version = self.context.metadata.get('general', 'version')
        self.setWindowTitle('MetaSearch %s' % version)

        self.rubber_band = QgsRubberBand(self.map, True)  # True = a polygon
        self.rubber_band.setColor(QColor(255, 0, 0, 75))
        self.rubber_band.setWidth(5)

        # form inputs
        self.startfrom = 0
        self.maxrecords = 10
        self.timeout = 10
        self.constraints = []

        # Servers tab
        self.cmbConnectionsServices.activated.connect(self.save_connection)
        self.cmbConnectionsSearch.activated.connect(self.save_connection)
        self.btnServerInfo.clicked.connect(self.connection_info)
        self.btnAddDefault.clicked.connect(self.add_default_connections)
        self.btnCapabilities.clicked.connect(self.show_xml)
        self.tabWidget.currentChanged.connect(self.populate_connection_list)

        # server management buttons
        self.btnNew.clicked.connect(self.add_connection)
        self.btnEdit.clicked.connect(self.edit_connection)
        self.btnDelete.clicked.connect(self.delete_connection)
        self.btnLoad.clicked.connect(self.load_connections)
        self.btnSave.clicked.connect(save_connections)

        # Search tab
        self.treeRecords.itemSelectionChanged.connect(self.record_clicked)
        self.treeRecords.itemDoubleClicked.connect(self.show_metadata)
        self.btnSearch.clicked.connect(self.search)
        self.leKeywords.returnPressed.connect(self.search)
        # prevent dialog from closing upon pressing enter
        self.buttonBox.button(QDialogButtonBox.Close).setAutoDefault(False)
        # launch help from button
        self.buttonBox.helpRequested.connect(self.help)
        self.btnCanvasBbox.setAutoDefault(False)
        self.btnCanvasBbox.clicked.connect(self.set_bbox_from_map)
        self.btnGlobalBbox.clicked.connect(self.set_bbox_global)

        # navigation buttons
        self.btnFirst.clicked.connect(self.navigate)
        self.btnPrev.clicked.connect(self.navigate)
        self.btnNext.clicked.connect(self.navigate)
        self.btnLast.clicked.connect(self.navigate)

        self.btnAddToWms.clicked.connect(self.add_to_ows)
        self.btnAddToWfs.clicked.connect(self.add_to_ows)
        self.btnAddToWcs.clicked.connect(self.add_to_ows)
        self.btnShowXml.clicked.connect(self.show_xml)

        # settings
        self.radioTitleAsk.clicked.connect(self.set_ows_save_title_ask)
        self.radioTitleNoAsk.clicked.connect(self.set_ows_save_title_no_ask)
        self.radioTempName.clicked.connect(self.set_ows_save_temp_name)

        self.manageGui()

    def manageGui(self):
        """open window"""

        self.tabWidget.setCurrentIndex(0)
        self.populate_connection_list()
        self.btnCapabilities.setEnabled(False)
        self.spnRecords.setValue(
            self.settings.value('/MetaSearch/returnRecords', 10, int))

        key = '/MetaSearch/%s' % self.cmbConnectionsSearch.currentText()
        self.catalog_url = self.settings.value('%s/url' % key)

        self.set_bbox_global()

        self.reset_buttons()

        # get preferred connection save strategy from settings and set it
        save_strat = self.settings.value('/MetaSearch/ows_save_strategy',
                                         'title_ask')
        if save_strat == 'temp_name':
            self.radioTempName.setChecked(True)
        elif save_strat == 'title_no_ask':
            self.radioTitleNoAsk.setChecked(True)
        else:
            self.radioTitleAsk.setChecked(True)

        # install proxy handler if specified in QGIS settings
        self.install_proxy()

    # Servers tab

    def populate_connection_list(self):
        """populate select box with connections"""

        self.settings.beginGroup('/MetaSearch/')
        self.cmbConnectionsServices.clear()
        self.cmbConnectionsServices.addItems(self.settings.childGroups())
        self.cmbConnectionsSearch.clear()
        self.cmbConnectionsSearch.addItems(self.settings.childGroups())
        self.settings.endGroup()

        self.set_connection_list_position()

        if self.cmbConnectionsServices.count() == 0:
            # no connections - disable various buttons
            state_disabled = False
            self.btnSave.setEnabled(state_disabled)
            # and start with connection tab open
            self.tabWidget.setCurrentIndex(1)
            # tell the user to add services
            msg = self.tr('No services/connections defined. To get '
                          'started with MetaSearch, create a new '
                          'connection by clicking \'New\' or click '
                          '\'Add default services\'.')
            self.textMetadata.setHtml('<p><h3>%s</h3></p>' % msg)
        else:
            # connections - enable various buttons
            state_disabled = True

        self.btnServerInfo.setEnabled(state_disabled)
        self.btnEdit.setEnabled(state_disabled)
        self.btnDelete.setEnabled(state_disabled)

    def set_connection_list_position(self):
        """set the current index to the selected connection"""
        to_select = self.settings.value('/MetaSearch/selected')
        conn_count = self.cmbConnectionsServices.count()

        if conn_count == 0:
            self.btnDelete.setEnabled(False)
            self.btnServerInfo.setEnabled(False)
            self.btnEdit.setEnabled(False)

        # does to_select exist in cmbConnectionsServices?
        exists = False
        for i in range(conn_count):
            if self.cmbConnectionsServices.itemText(i) == to_select:
                self.cmbConnectionsServices.setCurrentIndex(i)
                self.cmbConnectionsSearch.setCurrentIndex(i)
                exists = True
                break

        # If we couldn't find the stored item, but there are some, default
        # to the last item (this makes some sense when deleting items as it
        # allows the user to repeatidly click on delete to remove a whole
        # lot of items)
        if not exists and conn_count > 0:
            # If to_select is null, then the selected connection wasn't found
            # by QSettings, which probably means that this is the first time
            # the user has used CSWClient, so default to the first in the list
            # of connetions. Otherwise default to the last.
            if not to_select:
                current_index = 0
            else:
                current_index = conn_count - 1

            self.cmbConnectionsServices.setCurrentIndex(current_index)
            self.cmbConnectionsSearch.setCurrentIndex(current_index)

    def save_connection(self):
        """save connection"""

        caller = self.sender().objectName()

        if caller == 'cmbConnectionsServices':  # servers tab
            current_text = self.cmbConnectionsServices.currentText()
        elif caller == 'cmbConnectionsSearch':  # search tab
            current_text = self.cmbConnectionsSearch.currentText()

        self.settings.setValue('/MetaSearch/selected', current_text)
        key = '/MetaSearch/%s' % current_text

        if caller == 'cmbConnectionsSearch':  # bind to service in search tab
            self.catalog_url = self.settings.value('%s/url' % key)

        if caller == 'cmbConnectionsServices':  # clear server metadata
            self.textMetadata.clear()

        self.btnCapabilities.setEnabled(False)

    def connection_info(self):
        """show connection info"""

        current_text = self.cmbConnectionsServices.currentText()
        key = '/MetaSearch/%s' % current_text
        self.catalog_url = self.settings.value('%s/url' % key)

        # connect to the server
        if not self._get_csw():
            return

        QApplication.restoreOverrideCursor()

        if self.catalog:  # display service metadata
            self.btnCapabilities.setEnabled(True)
            metadata = render_template('en', self.context,
                                       self.catalog,
                                       'service_metadata.html')
            style = QgsApplication.reportStyleSheet()
            self.textMetadata.clear()
            self.textMetadata.document().setDefaultStyleSheet(style)
            self.textMetadata.setHtml(metadata)

    def add_connection(self):
        """add new service"""

        conn_new = NewConnectionDialog()
        conn_new.setWindowTitle(self.tr('New Catalogue service'))
        if conn_new.exec_() == QDialog.Accepted:  # add to service list
            self.populate_connection_list()
        self.textMetadata.clear()

    def edit_connection(self):
        """modify existing connection"""

        current_text = self.cmbConnectionsServices.currentText()

        url = self.settings.value('/MetaSearch/%s/url' % current_text)

        conn_edit = NewConnectionDialog(current_text)
        conn_edit.setWindowTitle(self.tr('Edit Catalogue service'))
        conn_edit.leName.setText(current_text)
        conn_edit.leURL.setText(url)
        if conn_edit.exec_() == QDialog.Accepted:  # update service list
            self.populate_connection_list()

    def delete_connection(self):
        """delete connection"""

        current_text = self.cmbConnectionsServices.currentText()

        key = '/MetaSearch/%s' % current_text

        msg = self.tr('Remove service %s?') % current_text

        result = QMessageBox.information(self, self.tr('Confirm delete'), msg,
                                         QMessageBox.Ok | QMessageBox.Cancel)
        if result == QMessageBox.Ok:  # remove service from list
            self.settings.remove(key)
            index_to_delete = self.cmbConnectionsServices.currentIndex()
            self.cmbConnectionsServices.removeItem(index_to_delete)
            self.cmbConnectionsSearch.removeItem(index_to_delete)
            self.set_connection_list_position()

    def load_connections(self):
        """load services from list"""

        ManageConnectionsDialog(1).exec_()
        self.populate_connection_list()

    def add_default_connections(self):
        """add default connections"""

        filename = os.path.join(self.context.ppath,
                                'resources', 'connections-default.xml')
        doc = get_connections_from_file(self, filename)
        if doc is None:
            return

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

        for server in doc.findall('csw'):
            name = server.attrib.get('name')
            # check for duplicates
            if name in keys:
                msg = self.tr('%s exists.  Overwrite?') % name
                res = QMessageBox.warning(self,
                                          self.tr('Loading connections'), msg,
                                          QMessageBox.Yes | QMessageBox.No)
                if res != QMessageBox.Yes:
                    continue

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

        self.populate_connection_list()

    # Settings tab

    def set_ows_save_title_ask(self):
        """save ows save strategy as save ows title, ask if duplicate"""

        self.settings.setValue('/MetaSearch/ows_save_strategy', 'title_ask')

    def set_ows_save_title_no_ask(self):
        """save ows save strategy as save ows title, do NOT ask if duplicate"""

        self.settings.setValue('/MetaSearch/ows_save_strategy', 'title_no_ask')

    def set_ows_save_temp_name(self):
        """save ows save strategy as save with a temporary name"""

        self.settings.setValue('/MetaSearch/ows_save_strategy', 'temp_name')

    # Search tab

    def set_bbox_from_map(self):
        """set bounding box from map extent"""

        crs = self.map.mapRenderer().destinationCrs()
        crsid = int(crs.authid().split(':')[1])

        extent = self.map.extent()

        if crsid != 4326:  # reproject to EPSG:4326
            src = QgsCoordinateReferenceSystem(crsid)
            dest = QgsCoordinateReferenceSystem(4326)
            xform = QgsCoordinateTransform(src, dest)
            minxy = xform.transform(QgsPoint(extent.xMinimum(),
                                             extent.yMinimum()))
            maxxy = xform.transform(QgsPoint(extent.xMaximum(),
                                             extent.yMaximum()))
            minx, miny = minxy
            maxx, maxy = maxxy
        else:  # 4326
            minx = extent.xMinimum()
            miny = extent.yMinimum()
            maxx = extent.xMaximum()
            maxy = extent.yMaximum()

        self.leNorth.setText(unicode(maxy)[0:9])
        self.leSouth.setText(unicode(miny)[0:9])
        self.leWest.setText(unicode(minx)[0:9])
        self.leEast.setText(unicode(maxx)[0:9])

    def set_bbox_global(self):
        """set global bounding box"""
        self.leNorth.setText('90')
        self.leSouth.setText('-90')
        self.leWest.setText('-180')
        self.leEast.setText('180')

    def search(self):
        """execute search"""

        self.catalog = None
        self.constraints = []

        # clear all fields and disable buttons
        self.lblResults.clear()
        self.treeRecords.clear()

        self.reset_buttons()

        # save some settings
        self.settings.setValue('/MetaSearch/returnRecords',
                               self.spnRecords.cleanText())

        # set current catalogue
        current_text = self.cmbConnectionsSearch.currentText()
        key = '/MetaSearch/%s' % current_text
        self.catalog_url = self.settings.value('%s/url' % key)

        # start position and number of records to return
        self.startfrom = 0
        self.maxrecords = self.spnRecords.value()

        # set timeout
        self.timeout = self.spnTimeout.value()

        # bbox
        minx = self.leWest.text()
        miny = self.leSouth.text()
        maxx = self.leEast.text()
        maxy = self.leNorth.text()
        bbox = [minx, miny, maxx, maxy]

        # only apply spatial filter if bbox is not global
        # even for a global bbox, if a spatial filter is applied, then
        # the CSW server will skip records without a bbox
        if bbox != ['-180', '-90', '180', '90']:
            self.constraints.append(BBox(bbox))

        # keywords
        if self.leKeywords.text():
            # TODO: handle multiple word searches
            keywords = self.leKeywords.text()
            self.constraints.append(PropertyIsLike('csw:AnyText', keywords))

        if len(self.constraints) > 1:  # exclusive search (a && b)
            self.constraints = [self.constraints]

        # build request
        if not self._get_csw():
            return

        # TODO: allow users to select resources types
        # to find ('service', 'dataset', etc.)
        try:
            self.catalog.getrecords2(constraints=self.constraints,
                                     maxrecords=self.maxrecords, esn='full')
        except ExceptionReport as err:
            QApplication.restoreOverrideCursor()
            QMessageBox.warning(self, self.tr('Search error'),
                                self.tr('Search error: %s') % err)
            return
        except Exception as err:
            QApplication.restoreOverrideCursor()
            QMessageBox.warning(self, self.tr('Connection error'),
                                self.tr('Connection error: %s') % err)
            return

        if self.catalog.results['matches'] == 0:
            QApplication.restoreOverrideCursor()
            self.lblResults.setText(self.tr('0 results'))
            return

        QApplication.restoreOverrideCursor()
        self.display_results()

    def display_results(self):
        """display search results"""

        self.treeRecords.clear()

        position = self.catalog.results['returned'] + self.startfrom

        msg = self.tr('Showing %d - %d of %n result(s)', 'number of results',
                      self.catalog.results['matches']) % (self.startfrom + 1,
                                                          position)

        self.lblResults.setText(msg)

        for rec in self.catalog.records:
            item = QTreeWidgetItem(self.treeRecords)
            if self.catalog.records[rec].type:
                item.setText(0, normalize_text(self.catalog.records[rec].type))
            else:
                item.setText(0, 'unknown')
            if self.catalog.records[rec].title:
                item.setText(1,
                             normalize_text(self.catalog.records[rec].title))
            if self.catalog.records[rec].identifier:
                set_item_data(item, 'identifier',
                              self.catalog.records[rec].identifier)

        self.btnShowXml.setEnabled(True)

        if self.catalog.results["matches"] < self.maxrecords:
            disabled = False
        else:
            disabled = True

        self.btnFirst.setEnabled(disabled)
        self.btnPrev.setEnabled(disabled)
        self.btnNext.setEnabled(disabled)
        self.btnLast.setEnabled(disabled)

    def record_clicked(self):
        """record clicked signal"""

        # disable only service buttons
        self.reset_buttons(True, False, False)

        if not self.treeRecords.selectedItems():
            return

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

        identifier = get_item_data(item, 'identifier')
        try:
            record = self.catalog.records[identifier]
        except KeyError as err:
            QMessageBox.warning(self,
                                self.tr('Record parsing error'),
                                'Unable to locate record identifier')
            return

        # if the record has a bbox, show a footprint on the map
        if record.bbox is not None:
            points = bbox_to_polygon(record.bbox)
            if points is not None:
                src = QgsCoordinateReferenceSystem(4326)
                dst = self.map.mapSettings().destinationCrs()
                geom = QgsGeometry.fromPolygon(points)
                if src.postgisSrid() != dst.postgisSrid():
                    ctr = QgsCoordinateTransform(src, dst)
                    try:
                        geom.transform(ctr)
                    except Exception as err:
                        QMessageBox.warning(
                            self,
                            self.tr('Coordinate Transformation Error'),
                            unicode(err))
                self.rubber_band.setToGeometry(geom, None)

        # figure out if the data is interactive and can be operated on
        self.find_services(record, item)

    def find_services(self, record, item):
        """scan record for WMS/WMTS|WFS|WCS endpoints"""

        links = record.uris + record.references

        services = {}
        for link in links:

            if 'scheme' in link:
                link_type = link['scheme']
            elif 'protocol' in link:
                link_type = link['protocol']
            else:
                link_type = None

            if link_type is not None:
                link_type = link_type.upper()

            wmswmst_link_types = map(str.upper, link_types.WMSWMST_LINK_TYPES)
            wfs_link_types = map(str.upper, link_types.WFS_LINK_TYPES)
            wcs_link_types = map(str.upper, link_types.WCS_LINK_TYPES)

            # if the link type exists, and it is one of the acceptable
            # interactive link types, then set
            if all([link_type is not None,
                    link_type in wmswmst_link_types + wfs_link_types +
                    wcs_link_types]):
                if link_type in wmswmst_link_types:
                    services['wms'] = link['url']
                    self.btnAddToWms.setEnabled(True)
                if link_type in wfs_link_types:
                    services['wfs'] = link['url']
                    self.btnAddToWfs.setEnabled(True)
                if link_type in wcs_link_types:
                    services['wcs'] = link['url']
                    self.btnAddToWcs.setEnabled(True)

            set_item_data(item, 'link', json.dumps(services))

    def navigate(self):
        """manage navigation / paging"""

        caller = self.sender().objectName()

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

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

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

        QApplication.restoreOverrideCursor()

        self.display_results()

    def add_to_ows(self):
        """add to OWS provider connection list"""

        conn_name_matches = []

        item = self.treeRecords.currentItem()

        if not item:
            return

        item_data = json.loads(get_item_data(item, 'link'))

        caller = self.sender().objectName()

        # stype = human name,/Qgis/connections-%s,providername
        if caller == 'btnAddToWms':
            stype = ['OGC:WMS/OGC:WMTS', 'wms', 'wms']
            data_url = item_data['wms']
        elif caller == 'btnAddToWfs':
            stype = ['OGC:WFS', 'wfs', 'WFS']
            data_url = item_data['wfs']
        elif caller == 'btnAddToWcs':
            stype = ['OGC:WCS', 'wcs', 'wcs']
            data_url = item_data['wcs']

        QApplication.restoreOverrideCursor()

        sname = '%s from MetaSearch' % stype[1]

        # store connection
        # check if there is a connection with same name
        self.settings.beginGroup('/Qgis/connections-%s' % stype[1])
        keys = self.settings.childGroups()
        self.settings.endGroup()

        for key in keys:
            if key.startswith(sname):
                conn_name_matches.append(key)
        if conn_name_matches:
            sname = conn_name_matches[-1]

        # check for duplicates
        if sname in keys:  # duplicate found
            if self.radioTitleAsk.isChecked():  # ask to overwrite
                msg = self.tr('Connection %s exists. Overwrite?') % sname
                res = QMessageBox.warning(self, self.tr('Saving server'), msg,
                                          QMessageBox.Yes | QMessageBox.No)
                if res != QMessageBox.Yes:  # assign new name with serial
                    sname = serialize_string(sname)
            elif self.radioTitleNoAsk.isChecked():  # don't ask to overwrite
                pass
            elif self.radioTempName.isChecked():  # use temp name
                sname = serialize_string(sname)

        # no dups detected or overwrite is allowed
        self.settings.beginGroup('/Qgis/connections-%s' % stype[1])
        self.settings.setValue('/%s/url' % sname, data_url)
        self.settings.endGroup()

        # open provider window
        ows_provider = QgsProviderRegistry.instance().selectWidget(stype[2],
                                                                   self)

        service_type = stype[0]

        # connect dialog signals to iface slots
        if service_type == 'OGC:WMS/OGC:WMTS':
            ows_provider.addRasterLayer.connect(self.iface.addRasterLayer)
            conn_cmb = ows_provider.findChild(QWidget, 'cmbConnections')
            connect = 'on_btnConnect_clicked'
        elif service_type == 'OGC:WFS':
            ows_provider.addWfsLayer.connect(self.iface.mainWindow().addWfsLayer)
            conn_cmb = ows_provider.findChild(QWidget, 'cmbConnections')
            connect = 'connectToServer'
        elif service_type == 'OGC:WCS':
            ows_provider.addRasterLayer.connect(self.iface.addRasterLayer)
            conn_cmb = ows_provider.findChild(QWidget, 'mConnectionsComboBox')
            connect = 'on_mConnectButton_clicked'
        ows_provider.setModal(False)
        ows_provider.show()

        # open provider dialogue against added OWS
        index = conn_cmb.findText(sname)
        if index > -1:
            conn_cmb.setCurrentIndex(index)
            # only for wfs
            if service_type == 'OGC:WFS':
                ows_provider.on_cmbConnections_activated(index)
        getattr(ows_provider, connect)()

    def show_metadata(self):
        """show record metadata"""

        if not self.treeRecords.selectedItems():
            return

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

        identifier = get_item_data(item, 'identifier')

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

        QApplication.restoreOverrideCursor()

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

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

        style = QgsApplication.reportStyleSheet()
        crd.textMetadata.document().setDefaultStyleSheet(style)
        crd.textMetadata.setHtml(metadata)
        crd.exec_()

    def show_xml(self):
        """show XML request / response"""

        crd = XMLDialog()
        request_html = highlight_xml(self.context, self.catalog.request)
        response_html = highlight_xml(self.context, self.catalog.response)
        style = QgsApplication.reportStyleSheet()
        crd.txtbrXMLRequest.clear()
        crd.txtbrXMLResponse.clear()
        crd.txtbrXMLRequest.document().setDefaultStyleSheet(style)
        crd.txtbrXMLResponse.document().setDefaultStyleSheet(style)
        crd.txtbrXMLRequest.setHtml(request_html)
        crd.txtbrXMLResponse.setHtml(response_html)
        crd.exec_()

    def reset_buttons(self, services=True, xml=True, navigation=True):
        """Convenience function to disable WMS/WMTS|WFS|WCS buttons"""

        if services:
            self.btnAddToWms.setEnabled(False)
            self.btnAddToWfs.setEnabled(False)
            self.btnAddToWcs.setEnabled(False)

        if xml:
            self.btnShowXml.setEnabled(False)

        if navigation:
            self.btnFirst.setEnabled(False)
            self.btnPrev.setEnabled(False)
            self.btnNext.setEnabled(False)
            self.btnLast.setEnabled(False)

    def help(self):
        """launch help"""

        open_url(get_help_url())

    def reject(self):
        """back out of dialogue"""

        QDialog.reject(self)
        self.rubber_band.reset()

    def _get_csw(self):
        """convenience function to init owslib.csw.CatalogueServiceWeb"""

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

        QMessageBox.warning(self, self.tr('CSW Connection error'), msg)
        QApplication.restoreOverrideCursor()
        return False

    def install_proxy(self):
        """set proxy if one is set in QGIS network settings"""

        # initially support HTTP for now
        if self.settings.value('/proxy/proxyEnabled') == 'true':
            if self.settings.value('/proxy/proxyType') == 'HttpProxy':
                ptype = 'http'
            else:
                return

            user = self.settings.value('/proxy/proxyUser')
            password = self.settings.value('/proxy/proxyPassword')
            host = self.settings.value('/proxy/proxyHost')
            port = self.settings.value('/proxy/proxyPort')

            proxy_up = ''
            proxy_port = ''

            if all([user != '', password != '']):
                proxy_up = '%s:%s@' % (user, password)

            if port != '':
                proxy_port = ':%s' % port

            conn = '%s://%s%s%s' % (ptype, proxy_up, host, proxy_port)
            install_opener(build_opener(ProxyHandler({ptype: conn})))
Beispiel #45
0
class Pathfinder(QObject):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.command = COMMANDS[pf_system()]
        self.locs = []
        self.selected_layers = []
        self.settings = QSettings()
        self.settings.beginGroup('pathfinder')

    def copy(self) -> None:
        """Copy paths to clipboard."""
        text = self.build_string(self.locs)
        QApplication.clipboard().setText(text)
        self.notify(text)

    def copy_double_backslash(self) -> None:
        """Copy paths to clipboard with double backslashes."""
        text = self.build_string(self.locs).replace('\\', '\\\\')
        QApplication.clipboard().setText(text)
        self.notify(text)

    def notify(self, text: str) -> None:
        """Show QGIS notification."""
        if self.settings.value('show_notification', type=bool):
            iface.messageBar().pushMessage(tr('Copied to clipboard'), html.escape(text), level=0)

    def open_in_explorer(self) -> None:
        """Open unique parent directories in a file explorer."""
        # TODO: select files in file explorer
        for p in self.unique_parent_dirs():
            subprocess.run([self.command, str(p)])

    def parse_selected(self) -> None:
        """Parse selected layers. Populate self.locs."""
        for lyr in self.selected_layers:
            path, query = self.parse_path(lyr.layer().source())
            if path is not None:
                self.locs.append((path, query))

    def unique_parent_dirs(self) -> Set[Path]:
        """Return list of unique parent directories from list of paths.

        :return: List of unique parent directories paths within self.locs.
        """
        return set([path.parent for path, query in self.locs])

    @property
    def layers_selected(self) -> bool:
        """Check if there are any layers selected and populate self.selected_layers.

        :return: Whether there are any layers selected.
        """
        view = iface.layerTreeView()
        self.selected_layers = [n for n in view.selectedNodes() if QgsLayerTree.isLayer(n)]
        return len(self.selected_layers) > 0

    @staticmethod
    def build_string(paths: List[tuple]) -> str:
        """Construct a string using pathfinders current settings.

        :param paths: A list of tuples (path, query) where the first item contains
        the valid file path and the second contains data provider information such
        as the layer name and subset string.
        :return: Formatted string representing one or more file paths.
        """
        settings = QSettings()
        settings.beginGroup('pathfinder')
        n = len(paths)

        q = get_char('quote_char')
        s = get_char('separ_char')

        pre = settings.value('prefix', DEFAULTS['prefix'])
        post = settings.value('postfix', DEFAULTS['postfix'])

        # should file name be included?
        fn = settings.value('incl_file_name', type=bool)

        if n == 1:
            # should a single path be quoted?
            if not settings.value('single_path_quote', type=bool):
                q = ''
            # should pre- and postfix be applied to single path?
            if not settings.value('single_path_affix', type=bool):
                pre = ''
                post = ''

        # should paths go onto separate lines?
        if n > 1 and settings.value('paths_on_new_line', type=bool):
            s += '\n'

        out = s.join([f'{q}{p if fn else p.parent}{i}{q}' for p, i in paths])
        return f'{pre}{out}{post}'

    @staticmethod
    def parse_path(path: str, must_exist: bool = True) -> tuple:
        """Strip the path string and return path and query elements
        according to pathfinder settings and data provider.

        :param path: String that could be a file path.
        :param must_exist: Whether path has to be a file or folder.
        :return: Tuple containing a valid file path and the desired data provider information.
        """
        # TODO:
        #  - come up with a more clear return than a tuple
        settings = QSettings()
        settings.beginGroup('pathfinder')
        parts = path.split('?')[0].split('|')

        if parts[0] == '':
            return None, None

        try:
            if parts[0].startswith('file:'):
                # convert uri to path
                fp = Path(url2pathname(urlparse(parts[0]).path))
            else:
                fp = Path(parts[0])
        except OSError:
            # return None for now
            return None, None

        if must_exist and not exists(fp):
            return None, None

        n = len(parts)
        has_layer_name = n > 1
        is_subset = n > 2

        query = ''

        if has_layer_name and settings.value('incl_layer_name', type=bool):
            query += f'|{parts[1]}'

        if is_subset and settings.value('incl_subset_str', type=bool):
            query += f'|{parts[2]}'

        if fp.suffix == '.vrt' and settings.value('original_vrt_ds', type=bool):
            # return path to data source instead of virtual file
            ds = ET.fromstring(fp.read_text()).find('OGRVRTLayer').find('SrcDataSource')
            try:
                if ds.attrib['relativeToVRT'] == '1' and fp.parent.joinpath(ds.text).is_file():
                    return fp.parent / ds.text, query
                elif ds.attrib['relativeToVRT'] == '0':
                    ds_path = Path(ds.text)
                    if ds_path.is_file():
                        return ds_path, query

            except KeyError:
                ds_path = Path(ds.text)
                if ds_path.is_file():
                    return ds_path, query

        # in case a shapefile was loaded from a directory
        if fp.is_dir():
            # we slice the layername instead of splitting to account for the
            # unlikely case that the shapefile name contains an equal sign (=)
            # Please never do this
            layername = parts[1][parts[1].index('=') + 1:]
            shp_path = fp.joinpath(layername).with_suffix('.shp')
            if shp_path.exists():
                return shp_path, query

        return fp, query
Beispiel #46
0
    def parse_path(path: str, must_exist: bool = True) -> tuple:
        """Strip the path string and return path and query elements
        according to pathfinder settings and data provider.

        :param path: String that could be a file path.
        :param must_exist: Whether path has to be a file or folder.
        :return: Tuple containing a valid file path and the desired data provider information.
        """
        # TODO:
        #  - come up with a more clear return than a tuple
        settings = QSettings()
        settings.beginGroup('pathfinder')
        parts = path.split('?')[0].split('|')

        if parts[0] == '':
            return None, None

        try:
            if parts[0].startswith('file:'):
                # convert uri to path
                fp = Path(url2pathname(urlparse(parts[0]).path))
            else:
                fp = Path(parts[0])
        except OSError:
            # return None for now
            return None, None

        if must_exist and not exists(fp):
            return None, None

        n = len(parts)
        has_layer_name = n > 1
        is_subset = n > 2

        query = ''

        if has_layer_name and settings.value('incl_layer_name', type=bool):
            query += f'|{parts[1]}'

        if is_subset and settings.value('incl_subset_str', type=bool):
            query += f'|{parts[2]}'

        if fp.suffix == '.vrt' and settings.value('original_vrt_ds', type=bool):
            # return path to data source instead of virtual file
            ds = ET.fromstring(fp.read_text()).find('OGRVRTLayer').find('SrcDataSource')
            try:
                if ds.attrib['relativeToVRT'] == '1' and fp.parent.joinpath(ds.text).is_file():
                    return fp.parent / ds.text, query
                elif ds.attrib['relativeToVRT'] == '0':
                    ds_path = Path(ds.text)
                    if ds_path.is_file():
                        return ds_path, query

            except KeyError:
                ds_path = Path(ds.text)
                if ds_path.is_file():
                    return ds_path, query

        # in case a shapefile was loaded from a directory
        if fp.is_dir():
            # we slice the layername instead of splitting to account for the
            # unlikely case that the shapefile name contains an equal sign (=)
            # Please never do this
            layername = parts[1][parts[1].index('=') + 1:]
            shp_path = fp.joinpath(layername).with_suffix('.shp')
            if shp_path.exists():
                return shp_path, query

        return fp, query