From f9851abe3083e5ebb7a23e9b305a3de5efabf82d Mon Sep 17 00:00:00 2001 From: SimonSAMPERE Date: Mon, 19 Feb 2024 18:28:06 +0100 Subject: [PATCH] #258 Start replacing QSettings with inheriting custom module --- isogeo.py | 48 +++++++++------------- modules/__init__.py | 1 + modules/api/auth.py | 80 +++++++++++++++---------------------- modules/layer/add_layer.py | 2 - modules/layer/database.py | 29 ++++++++------ modules/metadata_display.py | 21 ++++------ modules/portal_base_url.py | 16 ++++---- modules/search_form.py | 7 ++-- modules/settings_manager.py | 64 +++++++++++++++++++++++++++++ modules/tools.py | 29 ++++++-------- modules/user_inform.py | 56 ++++++++++++++++++-------- 11 files changed, 204 insertions(+), 149 deletions(-) create mode 100644 modules/settings_manager.py diff --git a/isogeo.py b/isogeo.py index a3630f79..b65042ca 100644 --- a/isogeo.py +++ b/isogeo.py @@ -31,7 +31,7 @@ from functools import partial # PyQT -from qgis.PyQt.QtCore import QCoreApplication, QSettings, Qt, QTranslator, qVersion +from qgis.PyQt.QtCore import QCoreApplication, Qt, QTranslator from qgis.PyQt.QtWidgets import QAction, QComboBox, QDesktopWidget, QProgressBar from qgis.PyQt.QtGui import QIcon @@ -52,7 +52,7 @@ # UI classes from .ui.credits.dlg_credits import IsogeoCredits -# Plugin modules +# submodule from .modules import ( Authenticator, ApiRequester, @@ -61,6 +61,7 @@ SharesParser, SearchFormManager, UserInformer, + SettingsManager ) # ############################################################################ @@ -72,7 +73,7 @@ plg_reg_name = plg_basepath.name # QGIS useful tooling and shortcuts msgBar = iface.messageBar() -qsettings = QSettings() +settings_mng = SettingsManager() # required `_log` subfolder plg_logdir = Path(plg_basepath) / "_logs" @@ -169,34 +170,22 @@ def __init__(self, iface): pass # initialize locale - try: - locale = str(qsettings.value("locale/userLocale", "fr", type=str))[0:2] - except TypeError as exc: - logger.error( - "Bad type in QSettings: {}. Original error: {}".format( - type(qsettings.value("locale/userLocale")), exc - ) - ) - locale = "fr" - # load localized translation - locale_path = self.plugin_dir / "i18n" / "isogeo_search_engine_{}.qm".format(locale) - logger.info("Language applied: {0}".format(locale)) + locale = settings_mng.get_locale() - if locale_path.exists(): - self.translator = QTranslator() - self.translator.load(str(locale_path)) + i18n_file_path = self.plugin_dir / "i18n" / "isogeo_search_engine_{}.qm".format(locale) + logger.info("Language applied: {}".format(locale)) - if qVersion() > "4.3.3": - QCoreApplication.installTranslator(self.translator) - else: - pass + if i18n_file_path.exists(): + self.translator = QTranslator() + self.translator.load(str(i18n_file_path)) + QCoreApplication.installTranslator(self.translator) else: pass - if locale == "fr": - self.lang = "fr" - else: + if locale != "fr": self.lang = "en" + else: + self.lang = locale # Declare instance attributes self.actions = [] @@ -211,7 +200,7 @@ def __init__(self, iface): # SUBMODULES # instanciating - self.informer = UserInformer(message_bar=msgBar, trad=self.tr) + self.informer = UserInformer(message_bar=msgBar) self.authenticator = Authenticator() @@ -539,7 +528,7 @@ def search_slot(self, result: dict, tags: dict): if self.savedSearch == "": # Putting all the comboboxes selected index to their previous location. logger.debug("Classic search case (not quicksearch)") - params=params + params = params selected_keywords = params.get("keys") quicksearch = "" else: @@ -557,7 +546,7 @@ def search_slot(self, result: dict, tags: dict): selected_keywords_labels = params.get("labels").get("keys") # https://github.com/isogeo/isogeo-plugin-qgis/issues/436 else: selected_keywords_labels = [] - + # Setting widgets to their previous index self.form_mng.set_ccb_index(params=params, quicksearch=quicksearch) # Updating the keywords special combobox (filling + indexing) @@ -644,7 +633,7 @@ def set_widget_status(self): originCrs = QgsCoordinateReferenceSystem(search_params.get("epsg")) else: originCrs = QgsCoordinateReferenceSystem("EPSG:" + str(search_params.get("epsg"))) - + if originCrs.isValid(): qgs_prj.setCrs(originCrs) e = search_params.get("extent") @@ -889,7 +878,6 @@ def run(self): # add translator method in others modules plg_tools.tr = self.tr self.authenticator.tr = self.tr - self.authenticator.lang = self.lang # checks url_to_check = ( self.authenticator.api_params.get("url_base") diff --git a/modules/__init__.py b/modules/__init__.py index f5c7914f..80104e93 100644 --- a/modules/__init__.py +++ b/modules/__init__.py @@ -5,3 +5,4 @@ from .quick_search import QuickSearchManager from .search_form import SearchFormManager from .user_inform import UserInformer +from .settings_manager import SettingsManager diff --git a/modules/api/auth.py b/modules/api/auth.py index c81f0030..a4fe56c5 100644 --- a/modules/api/auth.py +++ b/modules/api/auth.py @@ -28,38 +28,26 @@ # Plugin modules from ..tools import IsogeoPlgTools from ..user_inform import UserInformer +from ..settings_manager import SettingsManager # ############################################################################ # ########## Globals ############### # ################################## logger = logging.getLogger("IsogeoQgisPlugin") -qsettings = QSettings() +settings_mng = SettingsManager() plg_tools = IsogeoPlgTools() +# initialize locale +locale = settings_mng.get_locale() plugin_dir = Path(__file__).parents[2] +i18n_file_path = plugin_dir / "i18n" / "isogeo_search_engine_{}.qm".format(locale) -try: - locale = str(qsettings.value("locale/userLocale", "fr", type=str))[0:2] -except TypeError as exc: - logger.error( - "Bad type in QSettings: {}. Original error: {}".format( - type(qsettings.value("locale/userLocale")), exc - ) - ) - locale = "fr" - -locale_path = plugin_dir / "i18n" / "isogeo_search_engine_{}.qm".format(locale) - -if locale_path.exists(): +if i18n_file_path.exists(): translator = QTranslator() - translator.load(str(locale_path)) - - if qVersion() > "4.3.3": - QCoreApplication.installTranslator(translator) - else: - pass + translator.load(str(i18n_file_path)) + QCoreApplication.installTranslator(translator) else: pass @@ -131,10 +119,6 @@ def __init__(self): self.auth_folder = plugin_dir / "_auth" self.cred_filepath = self.auth_folder / "client_secrets.json" - # translation - self.tr = object - self.lang = str - # inform user self.informer = object self.first_auth = bool @@ -171,13 +155,13 @@ def load_json_file_content(self): logger.info( "config.json file content successfully loaded : {}.".format(self.json_content) ) - qsettings.setValue("isogeo/env/api_base_url", self.json_content.get("api_base_url")) - qsettings.setValue("isogeo/env/api_auth_url", self.json_content.get("api_auth_url")) - qsettings.setValue("isogeo/env/app_base_url", self.json_content.get("app_base_url")) - qsettings.setValue( + settings_mng.set_value("isogeo/env/api_base_url", self.json_content.get("api_base_url")) + settings_mng.set_value("isogeo/env/api_auth_url", self.json_content.get("api_auth_url")) + settings_mng.set_value("isogeo/env/app_base_url", self.json_content.get("app_base_url")) + settings_mng.set_value( "isogeo/env/help_base_url", self.json_content.get("help_base_url") ) - qsettings.setValue( + settings_mng.set_value( "isogeo/settings/background_map_url", self.json_content.get("background_map_url"), ) @@ -191,19 +175,19 @@ def load_json_file_content(self): ) logger.warning("Let's create one with default values: {}.".format(self.json_path)) self.json_content = { - "api_base_url": qsettings.value( + "api_base_url": settings_mng.get_value( "isogeo/env/api_base_url", "https://v1.api.isogeo.com" ), - "api_auth_url": qsettings.value( + "api_auth_url": settings_mng.get_value( "isogeo/env/api_auth_url", "https://id.api.isogeo.com" ), - "app_base_url": qsettings.value( + "app_base_url": settings_mng.get_value( "isogeo/env/app_base_url", "https://app.isogeo.com" ), - "help_base_url": qsettings.value( + "help_base_url": settings_mng.get_value( "isogeo/env/help_base_url", "https://help.isogeo.com" ), - "background_map_url": qsettings.value( + "background_map_url": settings_mng.get_value( "isogeo/settings/background_map_url", "type=xyz&format=image/png&styles=default&tileMatrixSet=250m&url=http://tile.openstreetmap.org/{z}/{x}/{y}.png", ), @@ -249,21 +233,21 @@ def manage_api_initialization(self): def credentials_check_qsettings(self): """Retrieve Isogeo API credentials within QGIS QSettings.""" - if "isogeo-plugin" in qsettings.childGroups(): + if "isogeo-plugin" in settings_mng.childGroups(): logger.warning("Old credentials found and removed in QGIS QSettings: isogeo-plugin") - qsettings.remove("isogeo-plugin") + settings_mng.remove("isogeo-plugin") return False - elif "isogeo" in qsettings.childGroups(): + elif "isogeo" in settings_mng.childGroups(): # looking in child groups and clean a little if needed - qsettings.beginGroup("isogeo") - if "auth" in qsettings.childGroups() and qsettings.contains("auth/app_id"): + settings_mng.beginGroup("isogeo") + if "auth" in settings_mng.childGroups() and settings_mng.contains("auth/app_id"): logger.debug("Credentials found within QGIS QSettings: isogeo/") - qsettings.endGroup() + settings_mng.endGroup() return True else: logger.debug("Missing 'isogeo/auth' entry within QGIS QSettings.") - qsettings.endGroup() + settings_mng.endGroup() return False else: logger.debug("No Isogeo credentials found within QGIS QSettings.") @@ -304,8 +288,8 @@ def credentials_storer(self, store_location: str = "QSettings"): - QSettings """ if store_location == "QSettings": - qsettings.setValue("isogeo/auth/app_id", self.api_params.get("app_id")) - qsettings.setValue("isogeo/auth/app_secret", self.api_params.get("app_secret")) + settings_mng.set_value("isogeo/auth/app_id", self.api_params.get("app_id")) + settings_mng.set_value("isogeo/auth/app_secret", self.api_params.get("app_secret")) else: pass logger.debug("Credentials stored into: {}".format(store_location)) @@ -319,8 +303,8 @@ def credentials_update(self, credentials_source: str = "QSettings"): """ # update class attributes if credentials_source == "QSettings": - self.api_params["app_id"] = qsettings.value("isogeo/auth/app_id", "") - self.api_params["app_secret"] = qsettings.value("isogeo/auth/app_secret", "") + self.api_params["app_id"] = settings_mng.get_value("isogeo/auth/app_id", "") + self.api_params["app_secret"] = settings_mng.get_value("isogeo/auth/app_secret", "") elif credentials_source == "oAuth2_file": creds = plg_tools.credentials_loader(self.cred_filepath) self.api_params["app_id"] = creds.get("client_id") @@ -338,10 +322,10 @@ def credentials_update(self, credentials_source: str = "QSettings"): # AUTHENTICATION FORM -------------------------------------------------------------------------- def display_auth_form(self): """Show authentication form with prefilled fields and connected widgets.""" - self.informer = UserInformer(message_bar=self.msgbar, trad=self.tr) + self.informer = UserInformer(message_bar=self.msgbar) self.auth_sig.connect(self.informer.authentication_slot) self.ui_auth_form.chb_isogeo_editor.stateChanged.connect( - lambda: qsettings.setValue( + lambda: settings_mng.set_value( "isogeo/user/editor", int(self.ui_auth_form.chb_isogeo_editor.isChecked()), ) @@ -355,7 +339,7 @@ def display_auth_form(self): self.ui_auth_form.ent_app_secret.setText(self.api_params["app_secret"]) self.ui_auth_form.lbl_api_url_value.setText(self.api_params["url_base"]) self.ui_auth_form.chb_isogeo_editor.setChecked( - int(qsettings.value("isogeo/user/editor", 0)) + int(settings_mng.get_value("isogeo/user/editor", 0)) ) # display logger.debug("Authentication form filled and ready to be launched.") diff --git a/modules/layer/add_layer.py b/modules/layer/add_layer.py index 5b3d0d37..899337a4 100644 --- a/modules/layer/add_layer.py +++ b/modules/layer/add_layer.py @@ -6,7 +6,6 @@ import os # PyQT -from qgis.PyQt.QtCore import QSettings from qgis.PyQt.QtWidgets import QMessageBox # PyQGIS @@ -32,7 +31,6 @@ # ########## Globals ############### # ################################## -qsettings = QSettings() logger = logging.getLogger("IsogeoQgisPlugin") plg_tools = IsogeoPlgTools() diff --git a/modules/layer/database.py b/modules/layer/database.py index fa43aebc..b0018b98 100644 --- a/modules/layer/database.py +++ b/modules/layer/database.py @@ -28,13 +28,16 @@ # UI classes from ...ui.db_connections.dlg_db_connections import Isogeodb_connections +# Plugin modules +from ..settings_manager import SettingsManager + # ############################################################################ # ########## Globals ############### # ################################## qgis_version = int("".join(Qgis.QGIS_VERSION.split(".")[:2])) -qsettings = QSettings() +settings_mng = SettingsManager() logger = logging.getLogger("IsogeoQgisPlugin") # DBMS dependencies @@ -224,7 +227,7 @@ def set_qsettings_connections(self, dbms: str, connections_kind: str, li_connect "{}_key".format(connections_kind) ) - qsettings.setValue(qsettings_key, li_connections) + settings_mng.set_value(qsettings_key, li_connections) def fetch_qsettings_connections(self, dbms: str, connections_kind: str): """Retrieve the list of invalid or prefered (depending on connections_kind) connections saved in QSettings""" @@ -253,8 +256,8 @@ def fetch_qsettings_connections(self, dbms: str, connections_kind: str): ) dict_key = "{}_connections".format(connections_kind) - if qsettings.value(qsettings_key): - self.dbms_specifics_infos[dbms][dict_key] = qsettings.value(qsettings_key) + if settings_mng.get_value(qsettings_key): + self.dbms_specifics_infos[dbms][dict_key] = settings_mng.get_value(qsettings_key) logger.info( "{} {} {} connection retrieved from QSettings.".format( len(self.dbms_specifics_infos.get(dbms).get(dict_key)), @@ -375,11 +378,11 @@ def qsettings_content_parser(self, dbms: str, connection_name: str): conn_prefix = "{}/connections/{}".format(dbms, connection_name) - database = qsettings.value(conn_prefix + "/database") - host = qsettings.value(conn_prefix + "/host") - port = qsettings.value(conn_prefix + "/port") - username = qsettings.value(conn_prefix + "/username") - password = qsettings.value(conn_prefix + "/password") + database = settings_mng.get_value(conn_prefix + "/database") + host = settings_mng.get_value(conn_prefix + "/host") + port = settings_mng.get_value(conn_prefix + "/port") + username = settings_mng.get_value(conn_prefix + "/username") + password = settings_mng.get_value(conn_prefix + "/password") connection_dict = { "service": "", @@ -589,13 +592,13 @@ def build_connection_dict(self, dbms: str, skip_invalid: bool = True): li_db_aliases = [] # Loading connections saved into QGIS Settings - for k in sorted(qsettings.allKeys()): + for k in sorted(settings_mng.allKeys()): if k.startswith(dbms_prefix) and k.endswith("/database") and len(k.split("/")) == 4: connection_name = k.split("/")[2] - password_saved = qsettings.value(dbms_prefix + connection_name + "/savePassword") - user_saved = qsettings.value(dbms_prefix + connection_name + "/saveUsername") - connection_service = qsettings.value(dbms_prefix + connection_name + "/service") + password_saved = settings_mng.get_value(dbms_prefix + connection_name + "/savePassword") + user_saved = settings_mng.get_value(dbms_prefix + connection_name + "/saveUsername") + connection_service = settings_mng.get_value(dbms_prefix + connection_name + "/service") # For connections configured using config file and service if connection_service != "" and self.pg_configfile_path and dbms == "PostgreSQL": diff --git a/modules/metadata_display.py b/modules/metadata_display.py index dfa415e9..f5cd5842 100644 --- a/modules/metadata_display.py +++ b/modules/metadata_display.py @@ -20,7 +20,7 @@ ) # PyQT -from qgis.PyQt.QtCore import QSettings, Qt, QSize +from qgis.PyQt.QtCore import Qt from qgis.PyQt.QtGui import QColor from qgis.PyQt.QtWidgets import QTableWidgetItem, QLabel @@ -30,14 +30,17 @@ # Plugin modules from .tools import IsogeoPlgTools -# UI module +# UI classes from ..ui.metadata.dlg_md_details import IsogeoMdDetails +# Plugin modules +from .settings_manager import SettingsManager + # ############################################################################ # ########## Globals ############### # ################################## -qsettings = QSettings() +settings_mng = SettingsManager() logger = logging.getLogger("IsogeoQgisPlugin") plg_tools = IsogeoPlgTools() @@ -92,15 +95,7 @@ def show_complete_md(self, md: dict, tags: dict): :param md dict: Isogeo metadata dict """ logger.info("Displaying the whole metadata sheet.") - try: - locale = str(qsettings.value("locale/userLocale", "fr", type=str))[0:2] - except TypeError as e: - logger.error( - "Bad type in QSettings: {}. Original error: {}".format( - type(qsettings.value("locale/userLocale")), e - ) - ) - locale = "fr" + locale = settings_mng.get_locale() isogeo_tr = IsogeoTranslator(locale) # clean map canvas @@ -480,7 +475,7 @@ def show_complete_md(self, md: dict, tags: dict): self.app_base_url, wg_id, md.get("_id") ) - self.complete_md.btn_md_edit.setEnabled(int(qsettings.value("isogeo/user/editor", 1))) + self.complete_md.btn_md_edit.setEnabled(int(settings_mng.get_value("isogeo/user/editor", 0))) # -- DISPLAY --------------------------------------------------------- self.fields_displayer(md.get("type"), md.get("series")) diff --git a/modules/portal_base_url.py b/modules/portal_base_url.py index 5b1ce07b..771410b5 100644 --- a/modules/portal_base_url.py +++ b/modules/portal_base_url.py @@ -9,16 +9,18 @@ # PyQT from qgis.PyQt.QtGui import QIcon -from qgis.PyQt.QtCore import QSettings # UI classes from ..ui.portal.dlg_portal_base_url import IsogeoPortalBaseUrl +# Plugin modules +from .settings_manager import SettingsManager + # ############################################################################ # ########## Globals ############### # ################################## -qsettings = QSettings() +settings_mng = SettingsManager() logger = logging.getLogger("IsogeoQgisPlugin") @@ -52,22 +54,22 @@ def open_dialog(self): """""" self.portalURL_config_dialog.input_portal_url.setText( - qsettings.value("isogeo/settings/portal_base_url", "") + settings_mng.get_value("isogeo/settings/portal_base_url", "") ) self.portalURL_config_dialog.chb_portal_url.setChecked( - int(qsettings.value("isogeo/settings/add_metadata_url_portal", 0)) + int(settings_mng.get_value("isogeo/settings/add_metadata_url_portal", 0)) ) self.portalURL_config_dialog.open() def save(self): """""" - # save base portal URL in qsettings - qsettings.setValue( + # save base portal URL in QSettings + settings_mng.set_value( "isogeo/settings/portal_base_url", self.portalURL_config_dialog.input_portal_url.text() ) is_checked = int(self.portalURL_config_dialog.chb_portal_url.isChecked()) - qsettings.setValue("isogeo/settings/add_metadata_url_portal", is_checked) + settings_mng.set_value("isogeo/settings/add_metadata_url_portal", is_checked) def update_input_state(self): """""" diff --git a/modules/search_form.py b/modules/search_form.py index 6cb4372c..1a743518 100644 --- a/modules/search_form.py +++ b/modules/search_form.py @@ -15,7 +15,7 @@ from qgis.utils import iface # PyQT -from qgis.PyQt.QtCore import pyqtSignal, QSettings, Qt, QEvent +from qgis.PyQt.QtCore import pyqtSignal, Qt, QEvent from qgis.PyQt.QtWidgets import QComboBox from qgis.PyQt.QtGui import QIcon, QStandardItem @@ -27,6 +27,7 @@ from .quick_search import QuickSearchManager from .portal_base_url import PortalURLManager from .results import ResultsManager +from .settings_manager import SettingsManager # ############################################################################ # ########## Globals ############### @@ -37,7 +38,7 @@ plg_tools = IsogeoPlgTools() -qsettings = QSettings() +settings_mng = SettingsManager() # icons ico_od_asc = QIcon(":/plugins/Isogeo/resources/results/sort-alpha-asc.svg") ico_od_desc = QIcon(":/plugins/Isogeo/resources/results/sort-alpha-desc.svg") @@ -514,7 +515,7 @@ def save_params(self): else: pass # saving params in QSettings - qsettings.setValue("isogeo/settings/georelation", params.get("operation")) + settings_mng.set_value("isogeo/settings/georelation", params.get("operation")) return params def get_coords(self, filter: str): diff --git a/modules/settings_manager.py b/modules/settings_manager.py new file mode 100644 index 00000000..219ab6e6 --- /dev/null +++ b/modules/settings_manager.py @@ -0,0 +1,64 @@ +# -*- coding: utf-8 -*- +#! python3 # noqa: E265 + +# Standard library +import logging + +# PyQGIS +from qgis.utils import iface + +# PyQT +from qgis.PyQt.QtCore import QSettings + + +# ############################################################################ +# ########## Globals ############### +# ################################## + +logger = logging.getLogger("IsogeoQgisPlugin") +msgBar = iface.messageBar() + +# ############################################################################ +# ########## Classes ############### +# ################################## + + +class SettingsManager(QSettings): + """Inheritance from Isogeo Python SDK utils class. It adds some + specific tools for QGIS plugin.""" + + def __init__(self): + """Check and manage authentication credentials.""" + # instanciate + super().__init__() + + def get_locale(self): + """Return 'locale/userLocale' setting value about QGIS language configuration""" + + try: + locale = str(self.value("locale/userLocale", "fr", type=str))[0:2] + except TypeError as e: + logger.error( + "Bad type in QSettings: {}. Original error: {}".format( + type(self.value("locale/userLocale")), e + ) + ) + locale = "fr" + return locale + + def get_value(self, setting_name: str, default_value=None, type=None): + if type is None: + return self.value(setting_name, default_value) + else: + return self.value(setting_name, default_value, type) + + def set_value(self, setting_name: str, value): + self.setValue(setting_name, value) + return value + + +# ############################################################################# +# ##### Stand alone program ######## +# ################################## +if __name__ == "__main__": + """Standalone execution.""" diff --git a/modules/tools.py b/modules/tools.py index 9812c103..faa455e2 100644 --- a/modules/tools.py +++ b/modules/tools.py @@ -16,12 +16,15 @@ from qgis.utils import iface # PyQT -from qgis.PyQt.QtCore import QSettings, QUrl +from qgis.PyQt.QtCore import QUrl from qgis.PyQt.QtWidgets import QMessageBox # 3rd party from .isogeo_pysdk import IsogeoUtils +# Plugin modules +from .settings_manager import SettingsManager + # Depending on operating system if opersys == "win32": """ windows """ @@ -33,7 +36,7 @@ # ########## Globals ############### # ################################## -qsettings = QSettings() +settings_mng = SettingsManager() logger = logging.getLogger("IsogeoQgisPlugin") msgBar = iface.messageBar() @@ -110,15 +113,7 @@ def handle_date(self, input_date): :param str input_date: input date to format """ - try: - locale = str(qsettings.value("locale/userLocale", "fr", type=str))[0:2] - except TypeError as e: - logger.error( - "Bad type in QSettings: {}. Original error: {}".format( - type(qsettings.value("locale/userLocale")), e - ) - ) - locale = "fr" + locale = settings_mng.get_locale() if input_date != "NR": date = input_date.split("T")[0] @@ -316,9 +311,9 @@ def check_proxy_configuration(self, url_to_check: str) -> bool: logger.info("No proxy settings found on the system.") # retrieve QGIS proxy settings - qgis_proxy_enabled = qsettings.value("proxy/proxyEnabled", False, type=bool) + qgis_proxy_enabled = settings_mng.get_value("proxy/proxyEnabled", False, type=bool) if qgis_proxy_enabled is True: - qgis_proxy_type = qsettings.value("proxy/proxyType", "DefaultProxy", type=str) + qgis_proxy_type = settings_mng.get_value("proxy/proxyType", "DefaultProxy") logger.info("Proxy enabled in QGIS: {}".format(qgis_proxy_type)) else: logger.info("No proxy enabled in QGIS.") @@ -434,8 +429,8 @@ def check_proxy_configuration(self, url_to_check: str) -> bool: # compare system and QGIS settings qgis_proxy_params = { - "host": qsettings.value("proxy/proxyHost", None, type=str), - "port": qsettings.value("proxy/proxyPort", None, type=int), + "host": settings_mng.get_value("proxy/proxyHost", None), + "port": settings_mng.get_value("proxy/proxyPort", None), } logger.debug(qgis_proxy_params) return True @@ -446,9 +441,9 @@ def test_qgis_style(self): Avert the user and force change if the selected is not adapted. See: https://github.com/isogeo/isogeo-plugin-qgis/issues/137. """ - style_qgis = qsettings.value("qgis/style", "Default") + style_qgis = settings_mng.get_value("qgis/style", "Default") if style_qgis in ("macintosh", "cleanlooks"): - qsettings.setValue("qgis/style", "Plastique") + settings_mng.set_value("qgis/style", "Plastique") msgBar.pushMessage( self.tr( "The '{}' QGIS style is not " diff --git a/modules/user_inform.py b/modules/user_inform.py index d74f6606..28eb2732 100644 --- a/modules/user_inform.py +++ b/modules/user_inform.py @@ -2,16 +2,38 @@ #! python3 # noqa: E265 # Standard library +from pathlib import Path import logging +# PyQT +from qgis.PyQt.QtCore import QCoreApplication, Qt, QTranslator + # PyQGIS from qgis.gui import QgsMessageBar +# submodule +from .settings_manager import SettingsManager + # ############################################################################ # ########## Globals ############### # ################################## logger = logging.getLogger("IsogeoQgisPlugin") +settings_mng = SettingsManager() + + +# initialize locale +locale = settings_mng.get_locale() +plugin_dir = Path(__file__).parents[1] + +i18n_file_path = plugin_dir / "i18n" / "isogeo_search_engine_{}.qm".format(locale) + +if i18n_file_path.exists(): + translator = QTranslator() + translator.load(str(i18n_file_path)) + QCoreApplication.installTranslator(translator) +else: + pass # ############################################################################ # ########## Classes ############### @@ -21,12 +43,11 @@ class UserInformer: """A basic class to manage the displaying of message to the user.""" - def __init__(self, message_bar: object, trad: object): + def __init__(self, message_bar: object): if isinstance(message_bar, QgsMessageBar): self.bar = message_bar else: raise TypeError - self.tr = trad def display(self, message: str, duration: int = 6, level: int = 1): """A simple relay in charge of displaying messages to the user in the message @@ -50,14 +71,13 @@ def authentication_slot(self, auth_sig: str = "ok"): """ msg_dict = { "path": [ - self.tr("The specified file does not exist.", context=__class__.__name__), + self.tr("The specified file does not exist."), 5, 1, ], "file": [ self.tr( "The selected credentials file's format is not valid.", - context=__class__.__name__, ), 5, 1, @@ -65,7 +85,6 @@ def authentication_slot(self, auth_sig: str = "ok"): "ok": [ self.tr( "Authentication file is valid. Asking for authorization to Isogeo's" " API.", - context=__class__.__name__, ), 5, 0, @@ -94,39 +113,32 @@ def request_slot(self, api_sig: str): "creds_issue": self.tr( "ID and SECRET could be invalid. Provide them again." " If this error keeps happening, please report it in the bug tracker.", - context=__class__.__name__, ), "proxy_issue": self.tr( "Proxy error found. Check your OS and QGIS proxy configuration." "If this error keeps happening, please report it in the bug tracker.", - context=__class__.__name__, ), "shares_issue": self.tr( "The script is looping. Make sure you shared a catalog with the plugin " "and check your Internet connection. If this error keeps happening, " "please report it in the bug tracker.", - context=__class__.__name__, ), "unkown_error": self.tr( "Request to Isogeo's API failed : unkown error found. Please," " report it in the bug tracker.", - context=__class__.__name__, ), "unkonw_reply": self.tr( "API authentication failed : unexpected API's reply. Please," " report it in the bug tracker.", - context=__class__.__name__, ), "internet_issue": self.tr( "Request to Isogeo's API failed : please check your Internet connection" " and your proxy configuration. If this error keeps happening, please " "report it in the bug tracker.", - context=__class__.__name__, ), "config_issue": self.tr( "Search request to Isogeo's API failed : please check that 'api_base_url' and " "'api_auth_url' URLs specified into config.json file are pointing to the same API.", - context=__class__.__name__, ), } if api_sig in list(msg_dict.keys()): @@ -147,7 +159,6 @@ def shares_slot(self, shares_sig: str): "No share feeds the plugin. If you want to access resources via the " "plugin, you must share at least one catalog containing at least one " "metadata with it.", - context=__class__.__name__, ) } if shares_sig in list(msg_dict.keys()): @@ -164,9 +175,9 @@ def lim_slot(self, lim_sig: list): msg = ( "" + ( - self.tr("This data is subject to ", context=__class__.__name__) + self.tr("This data is subject to ") + str(len(lim_sig)) - + self.tr(" legal limitation(s) :", context=__class__.__name__) + + self.tr(" legal limitation(s) :") ) + "" ) @@ -176,8 +187,21 @@ def lim_slot(self, lim_sig: list): msg += lim.description else: msg += "" - msg += self.tr("No description provided", context=__class__.__name__) + msg += self.tr("No description provided") msg += "" self.display(message=msg, duration=14, level=0) else: raise TypeError + + # noinspection PyMethodMayBeStatic + def tr(self, message): + """Get the translation for a string using Qt translation API. + + We implement this ourselves since we do not inherit QObject. + :param message: String for translation. + :type message: str, QString + :returns: Translated version of message. + :rtype: QString + """ + # noinspection PyTypeChecker,PyArgumentList,PyCallByClass + return QCoreApplication.translate(__class__.__name__, message)