Skip to content

Commit

Permalink
#258 Start replacing QSettings with inheriting custom module
Browse files Browse the repository at this point in the history
  • Loading branch information
SimonSAMPERE committed Feb 19, 2024
1 parent d8e366a commit f9851ab
Show file tree
Hide file tree
Showing 11 changed files with 204 additions and 149 deletions.
48 changes: 18 additions & 30 deletions isogeo.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -52,7 +52,7 @@
# UI classes
from .ui.credits.dlg_credits import IsogeoCredits

# Plugin modules
# submodule
from .modules import (
Authenticator,
ApiRequester,
Expand All @@ -61,6 +61,7 @@
SharesParser,
SearchFormManager,
UserInformer,
SettingsManager
)

# ############################################################################
Expand All @@ -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"
Expand Down Expand Up @@ -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 = []
Expand All @@ -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()

Expand Down Expand Up @@ -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:
Expand All @@ -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)
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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")
Expand Down
1 change: 1 addition & 0 deletions modules/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@
from .quick_search import QuickSearchManager
from .search_form import SearchFormManager
from .user_inform import UserInformer
from .settings_manager import SettingsManager
80 changes: 32 additions & 48 deletions modules/api/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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"),
)
Expand All @@ -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",
),
Expand Down Expand Up @@ -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.")
Expand Down Expand Up @@ -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))
Expand All @@ -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")
Expand All @@ -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()),
)
Expand All @@ -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.")
Expand Down
2 changes: 0 additions & 2 deletions modules/layer/add_layer.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import os

# PyQT
from qgis.PyQt.QtCore import QSettings
from qgis.PyQt.QtWidgets import QMessageBox

# PyQGIS
Expand All @@ -32,7 +31,6 @@
# ########## Globals ###############
# ##################################

qsettings = QSettings()
logger = logging.getLogger("IsogeoQgisPlugin")

plg_tools = IsogeoPlgTools()
Expand Down
29 changes: 16 additions & 13 deletions modules/layer/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"""
Expand Down Expand Up @@ -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)),
Expand Down Expand Up @@ -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": "",
Expand Down Expand Up @@ -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":
Expand Down
Loading

0 comments on commit f9851ab

Please sign in to comment.