From b3d0ddb0b75da4abd59cae1508d983945c8e235d Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Fri, 19 Jul 2019 04:21:45 -0400 Subject: changed qDebug() to log::debug() removed some commented out logging --- src/loadmechanism.cpp | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) (limited to 'src/loadmechanism.cpp') diff --git a/src/loadmechanism.cpp b/src/loadmechanism.cpp index 8f0529ce..4d6cebd4 100644 --- a/src/loadmechanism.cpp +++ b/src/loadmechanism.cpp @@ -23,6 +23,7 @@ along with Mod Organizer. If not, see . #include #include #include +#include #include #include #include @@ -141,7 +142,7 @@ void LoadMechanism::deactivateScriptExtender() { vfsDLLName = ToQString(AppConfig::vfs64DLLName()); } - qDebug("USVFS DLL Name: " + vfsDLLName.toLatin1()); + log::debug("USVFS DLL Name: {}", vfsDLLName); if (vfsDLLName != "") { if (QFile(pluginsDir.absoluteFilePath(vfsDLLName)).exists()) { // remove dll from SE plugins directory @@ -215,8 +216,8 @@ void LoadMechanism::activateScriptExtender() QString targetPath = pluginsDir.absoluteFilePath(ToQString(vfsDLL)); QString vfsDLLPath = qApp->applicationDirPath() + "/" + QString::fromStdWString(vfsDLL); - qDebug("DLL USVFS Target Path: " + targetPath.toLatin1()); - qDebug("DLL USVFS VFS DLL Path: " + vfsDLLPath.toLatin1()); + log::debug("DLL USVFS Target Path: {}", targetPath); + log::debug("DLL USVFS VFS DLL Path: {}", vfsDLLPath); QFile dllFile(targetPath); @@ -297,17 +298,17 @@ void LoadMechanism::activate(EMechanism mechanism) { switch (mechanism) { case LOAD_MODORGANIZER: { - qDebug("Load Mechanism: Mod Organizer"); + log::debug("Load Mechanism: Mod Organizer"); deactivateProxyDLL(); deactivateScriptExtender(); } break; case LOAD_SCRIPTEXTENDER: { - qDebug("Load Mechanism: ScriptExtender"); + log::debug("Load Mechanism: ScriptExtender"); deactivateProxyDLL(); activateScriptExtender(); } break; case LOAD_PROXYDLL: { - qDebug("Load Mechanism: Proxy DLL"); + log::debug("Load Mechanism: Proxy DLL"); deactivateScriptExtender(); activateProxyDLL(); } break; -- cgit v1.3.1 From e4dcdb01ac2e3f99fea76b21e1acfd21d0de89c7 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sat, 20 Jul 2019 10:45:59 -0400 Subject: split workarounds tab --- src/CMakeLists.txt | 3 ++ src/loadmechanism.cpp | 6 +-- src/loadmechanism.h | 6 +-- src/settings.cpp | 73 +------------------------- src/settings.h | 20 +------ src/settingsdialog.cpp | 51 ------------------ src/settingsdialog.h | 14 +---- src/settingsdialogplugins.cpp | 9 ++++ src/settingsdialogplugins.h | 1 + src/settingsdialogworkarounds.cpp | 108 ++++++++++++++++++++++++++++++++++++++ src/settingsdialogworkarounds.h | 25 +++++++++ 11 files changed, 157 insertions(+), 159 deletions(-) create mode 100644 src/settingsdialogworkarounds.cpp create mode 100644 src/settingsdialogworkarounds.h (limited to 'src/loadmechanism.cpp') diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index a8ded510..86ef9721 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -42,6 +42,7 @@ SET(organizer_SRCS settingsdialogpaths.cpp settingsdialogplugins.cpp settingsdialogsteam.cpp + settingsdialogworkarounds.cpp settings.cpp selfupdater.cpp selectiondialog.cpp @@ -161,6 +162,7 @@ SET(organizer_HDRS settingsdialogpaths.h settingsdialogplugins.h settingsdialogsteam.h + settingsdialogworkarounds.h settings.h selfupdater.h selectiondialog.h @@ -446,6 +448,7 @@ set(settings settingsdialogpaths settingsdialogplugins settingsdialogsteam + settingsdialogworkarounds ) set(utilities diff --git a/src/loadmechanism.cpp b/src/loadmechanism.cpp index 4d6cebd4..2d01562d 100644 --- a/src/loadmechanism.cpp +++ b/src/loadmechanism.cpp @@ -63,7 +63,7 @@ void LoadMechanism::removeHintFile(QDir targetDirectory) } -bool LoadMechanism::isDirectLoadingSupported() +bool LoadMechanism::isDirectLoadingSupported() const { //FIXME: Seriously? isn't there a 'do i need steam' thing? IPluginGame const *game = qApp->property("managed_game").value(); @@ -76,7 +76,7 @@ bool LoadMechanism::isDirectLoadingSupported() } } -bool LoadMechanism::isScriptExtenderSupported() +bool LoadMechanism::isScriptExtenderSupported() const { IPluginGame const *game = qApp->property("managed_game").value(); ScriptExtender *extender = game->feature(); @@ -85,7 +85,7 @@ bool LoadMechanism::isScriptExtenderSupported() return extender != nullptr && extender->isInstalled(); } -bool LoadMechanism::isProxyDLLSupported() +bool LoadMechanism::isProxyDLLSupported() const { // using steam_api.dll as the proxy is way too game specific as many games will have different // versions of that dll. diff --git a/src/loadmechanism.h b/src/loadmechanism.h index c04473ab..51fefaf9 100644 --- a/src/loadmechanism.h +++ b/src/loadmechanism.h @@ -68,21 +68,21 @@ public: * * @return true if the load mechanism is supported **/ - bool isDirectLoadingSupported(); + bool isDirectLoadingSupported() const; /** * @brief test whether the "Script Extender" load mechanism is supported for the current game * * @return true if the load mechanism is supported **/ - bool isScriptExtenderSupported(); + bool isScriptExtenderSupported() const; /** * @brief test whether the "Proxy DLL" load mechanism is supported for the current game * * @return true if the load mechanism is supported **/ - bool isProxyDLLSupported(); + bool isProxyDLLSupported() const; private: diff --git a/src/settings.cpp b/src/settings.cpp index bc45b720..515ff907 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -27,6 +27,7 @@ along with Mod Organizer. If not, see . #include "settingsdialogpaths.h" #include "settingsdialogplugins.h" #include "settingsdialogsteam.h" +#include "settingsdialogworkarounds.h" #include "versioninfo.h" #include "appconfig.h" #include "organizercore.h" @@ -679,7 +680,7 @@ void Settings::query(PluginContainer *pluginContainer, QWidget *parent) tabs.push_back(std::unique_ptr(new NexusSettingsTab(this, dialog))); tabs.push_back(std::unique_ptr(new SteamSettingsTab(this, dialog))); tabs.push_back(std::unique_ptr(new PluginsSettingsTab(this, dialog))); - tabs.push_back(std::unique_ptr(new WorkaroundsTab(this, dialog))); + tabs.push_back(std::unique_ptr(new WorkaroundsSettingsTab(this, dialog))); QString key = QString("geometry/%1").arg(dialog.objectName()); @@ -770,73 +771,3 @@ void Settings::DiagnosticsTab::update() m_Settings.setValue("Settings/crash_dumps_type", m_dumpsTypeBox->currentIndex()); m_Settings.setValue("Settings/crash_dumps_max", m_dumpsMaxEdit->value()); } - - -Settings::WorkaroundsTab::WorkaroundsTab(Settings *m_parent, - SettingsDialog &m_dialog) - : SettingsTab(m_parent, m_dialog) - , m_appIDEdit(m_dialog.findChild("appIDEdit")) - , m_mechanismBox(m_dialog.findChild("mechanismBox")) - , m_hideUncheckedBox(m_dialog.findChild("hideUncheckedBox")) - , m_forceEnableBox(m_dialog.findChild("forceEnableBox")) - , m_displayForeignBox(m_dialog.findChild("displayForeignBox")) - , m_lockGUIBox(m_dialog.findChild("lockGUIBox")) - , m_enableArchiveParsingBox(m_dialog.findChild("enableArchiveParsingBox")) - , m_resetGeometriesBtn(m_dialog.findChild("resetGeometryBtn")) -{ - m_appIDEdit->setText(m_parent->getSteamAppID()); - - LoadMechanism::EMechanism mechanismID = m_parent->getLoadMechanism(); - int index = 0; - - if (m_parent->m_LoadMechanism.isDirectLoadingSupported()) { - m_mechanismBox->addItem(QObject::tr("Mod Organizer"), LoadMechanism::LOAD_MODORGANIZER); - if (mechanismID == LoadMechanism::LOAD_MODORGANIZER) { - index = m_mechanismBox->count() - 1; - } - } - - if (m_parent->m_LoadMechanism.isScriptExtenderSupported()) { - m_mechanismBox->addItem(QObject::tr("Script Extender"), LoadMechanism::LOAD_SCRIPTEXTENDER); - if (mechanismID == LoadMechanism::LOAD_SCRIPTEXTENDER) { - index = m_mechanismBox->count() - 1; - } - } - - if (m_parent->m_LoadMechanism.isProxyDLLSupported()) { - m_mechanismBox->addItem(QObject::tr("Proxy DLL"), LoadMechanism::LOAD_PROXYDLL); - if (mechanismID == LoadMechanism::LOAD_PROXYDLL) { - index = m_mechanismBox->count() - 1; - } - } - - m_mechanismBox->setCurrentIndex(index); - - m_hideUncheckedBox->setChecked(m_parent->hideUncheckedPlugins()); - m_forceEnableBox->setChecked(m_parent->forceEnableCoreFiles()); - m_displayForeignBox->setChecked(m_parent->displayForeign()); - m_lockGUIBox->setChecked(m_parent->lockGUI()); - m_enableArchiveParsingBox->setChecked(m_parent->archiveParsing()); - - m_resetGeometriesBtn->setChecked(m_parent->directInterface().value("reset_geometry", false).toBool()); - - m_dialog.setExecutableBlacklist(m_parent->executablesBlacklist()); - -} - -void Settings::WorkaroundsTab::update() -{ - if (m_appIDEdit->text() != m_parent->m_GamePlugin->steamAPPId()) { - m_Settings.setValue("Settings/app_id", m_appIDEdit->text()); - } else { - m_Settings.remove("Settings/app_id"); - } - m_Settings.setValue("Settings/load_mechanism", m_mechanismBox->itemData(m_mechanismBox->currentIndex()).toInt()); - m_Settings.setValue("Settings/hide_unchecked_plugins", m_hideUncheckedBox->isChecked()); - m_Settings.setValue("Settings/force_enable_core_files", m_forceEnableBox->isChecked()); - m_Settings.setValue("Settings/display_foreign", m_displayForeignBox->isChecked()); - m_Settings.setValue("Settings/lock_gui", m_lockGUIBox->isChecked()); - m_Settings.setValue("Settings/archive_parsing_experimental", m_enableArchiveParsingBox->isChecked()); - - m_Settings.setValue("Settings/executable_blacklist", m_dialog.getExecutableBlacklist()); -} diff --git a/src/settings.h b/src/settings.h index 5298103a..64068173 100644 --- a/src/settings.h +++ b/src/settings.h @@ -434,6 +434,7 @@ public: QMap m_PluginDescriptions; QSet m_PluginBlacklist; void writePluginBlacklist(); + const LoadMechanism& loadMechanism() const { return m_LoadMechanism; } public slots: @@ -466,25 +467,6 @@ private: void setLevelsBox(); }; - /** Display/store the configuration in the 'workarounds' tab of the settings dialogue */ - class WorkaroundsTab : public SettingsTab - { - public: - WorkaroundsTab(Settings *m_parent, SettingsDialog &m_dialog); - - void update(); - - private: - QLineEdit *m_appIDEdit; - QComboBox *m_mechanismBox; - QCheckBox *m_hideUncheckedBox; - QCheckBox *m_forceEnableBox; - QCheckBox *m_displayForeignBox; - QCheckBox *m_lockGUIBox; - QCheckBox *m_enableArchiveParsingBox; - QPushButton *m_resetGeometriesBtn; - }; - private slots: signals: diff --git a/src/settingsdialog.cpp b/src/settingsdialog.cpp index f43f7ae8..76b0a146 100644 --- a/src/settingsdialog.cpp +++ b/src/settingsdialog.cpp @@ -58,10 +58,6 @@ SettingsDialog::SettingsDialog(PluginContainer *pluginContainer, Settings* setti { ui->setupUi(this); ui->pluginSettingsList->setStyleSheet("QTreeWidget::item {padding-right: 10px;}"); - - QShortcut *delShortcut = new QShortcut( - QKeySequence(Qt::Key_Delete), ui->pluginBlacklist); - connect(delShortcut, SIGNAL(activated()), this, SLOT(deleteBlacklistItem())); } SettingsDialog::~SettingsDialog() @@ -111,50 +107,3 @@ bool SettingsDialog::getApiKeyChanged() { return m_keyChanged; } - -void SettingsDialog::on_execBlacklistBtn_clicked() -{ - bool ok = false; - QString result = QInputDialog::getMultiLineText( - this, - tr("Executables Blacklist"), - tr("Enter one executable per line to be blacklisted from the virtual file system.\n" - "Mods and other virtualized files will not be visible to these executables and\n" - "any executables launched by them.\n\n" - "Example:\n" - " Chrome.exe\n" - " Firefox.exe"), - m_ExecutableBlacklist.split(";").join("\n"), - &ok - ); - if (ok) { - QStringList blacklist; - for (auto exec : result.split("\n")) { - if (exec.trimmed().endsWith(".exe", Qt::CaseInsensitive)) { - blacklist << exec.trimmed(); - } - } - m_ExecutableBlacklist = blacklist.join(";"); - } -} - -void SettingsDialog::on_bsaDateBtn_clicked() -{ - IPluginGame const *game - = qApp->property("managed_game").value(); - QDir dir = game->dataDirectory(); - - Helper::backdateBSAs(qApp->applicationDirPath().toStdWString(), - dir.absolutePath().toStdWString()); -} - -void SettingsDialog::deleteBlacklistItem() -{ - ui->pluginBlacklist->takeItem(ui->pluginBlacklist->currentIndex().row()); -} - -void SettingsDialog::on_resetGeometryBtn_clicked() -{ - m_GeometriesReset = true; - ui->resetGeometryBtn->setChecked(true); -} diff --git a/src/settingsdialog.h b/src/settingsdialog.h index 319e6ed8..81c17f44 100644 --- a/src/settingsdialog.h +++ b/src/settingsdialog.h @@ -57,30 +57,20 @@ public: // temp Ui::SettingsDialog *ui; bool m_keyChanged; + bool m_GeometriesReset; PluginContainer *m_PluginContainer; public slots: virtual void accept(); public: - QString getExecutableBlacklist() { return m_ExecutableBlacklist; } - void setExecutableBlacklist(QString blacklist) { m_ExecutableBlacklist = blacklist; } - bool getResetGeometries(); bool getApiKeyChanged(); - -private slots: - void on_bsaDateBtn_clicked(); - void on_execBlacklistBtn_clicked(); - void on_resetGeometryBtn_clicked(); - - void deleteBlacklistItem(); + bool getResetGeometries(); private: Settings* m_settings; - bool m_GeometriesReset; - QString m_ExecutableBlacklist; }; #endif // SETTINGSDIALOG_H diff --git a/src/settingsdialogplugins.cpp b/src/settingsdialogplugins.cpp index 32269344..33bc1563 100644 --- a/src/settingsdialogplugins.cpp +++ b/src/settingsdialogplugins.cpp @@ -29,6 +29,10 @@ PluginsSettingsTab::PluginsSettingsTab(Settings *m_parent, SettingsDialog &m_dia QObject::connect( ui->pluginsList, &QListWidget::currentItemChanged, [&](auto* current, auto* previous) { on_pluginsList_currentItemChanged(current, previous); }); + + QShortcut *delShortcut = new QShortcut( + QKeySequence(Qt::Key_Delete), ui->pluginBlacklist); + QObject::connect(delShortcut, &QShortcut::activated, parentWidget(), [&]{ deleteBlacklistItem(); }); } void PluginsSettingsTab::update() @@ -95,6 +99,11 @@ void PluginsSettingsTab::on_pluginsList_currentItemChanged(QListWidgetItem *curr ui->pluginSettingsList->resizeColumnToContents(1); } +void PluginsSettingsTab::deleteBlacklistItem() +{ + ui->pluginBlacklist->takeItem(ui->pluginBlacklist->currentIndex().row()); +} + void PluginsSettingsTab::storeSettings(QListWidgetItem *pluginItem) { if (pluginItem != nullptr) { diff --git a/src/settingsdialogplugins.h b/src/settingsdialogplugins.h index 48d61858..9d21daa6 100644 --- a/src/settingsdialogplugins.h +++ b/src/settingsdialogplugins.h @@ -14,6 +14,7 @@ public: private: void on_pluginsList_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous); + void deleteBlacklistItem(); void storeSettings(QListWidgetItem *pluginItem); }; diff --git a/src/settingsdialogworkarounds.cpp b/src/settingsdialogworkarounds.cpp new file mode 100644 index 00000000..4cca5fd4 --- /dev/null +++ b/src/settingsdialogworkarounds.cpp @@ -0,0 +1,108 @@ +#include "settingsdialogworkarounds.h" +#include "ui_settingsdialog.h" +#include "helper.h" +#include + +WorkaroundsSettingsTab::WorkaroundsSettingsTab(Settings *m_parent, SettingsDialog &m_dialog) + : SettingsTab(m_parent, m_dialog) +{ + ui->appIDEdit->setText(m_parent->getSteamAppID()); + + LoadMechanism::EMechanism mechanismID = m_parent->getLoadMechanism(); + int index = 0; + + if (m_parent->loadMechanism().isDirectLoadingSupported()) { + ui->mechanismBox->addItem(QObject::tr("Mod Organizer"), LoadMechanism::LOAD_MODORGANIZER); + if (mechanismID == LoadMechanism::LOAD_MODORGANIZER) { + index = ui->mechanismBox->count() - 1; + } + } + + if (m_parent->loadMechanism().isScriptExtenderSupported()) { + ui->mechanismBox->addItem(QObject::tr("Script Extender"), LoadMechanism::LOAD_SCRIPTEXTENDER); + if (mechanismID == LoadMechanism::LOAD_SCRIPTEXTENDER) { + index = ui->mechanismBox->count() - 1; + } + } + + if (m_parent->loadMechanism().isProxyDLLSupported()) { + ui->mechanismBox->addItem(QObject::tr("Proxy DLL"), LoadMechanism::LOAD_PROXYDLL); + if (mechanismID == LoadMechanism::LOAD_PROXYDLL) { + index = ui->mechanismBox->count() - 1; + } + } + + ui->mechanismBox->setCurrentIndex(index); + + ui->hideUncheckedBox->setChecked(m_parent->hideUncheckedPlugins()); + ui->forceEnableBox->setChecked(m_parent->forceEnableCoreFiles()); + ui->displayForeignBox->setChecked(m_parent->displayForeign()); + ui->lockGUIBox->setChecked(m_parent->lockGUI()); + ui->enableArchiveParsingBox->setChecked(m_parent->archiveParsing()); + + ui->resetGeometryBtn->setChecked(m_parent->directInterface().value("reset_geometry", false).toBool()); + + setExecutableBlacklist(m_parent->executablesBlacklist()); + + QObject::connect(ui->bsaDateBtn, &QPushButton::clicked, [&]{ on_bsaDateBtn_clicked(); }); + QObject::connect(ui->execBlacklistBtn, &QPushButton::clicked, [&]{ on_execBlacklistBtn_clicked(); }); + QObject::connect(ui->resetGeometryBtn, &QPushButton::clicked, [&]{ on_resetGeometryBtn_clicked(); }); +} + +void WorkaroundsSettingsTab::update() +{ + if (ui->appIDEdit->text() != m_parent->gamePlugin()->steamAPPId()) { + m_Settings.setValue("Settings/app_id", ui->appIDEdit->text()); + } else { + m_Settings.remove("Settings/app_id"); + } + m_Settings.setValue("Settings/load_mechanism", ui->mechanismBox->itemData(ui->mechanismBox->currentIndex()).toInt()); + m_Settings.setValue("Settings/hide_unchecked_plugins", ui->hideUncheckedBox->isChecked()); + m_Settings.setValue("Settings/force_enable_core_files", ui->forceEnableBox->isChecked()); + m_Settings.setValue("Settings/display_foreign", ui->displayForeignBox->isChecked()); + m_Settings.setValue("Settings/lock_gui", ui->lockGUIBox->isChecked()); + m_Settings.setValue("Settings/archive_parsing_experimental", ui->enableArchiveParsingBox->isChecked()); + + m_Settings.setValue("Settings/executable_blacklist", getExecutableBlacklist()); +} + +void WorkaroundsSettingsTab::on_execBlacklistBtn_clicked() +{ + bool ok = false; + QString result = QInputDialog::getMultiLineText( + parentWidget(), + QObject::tr("Executables Blacklist"), + QObject::tr("Enter one executable per line to be blacklisted from the virtual file system.\n" + "Mods and other virtualized files will not be visible to these executables and\n" + "any executables launched by them.\n\n" + "Example:\n" + " Chrome.exe\n" + " Firefox.exe"), + m_ExecutableBlacklist.split(";").join("\n"), + &ok + ); + if (ok) { + QStringList blacklist; + for (auto exec : result.split("\n")) { + if (exec.trimmed().endsWith(".exe", Qt::CaseInsensitive)) { + blacklist << exec.trimmed(); + } + } + m_ExecutableBlacklist = blacklist.join(";"); + } +} + +void WorkaroundsSettingsTab::on_bsaDateBtn_clicked() +{ + const auto* game = qApp->property("managed_game").value(); + QDir dir = game->dataDirectory(); + + Helper::backdateBSAs(qApp->applicationDirPath().toStdWString(), + dir.absolutePath().toStdWString()); +} + +void WorkaroundsSettingsTab::on_resetGeometryBtn_clicked() +{ + m_dialog.m_GeometriesReset = true; + ui->resetGeometryBtn->setChecked(true); +} diff --git a/src/settingsdialogworkarounds.h b/src/settingsdialogworkarounds.h new file mode 100644 index 00000000..1687624b --- /dev/null +++ b/src/settingsdialogworkarounds.h @@ -0,0 +1,25 @@ +#ifndef SETTINGSDIALOGWORKAROUNDS_H +#define SETTINGSDIALOGWORKAROUNDS_H + +#include "settings.h" +#include "settingsdialog.h" + +class WorkaroundsSettingsTab : public SettingsTab +{ +public: + WorkaroundsSettingsTab(Settings *m_parent, SettingsDialog &m_dialog); + + void update(); + +private: + QString m_ExecutableBlacklist; + + void on_bsaDateBtn_clicked(); + void on_execBlacklistBtn_clicked(); + void on_resetGeometryBtn_clicked(); + + QString getExecutableBlacklist() { return m_ExecutableBlacklist; } + void setExecutableBlacklist(QString blacklist) { m_ExecutableBlacklist = blacklist; } +}; + +#endif // SETTINGSDIALOGWORKAROUNDS_H -- cgit v1.3.1 From ee43c405987d646fd15ad17cf1f1ffe2db45bc51 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sat, 20 Jul 2019 12:03:05 -0400 Subject: removed obsolete load mechanisms --- src/loadmechanism.cpp | 272 +------------------------------------- src/loadmechanism.h | 63 +-------- src/settings.cpp | 19 ++- src/settings.h | 8 +- src/settingsdialog.cpp | 2 +- src/settingsdialogworkarounds.cpp | 14 -- 6 files changed, 23 insertions(+), 355 deletions(-) (limited to 'src/loadmechanism.cpp') diff --git a/src/loadmechanism.cpp b/src/loadmechanism.cpp index 2d01562d..06e9f201 100644 --- a/src/loadmechanism.cpp +++ b/src/loadmechanism.cpp @@ -32,286 +32,20 @@ along with Mod Organizer. If not, see . #include #include - using namespace MOBase; using namespace MOShared; - LoadMechanism::LoadMechanism() : m_SelectedMechanism(LOAD_MODORGANIZER) { } -void LoadMechanism::writeHintFile(const QDir &targetDirectory) -{ - QString hintFilePath = targetDirectory.absoluteFilePath("mo_path.txt"); - QFile hintFile(hintFilePath); - if (hintFile.exists()) { - hintFile.remove(); - } - if (!hintFile.open(QIODevice::WriteOnly)) { - throw MyException(QObject::tr("failed to open %1: %2").arg(hintFilePath).arg(hintFile.errorString())); - } - hintFile.write(qApp->applicationDirPath().toUtf8().constData()); - hintFile.close(); -} - - -void LoadMechanism::removeHintFile(QDir targetDirectory) -{ - targetDirectory.remove("mo_path.txt"); -} - - bool LoadMechanism::isDirectLoadingSupported() const { - //FIXME: Seriously? isn't there a 'do i need steam' thing? - IPluginGame const *game = qApp->property("managed_game").value(); - if (game->gameName().compare("oblivion", Qt::CaseInsensitive) == 0) { - // oblivion can be loaded directly if it's not the steam variant - return !game->gameDirectory().exists("steam_api.dll"); - } else { - // all other games work afaik - return true; - } -} - -bool LoadMechanism::isScriptExtenderSupported() const -{ - IPluginGame const *game = qApp->property("managed_game").value(); - ScriptExtender *extender = game->feature(); - - // test if there even is an extender for the managed game and if so whether it's installed - return extender != nullptr && extender->isInstalled(); -} - -bool LoadMechanism::isProxyDLLSupported() const -{ - // using steam_api.dll as the proxy is way too game specific as many games will have different - // versions of that dll. - // plus: the proxy dll hasn't been working for at least the whole 1.12.x versions of MO and - // noone reported it so why maintain an unused feature? - return false; -/* IPluginGame const *game = qApp->property("managed_game").value(); - return game->gameDirectory().exists(QString::fromStdWString(AppConfig::proxyDLLTarget()));*/ -} - - -bool LoadMechanism::hashIdentical(const QString &fileNameLHS, const QString &fileNameRHS) -{ - QFile fileLHS(fileNameLHS); - if (!fileLHS.open(QIODevice::ReadOnly)) { - throw MyException(QObject::tr("file not found: %1").arg(qUtf8Printable(fileNameLHS))); - } - QByteArray dataLHS = fileLHS.readAll(); - QByteArray hashLHS = QCryptographicHash::hash(dataLHS, QCryptographicHash::Md5); - - fileLHS.close(); - - QFile fileRHS(fileNameRHS); - if (!fileRHS.open(QIODevice::ReadOnly)) { - throw MyException(QObject::tr("file not found: %1").arg(qUtf8Printable(fileNameRHS))); - } - QByteArray dataRHS = fileRHS.readAll(); - QByteArray hashRHS = QCryptographicHash::hash(dataRHS, QCryptographicHash::Md5); - - fileRHS.close(); - - return hashLHS == hashRHS; + return true; } - -void LoadMechanism::deactivateScriptExtender() +void LoadMechanism::activate(EMechanism) { - try { - IPluginGame const *game = qApp->property("managed_game").value(); - ScriptExtender *extender = game->feature(); - if (extender == nullptr) { - return; - } - - QDir pluginsDir(game->gameDirectory().absolutePath() + "/data/" + extender->PluginPath()); - -#pragma message("implement this for usvfs") - - QString vfsDLLName = ""; - if (extender->getArch() == IMAGE_FILE_MACHINE_I386) { - vfsDLLName = ToQString(AppConfig::vfs32DLLName()); - } - else if (extender->getArch() == IMAGE_FILE_MACHINE_AMD64) - { - vfsDLLName = ToQString(AppConfig::vfs64DLLName()); - } - log::debug("USVFS DLL Name: {}", vfsDLLName); - if (vfsDLLName != "") { - if (QFile(pluginsDir.absoluteFilePath(vfsDLLName)).exists()) { - // remove dll from SE plugins directory - if (!pluginsDir.remove(vfsDLLName)) { - throw MyException(QObject::tr("Failed to delete %1").arg(pluginsDir.absoluteFilePath(vfsDLLName))); - } - } - } - - removeHintFile(pluginsDir); - } catch (const std::exception &e) { - QMessageBox::critical(nullptr, QObject::tr("Failed to deactivate script extender loading"), e.what()); - } + // no-op } - - -void LoadMechanism::deactivateProxyDLL() -{ - try { - IPluginGame const *game = qApp->property("managed_game").value(); - - QString targetPath = game->gameDirectory().absoluteFilePath(QString::fromStdWString(AppConfig::proxyDLLTarget())); - - QFile targetDLL(targetPath); - if (targetDLL.exists()) { - QString origFile = game->gameDirectory().absoluteFilePath(QString::fromStdWString(AppConfig::proxyDLLOrig())); - // determine if a proxy-dll is installed - // this is a very crude way of making this decision but it should be good enough - if ((targetDLL.size() < 24576) && (QFile(origFile).exists())) { - // remove proxy-dll - if (!targetDLL.remove()) { - throw MyException(QObject::tr("Failed to remove %1: %2").arg(targetPath).arg(targetDLL.errorString())); - } else if (!QFile::rename(origFile, targetPath)) { - throw MyException(QObject::tr("Failed to rename %1 to %2").arg(origFile, targetPath)); - } - } - } - - removeHintFile(game->gameDirectory()); - } catch (const std::exception &e) { - QMessageBox::critical(nullptr, QObject::tr("Failed to deactivate proxy-dll loading"), e.what()); - } -} - - -void LoadMechanism::activateScriptExtender() -{ - try { - IPluginGame const *game = qApp->property("managed_game").value(); - ScriptExtender *extender = game->feature(); - if (extender == nullptr) { - return; - } - - QDir pluginsDir(game->gameDirectory().absolutePath() + "/data/" + extender->PluginPath()); - - if (!pluginsDir.exists()) { - pluginsDir.mkpath("."); - } - -#pragma message("implement this for usvfs") - std::wstring vfsDLL = L""; - if (extender->getArch() == IMAGE_FILE_MACHINE_I386) { - vfsDLL = AppConfig::vfs32DLLName(); - } - else if (extender->getArch() == IMAGE_FILE_MACHINE_AMD64) - { - vfsDLL = AppConfig::vfs64DLLName(); - } - if (vfsDLL != L"") { - QString targetPath = pluginsDir.absoluteFilePath(ToQString(vfsDLL)); - QString vfsDLLPath = qApp->applicationDirPath() + "/" + QString::fromStdWString(vfsDLL); - - log::debug("DLL USVFS Target Path: {}", targetPath); - log::debug("DLL USVFS VFS DLL Path: {}", vfsDLLPath); - - QFile dllFile(targetPath); - - if (dllFile.exists()) { - // may be outdated - if (!hashIdentical(targetPath, vfsDLLPath)) { - dllFile.remove(); - } - } - - if (!dllFile.exists()) { - // install dll to SE plugins - if (!QFile::copy(vfsDLLPath, targetPath)) { - throw MyException(QObject::tr("Failed to copy %1 to %2").arg(vfsDLLPath, targetPath)); - } - } - } - writeHintFile(pluginsDir); - } catch (const std::exception &e) { - QMessageBox::critical(nullptr, QObject::tr("Failed to set up script extender loading"), e.what()); - } -} - - -void LoadMechanism::activateProxyDLL() -{ - try { - IPluginGame const *game = qApp->property("managed_game").value(); - - QString targetPath = game->gameDirectory().absoluteFilePath(QString::fromStdWString(AppConfig::proxyDLLTarget())); - - QFile targetDLL(targetPath); - if (!targetDLL.exists()) { - return; - } - - QString sourcePath = qApp->applicationDirPath() + "/" + ToQString(AppConfig::proxyDLLSource()); - - // this is a very crude way of making this decision but it should be good enough - if (targetDLL.size() < 24576) { - // determine if a proxy-dll is already installed and if so, if it's the right one - if (!hashIdentical(targetPath, sourcePath)) { - // wrong proxy dll, probably outdated. delete and install the new one - if (!QFile::remove(targetPath)) { - throw MyException(QObject::tr("Failed to delete old proxy-dll %1").arg(targetPath)); - } - if (!QFile::copy(sourcePath, targetPath)) { - throw MyException(QObject::tr("Failed to copy %1 to %2").arg(sourcePath).arg(targetPath)); - } - } // otherwise the proxy-dll is already the right one - } else { - // no proxy dll installed yet. move the original and insert proxy-dll - - QString origFile = game->gameDirectory().absoluteFilePath(QString::fromStdWString(AppConfig::proxyDLLOrig())); - - if (QFile(origFile).exists()) { - // orig-file exists. this may happen if the steam-api was updated or the user messed with the - // dlls. - if (!QFile::remove(origFile)) { - throw MyException(QObject::tr("Failed to overwrite %1").arg(origFile)); - } - } - if (!QFile::rename(targetPath, origFile)) { - throw MyException(QObject::tr("Failed to rename %1 to %2").arg(targetPath).arg(origFile)); - } - if (!QFile::copy(sourcePath, targetPath)) { - throw MyException(QObject::tr("Failed to copy %1 to %2").arg(sourcePath).arg(targetPath)); - } - } - writeHintFile(game->gameDirectory()); - } catch (const std::exception &e) { - QMessageBox::critical(nullptr, QObject::tr("Failed to set up proxy-dll loading"), e.what()); - } -} - - -void LoadMechanism::activate(EMechanism mechanism) -{ - switch (mechanism) { - case LOAD_MODORGANIZER: { - log::debug("Load Mechanism: Mod Organizer"); - deactivateProxyDLL(); - deactivateScriptExtender(); - } break; - case LOAD_SCRIPTEXTENDER: { - log::debug("Load Mechanism: ScriptExtender"); - deactivateProxyDLL(); - activateScriptExtender(); - } break; - case LOAD_PROXYDLL: { - log::debug("Load Mechanism: Proxy DLL"); - deactivateScriptExtender(); - activateProxyDLL(); - } break; - } -} - diff --git a/src/loadmechanism.h b/src/loadmechanism.h index 51fefaf9..49eb0c52 100644 --- a/src/loadmechanism.h +++ b/src/loadmechanism.h @@ -27,33 +27,14 @@ along with Mod Organizer. If not, see . /** * @brief manages the various load mechanisms supported by Mod Organizer - * the load mechanisms is the means by which the mo-dll is injected into the target - * process. The default mode "mod organizer" requires the target process to be started - * from inside mod organizer. In certain cases (oblivion steam edition) this is not - * possible since the game can then only be started from steam. - * "Script Extender" is an alternative load mechanism that uses a script extender (obse, - * fose, nvse or skse) to load MO. This is reliable but prevents se plugins installed - * through MO from working. - * "Proxy DLL" replaces a dll belonging to the game by a proxy that will load MO and then - * chain-load the original dll. This currently only works with steam-versions of games and - * is intended as a last resort solution. **/ class LoadMechanism { public: - enum EMechanism { LOAD_MODORGANIZER = 0, - LOAD_SCRIPTEXTENDER, - LOAD_PROXYDLL }; -public: - - /** - * @brief constructor - * - **/ LoadMechanism(); /** @@ -66,54 +47,12 @@ public: /** * @brief test whether the "Mod Organizer" load mechanism is supported for the current game * - * @return true if the load mechanism is supported + * @return true **/ bool isDirectLoadingSupported() const; - /** - * @brief test whether the "Script Extender" load mechanism is supported for the current game - * - * @return true if the load mechanism is supported - **/ - bool isScriptExtenderSupported() const; - - /** - * @brief test whether the "Proxy DLL" load mechanism is supported for the current game - * - * @return true if the load mechanism is supported - **/ - bool isProxyDLLSupported() const; - -private: - - // write a hint file that is required for certain loading mechanisms for the dll to find - // the mod organizer installation - void writeHintFile(const QDir &targetDirectory); - - // remove the hint file if it exists. does nothing if the file doesn't exist - void removeHintFile(QDir targetDirectory); - - // compare the two files by md5-hash, returns true if they are identical - bool hashIdentical(const QString &fileNameLHS, const QString &fileNameRHS); - - // deactivate loading through script extender. does nothing if se-loading wasn't active - void deactivateScriptExtender(); - - // deactivate loading through proxy-dll. does nothing if se-loading wasn't active - void deactivateProxyDLL(); - - // activate loading through script extender. does nothing if already active. updates - // the dll if necessary - void activateScriptExtender(); - - // activate loading through proxy-dll. does nothing if already active. updates - // the dll if necessary - void activateProxyDLL(); - private: - EMechanism m_SelectedMechanism; - }; diff --git a/src/settings.cpp b/src/settings.cpp index e7a853a2..77db6918 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -429,12 +429,21 @@ void Settings::setSteamLogin(QString username, QString password) LoadMechanism::EMechanism Settings::getLoadMechanism() const { - switch (m_Settings.value("Settings/load_mechanism").toInt()) { - case LoadMechanism::LOAD_MODORGANIZER: return LoadMechanism::LOAD_MODORGANIZER; - case LoadMechanism::LOAD_SCRIPTEXTENDER: return LoadMechanism::LOAD_SCRIPTEXTENDER; - case LoadMechanism::LOAD_PROXYDLL: return LoadMechanism::LOAD_PROXYDLL; + const auto i = m_Settings.value("Settings/load_mechanism").toInt(); + + switch (i) + { + case LoadMechanism::LOAD_MODORGANIZER: + return LoadMechanism::LOAD_MODORGANIZER; + + default: + qCritical().nospace().noquote() + << "invalid load mechanism " << i << ", reverting to modorganizer"; + + m_Settings.setValue("Settings/load_mechanism", LoadMechanism::LOAD_MODORGANIZER); + + return LoadMechanism::LOAD_MODORGANIZER; } - throw std::runtime_error("invalid load mechanism"); } diff --git a/src/settings.h b/src/settings.h index b20e78d0..63718089 100644 --- a/src/settings.h +++ b/src/settings.h @@ -367,14 +367,14 @@ public: static QColor getIdealTextColor(const QColor& rBackgroundColor); - // temp - QSettings& settingsRef() { return m_Settings; } MOBase::IPluginGame const *gamePlugin() { return m_GamePlugin; } + const LoadMechanism& loadMechanism() const { return m_LoadMechanism; } + + // temp QMap m_PluginSettings; QMap m_PluginDescriptions; QSet m_PluginBlacklist; void writePluginBlacklist(); - const LoadMechanism& loadMechanism() const { return m_LoadMechanism; } public slots: void managedGameChanged(MOBase::IPluginGame const *gamePlugin); @@ -386,7 +386,7 @@ signals: private: static Settings *s_Instance; MOBase::IPluginGame const *m_GamePlugin; - QSettings m_Settings; + mutable QSettings m_Settings; LoadMechanism m_LoadMechanism; std::vector m_Plugins; diff --git a/src/settingsdialog.cpp b/src/settingsdialog.cpp index e008086a..d870c192 100644 --- a/src/settingsdialog.cpp +++ b/src/settingsdialog.cpp @@ -169,7 +169,7 @@ bool SettingsDialog::getApiKeyChanged() SettingsTab::SettingsTab(Settings *m_parent, SettingsDialog &m_dialog) : m_parent(m_parent) - , m_Settings(m_parent->settingsRef()) + , m_Settings(m_parent->directInterface()) , m_dialog(m_dialog) , ui(m_dialog.ui) { diff --git a/src/settingsdialogworkarounds.cpp b/src/settingsdialogworkarounds.cpp index 4cca5fd4..9ac46ac1 100644 --- a/src/settingsdialogworkarounds.cpp +++ b/src/settingsdialogworkarounds.cpp @@ -18,20 +18,6 @@ WorkaroundsSettingsTab::WorkaroundsSettingsTab(Settings *m_parent, SettingsDialo } } - if (m_parent->loadMechanism().isScriptExtenderSupported()) { - ui->mechanismBox->addItem(QObject::tr("Script Extender"), LoadMechanism::LOAD_SCRIPTEXTENDER); - if (mechanismID == LoadMechanism::LOAD_SCRIPTEXTENDER) { - index = ui->mechanismBox->count() - 1; - } - } - - if (m_parent->loadMechanism().isProxyDLLSupported()) { - ui->mechanismBox->addItem(QObject::tr("Proxy DLL"), LoadMechanism::LOAD_PROXYDLL); - if (mechanismID == LoadMechanism::LOAD_PROXYDLL) { - index = ui->mechanismBox->count() - 1; - } - } - ui->mechanismBox->setCurrentIndex(index); ui->hideUncheckedBox->setChecked(m_parent->hideUncheckedPlugins()); -- cgit v1.3.1 From ec3fb7b3509fb10a8a1392740e209509ae6c092c Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Mon, 2 Sep 2019 12:56:50 -0400 Subject: removed duplicate useProxy() use dedicated functions to set, get or remove settings, allows for logging --- src/loadmechanism.cpp | 13 + src/loadmechanism.h | 2 + src/mainwindow.cpp | 12 +- src/settings.cpp | 852 +++++++++++++++++++++++++++----------------- src/settings.h | 16 +- src/settingsdialognexus.cpp | 2 +- 6 files changed, 556 insertions(+), 341 deletions(-) (limited to 'src/loadmechanism.cpp') diff --git a/src/loadmechanism.cpp b/src/loadmechanism.cpp index 06e9f201..0c81b7b2 100644 --- a/src/loadmechanism.cpp +++ b/src/loadmechanism.cpp @@ -49,3 +49,16 @@ void LoadMechanism::activate(EMechanism) { // no-op } + + +QString toString(LoadMechanism::EMechanism e) +{ + switch (e) + { + case LoadMechanism::LOAD_MODORGANIZER: + return "ModOrganizer"; + + default: + return QString("unknown (%1)").arg(static_cast(e)); + } +} diff --git a/src/loadmechanism.h b/src/loadmechanism.h index 49eb0c52..151e804f 100644 --- a/src/loadmechanism.h +++ b/src/loadmechanism.h @@ -56,4 +56,6 @@ private: }; +QString toString(LoadMechanism::EMechanism e); + #endif // LOADMECHANISM_H diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 4c2594b8..42b19cb7 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -2157,10 +2157,8 @@ void MainWindow::readSettings(const Settings& settings) ui->displayCategoriesBtn->setChecked(v); } - if (auto v=settings.getUseProxy()) { - if (*v) { - activateProxy(true); - } + if (settings.getUseProxy()) { + activateProxy(true); } } @@ -5014,7 +5012,7 @@ void MainWindow::on_actionSettings_triggered() QString oldProfilesDirectory(settings.getProfileDirectory()); QString oldManagedGameDirectory(settings.getManagedGameDirectory().value_or("")); bool oldDisplayForeign(settings.displayForeign()); - bool proxy = settings.useProxy(); + bool proxy = settings.getUseProxy(); DownloadManager *dlManager = m_OrganizerCore.downloadManager(); @@ -5081,8 +5079,8 @@ void MainWindow::on_actionSettings_triggered() NexusInterface::instance(&m_PluginContainer)->setCacheDirectory(settings.getCacheDirectory()); } - if (proxy != settings.useProxy()) { - activateProxy(settings.useProxy()); + if (proxy != settings.getUseProxy()) { + activateProxy(settings.getUseProxy()); } ui->statusBar->checkSettings(m_OrganizerCore.settings()); diff --git a/src/settings.cpp b/src/settings.cpp index f6be8ba0..71288950 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -27,13 +27,164 @@ along with Mod Organizer. If not, see . using namespace MOBase; +template +struct ValueConverter +{ + static const T& convert(const T& t) + { + return t; + } +}; + +template +struct ValueConverter>> +{ + static QString convert(const T& t) + { + return QString("%1").arg(static_cast>(t)); + } +}; + + +template +void logChange( + const QString& displayName, std::optional oldValue, const T& newValue) +{ + using VC = ValueConverter; + + if (oldValue) { + log::debug( + "setting '{}' changed from '{}' to '{}'", + displayName, VC::convert(*oldValue), VC::convert(newValue)); + } else { + log::debug( + "setting '{}' set to '{}'", + displayName, VC::convert(newValue)); + } +} + +void logRemoval(const QString& name) +{ + log::debug("setting '{}' removed", name); +} + + +QString settingName(const QString& section, const QString& key) +{ + if (section.isEmpty()) { + return key; + } else if (key.isEmpty()) { + return section; + } else { + if (section.compare("General", Qt::CaseInsensitive) == 0) { + return key; + } else { + return section + "/" + key; + } + } +} + +template +void setImpl( + QSettings& settings, const QString& displayName, + const QString& section, const QString& key, const T& value) +{ + const auto current = getOptional(settings, section, key); + + if (current && *current == value) { + // no change + return; + } + + const auto name = settingName(section, key); + + logChange(displayName, current, value); + + if constexpr (std::is_enum_v) { + settings.setValue( + name, static_cast>(value)); + } else { + settings.setValue(name, value); + } +} + +void removeImpl( + QSettings& settings, const QString& displayName, + const QString& section, const QString& key) +{ + if (key.isEmpty()) { + if (!settings.childGroups().contains(section, Qt::CaseInsensitive)) { + // not there + return; + } + } else { + if (!settings.contains(settingName(section, key))) { + // not there + return; + } + } + + logRemoval(displayName); + settings.remove(settingName(section, key)); +} + + +template +std::optional getOptional( + const QSettings& settings, + const QString& section, const QString& key, std::optional def={}) +{ + if (settings.contains(settingName(section, key))) { + const auto v = settings.value(settingName(section, key)); + + if constexpr (std::is_enum_v) { + return static_cast(v.value>()); + } else { + return v.value(); + } + } + + return def; +} + +template +T get( + const QSettings& settings, + const QString& section, const QString& key, T def={}) +{ + if (auto v=getOptional(settings, section, key)) { + return *v; + } else { + return def; + } +} + +template +void set( + QSettings& settings, + const QString& section, const QString& key, const T& value) +{ + setImpl(settings, settingName(section, key), section, key, value); +} + +void remove(QSettings& settings, const QString& section, const QString& key) +{ + removeImpl(settings, settingName(section, key), section, key); +} + +void removeSection(QSettings& settings, const QString& section) +{ + removeImpl(settings, section, section, ""); +} + + class ScopedGroup { public: ScopedGroup(QSettings& s, const QString& name) - : m_settings(s) + : m_settings(s), m_name(name) { - m_settings.beginGroup(name); + m_settings.beginGroup(m_name); } ~ScopedGroup() @@ -44,18 +195,55 @@ public: ScopedGroup(const ScopedGroup&) = delete; ScopedGroup& operator=(const ScopedGroup&) = delete; + template + void set(const QString& key, const T& value) + { + setImpl(m_settings, settingName(m_name, key), "", key, value); + } + + void remove(const QString& key) + { + removeImpl(m_settings, settingName(m_name, key), "", key); + } + + QStringList keys() const + { + return m_settings.childKeys(); + } + + template + void for_each(F&& f) const + { + for (const QString& key : keys()) { + f(key); + } + } + + template + std::optional getOptional(const QString& key, std::optional def={}) const + { + return ::getOptional(m_settings, "", key, def); + } + + template + T get(const QString& key, T def={}) const + { + return ::get(m_settings, "", key, def); + } + private: QSettings& m_settings; + QString m_name; }; class ScopedReadArray { public: - ScopedReadArray(QSettings& s, const QString& name) + ScopedReadArray(QSettings& s, const QString& section) : m_settings(s), m_count(0) { - m_count = m_settings.beginReadArray(name); + m_count = m_settings.beginReadArray(section); } ~ScopedReadArray() @@ -66,11 +254,37 @@ public: ScopedReadArray(const ScopedReadArray&) = delete; ScopedReadArray& operator=(const ScopedReadArray&) = delete; + template + void for_each(F&& f) const + { + for (int i=0; i + std::optional getOptional(const QString& key, std::optional def={}) const + { + return ::getOptional(m_settings, "", key, def); + } + + template + T get(const QString& key, T def={}) const + { + return ::get(m_settings, "", key, def); + } + int count() const { return m_count; } + QStringList keys() const + { + return m_settings.childKeys(); + } + private: QSettings& m_settings; int m_count; @@ -80,10 +294,10 @@ private: class ScopedWriteArray { public: - ScopedWriteArray(QSettings& s, const QString& name) - : m_settings(s) + ScopedWriteArray(QSettings& s, const QString& section) + : m_settings(s), m_section(section), m_i(0) { - m_settings.beginWriteArray(name); + m_settings.beginWriteArray(section); } ~ScopedWriteArray() @@ -94,27 +308,28 @@ public: ScopedWriteArray(const ScopedWriteArray&) = delete; ScopedWriteArray& operator=(const ScopedWriteArray&) = delete; -private: - QSettings& m_settings; -}; - + void next() + { + m_settings.setArrayIndex(m_i); + ++m_i; + } -template -std::optional getOptional( - const QSettings& s, const QString& name, std::optional def={}) -{ - if (s.contains(name)) { - const auto v = s.value(name); + template + void set(const QString& key, const T& value) + { + const auto displayName = QString("%1/%2\\%3") + .arg(m_section) + .arg(m_i) + .arg(key); - if constexpr (std::is_enum_v) { - return static_cast(v.value>()); - } else { - return v.value(); - } + setImpl(m_settings, displayName, "", key, value); } - return def; -} +private: + QSettings& m_settings; + QString m_section; + int m_i; +}; EndorsementState endorsementStateFromString(const QString& s) @@ -132,15 +347,15 @@ QString toString(EndorsementState s) { switch (s) { - case EndorsementState::Accepted: - return "Endorsed"; + case EndorsementState::Accepted: + return "Endorsed"; - case EndorsementState::Refused: - return "Abstained"; + case EndorsementState::Refused: + return "Abstained"; - case EndorsementState::NoDecision: // fall-through - default: - return {}; + case EndorsementState::NoDecision: // fall-through + default: + return {}; } } @@ -198,24 +413,24 @@ QString widgetName(const QWidget* w) template QString geoSettingName(const Widget* widget) { - return "geometry/" + widgetName(widget) + "_geometry"; + return widgetName(widget) + "_geometry"; } template QString stateSettingName(const Widget* widget) { - return "geometry/" + widgetName(widget) + "_state"; + return widgetName(widget) + "_state"; } template QString visibilitySettingName(const Widget* widget) { - return "geometry/" + widgetName(widget) + "_visibility"; + return widgetName(widget) + "_visibility"; } QString dockSettingName(const QDockWidget* dock) { - return "geometry/MainWindow_docks_" + dock->objectName() + "_size"; + return "MainWindow_docks_" + dock->objectName() + "_size"; } QString indexSettingName(const QWidget* widget) @@ -278,40 +493,34 @@ void Settings::processUpdates( } if (lastVersion < QVersionNumber(2, 2, 0)) { - { - ScopedGroup sg(m_Settings, "Settings"); - m_Settings.remove("steam_password"); - m_Settings.remove("nexus_username"); - m_Settings.remove("nexus_password"); - m_Settings.remove("nexus_login"); - m_Settings.remove("nexus_api_key"); - m_Settings.remove("ask_for_nexuspw"); - m_Settings.remove("nmm_version"); - } + remove(m_Settings, "Settings", "steam_password"); + remove(m_Settings, "Settings", "nexus_username"); + remove(m_Settings, "Settings", "nexus_password"); + remove(m_Settings, "Settings", "nexus_login"); + remove(m_Settings, "Settings", "nexus_api_key"); + remove(m_Settings, "Settings", "ask_for_nexuspw"); + remove(m_Settings, "Settings", "nmm_version"); - { - ScopedGroup sg(m_Settings, "Servers"); - m_Settings.remove(""); - } + removeSection(m_Settings, "Servers"); } if (lastVersion < QVersionNumber(2, 2, 1)) { - m_Settings.remove("mod_info_tabs"); - m_Settings.remove("mod_info_conflict_expanders"); - m_Settings.remove("mod_info_conflicts"); - m_Settings.remove("mod_info_advanced_conflicts"); - m_Settings.remove("mod_info_conflicts_overwrite"); - m_Settings.remove("mod_info_conflicts_noconflict"); - m_Settings.remove("mod_info_conflicts_overwritten"); + remove(m_Settings, "General", "mod_info_tabs"); + remove(m_Settings, "General", "mod_info_conflict_expanders"); + remove(m_Settings, "General", "mod_info_conflicts"); + remove(m_Settings, "General", "mod_info_advanced_conflicts"); + remove(m_Settings, "General", "mod_info_conflicts_overwrite"); + remove(m_Settings, "General", "mod_info_conflicts_noconflict"); + remove(m_Settings, "General", "mod_info_conflicts_overwritten"); } if (lastVersion < QVersionNumber(2, 2, 2)) { // log splitter is gone, it's a dock now - m_Settings.remove("log_split"); + remove(m_Settings, "General", "log_split"); } //save version in all case - m_Settings.setValue("version", currentVersion.toString()); + set(m_Settings, "General", "version", currentVersion.toString()); } QString Settings::getFilename() const @@ -339,12 +548,12 @@ void Settings::registerAsNXMHandler(bool force) bool Settings::colorSeparatorScrollbar() const { - return m_Settings.value("Settings/colorSeparatorScrollbars", true).toBool(); + return get(m_Settings, "Settings", "colorSeparatorScrollbars", true); } void Settings::setColorSeparatorScrollbar(bool b) { - m_Settings.setValue("Settings/colorSeparatorScrollbars", b); + set(m_Settings, "Settings", "colorSeparatorScrollbars", b); } void Settings::managedGameChanged(IPluginGame const *gamePlugin) @@ -418,71 +627,69 @@ QColor Settings::getIdealTextColor(const QColor& rBackgroundColor) bool Settings::hideUncheckedPlugins() const { - return m_Settings.value("Settings/hide_unchecked_plugins", false).toBool(); + return get(m_Settings, "Settings", "hide_unchecked_plugins", false); } void Settings::setHideUncheckedPlugins(bool b) { - m_Settings.setValue("Settings/hide_unchecked_plugins", b); + set(m_Settings, "Settings", "hide_unchecked_plugins", b); } bool Settings::forceEnableCoreFiles() const { - return m_Settings.value("Settings/force_enable_core_files", true).toBool(); + return get(m_Settings, "Settings", "force_enable_core_files", true); } void Settings::setForceEnableCoreFiles(bool b) { - m_Settings.setValue("Settings/force_enable_core_files", b); + set(m_Settings, "Settings", "force_enable_core_files", b); } bool Settings::lockGUI() const { - return m_Settings.value("Settings/lock_gui", true).toBool(); + return get(m_Settings, "Settings", "lock_gui", true); } void Settings::setLockGUI(bool b) { - m_Settings.setValue("Settings/lock_gui", b); + set(m_Settings, "Settings", "lock_gui", b); } bool Settings::automaticLoginEnabled() const { - return m_Settings.value("Settings/nexus_login", false).toBool(); + return get(m_Settings, "Settings", "nexus_login", false); } QString Settings::getSteamAppID() const { - return m_Settings.value("Settings/app_id", m_GamePlugin->steamAPPId()).toString(); + return get(m_Settings, "Settings", "app_id", m_GamePlugin->steamAPPId()); } void Settings::setSteamAppID(const QString& id) { if (id.isEmpty()) { - m_Settings.remove("Settings/app_id"); + remove(m_Settings, "Settings", "app_id"); } else { - m_Settings.setValue("Settings/app_id", id); + set(m_Settings, "Settings", "app_id", id); } } bool Settings::usePrereleases() const { - return m_Settings.value("Settings/use_prereleases", false).toBool(); + return get(m_Settings, "Settings", "use_prereleases", false); } void Settings::setUsePrereleases(bool b) { - m_Settings.setValue("Settings/use_prereleases", b); + set(m_Settings, "Settings", "use_prereleases", b); } QString Settings::getConfigurablePath(const QString &key, - const QString &def, - bool resolve) const + const QString &def, + bool resolve) const { - const QString settingName = "Settings/" + key; - QString result = QDir::fromNativeSeparators( - m_Settings.value(settingName, QString("%BASE_DIR%/") + def).toString()); + get(m_Settings, "Settings", key, QString("%BASE_DIR%/") + def)); if (resolve) { result.replace("%BASE_DIR%", getBaseDirectory()); @@ -493,20 +700,17 @@ QString Settings::getConfigurablePath(const QString &key, void Settings::setConfigurablePath(const QString &key, const QString& path) { - const QString settingName = "Settings/" + key; - if (path.isEmpty()) { - m_Settings.remove(settingName); + remove(m_Settings, "Settings", key); } else { - m_Settings.setValue(settingName, path); + set(m_Settings, "Settings", key, path); } } QString Settings::getBaseDirectory() const { - return QDir::fromNativeSeparators(m_Settings.value( - "settings/base_directory", - qApp->property("dataPath").toString()).toString()); + return QDir::fromNativeSeparators(get(m_Settings, + "Settings", "base_directory", qApp->property("dataPath").toString())); } QString Settings::getDownloadDirectory(bool resolve) const @@ -552,9 +756,9 @@ QString Settings::getOverwriteDirectory(bool resolve) const void Settings::setBaseDirectory(const QString& path) { if (path.isEmpty()) { - m_Settings.remove("Settings/base_directory"); + remove(m_Settings, "Settings", "base_directory"); } else { - m_Settings.setValue("Settings/base_directory", path); + set(m_Settings, "Settings", "base_directory", path); } } @@ -585,7 +789,7 @@ void Settings::setOverwriteDirectory(const QString& path) std::optional Settings::getManagedGameDirectory() const { - if (auto v=getOptional(m_Settings, "gamePath")) { + if (auto v=getOptional(m_Settings, "General", "gamePath")) { return QString::fromUtf8(*v); } @@ -594,32 +798,32 @@ std::optional Settings::getManagedGameDirectory() const void Settings::setManagedGameDirectory(const QString& path) { - m_Settings.setValue("gamePath", QDir::toNativeSeparators(path).toUtf8()); + set(m_Settings, "General", "gamePath", QDir::toNativeSeparators(path).toUtf8()); } std::optional Settings::getManagedGameName() const { - return getOptional(m_Settings, "gameName"); + return getOptional(m_Settings, "General", "gameName"); } void Settings::setManagedGameName(const QString& name) { - m_Settings.setValue("gameName", name); + set(m_Settings, "General", "gameName", name); } std::optional Settings::getManagedGameEdition() const { - return getOptional(m_Settings, "game_edition"); + return getOptional(m_Settings, "General", "game_edition"); } void Settings::setManagedGameEdition(const QString& name) { - m_Settings.setValue("game_edition", name); + set(m_Settings, "General", "game_edition", name); } std::optional Settings::getSelectedProfileName() const { - if (auto v=getOptional(m_Settings, "selected_profile")) { + if (auto v=getOptional(m_Settings, "General", "selected_profile")) { return QString::fromUtf8(*v); } @@ -628,32 +832,32 @@ std::optional Settings::getSelectedProfileName() const void Settings::setSelectedProfileName(const QString& name) { - m_Settings.setValue("selected_profile", name.toUtf8()); + set(m_Settings, "General", "selected_profile", name.toUtf8()); } std::optional Settings::getStyleName() const { - return getOptional(m_Settings, "Settings/style"); + return getOptional(m_Settings, "Settings", "style"); } void Settings::setStyleName(const QString& name) { - m_Settings.setValue("Settings/style", name); + set(m_Settings, "Settings", "style", name); } -std::optional Settings::getUseProxy() const +bool Settings::getUseProxy() const { - return getOptional(m_Settings, "Settings/use_proxy"); + return get(m_Settings, "Settings", "use_proxy", false); } void Settings::setUseProxy(bool b) { - m_Settings.setValue("Settings/use_proxy", b); + set(m_Settings, "Settings", "use_proxy", b); } std::optional Settings::getVersion() const { - if (auto v=getOptional(m_Settings, "version")) { + if (auto v=getOptional(m_Settings, "General", "version")) { return QVersionNumber::fromString(*v).normalized(); } @@ -662,17 +866,17 @@ std::optional Settings::getVersion() const bool Settings::getFirstStart() const { - return getOptional(m_Settings, "first_start").value_or(true); + return get(m_Settings, "General", "first_start", true); } void Settings::setFirstStart(bool b) { - m_Settings.setValue("first_start", b); + set(m_Settings, "General", "first_start", b); } std::optional Settings::getPreviousSeparatorColor() const { - const auto c = getOptional(m_Settings, "previousSeparatorColor"); + const auto c = getOptional(m_Settings, "General", "previousSeparatorColor"); if (c && c->isValid()) { return c; } @@ -682,12 +886,12 @@ std::optional Settings::getPreviousSeparatorColor() const void Settings::setPreviousSeparatorColor(const QColor& c) const { - m_Settings.setValue("previousSeparatorColor", c); + set(m_Settings, "General", "previousSeparatorColor", c); } void Settings::removePreviousSeparatorColor() { - m_Settings.remove("previousSeparatorColor"); + remove(m_Settings, "General", "previousSeparatorColor"); } bool Settings::getNexusApiKey(QString &apiKey) const @@ -695,6 +899,7 @@ bool Settings::getNexusApiKey(QString &apiKey) const QString tempKey = deObfuscate("APIKEY"); if (tempKey.isEmpty()) return false; + apiKey = tempKey; return true; } @@ -722,7 +927,7 @@ bool Settings::hasNexusApiKey() const bool Settings::getSteamLogin(QString &username, QString &password) const { - username = m_Settings.value("Settings/steam_username", "").toString(); + username = get(m_Settings, "Settings", "steam_username", ""); password = deObfuscate("steam_password"); return !username.isEmpty() && !password.isEmpty(); @@ -730,95 +935,96 @@ bool Settings::getSteamLogin(QString &username, QString &password) const bool Settings::compactDownloads() const { - return m_Settings.value("Settings/compact_downloads", false).toBool(); + return get(m_Settings, "Settings", "compact_downloads", false); } void Settings::setCompactDownloads(bool b) { - m_Settings.setValue("Settings/compact_downloads", b); + set(m_Settings, "Settings", "compact_downloads", b); } bool Settings::metaDownloads() const { - return m_Settings.value("Settings/meta_downloads", false).toBool(); + return get(m_Settings, "Settings", "meta_downloads", false); } void Settings::setMetaDownloads(bool b) { - m_Settings.setValue("Settings/meta_downloads", b); + set(m_Settings, "Settings", "meta_downloads", b); } bool Settings::offlineMode() const { - return m_Settings.value("Settings/offline_mode", false).toBool(); + return get(m_Settings, "Settings/offline_mode", false); } void Settings::setOfflineMode(bool b) { - m_Settings.setValue("Settings/offline_mode", b); + set(m_Settings, "Settings", "offline_mode", b); } log::Levels Settings::logLevel() const { - return static_cast(m_Settings.value("Settings/log_level").toInt()); + return get(m_Settings, "Settings", "log_level", log::Levels::Info); } void Settings::setLogLevel(log::Levels level) { - m_Settings.setValue("Settings/log_level", static_cast(level)); + set(m_Settings, "Settings", "log_level", level); } CrashDumpsType Settings::crashDumpsType() const { - const auto v = getOptional(m_Settings, "Settings/crash_dumps_type"); - return v.value_or(CrashDumpsType::Mini); + return get(m_Settings, + "Settings", "crash_dumps_type", CrashDumpsType::Mini); } void Settings::setCrashDumpsType(CrashDumpsType type) { - m_Settings.setValue("Settings/crash_dumps_type", static_cast(type)); + set(m_Settings, "Settings", "crash_dumps_type", type); } int Settings::crashDumpsMax() const { - return m_Settings.value("Settings/crash_dumps_max", 5).toInt(); + return get(m_Settings, "Settings", "crash_dumps_max", 5); } void Settings::setCrashDumpsMax(int n) { - return m_Settings.setValue("Settings/crash_dumps_max", n); + set(m_Settings, "Settings", "crash_dumps_max", n); } QString Settings::executablesBlacklist() const { - return m_Settings.value("Settings/executable_blacklist", ( - QStringList() - << "Chrome.exe" - << "Firefox.exe" - << "TSVNCache.exe" - << "TGitCache.exe" - << "Steam.exe" - << "GameOverlayUI.exe" - << "Discord.exe" - << "GalaxyClient.exe" - << "Spotify.exe" - ).join(";") - ).toString(); + static const QString def = (QStringList() + << "Chrome.exe" + << "Firefox.exe" + << "TSVNCache.exe" + << "TGitCache.exe" + << "Steam.exe" + << "GameOverlayUI.exe" + << "Discord.exe" + << "GalaxyClient.exe" + << "Spotify.exe" + ).join(";"); + + return get(m_Settings, "Settings", "executable_blacklist", def); } void Settings::setExecutablesBlacklist(const QString& s) { - m_Settings.setValue("Settings/executable_blacklist", s); + set(m_Settings, "Settings", "executable_blacklist", s); } void Settings::setSteamLogin(QString username, QString password) { if (username == "") { - m_Settings.remove("Settings/steam_username"); + remove(m_Settings, "Settings", "steam_username"); password = ""; } else { - m_Settings.setValue("Settings/steam_username", username); + set(m_Settings, "Settings", "steam_username", username); } + if (!obfuscate("steam_password", password)) { const auto e = GetLastError(); log::error("Storing or deleting password failed: {}", formatSystemMessage(e)); @@ -827,26 +1033,37 @@ void Settings::setSteamLogin(QString username, QString password) LoadMechanism::EMechanism Settings::getLoadMechanism() const { - const auto i = m_Settings.value("Settings/load_mechanism").toInt(); + const auto def = LoadMechanism::LOAD_MODORGANIZER; + + const auto i = get(m_Settings, + "Settings", "load_mechanism", def); switch (i) { - case LoadMechanism::LOAD_MODORGANIZER: - return LoadMechanism::LOAD_MODORGANIZER; + // ok + case LoadMechanism::LOAD_MODORGANIZER: // fall-through + { + break; + } - default: - qCritical().nospace().noquote() - << "invalid load mechanism " << i << ", reverting to modorganizer"; + default: + { + log::error( + "invalid load mechanism {}, reverting to {}", + static_cast(i), toString(def)); - m_Settings.setValue("Settings/load_mechanism", LoadMechanism::LOAD_MODORGANIZER); + set(m_Settings, "Settings", "load_mechanism", def); - return LoadMechanism::LOAD_MODORGANIZER; + return def; } + } + + return i; } void Settings::setLoadMechanism(LoadMechanism::EMechanism m) { - m_Settings.setValue("Settings/load_mechanism", static_cast(m)); + set(m_Settings, "Settings", "load_mechanism", m); } void Settings::setupLoadMechanism() @@ -854,26 +1071,20 @@ void Settings::setupLoadMechanism() m_LoadMechanism.activate(getLoadMechanism()); } - -bool Settings::useProxy() const -{ - return m_Settings.value("Settings/use_proxy", false).toBool(); -} - bool Settings::endorsementIntegration() const { - return m_Settings.value("Settings/endorsement_integration", true).toBool(); + return get(m_Settings, "Settings", "endorsement_integration", true); } void Settings::setEndorsementIntegration(bool b) const { - m_Settings.setValue("Settings/endorsement_integration", b); + set(m_Settings, "Settings", "endorsement_integration", b); } EndorsementState Settings::endorsementState() const { - const auto v = getOptional(m_Settings, "endorse_state"); - return endorsementStateFromString(v.value_or("")); + return endorsementStateFromString( + get(m_Settings, "General", "endorse_state", "")); } void Settings::setEndorsementState(EndorsementState s) @@ -881,57 +1092,59 @@ void Settings::setEndorsementState(EndorsementState s) const auto v = toString(s); if (v.isEmpty()) { - m_Settings.remove("endorse_state"); + remove(m_Settings, "General", "endorse_state"); } else { - m_Settings.setValue("endorse_state", v); + set(m_Settings, "General", "endorse_state", v); } } bool Settings::hideAPICounter() const { - return m_Settings.value("Settings/hide_api_counter", false).toBool(); + return get(m_Settings, "Settings", "hide_api_counter", false); } void Settings::setHideAPICounter(bool b) { - m_Settings.setValue("Settings/hide_api_counter", b); + set(m_Settings, "Settings", "hide_api_counter", b); } bool Settings::displayForeign() const { - return m_Settings.value("Settings/display_foreign", true).toBool(); + return get(m_Settings, "Settings", "display_foreign", true); } void Settings::setDisplayForeign(bool b) { - m_Settings.setValue("Settings/display_foreign", b); + set(m_Settings, "Settings", "display_foreign", b); } void Settings::setMotDHash(uint hash) { - m_Settings.setValue("motd_hash", hash); + set(m_Settings, "General", "motd_hash", hash); } -uint Settings::getMotDHash() const +unsigned int Settings::getMotDHash() const { - return m_Settings.value("motd_hash", 0).toUInt(); + return get(m_Settings, "motd_hash", 0); } bool Settings::archiveParsing() const { - return m_Settings.value("Settings/archive_parsing_experimental", false).toBool(); + return get(m_Settings, "Settings", "archive_parsing_experimental", false); } void Settings::setArchiveParsing(bool b) { - m_Settings.setValue("Settings/archive_parsing_experimental", b); + set(m_Settings, "Settings", "archive_parsing_experimental", b); } QString Settings::language() { - QString result = m_Settings.value("Settings/language", "").toString(); + QString result = get(m_Settings, "Settings", "language", ""); + if (result.isEmpty()) { QStringList languagePreferences = QLocale::system().uiLanguages(); + if (languagePreferences.length() > 0) { // the users most favoritest language result = languagePreferences.at(0); @@ -940,12 +1153,13 @@ QString Settings::language() result = QLocale::system().name(); } } + return result; } void Settings::setLanguage(const QString& name) { - m_Settings.setValue("Settings/language", name); + set(m_Settings, "Settings", "language", name); } void Settings::setDownloadSpeed(const QString& name, int bytesPerSecond) @@ -972,18 +1186,13 @@ ServerList Settings::getServers() const // // so post 2.2.1, only one key is returned: "size", the size of the arrays; // in 2.2.1, one key per server is returned - - // getting the keys - QStringList keys; - { - ScopedGroup sg(m_Settings, "Servers"); - keys = m_Settings.childKeys(); - } + const QStringList keys = ScopedGroup(m_Settings, "Servers").keys(); - if (!keys.empty() && keys[0] != "size") { - // old format - return getServersFromOldMap(); + if (!keys.empty() && keys[0] != "size") { + // old format + return getServersFromOldMap(); + } } @@ -994,12 +1203,11 @@ ServerList Settings::getServers() const { ScopedReadArray sra(m_Settings, "Servers"); - for (int i=0; i("lastDownloads", ""); + for (const auto& s : lastDownloadsString.split(" ")) { const auto bytesPerSecond = s.toInt(); if (bytesPerSecond > 0) { @@ -1008,14 +1216,14 @@ ServerList Settings::getServers() const } ServerInfo server( - m_Settings.value("name").toString(), - m_Settings.value("premium").toBool(), - QDate::fromString(m_Settings.value("lastSeen").toString(), Qt::ISODate), - m_Settings.value("preferred").toInt(), + sra.get("name", ""), + sra.get("premium", false), + QDate::fromString(sra.get("lastSeen", ""), Qt::ISODate), + sra.get("preferred", 0), lastDownloads); list.add(std::move(server)); - } + }); } return list; @@ -1026,10 +1234,10 @@ ServerList Settings::getServersFromOldMap() const // for 2.2.1 and before ServerList list; - ScopedGroup sg(m_Settings, "Servers"); + const ScopedGroup sg(m_Settings, "Servers"); - for (const QString &serverKey : m_Settings.childKeys()) { - QVariantMap data = m_Settings.value(serverKey).toMap(); + sg.for_each([&](auto&& serverKey) { + QVariantMap data = sg.get(serverKey); ServerInfo server( serverKey, @@ -1042,7 +1250,7 @@ ServerList Settings::getServersFromOldMap() const // a total list.add(std::move(server)); - } + }); return list; } @@ -1052,22 +1260,18 @@ void Settings::updateServers(ServerList servers) // clean up unavailable servers servers.cleanup(); - { - ScopedGroup sg(m_Settings, "Servers"); - m_Settings.remove(""); - } + removeSection(m_Settings, "Servers"); { ScopedWriteArray swa(m_Settings, "Servers"); - int i=0; for (const auto& server : servers) { - m_Settings.setArrayIndex(i); + swa.next(); - m_Settings.setValue("name", server.name()); - m_Settings.setValue("premium", server.isPremium()); - m_Settings.setValue("lastSeen", server.lastSeen().toString(Qt::ISODate)); - m_Settings.setValue("preferred", server.preferred()); + swa.set("name", server.name()); + swa.set("premium", server.isPremium()); + swa.set("lastSeen", server.lastSeen().toString(Qt::ISODate)); + swa.set("preferred", server.preferred()); QString lastDownloads; for (const auto& speed : server.lastDownloads()) { @@ -1076,9 +1280,7 @@ void Settings::updateServers(ServerList servers) } } - m_Settings.setValue("lastDownloads", lastDownloads.trimmed()); - - ++i; + swa.set("lastDownloads", lastDownloads.trimmed()); } } } @@ -1087,35 +1289,31 @@ std::map Settings::getRecentDirectories() const { std::map map; - ScopedReadArray sra(m_Settings, "recentDirectories"); - - for (int i=0; i("name"); + const QVariant dir = sra.get("directory"); if (name.isValid() && dir.isValid()) { map.emplace(name.toString(), dir.toString()); } - } + }); return map; } void Settings::setRecentDirectories(const std::map& map) { - m_Settings.remove("recentDirectories"); + removeSection(m_Settings, "RecentDirectories"); ScopedWriteArray swa(m_Settings, "recentDirectories"); - int index = 0; for (auto&& p : map) { - m_Settings.setArrayIndex(index); - m_Settings.setValue("name", p.first); - m_Settings.setValue("directory", p.second); + swa.next(); - ++index; + swa.set("name", p.first); + swa.set("directory", p.second); } } @@ -1124,78 +1322,67 @@ std::vector> Settings::getExecutables() const ScopedReadArray sra(m_Settings, "customExecutables"); std::vector> v; - for (int i=0; i map; - const auto keys = m_Settings.childKeys(); - for (auto&& key : keys) { + for (auto&& key : sra.keys()) { map[key] = m_Settings.value(key); } v.push_back(map); - } + }); return v; } void Settings::setExecutables(const std::vector>& v) { - m_Settings.remove("customExecutables"); + removeSection(m_Settings, "customExecutables"); ScopedWriteArray swa(m_Settings, "customExecutables"); - int i = 0; - for (const auto& map : v) { - m_Settings.setArrayIndex(i); + swa.next(); for (auto&& p : map) { - m_Settings.setValue(p.first, p.second); + swa.set(p.first, p.second); } - - ++i; } } bool Settings::isTutorialCompleted(const QString& windowName) const { - const auto v = getOptional( - m_Settings, "CompletedWindowTutorials/" + windowName); - - return v.value_or(false); + return get(m_Settings, "CompletedWindowTutorials", windowName, false); } void Settings::setTutorialCompleted(const QString& windowName, bool b) { - m_Settings.setValue("CompletedWindowTutorials/" + windowName, true); + set(m_Settings, "CompletedWindowTutorials", windowName, b); } bool Settings::keepBackupOnInstall() const { - return getOptional(m_Settings, "backup_install").value_or(false); + return get(m_Settings, "backup_install", false); } void Settings::setKeepBackupOnInstall(bool b) { - m_Settings.setValue("backup_install", b); + set(m_Settings, "General", "backup_install", b); } QuestionBoxMemory::Button Settings::getQuestionButton( const QString& windowName, const QString& filename) const { - const QString windowSetting("DialogChoices/" + windowName); + const QString sectionName("DialogChoices"); if (!filename.isEmpty()) { - const auto fileSetting = windowSetting + "/" + filename; - - if (auto v=getOptional(m_Settings, fileSetting)) { + const auto fileSetting = windowName + "/" + filename; + if (auto v=getOptional(m_Settings, sectionName, filename)) { return static_cast(*v); } } - if (auto v=getOptional(m_Settings, windowSetting)) { + if (auto v=getOptional(m_Settings, sectionName, windowName)) { return static_cast(*v); } @@ -1205,12 +1392,12 @@ QuestionBoxMemory::Button Settings::getQuestionButton( void Settings::setQuestionWindowButton( const QString& windowName, QuestionBoxMemory::Button button) { - const QString settingName("DialogChoices/" + windowName); + const QString sectionName("DialogChoices/"); if (button == QuestionBoxMemory::NoButton) { - m_Settings.remove(settingName); + remove(m_Settings, sectionName, windowName); } else { - m_Settings.setValue(settingName, static_cast(button)); + set(m_Settings, sectionName, windowName, button); } } @@ -1218,51 +1405,51 @@ void Settings::setQuestionFileButton( const QString& windowName, const QString& filename, QuestionBoxMemory::Button button) { - const QString settingName("DialogChoices/" + windowName + "/" + filename); + const QString sectionName("DialogChoices"); + const QString settingName(windowName + "/" + filename); if (button == QuestionBoxMemory::NoButton) { - m_Settings.remove(settingName); + remove(m_Settings, sectionName, settingName); } else { - m_Settings.setValue(settingName, static_cast(button)); + set(m_Settings, sectionName, settingName, button); } } void Settings::resetQuestionButtons() { - ScopedGroup sg(m_Settings, "DialogChoices"); - m_Settings.remove(""); + removeSection(m_Settings, "DialogChoices"); } std::optional Settings::getIndex(const QComboBox* cb) const { - return getOptional(m_Settings, indexSettingName(cb)); + return getOptional(m_Settings, "Widgets", indexSettingName(cb)); } void Settings::saveIndex(const QComboBox* cb) { - m_Settings.setValue(indexSettingName(cb), cb->currentIndex()); + set(m_Settings, "Widgets", indexSettingName(cb), cb->currentIndex()); } void Settings::restoreIndex(QComboBox* cb, std::optional def) const { - if (auto v=getOptional(m_Settings, indexSettingName(cb), def)) { + if (auto v=getOptional(m_Settings, "Widgets", indexSettingName(cb), def)) { cb->setCurrentIndex(*v); } } std::optional Settings::getIndex(const QTabWidget* w) const { - return getOptional(m_Settings, indexSettingName(w)); + return getOptional(m_Settings, "Widgets", indexSettingName(w)); } void Settings::saveIndex(const QTabWidget* w) { - m_Settings.setValue(indexSettingName(w), w->currentIndex()); + set(m_Settings, "Widgets", indexSettingName(w), w->currentIndex()); } void Settings::restoreIndex(QTabWidget* w, std::optional def) const { - if (auto v=getOptional(m_Settings, indexSettingName(w), def)) { + if (auto v=getOptional(m_Settings, "Widgets", indexSettingName(w), def)) { w->setCurrentIndex(*v); } } @@ -1270,20 +1457,20 @@ void Settings::restoreIndex(QTabWidget* w, std::optional def) const std::optional Settings::getChecked(const QAbstractButton* w) const { warnIfNotCheckable(w); - return getOptional(m_Settings, checkedSettingName(w)); + return getOptional(m_Settings, "Widgets", checkedSettingName(w)); } void Settings::saveChecked(const QAbstractButton* w) { warnIfNotCheckable(w); - m_Settings.setValue(checkedSettingName(w), w->isChecked()); + set(m_Settings, "Widgets", checkedSettingName(w), w->isChecked()); } void Settings::restoreChecked(QAbstractButton* w, std::optional def) const { warnIfNotCheckable(w); - if (auto v=getOptional(m_Settings, checkedSettingName(w), def)) { + if (auto v=getOptional(m_Settings, "Widgets", checkedSettingName(w), def)) { w->setChecked(*v); } } @@ -1328,7 +1515,7 @@ void Settings::dump() const { static const QStringList ignore({ "username", "password", "nexus_api_key" - }); + }); log::debug("settings:"); @@ -1379,18 +1566,17 @@ void GeometrySettings::resetIfNeeded() return; } - ScopedGroup sg(m_Settings, "geometry"); - m_Settings.remove(""); + removeSection(m_Settings, "Geometry"); } void GeometrySettings::saveGeometry(const QWidget* w) { - m_Settings.setValue(geoSettingName(w), w->saveGeometry()); + set(m_Settings, "Geometry", geoSettingName(w), w->saveGeometry()); } bool GeometrySettings::restoreGeometry(QWidget* w) const { - if (auto v=getOptional(m_Settings, geoSettingName(w))) { + if (auto v=getOptional(m_Settings, "Geometry", geoSettingName(w))) { w->restoreGeometry(*v); return true; } @@ -1400,12 +1586,12 @@ bool GeometrySettings::restoreGeometry(QWidget* w) const void GeometrySettings::saveState(const QMainWindow* w) { - m_Settings.setValue(stateSettingName(w), w->saveState()); + set(m_Settings, "Geometry", stateSettingName(w), w->saveState()); } bool GeometrySettings::restoreState(QMainWindow* w) const { - if (auto v=getOptional(m_Settings, stateSettingName(w))) { + if (auto v=getOptional(m_Settings, "Geometry", stateSettingName(w))) { w->restoreState(*v); return true; } @@ -1415,12 +1601,12 @@ bool GeometrySettings::restoreState(QMainWindow* w) const void GeometrySettings::saveState(const QHeaderView* w) { - m_Settings.setValue(stateSettingName(w), w->saveState()); + set(m_Settings, "Geometry", stateSettingName(w), w->saveState()); } bool GeometrySettings::restoreState(QHeaderView* w) const { - if (auto v=getOptional(m_Settings, stateSettingName(w))) { + if (auto v=getOptional(m_Settings, "Geometry", stateSettingName(w))) { w->restoreState(*v); return true; } @@ -1430,12 +1616,12 @@ bool GeometrySettings::restoreState(QHeaderView* w) const void GeometrySettings::saveState(const QSplitter* w) { - m_Settings.setValue(stateSettingName(w), w->saveState()); + set(m_Settings, "Geometry", stateSettingName(w), w->saveState()); } bool GeometrySettings::restoreState(QSplitter* w) const { - if (auto v=getOptional(m_Settings, stateSettingName(w))) { + if (auto v=getOptional(m_Settings, "Geometry", stateSettingName(w))) { w->restoreState(*v); return true; } @@ -1445,12 +1631,12 @@ bool GeometrySettings::restoreState(QSplitter* w) const void GeometrySettings::saveState(const ExpanderWidget* expander) { - m_Settings.setValue(stateSettingName(expander), expander->saveState()); + set(m_Settings, "Geometry", stateSettingName(expander), expander->saveState()); } bool GeometrySettings::restoreState(ExpanderWidget* expander) const { - if (auto v=getOptional(m_Settings, stateSettingName(expander))) { + if (auto v=getOptional(m_Settings, "Geometry", stateSettingName(expander))) { expander->restoreState(*v); return true; } @@ -1460,12 +1646,12 @@ bool GeometrySettings::restoreState(ExpanderWidget* expander) const void GeometrySettings::saveVisibility(const QWidget* w) { - m_Settings.setValue(visibilitySettingName(w), w->isVisible()); + set(m_Settings, "Geometry", visibilitySettingName(w), w->isVisible()); } bool GeometrySettings::restoreVisibility(QWidget* w, std::optional def) const { - if (auto v=getOptional(m_Settings, visibilitySettingName(w), def)) { + if (auto v=getOptional(m_Settings, "Geometry", visibilitySettingName(w), def)) { w->setVisible(*v); return true; } @@ -1476,8 +1662,8 @@ bool GeometrySettings::restoreVisibility(QWidget* w, std::optional def) co void GeometrySettings::restoreToolbars(QMainWindow* w) const { // all toolbars have the same size and button style settings - const auto size = getOptional(m_Settings, "toolbar_size"); - const auto style = getOptional(m_Settings, "toolbar_button_style"); + const auto size = getOptional(m_Settings, "Geometry", "toolbar_size"); + const auto style = getOptional(m_Settings, "Geometry", "toolbar_button_style"); for (auto* tb : w->findChildren()) { if (size) { @@ -1506,8 +1692,8 @@ void GeometrySettings::saveToolbars(const QMainWindow* w) if (!tbs.isEmpty()) { const auto* tb = tbs[0]; - m_Settings.setValue("toolbar_size", tb->iconSize()); - m_Settings.setValue("toolbar_button_style", static_cast(tb->toolButtonStyle())); + set(m_Settings, "Geometry", "toolbar_size", tb->iconSize()); + set(m_Settings, "Geometry", "toolbar_button_style", static_cast(tb->toolButtonStyle())); } } @@ -1544,12 +1730,13 @@ QStringList GeometrySettings::getModInfoTabOrder() const void GeometrySettings::setModInfoTabOrder(const QString& names) { - m_Settings.setValue("mod_info_tab_order", names); + set(m_Settings, "Geometry", "mod_info_tab_order", names); } void GeometrySettings::centerOnMainWindowMonitor(QWidget* w) { - const auto monitor = getOptional(m_Settings, "geometry/MainWindow_monitor"); + const auto monitor = getOptional( + m_Settings, "Geometry", "MainWindow_monitor"); QPoint center; @@ -1567,7 +1754,7 @@ void GeometrySettings::saveMainWindowMonitor(const QMainWindow* w) if (auto* handle=w->windowHandle()) { if (auto* screen = handle->screen()) { const int screenId = QGuiApplication::screens().indexOf(screen); - m_Settings.setValue("geometry/MainWindow_monitor", screenId); + set(m_Settings, "Geometry", "MainWindow_monitor", screenId); } } } @@ -1617,7 +1804,7 @@ void GeometrySettings::saveDocks(const QMainWindow* mw) size = dock->size().height(); } - m_Settings.setValue(dockSettingName(dock), size); + set(m_Settings, "Geometry", dockSettingName(dock), size); } } @@ -1634,7 +1821,7 @@ void GeometrySettings::restoreDocks(QMainWindow* mw) const // for each dock for (auto* dock : mw->findChildren()) { - if (auto size=getOptional(m_Settings, dockSettingName(dock))) { + if (auto size=getOptional(m_Settings, "Geometry", dockSettingName(dock))) { // remember this dock, its size and orientation dockInfos.push_back({dock, *size, dockOrientation(mw, dock)}); } @@ -1649,7 +1836,7 @@ void GeometrySettings::restoreDocks(QMainWindow* mw) const for (const auto& info : dockInfos) { mw->resizeDocks({info.d}, {info.size}, info.ori); } - }); + }); } @@ -1660,68 +1847,74 @@ ColorSettings::ColorSettings(QSettings& s) QColor ColorSettings::modlistOverwrittenLoose() const { - return getOptional(m_Settings, "Settings/overwrittenLooseFilesColor") - .value_or(QColor(0, 255, 0, 64)); + return get( + m_Settings, "Settings", "overwrittenLooseFilesColor", + QColor(0, 255, 0, 64)); } void ColorSettings::setModlistOverwrittenLoose(const QColor& c) { - m_Settings.setValue("Settings/overwrittenLooseFilesColor", c); + set(m_Settings, "Settings", "overwrittenLooseFilesColor", c); } QColor ColorSettings::modlistOverwritingLoose() const { - return getOptional(m_Settings, "Settings/overwritingLooseFilesColor") - .value_or(QColor(255, 0, 0, 64)); + return get( + m_Settings, "Settings", "overwritingLooseFilesColor", + QColor(255, 0, 0, 64)); } void ColorSettings::setModlistOverwritingLoose(const QColor& c) { - m_Settings.setValue("Settings/overwritingLooseFilesColor", c); + set(m_Settings, "Settings", "overwritingLooseFilesColor", c); } QColor ColorSettings::modlistOverwrittenArchive() const { - return getOptional(m_Settings, "Settings/overwrittenArchiveFilesColor") - .value_or(QColor(0, 255, 255, 64)); + return get( + m_Settings, "Settings", "overwrittenArchiveFilesColor", + QColor(0, 255, 255, 64)); } void ColorSettings::setModlistOverwrittenArchive(const QColor& c) { - m_Settings.setValue("Settings/overwrittenArchiveFilesColor", c); + set(m_Settings, "Settings", "overwrittenArchiveFilesColor", c); } QColor ColorSettings::modlistOverwritingArchive() const { - return getOptional(m_Settings, "Settings/overwritingArchiveFilesColor") - .value_or(QColor(255, 0, 255, 64)); + return get( + m_Settings, "Settings", "overwritingArchiveFilesColor", + QColor(255, 0, 255, 64)); } void ColorSettings::setModlistOverwritingArchive(const QColor& c) { - m_Settings.setValue("Settings/overwritingArchiveFilesColor", c); + set(m_Settings, "Settings", "overwritingArchiveFilesColor", c); } QColor ColorSettings::modlistContainsPlugin() const { - return getOptional(m_Settings, "Settings/containsPluginColor") - .value_or(QColor(0, 0, 255, 64)); + return get( + m_Settings, "Settings", "containsPluginColor", + QColor(0, 0, 255, 64)); } void ColorSettings::setModlistContainsPlugin(const QColor& c) { - m_Settings.setValue("Settings/containsPluginColor", c); + set(m_Settings, "Settings", "containsPluginColor", c); } QColor ColorSettings::pluginListContained() const { - return getOptional(m_Settings, "Settings/containedColor") - .value_or(QColor(0, 0, 255, 64)); + return get( + m_Settings, "Settings", "containedColor", + QColor(0, 0, 255, 64)); } void ColorSettings::setPluginListContained(const QColor& c) { - m_Settings.setValue("Settings/containedColor", c); + set(m_Settings, "Settings", "containedColor", c); } @@ -1738,10 +1931,9 @@ void PluginSettings::clearPlugins() m_PluginBlacklist.clear(); ScopedReadArray sra(m_Settings, "pluginBlacklist"); - for (int i = 0; i < sra.count(); ++i) { - m_Settings.setArrayIndex(i); - m_PluginBlacklist.insert(m_Settings.value("name").toString()); - } + sra.for_each([&]{ + m_PluginBlacklist.insert(sra.get("name")); + }); } void PluginSettings::registerPlugin(IPlugin *plugin) @@ -1749,16 +1941,26 @@ void PluginSettings::registerPlugin(IPlugin *plugin) m_Plugins.push_back(plugin); m_PluginSettings.insert(plugin->name(), QVariantMap()); m_PluginDescriptions.insert(plugin->name(), QVariantMap()); + for (const PluginSetting &setting : plugin->settings()) { - QVariant temp = m_Settings.value("Plugins/" + plugin->name() + "/" + setting.key, setting.defaultValue); + const QString settingName = plugin->name() + "/" + setting.key; + + QVariant temp = get( + m_Settings, "Plugins", settingName, setting.defaultValue); + if (!temp.convert(setting.defaultValue.type())) { log::warn( "failed to interpret \"{}\" as correct type for \"{}\" in plugin \"{}\", using default", temp.toString(), setting.key, plugin->name()); + temp = setting.defaultValue; } + m_PluginSettings[plugin->name()][setting.key] = temp; - m_PluginDescriptions[plugin->name()][setting.key] = QString("%1 (default: %2)").arg(setting.description).arg(setting.defaultValue.toString()); + + m_PluginDescriptions[plugin->name()][setting.key] = QString("%1 (default: %2)") + .arg(setting.description) + .arg(setting.defaultValue.toString()); } } @@ -1773,6 +1975,7 @@ QVariant PluginSettings::pluginSetting(const QString &pluginName, const QString if (iterPlugin == m_PluginSettings.end()) { return QVariant(); } + auto iterSetting = iterPlugin->find(key); if (iterSetting == iterPlugin->end()) { return QVariant(); @@ -1784,13 +1987,16 @@ QVariant PluginSettings::pluginSetting(const QString &pluginName, const QString void PluginSettings::setPluginSetting(const QString &pluginName, const QString &key, const QVariant &value) { auto iterPlugin = m_PluginSettings.find(pluginName); + if (iterPlugin == m_PluginSettings.end()) { - throw MyException(QObject::tr("attempt to store setting for unknown plugin \"%1\"").arg(pluginName)); + throw MyException( + QObject::tr("attempt to store setting for unknown plugin \"%1\"") + .arg(pluginName)); } // store the new setting both in memory and in the ini m_PluginSettings[pluginName][key] = value; - m_Settings.setValue("Plugins/" + pluginName + "/" + key, value); + set(m_Settings, "Plugins", pluginName + "/" + key, value); } QVariant PluginSettings::pluginPersistent(const QString &pluginName, const QString &key, const QVariant &def) const @@ -1798,15 +2004,21 @@ QVariant PluginSettings::pluginPersistent(const QString &pluginName, const QStri if (!m_PluginSettings.contains(pluginName)) { return def; } - return m_Settings.value("PluginPersistance/" + pluginName + "/" + key, def); + + return get(m_Settings, "PluginPersistance", pluginName + "/" + key, def); } -void PluginSettings::setPluginPersistent(const QString &pluginName, const QString &key, const QVariant &value, bool sync) +void PluginSettings::setPluginPersistent( + const QString &pluginName, const QString &key, const QVariant &value, bool sync) { if (!m_PluginSettings.contains(pluginName)) { - throw MyException(QObject::tr("attempt to store setting for unknown plugin \"%1\"").arg(pluginName)); + throw MyException( + QObject::tr("attempt to store setting for unknown plugin \"%1\"") + .arg(pluginName)); } - m_Settings.setValue("PluginPersistance/" + pluginName + "/" + key, value); + + set(m_Settings, "PluginPersistance", pluginName + "/" + key, value); + if (sync) { m_Settings.sync(); } @@ -1820,13 +2032,13 @@ void PluginSettings::addBlacklistPlugin(const QString &fileName) void PluginSettings::writePluginBlacklist() { - m_Settings.remove("pluginBlacklist"); + removeSection(m_Settings, "PluginBlacklist"); + + ScopedWriteArray swa(m_Settings, "PluginBlacklist"); - ScopedWriteArray swa(m_Settings, "pluginBlacklist"); - int idx = 0; for (const QString &plugin : m_PluginBlacklist) { - m_Settings.setArrayIndex(idx++); - m_Settings.setValue("name", plugin); + swa.next(); + swa.set("name", plugin); } } @@ -1868,8 +2080,8 @@ void PluginSettings::save() { for (auto iterPlugins=m_PluginSettings.begin(); iterPlugins!=m_PluginSettings.end(); ++iterPlugins) { for (auto iterSettings=iterPlugins->begin(); iterSettings!=iterPlugins->end(); ++iterSettings) { - const auto key = "Plugins/" + iterPlugins.key() + "/" + iterSettings.key(); - m_Settings.setValue(key, iterSettings.value()); + const auto key = iterPlugins.key() + "/" + iterSettings.key(); + set(m_Settings, "Plugins", key, iterSettings.value()); } } diff --git a/src/settings.h b/src/settings.h index ae29d788..403c2d71 100644 --- a/src/settings.h +++ b/src/settings.h @@ -68,9 +68,6 @@ public: void saveState(const QHeaderView* header); bool restoreState(QHeaderView* header) const; - void saveState(const QToolBar* toolbar); - bool restoreState(QToolBar* toolbar) const; - void saveState(const QSplitter* splitter); bool restoreState(QSplitter* splitter) const; @@ -258,8 +255,6 @@ public: std::optional getStyleName() const; void setStyleName(const QString& name); - std::optional getUseProxy() const; - std::optional getVersion() const; bool getFirstStart() const; @@ -408,7 +403,7 @@ public: /** * @return true if the user configured the use of a network proxy */ - bool useProxy() const; + bool getUseProxy() const; void setUseProxy(bool b); /** @@ -419,7 +414,6 @@ public: EndorsementState endorsementState() const; void setEndorsementState(EndorsementState s); - void setEndorsementState(const QString& s); /** * @return true if the API counter should be hidden @@ -436,7 +430,8 @@ public: /** * @brief sets the new motd hash **/ - void setMotDHash(uint hash); + unsigned int getMotDHash() const; + void setMotDHash(unsigned int hash); /** * @return true if the user wants to have archives being parsed to show conflicts and contents @@ -444,11 +439,6 @@ public: bool archiveParsing() const; void setArchiveParsing(bool b); - /** - * @return hash of the last displayed message of the day - **/ - uint getMotDHash() const; - /** * @return short code of the configured language (corresponding to the translation files) */ diff --git a/src/settingsdialognexus.cpp b/src/settingsdialognexus.cpp index 3de1a6ba..8822200e 100644 --- a/src/settingsdialognexus.cpp +++ b/src/settingsdialognexus.cpp @@ -75,7 +75,7 @@ NexusSettingsTab::NexusSettingsTab(Settings& s, SettingsDialog& d) : SettingsTab(s, d) { ui->offlineBox->setChecked(settings().offlineMode()); - ui->proxyBox->setChecked(settings().useProxy()); + ui->proxyBox->setChecked(settings().getUseProxy()); ui->endorsementBox->setChecked(settings().endorsementIntegration()); ui->hideAPICounterBox->setChecked(settings().hideAPICounter()); -- cgit v1.3.1