From bca6283311cf1dea4c96f8ee5bf192bdb1640cb3 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Wed, 17 Jul 2019 08:56:16 -0400 Subject: use log::Levels instead of ints create log level combobox in code, set selected index based on value instead added log level to context menu in log list --- src/settings.cpp | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/settings.cpp b/src/settings.cpp index 5cb2524f..e622d632 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -415,9 +415,14 @@ bool Settings::offlineMode() const return m_Settings.value("Settings/offline_mode", false).toBool(); } -int Settings::logLevel() const +log::Levels Settings::logLevel() const { - return m_Settings.value("Settings/log_level", static_cast(LogLevel::Info)).toInt(); + return static_cast(m_Settings.value("Settings/log_level").toInt()); +} + +void Settings::setLogLevel(log::Levels level) +{ + m_Settings.setValue("Settings/log_level", static_cast(level)); } int Settings::crashDumpsType() const @@ -1000,7 +1005,7 @@ Settings::DiagnosticsTab::DiagnosticsTab(Settings *m_parent, SettingsDialog &m_d , m_dumpsMaxEdit(m_dialog.findChild("dumpsMaxEdit")) , m_diagnosticsExplainedLabel(m_dialog.findChild("diagnosticsExplainedLabel")) { - m_logLevelBox->setCurrentIndex(m_parent->logLevel()); + setLevelsBox(); m_dumpsTypeBox->setCurrentIndex(m_parent->crashDumpsType()); m_dumpsMaxEdit->setValue(m_parent->crashDumpsMax()); QString logsPath = qApp->property("dataPath").toString() @@ -1016,11 +1021,28 @@ Settings::DiagnosticsTab::DiagnosticsTab(Settings *m_parent, SettingsDialog &m_d void Settings::DiagnosticsTab::update() { - m_Settings.setValue("Settings/log_level", m_logLevelBox->currentIndex()); + m_Settings.setValue("Settings/log_level", m_logLevelBox->currentData().toInt()); m_Settings.setValue("Settings/crash_dumps_type", m_dumpsTypeBox->currentIndex()); m_Settings.setValue("Settings/crash_dumps_max", m_dumpsMaxEdit->value()); } +void Settings::DiagnosticsTab::setLevelsBox() +{ + m_logLevelBox->clear(); + + m_logLevelBox->addItem(tr("Debug"), log::Debug); + m_logLevelBox->addItem(tr("Info (recommended)"), log::Info); + m_logLevelBox->addItem(tr("Warning"), log::Warning); + m_logLevelBox->addItem(tr("Error"), log::Error); + + for (int i=0; icount(); ++i) { + if (m_logLevelBox->itemData(i) == m_parent->logLevel()) { + m_logLevelBox->setCurrentIndex(i); + break; + } + } +} + Settings::NexusTab::NexusTab(Settings *parent, SettingsDialog &dialog) : Settings::SettingsTab(parent, dialog) , m_offlineBox(dialog.findChild("offlineBox")) -- cgit v1.3.1 From aae6d6a5aa8d6b101fcc38388222a8a6e7ee2ec6 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Fri, 19 Jul 2019 01:09:19 -0400 Subject: replaced qWarning() --- src/bbcode.cpp | 9 ++++---- src/categories.cpp | 3 ++- src/directoryrefresher.cpp | 4 ++-- src/downloadmanager.cpp | 21 +++++++++--------- src/editexecutablesdialog.cpp | 19 ++++++++-------- src/executableslist.cpp | 6 +++--- src/filerenamer.cpp | 7 ++++-- src/icondelegate.cpp | 4 +++- src/installationmanager.cpp | 2 +- src/instancemanager.cpp | 14 +++++++----- src/mainwindow.cpp | 50 +++++++++++++++++++++++-------------------- src/moapplication.cpp | 5 +++-- src/modflagicondelegate.cpp | 4 +++- src/modinfo.cpp | 2 +- src/modinfodialogesps.cpp | 7 +++--- src/modlist.cpp | 7 +++--- src/modlistsortproxy.cpp | 6 ++++-- src/nexusinterface.cpp | 27 +++++++++++++---------- src/nxmaccessmanager.cpp | 2 +- src/organizercore.cpp | 46 +++++++++++++++++++-------------------- src/plugincontainer.cpp | 11 +++++----- src/pluginlist.cpp | 4 ++-- src/problemsdialog.cpp | 2 +- src/profile.cpp | 21 ++++++++++-------- src/profilesdialog.cpp | 4 ++-- src/settings.cpp | 5 +++-- 26 files changed, 161 insertions(+), 131 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/bbcode.cpp b/src/bbcode.cpp index 323dd128..d9b7debd 100644 --- a/src/bbcode.cpp +++ b/src/bbcode.cpp @@ -18,13 +18,13 @@ along with Mod Organizer. If not, see . */ #include "bbcode.h" - +#include #include #include - namespace BBCode { +namespace log = MOBase::log; class BBCodeMap { @@ -88,7 +88,7 @@ public: return temp.replace(tagIter->second.first, QString("%2").arg(color, content)); } } else { - qWarning("don't know how to deal with tag %s", qUtf8Printable(tagName)); + log::warn("don't know how to deal with tag {}", tagName); } } else { if (tagName == "*") { @@ -99,8 +99,7 @@ public: } else { // expression doesn't match. either the input string is invalid // or the expression is - qWarning("%s doesn't match the expression for %s", - qUtf8Printable(temp), qUtf8Printable(tagName)); + log::warn("{} doesn't match the expression for {}", temp, tagName); length = 0; return QString(); } diff --git a/src/categories.cpp b/src/categories.cpp index 9e5fa9f7..8f9d3ad8 100644 --- a/src/categories.cpp +++ b/src/categories.cpp @@ -21,6 +21,7 @@ along with Mod Organizer. If not, see . #include #include +#include #include #include @@ -294,7 +295,7 @@ bool CategoryFactory::isDecendantOf(int id, int parentID) const return isDecendantOf(m_Categories[index].m_ParentID, parentID); } } else { - qWarning("%d is no valid category id", id); + log::warn("{} is no valid category id", id); return false; } } diff --git a/src/directoryrefresher.cpp b/src/directoryrefresher.cpp index 3ce4691b..87305599 100644 --- a/src/directoryrefresher.cpp +++ b/src/directoryrefresher.cpp @@ -127,7 +127,7 @@ void DirectoryRefresher::addModFilesToStructure(DirectoryEntry *directoryStructu FilesOrigin &origin = directoryStructure->createOrigin(ToWString(modName), directoryW, priority); for (const QString &filename : stealFiles) { if (filename.isEmpty()) { - qWarning("Trying to find file with no name"); + log::warn("Trying to find file with no name"); continue; } QFileInfo fileInfo(filename); @@ -143,7 +143,7 @@ void DirectoryRefresher::addModFilesToStructure(DirectoryEntry *directoryStructu QString warnStr = fileInfo.absolutePath(); if (warnStr.isEmpty()) warnStr = filename; - qWarning("file not found: %s", qUtf8Printable(warnStr)); + log::warn("file not found: {}", warnStr); } } } else { diff --git a/src/downloadmanager.cpp b/src/downloadmanager.cpp index 648b102a..e3ceb261 100644 --- a/src/downloadmanager.cpp +++ b/src/downloadmanager.cpp @@ -924,7 +924,7 @@ void DownloadManager::queryInfo(int index) DownloadInfo *info = m_ActiveDownloads[index]; if (info->m_FileInfo->repository != "Nexus") { - qWarning("re-querying file info is currently only possible with Nexus"); + log::warn("re-querying file info is currently only possible with Nexus"); return; } @@ -976,7 +976,7 @@ void DownloadManager::queryInfoMd5(int index) DownloadInfo *info = m_ActiveDownloads[index]; if (info->m_FileInfo->repository != "Nexus") { - qWarning("re-querying file info is currently only possible with Nexus"); + log::warn("re-querying file info is currently only possible with Nexus"); return; } @@ -1016,7 +1016,7 @@ void DownloadManager::visitOnNexus(int index) DownloadInfo *info = m_ActiveDownloads[index]; if (info->m_FileInfo->repository != "Nexus") { - qWarning("Visiting mod page is currently only possible with Nexus"); + log::warn("Visiting mod page is currently only possible with Nexus"); return; } @@ -1614,8 +1614,9 @@ void DownloadManager::nxmFilesAvailable(QString, int, QVariant userData, QVarian } } else { if (info->m_FileInfo->fileID == 0) { - qWarning("could not determine file id for %s (state %d)", - qUtf8Printable(info->m_FileName), info->m_State); + log::warn( + "could not determine file id for {} (state {})", + info->m_FileName, info->m_State); } } @@ -1999,7 +2000,7 @@ void DownloadManager::downloadFinished(int index) resumeDownloadInt(index); } } else { - qWarning("no download index %d", index); + log::warn("no download index {}", index); } } @@ -2008,9 +2009,9 @@ void DownloadManager::downloadError(QNetworkReply::NetworkError error) { if (error != QNetworkReply::OperationCanceledError) { QNetworkReply *reply = qobject_cast(sender()); - qWarning("%s (%d)", reply != nullptr ? qUtf8Printable(reply->errorString()) - : "Download error occured", - error); + log::warn("{} ({})", + reply != nullptr ? reply->errorString() : "Download error occured", + error); } } @@ -2033,7 +2034,7 @@ void DownloadManager::metaDataChanged() } } } else { - qWarning("meta data event for unknown download"); + log::warn("meta data event for unknown download"); } } diff --git a/src/editexecutablesdialog.cpp b/src/editexecutablesdialog.cpp index 8929d207..3ec3d64f 100644 --- a/src/editexecutablesdialog.cpp +++ b/src/editexecutablesdialog.cpp @@ -101,9 +101,7 @@ ExecutablesList EditExecutablesDialog::getExecutablesList() const auto itor = m_executablesList.find(title); if (itor == m_executablesList.end()) { - qWarning().nospace() - << "getExecutablesList(): executable '" << title << "' not found"; - + log::warn("getExecutablesList(): executable '{}' not found", title); continue; } @@ -293,9 +291,10 @@ void EditExecutablesDialog::setEdits(const Executable& e) modIndex = ui->mods->findText(modName->value); if (modIndex == -1) { - qWarning().nospace() - << "executable '" << e.title() << "' uses mod '" << modName->value << "' " - << "as a custom overwrite, but that mod doesn't exist"; + log::warn( + "executable '{}' uses mod '{}' as a custom overwrite, but that mod " + "doesn't exist", + e.title(), modName->value); } } @@ -335,7 +334,7 @@ void EditExecutablesDialog::save() auto* e = selectedExe(); if (!e) { - qWarning("trying to save but nothing is selected"); + log::warn("trying to save but nothing is selected"); return; } @@ -475,13 +474,13 @@ void EditExecutablesDialog::on_remove_clicked() { auto* item = selectedItem(); if (!item) { - qWarning("trying to remove entry but nothing is selected"); + log::warn("trying to remove entry but nothing is selected"); return; } auto* exe = selectedExe(); if (!exe) { - qWarning("trying to remove entry but nothing is selected"); + log::warn("trying to remove entry but nothing is selected"); return; } @@ -646,7 +645,7 @@ void EditExecutablesDialog::on_configureLibraries_clicked() { auto* e = selectedExe(); if (!e) { - qWarning("trying to configure libraries but nothing is selected"); + log::warn("trying to configure libraries but nothing is selected"); return; } diff --git a/src/executableslist.cpp b/src/executableslist.cpp index 0ca880cd..fbb96bd4 100644 --- a/src/executableslist.cpp +++ b/src/executableslist.cpp @@ -250,9 +250,9 @@ void ExecutablesList::setExecutable(const Executable &exe, SetFlags flags) return; } - qWarning().nospace() - << "executable '" << itor->title() << "' was in the way and was " - << "renamed to '" << *newTitle << "'"; + log::warn( + "executable '{}' was in the way and was renamed to '{}'", + itor->title(), *newTitle); itor->title(*newTitle); itor = end(); diff --git a/src/filerenamer.cpp b/src/filerenamer.cpp index c5c6782b..b516c902 100644 --- a/src/filerenamer.cpp +++ b/src/filerenamer.cpp @@ -1,7 +1,10 @@ #include "filerenamer.h" +#include #include #include +using namespace MOBase; + FileRenamer::FileRenamer(QWidget* parent, QFlags flags) : m_parent(parent), m_flags(flags) { @@ -34,7 +37,7 @@ FileRenamer::RenameResults FileRenamer::rename(const QString& oldName, const QSt qDebug().nospace() << "removing " << newName; // user wants to replace the file, so remove it if (!QFile(newName).remove()) { - qWarning().nospace() << "failed to remove " << newName; + log::warn("failed to remove '{}'", newName); // removal failed, warn the user and allow canceling if (!removeFailed(newName)) { qDebug().nospace() << "canceling " << oldName; @@ -62,7 +65,7 @@ FileRenamer::RenameResults FileRenamer::rename(const QString& oldName, const QSt // target either didn't exist or was removed correctly if (!QFile::rename(oldName, newName)) { - qWarning().nospace() << "failed to rename " << oldName << " to " << newName; + log::warn("failed to rename '{}' to '{}'", oldName, newName); // renaming failed, warn the user and allow canceling if (!renameFailed(oldName, newName)) { diff --git a/src/icondelegate.cpp b/src/icondelegate.cpp index 249dae6f..39038f3c 100644 --- a/src/icondelegate.cpp +++ b/src/icondelegate.cpp @@ -18,12 +18,14 @@ along with Mod Organizer. If not, see . */ #include "icondelegate.h" +#include #include #include #include #include #include +using namespace MOBase; IconDelegate::IconDelegate(QObject *parent) : QStyledItemDelegate(parent) @@ -54,7 +56,7 @@ void IconDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, if (!QPixmapCache::find(fullIconId, &icon)) { icon = QIcon(iconId).pixmap(iconWidth, iconWidth); if (icon.isNull()) { - qWarning("failed to load icon %s", qUtf8Printable(iconId)); + log::warn("failed to load icon {}", iconId); } QPixmapCache::insert(fullIconId, icon); } diff --git a/src/installationmanager.cpp b/src/installationmanager.cpp index e443a8f2..0e50de52 100644 --- a/src/installationmanager.cpp +++ b/src/installationmanager.cpp @@ -693,7 +693,7 @@ void InstallationManager::postInstallCleanup() QFile::setPermissions(fileInfo.absoluteFilePath(), QFile::ReadOther | QFile::WriteOther); } if (!QFile::remove(fileInfo.absoluteFilePath())) { - qWarning() << "Unable to delete " << fileInfo.absoluteFilePath(); + log::warn("Unable to delete {}", fileInfo.absoluteFilePath()); } } directoriesToRemove.insert(fileInfo.absolutePath()); diff --git a/src/instancemanager.cpp b/src/instancemanager.cpp index ddc2d067..55ef3fc8 100644 --- a/src/instancemanager.cpp +++ b/src/instancemanager.cpp @@ -21,6 +21,7 @@ along with Mod Organizer. If not, see . #include "instancemanager.h" #include "selectiondialog.h" #include +#include #include #include #include @@ -29,13 +30,13 @@ along with Mod Organizer. If not, see . #include #include +using namespace MOBase; static const char COMPANY_NAME[] = "Tannin"; static const char APPLICATION_NAME[] = "Mod Organizer"; static const char INSTANCE_KEY[] = "CurrentInstance"; - InstanceManager::InstanceManager() : m_AppSettings(COMPANY_NAME, APPLICATION_NAME) { @@ -86,10 +87,13 @@ bool InstanceManager::deleteLocalInstance(const QString &instanceId) const if (!MOBase::shellDelete(QStringList(instancePath),true)) { - qWarning("Failed to shell-delete \"%s\" (errorcode %lu), trying regular delete", qUtf8Printable(instancePath), ::GetLastError()); + log::warn( + "Failed to shell-delete \"{}\" (errorcode {}), trying regular delete", + instancePath, ::GetLastError()); + if (!MOBase::removeDir(instancePath)) { - qWarning("regular delete failed too"); + log::warn("regular delete failed too"); result = false; } } @@ -153,7 +157,7 @@ QString InstanceManager::queryInstanceName(const QStringList &instanceList) cons dialogText = dialog.textValue(); instanceId = sanitizeInstanceName(dialogText); if (instanceId != dialogText) { - if (QMessageBox::question( nullptr, + if (QMessageBox::question( nullptr, QObject::tr("Invalid instance name"), QObject::tr("The instance name \"%1\" is invalid. Use the name \"%2\" instead?").arg(dialogText,instanceId), QMessageBox::Yes | QMessageBox::No) == QMessageBox::No) { @@ -323,7 +327,7 @@ QString InstanceManager::sanitizeInstanceName(const QString &name) const // Don't end in spaces and periods new_name = new_name.remove(QRegExp("\\.*$")); new_name = new_name.remove(QRegExp(" *$")); - + // Recurse until stuff stops changing if (new_name != name) { return sanitizeInstanceName(new_name); diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 9dbada1c..70ace8f1 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -800,7 +800,7 @@ void MainWindow::setupToolbar() ui->toolBar->insertWidget(m_linksSeparator, spacer); } else { - qWarning("no separator found on the toolbar, icons won't be right-aligned"); + log::warn("no separator found on the toolbar, icons won't be right-aligned"); } } @@ -1646,9 +1646,7 @@ void MainWindow::startExeAction() auto itor = list.find(title); if (itor == list.end()) { - qWarning().nospace() - << "startExeAction(): executable '" << title << "' not found"; - + log::warn("startExeAction(): executable '{}' not found", title); return; } @@ -1874,17 +1872,18 @@ void MainWindow::expandDataTreeItem(QTreeWidgetItem *item) if ((item->childCount() == 1) && (item->child(0)->data(0, Qt::UserRole).toString() == "__loaded_on_demand__")) { // read the data we need from the sub-item, then dispose of it QTreeWidgetItem *onDemandDataItem = item->child(0); - std::wstring path = ToWString(onDemandDataItem->data(0, Qt::UserRole + 1).toString()); + const QString path = onDemandDataItem->data(0, Qt::UserRole + 1).toString(); + std::wstring wspath = path.toStdWString(); bool conflictsOnly = onDemandDataItem->data(0, Qt::UserRole + 2).toBool(); - std::wstring virtualPath = (path + L"\\").substr(6) + ToWString(item->text(0)); + std::wstring virtualPath = (wspath + L"\\").substr(6) + ToWString(item->text(0)); DirectoryEntry *dir = m_OrganizerCore.directoryStructure()->findSubDirectoryRecursive(virtualPath); if (dir != nullptr) { QIcon folderIcon = (new QFileIconProvider())->icon(QFileIconProvider::Folder); QIcon fileIcon = (new QFileIconProvider())->icon(QFileIconProvider::File); - updateTo(item, path, *dir, conflictsOnly, &fileIcon, &folderIcon); + updateTo(item, wspath, *dir, conflictsOnly, &fileIcon, &folderIcon); } else { - qWarning("failed to update view of %ls", path.c_str()); + log::warn("failed to update view of {}", path); } m_RemoveWidget.push_back(item); QTimer::singleShot(5, this, SLOT(delayedRemove())); @@ -2380,10 +2379,17 @@ void MainWindow::processUpdates() { if (currentVersion > lastVersion) { //NOP - } else if (currentVersion < lastVersion) - qWarning() << tr("Notice: Your current MO version (%1) is lower than the previously used one (%2). " - "The GUI may not downgrade gracefully, so you may experience oddities. " - "However, there should be no serious issues.").arg(currentVersion.toString()).arg(lastVersion.toString()).toStdWString(); + } else if (currentVersion < lastVersion) { + const auto text = tr( + "Notice: Your current MO version (%1) is lower than the previously used one (%2). " + "The GUI may not downgrade gracefully, so you may experience oddities. " + "However, there should be no serious issues.") + .arg(currentVersion.toString()) + .arg(lastVersion.toString()); + + log::warn("{}", text); + } + //save version in all case settings.setValue("version", currentVersion.toString()); } @@ -2924,7 +2930,7 @@ void MainWindow::refreshFilters() while (currentID != 0) { categoriesUsed.insert(currentID); if (!cycleTest.insert(currentID).second) { - qWarning("cycle in categories: %s", qUtf8Printable(SetJoin(cycleTest, ", "))); + log::warn("cycle in categories: {}", SetJoin(cycleTest, ", ")); break; } currentID = m_CategoryFactory.getParentID(m_CategoryFactory.getCategoryIndex(currentID)); @@ -4008,7 +4014,7 @@ void MainWindow::moveOverwriteContentToExistingMod() } if (modAbsolutePath.isNull()) { - qWarning("Mod %s has not been found, for some reason", qUtf8Printable(result)); + log::warn("Mod {} has not been found, for some reason", result); return; } @@ -4404,7 +4410,7 @@ void MainWindow::saveArchiveList() qDebug("%s saved", qUtf8Printable(QDir::toNativeSeparators(m_OrganizerCore.currentProfile()->getArchivesFileName()))); } } else { - qWarning("archive list not initialised"); + log::warn("archive list not initialised"); } } @@ -4421,7 +4427,7 @@ void MainWindow::checkModsForUpdates() m_OrganizerCore.doAfterLogin([this] () { this->checkModsForUpdates(); }); NexusInterface::instance(&m_PluginContainer)->getAccessManager()->apiCheck(apiKey); } else { - qWarning("You are not currently authenticated with Nexus. Please do so under Settings -> Nexus."); + log::warn("You are not currently authenticated with Nexus. Please do so under Settings -> Nexus."); } } @@ -5802,7 +5808,7 @@ void MainWindow::modUpdateCheck(std::multimap IDs) m_OrganizerCore.doAfterLogin([=]() { this->modUpdateCheck(IDs); }); NexusInterface::instance(&m_PluginContainer)->getAccessManager()->apiCheck(apiKey); } else - qWarning("You are not currently authenticated with Nexus. Please do so under Settings -> Nexus."); + log::warn("You are not currently authenticated with Nexus. Please do so under Settings -> Nexus."); } } @@ -5918,7 +5924,7 @@ void MainWindow::finishUpdateInfo() } if (!finalMods.empty() && organizedGames.empty()) - qWarning("All of your mods have been checked recently. We restrict update checks to help preserve your available API requests."); + log::warn("All of your mods have been checked recently. We restrict update checks to help preserve your available API requests."); for (auto game : organizedGames) NexusInterface::instance(&m_PluginContainer)->requestUpdates(game.second, this, QVariant(), game.first, QString()); @@ -6368,9 +6374,7 @@ void MainWindow::removeFromToolbar() auto itor = list.find(title); if (itor == list.end()) { - qWarning().nospace() - << "removeFromToolbar(): executable '" << title << "' not found"; - + log::warn("removeFromToolbar(): executable '{}' not found", title); return; } @@ -6570,7 +6574,7 @@ void MainWindow::processLOOTOut(const std::string &lootOut, std::string &errorMe if (progidx != std::string::npos) { dialog.setLabelText(line.substr(progidx + 11).c_str()); } else if (erroridx != std::string::npos) { - qWarning("%s", line.c_str()); + log::warn("{}", line); errorMessages.append(boost::algorithm::trim_copy(line.substr(erroridx + 8)) + "\n"); } else { std::smatch match; @@ -6928,7 +6932,7 @@ void MainWindow::dropLocalFile(const QUrl &url, const QString &outputDir, bool m { QFileInfo file(url.toLocalFile()); if (!file.exists()) { - qWarning("invalid source file: %s", qUtf8Printable(file.absoluteFilePath())); + log::warn("invalid source file: {}", file.absoluteFilePath()); return; } QString target = outputDir + "/" + file.fileName(); diff --git a/src/moapplication.cpp b/src/moapplication.cpp index 5652833a..3d55b28d 100644 --- a/src/moapplication.cpp +++ b/src/moapplication.cpp @@ -20,6 +20,7 @@ along with Mod Organizer. If not, see . #include "moapplication.h" #include #include +#include #include #include #include @@ -36,7 +37,7 @@ along with Mod Organizer. If not, see . #include -using MOBase::reportError; +using namespace MOBase; class ProxyStyle : public QProxyStyle { @@ -137,7 +138,7 @@ void MOApplication::updateStyle(const QString &fileName) if (QFile::exists(fileName)) { setStyleSheet(QString("file:///%1").arg(fileName)); } else { - qWarning("invalid stylesheet: %s", qUtf8Printable(fileName)); + log::warn("invalid stylesheet: {}", fileName); } } } diff --git a/src/modflagicondelegate.cpp b/src/modflagicondelegate.cpp index c3142962..7110a590 100644 --- a/src/modflagicondelegate.cpp +++ b/src/modflagicondelegate.cpp @@ -1,6 +1,8 @@ #include "modflagicondelegate.h" +#include #include +using namespace MOBase; ModInfo::EFlag ModFlagIconDelegate::m_ConflictFlags[4] = { ModInfo::FLAG_CONFLICT_MIXED , ModInfo::FLAG_CONFLICT_OVERWRITE @@ -117,7 +119,7 @@ QString ModFlagIconDelegate::getFlagIcon(ModInfo::EFlag flag) const case ModInfo::FLAG_PLUGIN_SELECTED: return QString(); case ModInfo::FLAG_TRACKED: return QStringLiteral(":/MO/gui/tracked"); default: - qWarning("ModInfo flag %d has no defined icon", flag); + log::warn("ModInfo flag {} has no defined icon", flag); return QString(); } } diff --git a/src/modinfo.cpp b/src/modinfo.cpp index 92c7366c..ca6e8046 100644 --- a/src/modinfo.cpp +++ b/src/modinfo.cpp @@ -320,7 +320,7 @@ bool ModInfo::checkAllForUpdate(PluginContainer *pluginContainer, QObject *recei } if (organizedGames.empty()) { - qWarning() << tr("All of your mods have been checked recently. We restrict update checks to help preserve your available API requests."); + log::warn("{}", tr("All of your mods have been checked recently. We restrict update checks to help preserve your available API requests.")); updatesAvailable = false; } else { log::info("{}", tr( diff --git a/src/modinfodialogesps.cpp b/src/modinfodialogesps.cpp index fba5d39a..3130b4bd 100644 --- a/src/modinfodialogesps.cpp +++ b/src/modinfodialogesps.cpp @@ -3,8 +3,9 @@ #include "modinfodialog.h" #include "settings.h" #include +#include -using MOBase::reportError; +using namespace MOBase; class ESPItem { @@ -297,7 +298,7 @@ void ESPsTab::onActivate() } if (esp->isActive()) { - qWarning("ESPsTab::onActive(): item is already active"); + log::warn("ESPsTab::onActive(): item is already active"); return; } @@ -348,7 +349,7 @@ void ESPsTab::onDeactivate() } if (!esp->isActive()) { - qWarning("ESPsTab::onDeactivate(): item is already inactive"); + log::warn("ESPsTab::onDeactivate(): item is already inactive"); return; } diff --git a/src/modlist.cpp b/src/modlist.cpp index 7b71355c..df25df0d 100644 --- a/src/modlist.cpp +++ b/src/modlist.cpp @@ -275,7 +275,7 @@ QVariant ModList::data(const QModelIndex &modelIndex, int role) const return QString(); } } else { - qWarning("category %d doesn't exist (may have been removed)", category); + log::warn("category {} doesn't exist (may have been removed)", category); modInfo->setCategory(category, false); return QString(); } @@ -618,8 +618,9 @@ bool ModList::setData(const QModelIndex &index, const QVariant &value, int role) result = true; } break; default: { - qWarning("edit on column \"%s\" not supported", - getColumnName(index.column()).toUtf8().constData()); + log::warn( + "edit on column \"{}\" not supported", + getColumnName(index.column()).toUtf8().constData()); result = false; } break; } diff --git a/src/modlistsortproxy.cpp b/src/modlistsortproxy.cpp index 2d9ea4a5..1127c7d4 100644 --- a/src/modlistsortproxy.cpp +++ b/src/modlistsortproxy.cpp @@ -22,6 +22,7 @@ along with Mod Organizer. If not, see . #include "profile.h" #include "messagedialog.h" #include "qtgroupingproxy.h" +#include #include #include #include @@ -30,6 +31,7 @@ along with Mod Organizer. If not, see . #include #include +using namespace MOBase; ModListSortProxy::ModListSortProxy(Profile* profile, QObject *parent) : QSortFilterProxyModel(parent) @@ -240,7 +242,7 @@ bool ModListSortProxy::lessThan(const QModelIndex &left, // nop, already compared by priority } break; default: { - qWarning() << "Sorting is not defined for column " << left.column(); + log::warn("Sorting is not defined for column {}", left.column()); } break; } return lt; @@ -474,7 +476,7 @@ bool ModListSortProxy::filterAcceptsRow(int row, const QModelIndex &parent) cons } if (row >= static_cast(m_Profile->numMods())) { - qWarning("invalid row index: %d", row); + log::warn("invalid row index: {}", row); return false; } diff --git a/src/nexusinterface.cpp b/src/nexusinterface.cpp index 2bcd72f3..008f3c0d 100644 --- a/src/nexusinterface.cpp +++ b/src/nexusinterface.cpp @@ -25,6 +25,7 @@ along with Mod Organizer. If not, see . #include "bbcode.h" #include #include +#include #include #include @@ -695,9 +696,13 @@ void NexusInterface::nextRequest() QTime time = QTime::currentTime(); QTime targetTime; targetTime.setHMS((time.hour() + 1) % 23, 5, 0); - QString warning = tr("You've exceeded the Nexus API rate limit and requests are now being throttled. " - "Your next batch of requests will be available in approximately %1 minutes and %2 seconds."); - qWarning() << warning.arg(time.secsTo(targetTime) / 60).arg(time.secsTo(targetTime) % 60); + QString warning = tr( + "You've exceeded the Nexus API rate limit and requests are now being throttled. " + "Your next batch of requests will be available in approximately %1 minutes and %2 seconds.") + .arg(time.secsTo(targetTime) / 60) + .arg(time.secsTo(targetTime) % 60); + + log::warn("{}", warning); return; } @@ -747,8 +752,8 @@ void NexusInterface::nextRequest() url = QString("%1/games/%2/mods/%3/files/%4/download_link?key=%5&expires=%6") .arg(info.m_URL).arg(info.m_GameName).arg(info.m_ModID).arg(info.m_FileID).arg(fileInfo->nexusKey).arg(fileInfo->nexusExpires); } else { - qWarning() << tr("Aborting download: Either you clicked on a premium-only link and your account is not premium, " - "or the download link was generated by a different account than the one stored in Mod Organizer."); + log::warn("{}", tr("Aborting download: Either you clicked on a premium-only link and your account is not premium, " + "or the download link was generated by a different account than the one stored in Mod Organizer.")); return; } } break; @@ -828,16 +833,16 @@ void NexusInterface::requestFinished(std::list::iterator iter) m_User.limits(parseLimits(reply)); if (!m_User.exhausted()) { - qWarning("You appear to be making requests to the Nexus API too quickly and are being throttled. Please inform the MO2 team."); + log::warn("You appear to be making requests to the Nexus API too quickly and are being throttled. Please inform the MO2 team."); } else { - qWarning("All API requests have been consumed and are now being denied."); + log::warn("All API requests have been consumed and are now being denied."); } emit requestsChanged(getAPIStats(), m_User); - qWarning("Error: %s", reply->errorString().toUtf8().constData()); + log::warn("Error: {}", reply->errorString()); } else { - qWarning("request failed: %s", reply->errorString().toUtf8().constData()); + log::warn("request failed: {}", reply->errorString()); } emit nxmRequestFailed(iter->m_GameName, iter->m_ModID, iter->m_FileID, iter->m_UserData, iter->m_ID, reply->error(), reply->errorString()); } else { @@ -940,7 +945,7 @@ void NexusInterface::requestError(QNetworkReply::NetworkError) { QNetworkReply *reply = qobject_cast(sender()); if (reply == nullptr) { - qWarning("invalid sender type"); + log::warn("invalid sender type"); return; } @@ -955,7 +960,7 @@ void NexusInterface::requestTimeout() { QTimer *timer = qobject_cast(sender()); if (timer == nullptr) { - qWarning("invalid sender type"); + log::warn("invalid sender type"); return; } for (std::list::iterator iter = m_ActiveRequest.begin(); iter != m_ActiveRequest.end(); ++iter) { diff --git a/src/nxmaccessmanager.cpp b/src/nxmaccessmanager.cpp index c413e156..9f40894e 100644 --- a/src/nxmaccessmanager.cpp +++ b/src/nxmaccessmanager.cpp @@ -612,7 +612,7 @@ void NXMAccessManager::clearCookies() if (jar != nullptr) { jar->clear(); } else { - qWarning("failed to clear cookies, invalid cookie jar"); + log::warn("failed to clear cookies, invalid cookie jar"); } } diff --git a/src/organizercore.cpp b/src/organizercore.cpp index 400f5391..dbff1a2a 100644 --- a/src/organizercore.cpp +++ b/src/organizercore.cpp @@ -200,26 +200,26 @@ bool checkService() try { serviceManagerHandle = OpenSCManager(NULL, NULL, SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG); if (!serviceManagerHandle) { - qWarning("failed to open service manager (query status) (error %d)", GetLastError()); + log::warn("failed to open service manager (query status) (error {})", GetLastError()); throw 1; } serviceHandle = OpenService(serviceManagerHandle, L"EventLog", SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG); if (!serviceHandle) { - qWarning("failed to open EventLog service (query status) (error %d)", GetLastError()); + log::warn("failed to open EventLog service (query status) (error {})", GetLastError()); throw 2; } if (QueryServiceConfig(serviceHandle, NULL, 0, &bytesNeeded) || (GetLastError() != ERROR_INSUFFICIENT_BUFFER)) { - qWarning("failed to get size of service config (error %d)", GetLastError()); + log::warn("failed to get size of service config (error {})", GetLastError()); throw 3; } DWORD serviceConfigSize = bytesNeeded; serviceConfig = (LPQUERY_SERVICE_CONFIG)LocalAlloc(LMEM_FIXED, serviceConfigSize); if (!QueryServiceConfig(serviceHandle, serviceConfig, serviceConfigSize, &bytesNeeded)) { - qWarning("failed to query service config (error %d)", GetLastError()); + log::warn("failed to query service config (error {})", GetLastError()); throw 4; } @@ -230,14 +230,14 @@ bool checkService() if (QueryServiceStatusEx(serviceHandle, SC_STATUS_PROCESS_INFO, NULL, 0, &bytesNeeded) || (GetLastError() != ERROR_INSUFFICIENT_BUFFER)) { - qWarning("failed to get size of service status (error %d)", GetLastError()); + log::warn("failed to get size of service status (error {})", GetLastError()); throw 5; } DWORD serviceStatusSize = bytesNeeded; serviceStatus = (LPSERVICE_STATUS_PROCESS)LocalAlloc(LMEM_FIXED, serviceStatusSize); if (!QueryServiceStatusEx(serviceHandle, SC_STATUS_PROCESS_INFO, (LPBYTE)serviceStatus, serviceStatusSize, &bytesNeeded)) { - qWarning("failed to query service status (error %d)", GetLastError()); + log::warn("failed to query service status (error {})", GetLastError()); throw 6; } @@ -402,8 +402,9 @@ void OrganizerCore::storeSettings() if (result == QSettings::NoError) { QString errMsg = commitSettings(iniFile); if (!errMsg.isEmpty()) { - qWarning("settings file not writable, may be locked by another " - "application, trying direct write"); + log::warn( + "settings file not writable, may be locked by another " + "application, trying direct write"); writeTarget = iniFile; result = storeSettings(iniFile); } @@ -1381,9 +1382,9 @@ bool OrganizerCore::previewFileWithAlternatives( // sanity check, this shouldn't happen unless the caller passed an // incorrect id - qWarning().nospace() - << "selected preview origin " << selectedOrigin << " not found in " - << "list of alternatives"; + log::warn( + "selected preview origin {} not found in list of alternatives", + selectedOrigin); } for (int id : origins) { @@ -1798,8 +1799,7 @@ HANDLE OrganizerCore::startApplication(const QString &executable, currentDirectory = exe.workingDirectory(); } } catch (const std::runtime_error &) { - qWarning("\"%s\" not set up as executable", - qUtf8Printable(executable)); + log::warn("\"{}\" not set up as executable", executable); binary = QFileInfo(executable); } } @@ -1881,7 +1881,7 @@ bool OrganizerCore::waitForProcessCompletion(HANDLE handle, LPDWORD exitCode, IL // Wait for a an event on the handle, a key press, mouse click or timeout res = MsgWaitForMultipleObjects(1, &handle, FALSE, 200, QS_KEY | QS_MOUSEBUTTON); if (res == WAIT_FAILED) { - qWarning() << "Failed waiting for process completion : MsgWaitForMultipleObjects WAIT_FAILED" << GetLastError(); + log::warn("Failed waiting for process completion : MsgWaitForMultipleObjects WAIT_FAILED {}", GetLastError()); break; } @@ -1897,7 +1897,7 @@ bool OrganizerCore::waitForProcessCompletion(HANDLE handle, LPDWORD exitCode, IL if (res == WAIT_OBJECT_0) { // process we were waiting on has completed if (originalHandle && exitCode && !::GetExitCodeProcess(handle, exitCode)) - qWarning() << "Failed getting exit code of complete process :" << GetLastError(); + log::warn("Failed getting exit code of complete process: {}", GetLastError()); CloseHandle(handle); handle = INVALID_HANDLE_VALUE; originalHandle = false; @@ -1962,7 +1962,7 @@ HANDLE OrganizerCore::findAndOpenAUSVFSProcess(const std::vector& hidde DWORD pids[querySize]; size_t found = querySize; if (!::GetVFSProcessList(&found, pids)) { - qWarning() << "Failed seeking USVFS processes : GetVFSProcessList failed?!"; + log::warn("Failed seeking USVFS processes : GetVFSProcessList failed?!"); return INVALID_HANDLE_VALUE; } @@ -1974,7 +1974,7 @@ HANDLE OrganizerCore::findAndOpenAUSVFSProcess(const std::vector& hidde HANDLE handle = ::OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, FALSE, pids[i]); if (handle == INVALID_HANDLE_VALUE) { - qWarning() << "Failed openning USVFS process " << pids[i] << " : OpenProcess failed" << GetLastError(); + log::warn("Failed opening USVFS process {}: OpenProcess failed {}", pids[i], GetLastError()); continue; } @@ -2118,7 +2118,7 @@ void OrganizerCore::updateModsActiveState(const QList &modIndices, dir.entryList(QStringList() << "*.esm", QDir::Files)) { const FileEntry::Ptr file = m_DirectoryStructure->findFile(ToWString(esm)); if (file.get() == nullptr) { - qWarning("failed to activate %s", qUtf8Printable(esm)); + log::warn("failed to activate {}", esm); continue; } @@ -2134,7 +2134,7 @@ void OrganizerCore::updateModsActiveState(const QList &modIndices, dir.entryList(QStringList() << "*.esl", QDir::Files)) { const FileEntry::Ptr file = m_DirectoryStructure->findFile(ToWString(esl)); if (file.get() == nullptr) { - qWarning("failed to activate %s", qUtf8Printable(esl)); + log::warn("failed to activate {}", esl); continue; } @@ -2150,7 +2150,7 @@ void OrganizerCore::updateModsActiveState(const QList &modIndices, for (const QString &esp : esps) { const FileEntry::Ptr file = m_DirectoryStructure->findFile(ToWString(esp)); if (file.get() == nullptr) { - qWarning("failed to activate %s", qUtf8Printable(esp)); + log::warn("failed to activate {}", esp); continue; } @@ -2558,7 +2558,7 @@ std::vector OrganizerCore::activeProblems() const // of a "log spam". But since this is a sevre error which will most likely make the // game crash/freeze/etc. and is very hard to diagnose, this "log spam" will make it // easier for the user to notice the warning. - qWarning("hook.dll found in game folder: %s", qUtf8Printable(hookdll)); + log::warn("hook.dll found in game folder: {}", hookdll); problems.push_back(PROBLEM_MO1SCRIPTEXTENDERWORKAROUND); } return problems; @@ -2604,7 +2604,7 @@ void OrganizerCore::startGuidedFix(unsigned int) const bool OrganizerCore::saveCurrentLists() { if (m_DirectoryUpdate) { - qWarning("not saving lists during directory update"); + log::warn("not saving lists during directory update"); return false; } @@ -2698,7 +2698,7 @@ std::vector OrganizerCore::fileMapping(const QString &profileName, result.reserve(result.size() + saveMap.size()); result.insert(result.end(), saveMap.begin(), saveMap.end()); } else { - qWarning("local save games not supported by this game plugin"); + log::warn("local save games not supported by this game plugin"); } } diff --git a/src/plugincontainer.cpp b/src/plugincontainer.cpp index 2126c5ef..d47fa2c6 100644 --- a/src/plugincontainer.cpp +++ b/src/plugincontainer.cpp @@ -69,7 +69,7 @@ bool PluginContainer::verifyPlugin(IPlugin *plugin) if (plugin == nullptr) { return false; } else if (!plugin->init(new OrganizerProxy(m_Organizer, this, plugin->name()))) { - qWarning("plugin failed to initialize"); + log::warn("plugin failed to initialize"); return false; } return true; @@ -167,9 +167,10 @@ bool PluginContainer::registerPlugin(QObject *plugin, const QString &fileName) qDebug("loaded plugin \"%s\"", qUtf8Printable(QFileInfo(pluginName).fileName())); } else { - qWarning("plugin \"%s\" failed to load. If this plugin is for an older version of MO " - "you have to update it or delete it if no update exists.", - qUtf8Printable(pluginName)); + log::warn( + "plugin \"{}\" failed to load. If this plugin is for an older version of MO " + "you have to update it or delete it if no update exists.", + pluginName); } } } @@ -298,7 +299,7 @@ void PluginContainer::loadPlugins() m_PluginLoaders.push_back(pluginLoader.release()); } else { m_FailedPlugins.push_back(pluginName); - qWarning("plugin \"%s\" failed to load (may be outdated)", qUtf8Printable(pluginName)); + log::warn("plugin \"{}\" failed to load (may be outdated)", pluginName); } } } diff --git a/src/pluginlist.cpp b/src/pluginlist.cpp index 2edb92f5..2fb743d0 100644 --- a/src/pluginlist.cpp +++ b/src/pluginlist.cpp @@ -417,7 +417,7 @@ void PluginList::addInformation(const QString &name, const QString &message) if (iter != m_ESPsByName.end()) { m_AdditionalInfo[name.toLower()].m_Messages.append(message); } else { - qWarning("failed to associate message for \"%s\"", qUtf8Printable(name)); + log::warn("failed to associate message for \"{}\"", name); } } @@ -694,7 +694,7 @@ void PluginList::setState(const QString &name, PluginStates state) { m_ESPs[iter->second].m_Enabled = (state == IPluginList::STATE_ACTIVE) || m_ESPs[iter->second].m_ForceEnabled; } else { - qWarning("Plugin not found: %s", qUtf8Printable(name)); + log::warn("Plugin not found: {}", name); } } diff --git a/src/problemsdialog.cpp b/src/problemsdialog.cpp index 1e8e800f..da09935b 100644 --- a/src/problemsdialog.cpp +++ b/src/problemsdialog.cpp @@ -96,7 +96,7 @@ void ProblemsDialog::startFix() { QObject *fixButton = QObject::sender(); if (fixButton == NULL) { - qWarning("no button"); + log::warn("no button"); return; } IPluginDiagnose *plugin = reinterpret_cast(fixButton ->property("fix").value()); diff --git a/src/profile.cpp b/src/profile.cpp index 01906903..d4778305 100644 --- a/src/profile.cpp +++ b/src/profile.cpp @@ -125,7 +125,7 @@ Profile::Profile(const QDir &directory, IPluginGame const *gamePlugin) findProfileSettings(); if (!QFile::exists(m_Directory.filePath("modlist.txt"))) { - qWarning("missing modlist.txt in %s", qUtf8Printable(directory.path())); + log::warn("missing modlist.txt in {}", directory.path()); touchFile(m_Directory.filePath("modlist.txt")); } @@ -307,7 +307,7 @@ void Profile::renameModInAllProfiles(const QString& oldName, const QString& newN if (modList.exists()) renameModInList(modList, oldName, newName); else - qWarning("Profile has no modlist.txt : %s", qUtf8Printable(profileIter.filePath())); + log::warn("Profile has no modlist.txt: {}", profileIter.filePath()); } } @@ -328,7 +328,7 @@ void Profile::renameModInList(QFile &modList, const QString &oldName, const QStr if (line.length() == 0) { // ignore empty lines - qWarning("mod list contained invalid data: empty line"); + log::warn("mod list contained invalid data: empty line"); continue; } @@ -343,7 +343,7 @@ void Profile::renameModInList(QFile &modList, const QString &oldName, const QStr if (modName.isEmpty()) { // file broken? - qWarning("mod list contained invalid data: missing mod name"); + log::warn("mod list contained invalid data: missing mod name"); continue; } @@ -424,8 +424,9 @@ void Profile::refreshModStatus() m_ModStatus[modIndex].m_Priority = index++; } } else { - qWarning("no mod state for \"%s\" (profile \"%s\")", - qUtf8Printable(modName), qUtf8Printable(m_Directory.path())); + log::warn( + "no mod state for \"{}\" (profile \"{}\")", + modName, m_Directory.path()); // need to rewrite the modlist to fix this modStatusModified = true; } @@ -495,8 +496,10 @@ void Profile::dumpModStatus() const { for (unsigned int i = 0; i < m_ModStatus.size(); ++i) { ModInfo::Ptr info = ModInfo::getByIndex(i); - qWarning("%d: %s - %d (%s)", i, info->name().toUtf8().constData(), m_ModStatus[i].m_Priority, - m_ModStatus[i].m_Enabled ? "enabled" : "disabled"); + log::warn( + "{}: {} - {} ({})", + i, info->name(), m_ModStatus[i].m_Priority, + m_ModStatus[i].m_Enabled ? "enabled" : "disabled"); } } @@ -803,7 +806,7 @@ bool Profile::localSettingsEnabled() const QStringList missingFiles; for (QString file : m_GamePlugin->iniFiles()) { if (!QFile::exists(m_Directory.filePath(file))) { - qWarning("missing %s in %s", qUtf8Printable(file), qUtf8Printable(m_Directory.path())); + log::warn("missing {} in {}", file, m_Directory.path()); missingFiles << file; } } diff --git a/src/profilesdialog.cpp b/src/profilesdialog.cpp index f9ea655f..d7863fc8 100644 --- a/src/profilesdialog.cpp +++ b/src/profilesdialog.cpp @@ -214,9 +214,9 @@ void ProfilesDialog::on_removeProfileButton_clicked() delete item; } if (!shellDelete(QStringList(profilePath))) { - qWarning("Failed to shell-delete \"%s\" (errorcode %lu), trying regular delete", qUtf8Printable(profilePath), ::GetLastError()); + log::warn("Failed to shell-delete \"{}\" (errorcode {}), trying regular delete", profilePath, ::GetLastError()); if (!removeDir(profilePath)) { - qWarning("regular delete failed too"); + log::warn("regular delete failed too"); } } } diff --git a/src/settings.cpp b/src/settings.cpp index e622d632..92ae2251 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -165,8 +165,9 @@ void Settings::registerPlugin(IPlugin *plugin) for (const PluginSetting &setting : plugin->settings()) { QVariant temp = m_Settings.value("Plugins/" + plugin->name() + "/" + setting.key, setting.defaultValue); if (!temp.convert(setting.defaultValue.type())) { - qWarning("failed to interpret \"%s\" as correct type for \"%s\" in plugin \"%s\", using default", - qUtf8Printable(temp.toString()), qUtf8Printable(setting.key), qUtf8Printable(plugin->name())); + 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; -- cgit v1.3.1 From e071dfdfaa369a475a2d93df623c1696feee56ba Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Fri, 19 Jul 2019 02:47:13 -0400 Subject: changed qCritical() to log::error() removed now unused vlog() --- src/browserdialog.cpp | 12 ++++---- src/categories.cpp | 10 +++---- src/downloadlist.cpp | 5 ++-- src/downloadmanager.cpp | 10 +++++-- src/envmodule.cpp | 66 +++++++++++++++++------------------------- src/envsecurity.cpp | 58 +++++++++++++------------------------ src/envshortcut.cpp | 56 +++++++++++++++++------------------ src/envshortcut.h | 9 ------ src/envwindows.cpp | 19 ++++++------ src/executableslist.cpp | 10 +++---- src/filerenamer.cpp | 2 +- src/filterwidget.cpp | 5 +++- src/forcedloaddialogwidget.cpp | 9 +++--- src/installationmanager.cpp | 7 ++--- src/loglist.cpp | 18 ------------ src/mainwindow.cpp | 34 +++++++++++----------- src/moapplication.cpp | 10 ++++--- src/modinfo.cpp | 5 +--- src/modinfodialog.cpp | 12 ++++---- src/modinfodialogconflicts.cpp | 6 ++-- src/modinfodialogfiletree.cpp | 9 +++--- src/modinfodialogimages.cpp | 9 +++--- src/modinforegular.cpp | 20 ++++++------- src/modlist.cpp | 12 ++++---- src/modlistsortproxy.cpp | 2 +- src/nexusinterface.cpp | 28 +++++++++--------- src/organizercore.cpp | 22 +++++++------- src/overwriteinfodialog.cpp | 6 ++-- src/persistentcookiejar.cpp | 8 +++-- src/plugincontainer.cpp | 5 ++-- src/pluginlist.cpp | 10 +++---- src/profile.cpp | 4 +-- src/settings.cpp | 14 ++------- src/settingsdialog.cpp | 1 - src/shared/directoryentry.cpp | 23 ++++++++------- src/shared/error_report.h | 2 -- src/syncoverwritedialog.cpp | 3 +- src/texteditor.cpp | 7 +++-- src/transfersavesdialog.cpp | 13 ++++----- 39 files changed, 251 insertions(+), 310 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/browserdialog.cpp b/src/browserdialog.cpp index e186ad63..1fde7f15 100644 --- a/src/browserdialog.cpp +++ b/src/browserdialog.cpp @@ -24,9 +24,10 @@ along with Mod Organizer. If not, see . #include "messagedialog.h" #include "report.h" #include "persistentcookiejar.h" +#include "settings.h" #include -#include "settings.h" +#include #include #include @@ -38,6 +39,7 @@ along with Mod Organizer. If not, see . #include #include +using namespace MOBase; BrowserDialog::BrowserDialog(QWidget *parent) @@ -192,12 +194,12 @@ void BrowserDialog::unsupportedContent(QNetworkReply *reply) try { QWebEnginePage *page = qobject_cast(sender()); if (page == nullptr) { - qCritical("sender not a page"); + log::error("sender not a page"); return; } BrowserView *view = qobject_cast(page->view()); if (view == nullptr) { - qCritical("no view?"); + log::error("no view?"); return; } @@ -206,14 +208,14 @@ void BrowserDialog::unsupportedContent(QNetworkReply *reply) if (isVisible()) { MessageDialog::showMessage(tr("failed to start download"), this); } - qCritical("exception downloading unsupported content: %s", e.what()); + log::error("exception downloading unsupported content: {}", e.what()); } } void BrowserDialog::downloadRequested(const QNetworkRequest &request) { - qCritical("download request %s ignored", request.url().toString().toUtf8().constData()); + log::error("download request {} ignored", request.url().toString()); } diff --git a/src/categories.cpp b/src/categories.cpp index 8f9d3ad8..7acf6ff5 100644 --- a/src/categories.cpp +++ b/src/categories.cpp @@ -62,8 +62,9 @@ void CategoryFactory::loadCategories() ++lineNum; QList cells = line.split('|'); if (cells.count() != 4) { - qCritical("invalid category line %d: %s (%d cells)", - lineNum, line.constData(), cells.count()); + log::error( + "invalid category line {}: {} ({} cells)", + lineNum, line.constData(), cells.count()); } else { std::vector nexusIDs; if (cells[2].length() > 0) { @@ -73,7 +74,7 @@ void CategoryFactory::loadCategories() bool ok = false; int temp = iter->toInt(&ok); if (!ok) { - qCritical("invalid category id %s", iter->constData()); + log::error("invalid category id {}", iter->constData()); } nexusIDs.push_back(temp); } @@ -83,8 +84,7 @@ void CategoryFactory::loadCategories() int id = cells[0].toInt(&cell0Ok); int parentID = cells[3].trimmed().toInt(&cell3Ok); if (!cell0Ok || !cell3Ok) { - qCritical("invalid category line %d: %s", - lineNum, line.constData()); + log::error("invalid category line {}: {}", lineNum, line.constData()); } addCategory(id, QString::fromUtf8(cells[1].constData()), nexusIDs, parentID); } diff --git a/src/downloadlist.cpp b/src/downloadlist.cpp index 5e698e0e..36bc2b7f 100644 --- a/src/downloadlist.cpp +++ b/src/downloadlist.cpp @@ -19,12 +19,13 @@ along with Mod Organizer. If not, see . #include "downloadlist.h" #include "downloadmanager.h" +#include #include #include #include - #include +using namespace MOBase; DownloadList::DownloadList(DownloadManager *manager, QObject *parent) : QAbstractTableModel(parent), m_Manager(manager) @@ -192,7 +193,7 @@ void DownloadList::update(int row) else if (row < this->rowCount()) emit dataChanged(this->index(row, 0, QModelIndex()), this->index(row, this->columnCount(QModelIndex())-1, QModelIndex())); else - qCritical("invalid row %d in download list, update failed", row); + log::error("invalid row {} in download list, update failed", row); } QString DownloadList::sizeFormat(quint64 size) const diff --git a/src/downloadmanager.cpp b/src/downloadmanager.cpp index e3ceb261..348b2108 100644 --- a/src/downloadmanager.cpp +++ b/src/downloadmanager.cpp @@ -660,7 +660,7 @@ void DownloadManager::removeFile(int index, bool deleteFile) if ((download->m_State == STATE_STARTED) || (download->m_State == STATE_DOWNLOADING)) { // shouldn't have been possible - qCritical("tried to remove active download"); + log::error("tried to remove active download"); endDisableDirWatcher(); return; } @@ -798,7 +798,7 @@ void DownloadManager::removeDownload(int index, bool deleteFile) emit update(-1); endDisableDirWatcher(); } catch (const std::exception &e) { - qCritical("failed to remove download: %s", e.what()); + log::error("failed to remove download: {}", e.what()); } refreshList(); } @@ -2069,7 +2069,11 @@ void DownloadManager::writeData(DownloadInfo *info) if (ret < info->m_Reply->size()) { QString fileName = info->m_FileName; // m_FileName may be destroyed after setState setState(info, DownloadState::STATE_CANCELED); - qCritical(QString("Unable to write download \"%2\" to drive (return %1)").arg(ret).arg(info->m_FileName).toLocal8Bit()); + + log::error( + "Unable to write download \"{}\" to drive (return {})", + info->m_FileName, ret); + reportError(tr("Unable to write download to drive (return %1).\n" "Check the drive's available storage.\n\n" "Canceling download \"%2\"...").arg(ret).arg(fileName)); diff --git a/src/envmodule.cpp b/src/envmodule.cpp index 1717da15..aae4e0b1 100644 --- a/src/envmodule.cpp +++ b/src/envmodule.cpp @@ -1,6 +1,7 @@ #include "envmodule.h" #include "env.h" #include +#include namespace env { @@ -114,9 +115,9 @@ Module::FileInfo Module::getFileInfo() const return {}; } - qCritical().nospace().noquote() - << "GetFileVersionInfoSizeW() failed on '" << m_path << "', " - << formatSystemMessageQ(e); + log::error( + "GetFileVersionInfoSizeW() failed on '{}', {}", + m_path, formatSystemMessageQ(e)); return {}; } @@ -127,9 +128,9 @@ Module::FileInfo Module::getFileInfo() const if (!GetFileVersionInfoW(wspath.c_str(), 0, size, buffer.get())) { const auto e = GetLastError(); - qCritical().nospace().noquote() - << "GetFileVersionInfoW() failed on '" << m_path << "', " - << formatSystemMessageQ(e); + log::error( + "GetFileVersionInfoW() failed on '{}', {}", + m_path, formatSystemMessageQ(e)); return {}; } @@ -161,9 +162,9 @@ VS_FIXEDFILEINFO Module::getFixedFileInfo(std::byte* buffer) const // signature is always 0xfeef04bd if (fi->dwSignature != 0xfeef04bd) { - qCritical().nospace().noquote() - << "bad file info signature 0x" << hex << fi->dwSignature << " for " - << "'" << m_path << "'"; + log::error( + "bad file info signature {:#x} for '{}'", + fi->dwSignature, m_path); return {}; } @@ -187,9 +188,7 @@ QString Module::getFileDescription(std::byte* buffer) const buffer, L"\\VarFileInfo\\Translation", &valuePointer, &valueSize); if (!ret || !valuePointer || valueSize == 0) { - qCritical().nospace().noquote() - << "VerQueryValueW() for translations failed on '" << m_path << "'"; - + log::error("VerQueryValueW() for translations failed on '{}'", m_path); return {}; } @@ -254,9 +253,9 @@ QDateTime Module::getTimestamp(const VS_FIXEDFILEINFO& fi) const if (h.get() == INVALID_HANDLE_VALUE) { const auto e = GetLastError(); - qCritical().nospace().noquote() - << "can't open file '" << m_path << "' for timestamp, " - << formatSystemMessageQ(e); + log::error( + "can't open file '{}' for timestamp, {}", + m_path, formatSystemMessageQ(e)); return {}; } @@ -264,9 +263,10 @@ QDateTime Module::getTimestamp(const VS_FIXEDFILEINFO& fi) const // getting the file time if (!GetFileTime(h.get(), &ft, nullptr, nullptr)) { const auto e = GetLastError(); - qCritical().nospace().noquote() - << "can't get file time for '" << m_path << "', " - << formatSystemMessageQ(e); + + log::error( + "can't get file time for '{}', {}", + m_path, formatSystemMessageQ(e)); return {}; } @@ -281,11 +281,9 @@ QDateTime Module::getTimestamp(const VS_FIXEDFILEINFO& fi) const SYSTEMTIME utc = {}; if (!FileTimeToSystemTime(&ft, &utc)) { - qCritical().nospace().noquote() - << "FileTimeToSystemTime() failed on timestamp " - << "high=0x" << hex << ft.dwHighDateTime << " " - << "low=0x" << hex << ft.dwLowDateTime << " for " - << "'" << m_path << "'"; + log::error( + "FileTimeToSystemTime() failed on timestamp high={:#x} low={:#x} for '{}'", + ft.dwHighDateTime, ft.dwLowDateTime, m_path); return {}; } @@ -307,18 +305,14 @@ QString Module::getMD5() const QFile f(m_path); if (!f.open(QFile::ReadOnly)) { - qCritical().nospace().noquote() - << "failed to open file '" << m_path << "' for md5"; - + log::error("failed to open file '{}' for md5", m_path); return {}; } // hashing QCryptographicHash hash(QCryptographicHash::Md5); if (!hash.addData(&f)) { - qCritical().nospace().noquote() - << "failed to calculate md5 for '" << m_path << "'"; - + log::error("failed to calculate md5 for '{}'", m_path); return {}; } @@ -334,11 +328,7 @@ std::vector getLoadedModules() if (snapshot.get() == INVALID_HANDLE_VALUE) { const auto e = GetLastError(); - - qCritical().nospace().noquote() - << "CreateToolhelp32Snapshot() failed, " - << formatSystemMessageQ(e); - + log::error("CreateToolhelp32Snapshot() failed, {}", formatSystemMessageQ(e)); return {}; } @@ -349,10 +339,7 @@ std::vector getLoadedModules() if (!Module32First(snapshot.get(), &me)) { const auto e = GetLastError(); - - qCritical().nospace().noquote() - << "Module32First() failed, " << formatSystemMessageQ(e); - + log::error("Module32First() failed, {}", formatSystemMessageQ(e)); return {}; } @@ -371,8 +358,7 @@ std::vector getLoadedModules() // no more modules is not an error if (e != ERROR_NO_MORE_FILES) { - qCritical().nospace().noquote() - << "Module32Next() failed, " << formatSystemMessageQ(e); + log::error("Module32Next() failed, {}", formatSystemMessageQ(e)); } break; diff --git a/src/envsecurity.cpp b/src/envsecurity.cpp index 559ce4ad..015e4000 100644 --- a/src/envsecurity.cpp +++ b/src/envsecurity.cpp @@ -1,6 +1,7 @@ #include "envsecurity.h" #include "env.h" #include +#include #include #include @@ -57,8 +58,7 @@ public: } if (FAILED(ret)) { - qCritical() - << "enumerator->next() failed, " << formatSystemMessageQ(ret); + log::error("enum->next() failed, {}", formatSystemMessageQ(ret)); break; } @@ -82,9 +82,9 @@ private: IID_IWbemLocator, &rawLocator); if (FAILED(ret) || !rawLocator) { - qCritical() - << "CoCreateInstance for WbemLocator failed, " - << formatSystemMessageQ(ret); + log::error( + "CoCreateInstance for WbemLocator failed, {}", + formatSystemMessageQ(ret)); throw failed(); } @@ -102,10 +102,9 @@ private: &rawService); if (FAILED(res) || !rawService) { - qCritical() - << "locator->ConnectServer() failed for namespace " - << "'" << QString::fromStdString(ns) << "', " - << formatSystemMessageQ(res); + log::error( + "locator->ConnectServer() failed for namespace '{}', {}", + ns, formatSystemMessageQ(res)); throw failed(); } @@ -121,9 +120,7 @@ private: if (FAILED(ret)) { - qCritical() - << "CoSetProxyBlanket() failed, " << formatSystemMessageQ(ret); - + log::error("CoSetProxyBlanket() failed, {}", formatSystemMessageQ(ret)); throw failed(); } } @@ -142,10 +139,7 @@ private: if (FAILED(ret) || !rawEnumerator) { - qCritical() - << "query '" << QString::fromStdString(query) << "' failed, " - << formatSystemMessageQ(ret); - + log::error("query '{}' failed, {}", query, formatSystemMessageQ(ret)); return {}; } @@ -256,15 +250,12 @@ std::vector getSecurityProductsFromWMI() // display name auto ret = o->Get(L"displayName", 0, &prop, 0, 0); if (FAILED(ret)) { - qCritical() - << "failed to get displayName, " - << formatSystemMessageQ(ret); - + log::error("failed to get displayName, {}", formatSystemMessageQ(ret)); return; } if (prop.vt != VT_BSTR) { - qCritical() << "displayName is a " << prop.vt << ", not a bstr"; + log::error("displayName is a {}, not a bstr", prop.vt); return; } @@ -274,15 +265,12 @@ std::vector getSecurityProductsFromWMI() // product state ret = o->Get(L"productState", 0, &prop, 0, 0); if (FAILED(ret)) { - qCritical() - << "failed to get productState, " - << formatSystemMessageQ(ret); - + log::error("failed to get productState, {}", formatSystemMessageQ(ret)); return; } if (prop.vt != VT_UI4 && prop.vt != VT_I4) { - qCritical() << "productState is a " << prop.vt << ", is not a VT_UI4"; + log::error("productState is a {}, is not a VT_UI4", prop.vt); return; } @@ -298,15 +286,12 @@ std::vector getSecurityProductsFromWMI() // guid ret = o->Get(L"instanceGuid", 0, &prop, 0, 0); if (FAILED(ret)) { - qCritical() - << "failed to get instanceGuid, " - << formatSystemMessageQ(ret); - + log::error("failed to get instanceGuid, {}", formatSystemMessageQ(ret)); return; } if (prop.vt != VT_BSTR) { - qCritical() << "instanceGuid is a " << prop.vt << ", is not a bstr"; + log::error("instanceGuid is a {}, is not a bstr", prop.vt); return; } @@ -362,9 +347,9 @@ std::optional getWindowsFirewall() __uuidof(INetFwPolicy2), &rawPolicy); if (FAILED(hr) || !rawPolicy) { - qCritical() - << "CoCreateInstance for NetFwPolicy2 failed, " - << formatSystemMessageQ(hr); + log::error( + "CoCreateInstance for NetFwPolicy2 failed, {}", + formatSystemMessageQ(hr)); return {}; } @@ -378,10 +363,7 @@ std::optional getWindowsFirewall() hr = policy->get_FirewallEnabled(NET_FW_PROFILE2_PUBLIC, &enabledVariant); if (FAILED(hr)) { - qCritical() - << "get_FirewallEnabled failed, " - << formatSystemMessageQ(hr); - + log::error("get_FirewallEnabled failed, {}", formatSystemMessageQ(hr)); return {}; } } diff --git a/src/envshortcut.cpp b/src/envshortcut.cpp index 30ef4633..1deb9dad 100644 --- a/src/envshortcut.cpp +++ b/src/envshortcut.cpp @@ -3,6 +3,7 @@ #include "executableslist.h" #include "instancemanager.h" #include +#include namespace env { @@ -218,17 +219,24 @@ bool Shortcut::toggle(Locations loc) bool Shortcut::add(Locations loc) { - debug() - << "adding shortcut to " << toString(loc) << ":\n" - << " . name: '" << m_name << "'\n" - << " . target: '" << m_target << "'\n" - << " . arguments: '" << m_arguments << "'\n" - << " . description: '" << m_description << "'\n" - << " . icon: '" << m_icon << "' @ " << m_iconIndex << "\n" - << " . working directory: '" << m_workingDirectory << "'"; + log::debug( + "adding shortcut to {}:\n" + " . name: '{}'\n" + " . target: '{}'\n" + " . arguments: '{}'\n" + " . description: '{}'\n" + " . icon: '{}' @ {}\n" + " . working directory: '{}'", + toString(loc), + m_name, + m_target, + m_arguments, + m_description, + m_icon, m_iconIndex, + m_workingDirectory); if (m_target.isEmpty()) { - critical() << "target is empty"; + log::error("shortcut: target is empty"); return false; } @@ -237,7 +245,7 @@ bool Shortcut::add(Locations loc) return false; } - debug() << "shorcut file will be saved at '" << path << "'"; + log::debug("shorcut file will be saved at '{}'", path); try { @@ -255,7 +263,7 @@ bool Shortcut::add(Locations loc) } catch(ShellLinkException& e) { - critical() << e.what() << "\nshortcut file was not saved"; + log::error("{}\nshortcut file was not saved", e.what()); } return false; @@ -263,26 +271,26 @@ bool Shortcut::add(Locations loc) bool Shortcut::remove(Locations loc) { - debug() << "removing shortcut for '" << m_name << "' from " << toString(loc); + log::debug("removing shortcut for '{}' from {}", m_name, toString(loc)); const auto path = shortcutPath(loc); if (path.isEmpty()) { return false; } - debug() << "path to shortcut file is '" << path << "'"; + log::debug("path to shortcut file is '{}'", path); if (!QFile::exists(path)) { - critical() << "can't remove '" << path << "', file not found"; + log::error("can't remove shortcut '{}', file not found", path); return false; } if (!MOBase::shellDelete({path})) { const auto e = ::GetLastError(); - critical() - << "failed to remove '" << path << "', " - << formatSystemMessageQ(e); + log::error( + "failed to remove shortcut '{}', {}", + path, formatSystemMessageQ(e)); return false; } @@ -323,7 +331,7 @@ QString Shortcut::shortcutDirectory(Locations loc) const case None: default: - critical() << "bad location " << loc; + log::error("shortcut: bad location {}", loc); break; } } @@ -337,23 +345,13 @@ QString Shortcut::shortcutDirectory(Locations loc) const QString Shortcut::shortcutFilename() const { if (m_name.isEmpty()) { - critical() << "name is empty"; + log::error("shortcut name is empty"); return {}; } return m_name + ".lnk"; } -QDebug Shortcut::debug() const -{ - return qDebug().noquote().nospace() << "system shortcut: "; -} - -QDebug Shortcut::critical() const -{ - return qCritical().noquote().nospace() << "system shortcut: "; -} - QString toString(Shortcut::Locations loc) { diff --git a/src/envshortcut.h b/src/envshortcut.h index 904b3ab7..82eea191 100644 --- a/src/envshortcut.h +++ b/src/envshortcut.h @@ -84,15 +84,6 @@ private: int m_iconIndex; QString m_workingDirectory; - // returns a qCritical() logger with a prefix already logged - // - QDebug critical() const; - - // returns a qDebug() logger with a prefix already logged - // - QDebug debug() const; - - // returns the path where the shortcut file should be saved // QString shortcutPath(Locations loc) const; diff --git a/src/envwindows.cpp b/src/envwindows.cpp index 4fbd788a..8a98036a 100644 --- a/src/envwindows.cpp +++ b/src/envwindows.cpp @@ -1,6 +1,7 @@ #include "envwindows.h" #include "env.h" #include +#include namespace env { @@ -13,7 +14,7 @@ WindowsInfo::WindowsInfo() LibraryPtr ntdll(LoadLibraryW(L"ntdll.dll")); if (!ntdll) { - qCritical() << "failed to load ntdll.dll while getting version"; + log::error("failed to load ntdll.dll while getting version"); return; } else { m_reported = getReportedVersion(ntdll.get()); @@ -122,7 +123,7 @@ WindowsInfo::Version WindowsInfo::getReportedVersion(HINSTANCE ntdll) const GetProcAddress(ntdll, "RtlGetVersion")); if (!RtlGetVersion) { - qCritical() << "RtlGetVersion() not found in ntdll.dll"; + log::error("RtlGetVersion() not found in ntdll.dll"); return {}; } @@ -149,7 +150,7 @@ WindowsInfo::Version WindowsInfo::getRealVersion(HINSTANCE ntdll) const GetProcAddress(ntdll, "RtlGetNtVersionNumbers")); if (!RtlGetNtVersionNumbers) { - qCritical() << "RtlGetNtVersionNumbers not found in ntdll.dll"; + log::error("RtlGetNtVersionNumbers not found in ntdll.dll"); return {}; } @@ -207,9 +208,9 @@ std::optional WindowsInfo::getElevated() const if (!OpenProcessToken(GetCurrentProcess( ), TOKEN_QUERY, &rawToken)) { const auto e = GetLastError(); - qCritical() - << "while trying to check if process is elevated, " - << "OpenProcessToken() failed: " << formatSystemMessageQ(e); + log::error( + "while trying to check if process is elevated, " + "OpenProcessToken() failed: {}", formatSystemMessageQ(e)); return {}; } @@ -223,9 +224,9 @@ std::optional WindowsInfo::getElevated() const if (!GetTokenInformation(token.get(), TokenElevation, &e, sizeof(e), &size)) { const auto e = GetLastError(); - qCritical() - << "while trying to check if process is elevated, " - << "GetTokenInformation() failed: " << formatSystemMessageQ(e); + log::error( + "while trying to check if process is elevated, " + "GetTokenInformation() failed: {}", formatSystemMessageQ(e)); return {}; } diff --git a/src/executableslist.cpp b/src/executableslist.cpp index fbb96bd4..2408e8f3 100644 --- a/src/executableslist.cpp +++ b/src/executableslist.cpp @@ -243,9 +243,9 @@ void ExecutablesList::setExecutable(const Executable &exe, SetFlags flags) if (flags == MoveExisting) { const auto newTitle = makeNonConflictingTitle(exe.title()); if (!newTitle) { - qCritical().nospace() - << "executable '" << exe.title() << "' was in the way but could " - << "not be renamed"; + log::error( + "executable '{}' was in the way but could not be renamed", + exe.title()); return; } @@ -289,9 +289,7 @@ std::optional ExecutablesList::makeNonConflictingTitle( title = prefix + QString(" (%1)").arg(i); } - qCritical().nospace() - << "ran out of executable titles for prefix '" << prefix << "'"; - + log::error("ran out of executable titles for prefix '{}'", prefix); return {}; } diff --git a/src/filerenamer.cpp b/src/filerenamer.cpp index b516c902..8835f52f 100644 --- a/src/filerenamer.cpp +++ b/src/filerenamer.cpp @@ -10,7 +10,7 @@ FileRenamer::FileRenamer(QWidget* parent, QFlags flags) { // sanity check for flags if ((m_flags & (HIDE|UNHIDE)) == 0) { - qCritical("renameFile() missing hide flag"); + log::error("renameFile() missing hide flag"); // doesn't really matter, it's just for text m_flags = HIDE; } diff --git a/src/filterwidget.cpp b/src/filterwidget.cpp index 44cbb274..0638add3 100644 --- a/src/filterwidget.cpp +++ b/src/filterwidget.cpp @@ -1,5 +1,8 @@ #include "filterwidget.h" #include "eventfilter.h" +#include + +using namespace MOBase; FilterWidgetProxyModel::FilterWidgetProxyModel(FilterWidget& fw, QWidget* parent) : QSortFilterProxyModel(parent), m_filter(fw) @@ -80,7 +83,7 @@ QModelIndex FilterWidget::map(const QModelIndex& index) if (m_proxy) { return m_proxy->mapToSource(index); } else { - qCritical() << "FilterWidget::map() called, but proxy isn't set up"; + log::error("FilterWidget::map() called, but proxy isn't set up"); return index; } } diff --git a/src/forcedloaddialogwidget.cpp b/src/forcedloaddialogwidget.cpp index b92838c3..b84f785f 100644 --- a/src/forcedloaddialogwidget.cpp +++ b/src/forcedloaddialogwidget.cpp @@ -1,9 +1,8 @@ #include "forcedloaddialogwidget.h" #include "ui_forcedloaddialogwidget.h" - -#include - #include "executableinfo.h" +#include +#include using namespace MOBase; @@ -85,7 +84,7 @@ void ForcedLoadDialogWidget::on_libraryPathBrowseButton_clicked() if (fileInfo.exists()) { ui->libraryPathEdit->setText(filePath); } else { - qCritical("%ls does not exist", filePath.toStdWString().c_str()); + log::error("{} does not exist", filePath); } } } @@ -102,7 +101,7 @@ void ForcedLoadDialogWidget::on_processBrowseButton_clicked() if (fileInfo.exists()) { ui->processEdit->setText(fileName); } else { - qCritical("%ls does not exist", fileInfo.filePath().toStdWString().c_str()); + log::error("{} does not exist", fileInfo.filePath()); } } } diff --git a/src/installationmanager.cpp b/src/installationmanager.cpp index 0e50de52..fd971f47 100644 --- a/src/installationmanager.cpp +++ b/src/installationmanager.cpp @@ -263,7 +263,7 @@ QStringList InstallationManager::extractFiles(const QStringList &filesOrig, bool targetFile = wcsrchr(origFile/*data[i]->getFileName()*/, '/'); } if (targetFile == nullptr) { - qCritical() << "Failed to find backslash in " << data[i]->getFileName(); + log::error("Failed to find backslash in {}", data[i]->getFileName()); continue; } else { // skip the slash @@ -527,7 +527,7 @@ bool InstallationManager::testOverwrite(GuessedValue &modName, bool *me settingsFile.write(originalSettings); settingsFile.close(); } else { - qCritical("failed to restore original settings: %s", qUtf8Printable(metaFilename)); + log::error("failed to restore original settings: {}", metaFilename); } return true; } else if (overwriteDialog.action() == QueryOverwriteDialog::ACT_MERGE) { @@ -856,8 +856,7 @@ bool InstallationManager::install(const QString &fileName, } } } catch (const IncompatibilityException &e) { - qCritical("plugin \"%s\" incompatible: %s", - qUtf8Printable(installer->name()), e.what()); + log::error("plugin \"{}\" incompatible: {}", installer->name(), e.what()); } // act upon the installation result. at this point the files have already been diff --git a/src/loglist.cpp b/src/loglist.cpp index 207f412b..c34ac76e 100644 --- a/src/loglist.cpp +++ b/src/loglist.cpp @@ -196,21 +196,3 @@ void LogList::copyToClipboard() QApplication::clipboard()->setText(QString::fromStdString(s)); } - - -void vlog(const char *format, ...) -{ - va_list argList; - va_start(argList, format); - - static const int BUFFERSIZE = 1000; - - char buffer[BUFFERSIZE + 1]; - buffer[BUFFERSIZE] = '\0'; - - vsnprintf(buffer, BUFFERSIZE, format, argList); - - qCritical("%s", buffer); - - va_end(argList); -} diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 70ace8f1..ad87ba03 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -1212,14 +1212,14 @@ void MainWindow::createHelpMenu() QFile file(dirIter.filePath()); if (!file.open(QIODevice::ReadOnly)) { - qCritical() << "Failed to open " << fileName; + log::error("Failed to open {}", fileName); continue; } QString firstLine = QString::fromUtf8(file.readLine()); if (firstLine.startsWith("//TL")) { QStringList params = firstLine.mid(4).trimmed().split('#'); if (params.size() != 2) { - qCritical() << "invalid header line for tutorial " << fileName << " expected 2 parameters"; + log::error("invalid header line for tutorial {}, expected 2 parameters", fileName); continue; } QAction *tutAction = new QAction(params.at(0), tutorialMenu); @@ -1323,7 +1323,7 @@ void MainWindow::hookUpWindowTutorials() QString fileName = dirIter.fileName(); QFile file(dirIter.filePath()); if (!file.open(QIODevice::ReadOnly)) { - qCritical() << "Failed to open " << fileName; + log::error("Failed to open {}", fileName); continue; } QString firstLine = QString::fromUtf8(file.readLine()); @@ -1369,7 +1369,7 @@ void MainWindow::showEvent(QShowEvent *event) TutorialManager::instance().activateTutorial("MainWindow", firstStepsTutorial); } } else { - qCritical() << firstStepsTutorial << " missing"; + log::error("{} missing", firstStepsTutorial); QPoint pos = ui->toolBar->mapToGlobal(QPoint()); pos.rx() += ui->toolBar->width() / 2; pos.ry() += ui->toolBar->height(); @@ -1636,7 +1636,7 @@ void MainWindow::startExeAction() QAction *action = qobject_cast(sender()); if (action == nullptr) { - qCritical("not an action?"); + log::error("not an action?"); return; } @@ -3415,7 +3415,7 @@ void MainWindow::displayModInformation(const QString &modName, ModInfoTabIDs tab { unsigned int index = ModInfo::getIndex(modName); if (index == UINT_MAX) { - qCritical("failed to resolve mod name %s", qUtf8Printable(modName)); + log::error("failed to resolve mod name {}", modName); return; } @@ -3500,7 +3500,7 @@ void MainWindow::visitOnNexus_clicked() if (modID > 0) { linkClicked(NexusInterface::instance(&m_PluginContainer)->getModURL(modID, gameName)); } else { - qCritical() << "mod '" << info->name() << "' has no nexus id"; + log::error("mod '{}' has no nexus id", info->name()); } } } @@ -4038,7 +4038,7 @@ void MainWindow::doMoveOverwriteContentToMod(const QString &modAbsolutePath) MessageDialog::showMessage(tr("Move successful."), this); } else { - qCritical("Move operation failed: %s", qUtf8Printable(windowsErrorString(::GetLastError()))); + log::error("Move operation failed: {}", windowsErrorString(::GetLastError())); } m_OrganizerCore.refreshModList(); @@ -4067,7 +4067,7 @@ void MainWindow::clearOverwrite() updateProblemsButton(); m_OrganizerCore.refreshModList(); } else { - qCritical("Delete operation failed: %s", qUtf8Printable(windowsErrorString(::GetLastError()))); + log::error("Delete operation failed: {}", windowsErrorString(::GetLastError())); } } } @@ -4311,7 +4311,7 @@ void MainWindow::addRemoveCategoriesFromMenu(QMenu *menu, int modRow, int refere void MainWindow::addRemoveCategories_MenuHandler() { QMenu *menu = qobject_cast(sender()); if (menu == nullptr) { - qCritical("not a menu?"); + log::error("not a menu?"); return; } @@ -4352,7 +4352,7 @@ void MainWindow::addRemoveCategories_MenuHandler() { void MainWindow::replaceCategories_MenuHandler() { QMenu *menu = qobject_cast(sender()); if (menu == nullptr) { - qCritical("not a menu?"); + log::error("not a menu?"); return; } @@ -4547,7 +4547,7 @@ void MainWindow::addPrimaryCategoryCandidates(QMenu *primaryCategoryMenu, categoryBox->setChecked(categoryID == info->getPrimaryCategory()); action->setDefaultWidget(categoryBox); } catch (const std::exception &e) { - qCritical("failed to create category checkbox: %s", e.what()); + log::error("failed to create category checkbox: {}", e.what()); } action->setData(categoryID); @@ -4559,7 +4559,7 @@ void MainWindow::addPrimaryCategoryCandidates() { QMenu *menu = qobject_cast(sender()); if (menu == nullptr) { - qCritical("not a menu?"); + log::error("not a menu?"); return; } menu->clear(); @@ -6067,7 +6067,7 @@ void MainWindow::nxmEndorsementToggled(QString, int, QVariant, QVariant resultDa toggleMO2EndorseState(); if (!disconnect(sender(), SIGNAL(nxmEndorsementToggled(QString, int, QVariant, QVariant, int)), this, SLOT(nxmEndorsementToggled(QString, int, QVariant, QVariant, int)))) { - qCritical("failed to disconnect endorsement slot"); + log::error("failed to disconnect endorsement slot"); } } @@ -6527,11 +6527,11 @@ void MainWindow::createStdoutPipe(HANDLE *stdOutRead, HANDLE *stdOutWrite) secAttributes.lpSecurityDescriptor = nullptr; if (!::CreatePipe(stdOutRead, stdOutWrite, &secAttributes, 0)) { - qCritical("failed to create stdout reroute"); + log::error("failed to create stdout reroute"); } if (!::SetHandleInformation(*stdOutRead, HANDLE_FLAG_INHERIT, 0)) { - qCritical("failed to correctly set up the stdout reroute"); + log::error("failed to correctly set up the stdout reroute"); *stdOutWrite = *stdOutRead = INVALID_HANDLE_VALUE; } } @@ -6965,7 +6965,7 @@ void MainWindow::dropLocalFile(const QUrl &url, const QString &outputDir, bool m success = shellCopy(file.absoluteFilePath(), target, true, this); } if (!success) { - qCritical("file operation failed: %s", qUtf8Printable(windowsErrorString(::GetLastError()))); + log::error("file operation failed: {}", windowsErrorString(::GetLastError())); } } diff --git a/src/moapplication.cpp b/src/moapplication.cpp index 3d55b28d..370a23b5 100644 --- a/src/moapplication.cpp +++ b/src/moapplication.cpp @@ -115,13 +115,15 @@ bool MOApplication::notify(QObject *receiver, QEvent *event) try { return QApplication::notify(receiver, event); } catch (const std::exception &e) { - qCritical("uncaught exception in handler (object %s, eventtype %d): %s", - receiver->objectName().toUtf8().constData(), event->type(), e.what()); + log::error( + "uncaught exception in handler (object {}, eventtype {}): {}", + receiver->objectName(), event->type(), e.what()); reportError(tr("an error occurred: %1").arg(e.what())); return false; } catch (...) { - qCritical("uncaught non-std exception in handler (object %s, eventtype %d)", - receiver->objectName().toUtf8().constData(), event->type()); + log::error( + "uncaught non-std exception in handler (object {}, eventtype {})", + receiver->objectName(), event->type()); reportError(tr("an error occurred")); return false; } diff --git a/src/modinfo.cpp b/src/modinfo.cpp index ca6e8046..5a05e7ca 100644 --- a/src/modinfo.cpp +++ b/src/modinfo.cpp @@ -530,10 +530,7 @@ QUrl ModInfo::parseCustomURL() const const auto url = QUrl::fromUserInput(getCustomURL()); if (!url.isValid()) { - qCritical() - << "mod '" << name() << "' has an invalid custom url " - << "'" << getCustomURL() << "'"; - + log::error("mod '{}' has an invalid custom url '{}'", name(), getCustomURL()); return {}; } diff --git a/src/modinfodialog.cpp b/src/modinfodialog.cpp index 47ac84be..a7a6b0d7 100644 --- a/src/modinfodialog.cpp +++ b/src/modinfodialog.cpp @@ -176,7 +176,7 @@ void ModInfoDialog::createTabs() // check for tabs in the ui not having a corresponding tab in the list int count = ui->tabWidget->count(); if (count < 0 || count > static_cast(m_tabs.size())) { - qCritical() << "mod info dialog has more tabs than expected"; + log::error("mod info dialog has more tabs than expected"); count = static_cast(m_tabs.size()); } @@ -239,13 +239,13 @@ void ModInfoDialog::setMod(const QString& name) { unsigned int index = ModInfo::getIndex(name); if (index == UINT_MAX) { - qCritical() << "failed to resolve mod name " << name; + log::error("failed to resolve mod name {}", name); return; } auto mod = ModInfo::getByIndex(index); if (!mod) { - qCritical() << "mod by index " << index << " is null"; + log::error("mod by index {} is null", index); return; } @@ -307,7 +307,7 @@ void ModInfoDialog::update(bool firstTime) // changed tabInfo->tab->activated(); } else { - qCritical() << "tab index " << oldTab << " not found"; + log::error("tab index {} not found", oldTab); } } } @@ -400,7 +400,7 @@ void ModInfoDialog::reAddTabs( if (itor == orderedNames.end()) { // this shouldn't happen, it means there's a tab in the UI that's no // in the list - qCritical() << "can't sort tabs, '" << objectName << "' not found"; + log::error("can't sort tabs, '{}' not found", objectName); canSort = false; } } @@ -753,7 +753,7 @@ void ModInfoDialog::onTabMoved() } if (!found) { - qCritical() << "unknown tab at index " << i; + log::error("unknown tab at index {}", i); } } } diff --git a/src/modinfodialogconflicts.cpp b/src/modinfodialogconflicts.cpp index 511d48ad..d16d548c 100644 --- a/src/modinfodialogconflicts.cpp +++ b/src/modinfodialogconflicts.cpp @@ -365,7 +365,7 @@ void for_each_in_selection(QTreeView* tree, F&& f) const auto* model = dynamic_cast(tree->model()); if (!model) { - qCritical() << "tree doesn't have a ConflictListModel"; + log::error("tree doesn't have a ConflictListModel"); return; } @@ -454,7 +454,7 @@ void ConflictsTab::changeItemsVisibility(QTreeView* tree, bool visible) auto* model = dynamic_cast(tree->model()); if (!model) { - qCritical() << "list doesn't have a ConflictListModel"; + log::error("list doesn't have a ConflictListModel"); return; } @@ -633,7 +633,7 @@ ConflictsTab::Actions ConflictsTab::createMenuActions(QTreeView* tree) const auto* model = dynamic_cast(tree->model()); if (!model) { - qCritical() << "tree doesn't have a ConflictListModel"; + log::error("tree doesn't have a ConflictListModel"); return {}; } diff --git a/src/modinfodialogfiletree.cpp b/src/modinfodialogfiletree.cpp index 0b519932..219ddf35 100644 --- a/src/modinfodialogfiletree.cpp +++ b/src/modinfodialogfiletree.cpp @@ -5,8 +5,9 @@ #include "filerenamer.h" #include #include +#include -using MOBase::reportError; +using namespace MOBase; namespace shell = MOBase::shell; // if there are more than 50 selected items in the filetree, don't bother @@ -230,19 +231,19 @@ bool FileTreeTab::deleteFileRecursive(const QModelIndex& parent) if (m_fs->isDir(index)) { if (!deleteFileRecursive(index)) { - qCritical() << "failed to delete" << m_fs->fileName(index); + log::error("failed to delete {}", m_fs->fileName(index)); return false; } } else { if (!m_fs->remove(index)) { - qCritical() << "failed to delete", m_fs->fileName(index); + log::error("failed to delete {}", m_fs->fileName(index)); return false; } } } if (!m_fs->remove(parent)) { - qCritical() << "failed to delete" << m_fs->fileName(parent); + log::error("failed to delete {}", m_fs->fileName(parent)); return false; } diff --git a/src/modinfodialogimages.cpp b/src/modinfodialogimages.cpp index 69866902..10362058 100644 --- a/src/modinfodialogimages.cpp +++ b/src/modinfodialogimages.cpp @@ -2,7 +2,9 @@ #include "ui_modinfodialog.h" #include "settings.h" #include "utility.h" +#include +using namespace MOBase; using namespace ImagesTabHelpers; QSize resizeWithAspectRatio(const QSize& original, const QSize& available) @@ -896,10 +898,9 @@ void File::ensureOriginalLoaded() QImageReader reader(m_path); if (!reader.read(&m_original)) { - qCritical().noquote().nospace() - << "failed to load '" << m_path << "'\n" - << reader.errorString() << " " - << "(error " << static_cast(reader.error()) << ")"; + log::error( + "failed to load '{}'\n{} (error {})", + m_path, reader.errorString(), static_cast(reader.error())); m_failed = true; } diff --git a/src/modinforegular.cpp b/src/modinforegular.cpp index 448447e1..074fa9e2 100644 --- a/src/modinforegular.cpp +++ b/src/modinforegular.cpp @@ -68,8 +68,7 @@ ModInfoRegular::~ModInfoRegular() try { saveMeta(); } catch (const std::exception &e) { - qCritical("failed to save meta information for \"%s\": %s", - qUtf8Printable(m_Name), e.what()); + log::error("failed to save meta information for \"{}\": {}", m_Name, e.what()); } } @@ -258,14 +257,14 @@ void ModInfoRegular::saveMeta() if (metaFile.status() == QSettings::NoError) { m_MetaInfoChanged = false; } else { - qCritical() - << QString("failed to write %1/meta.ini: error %2") - .arg(absolutePath()).arg(metaFile.status()); + log::error( + "failed to write {}/meta.ini: error {}", + absolutePath(), metaFile.status()); } } else { - qCritical() - << QString("failed to write %1/meta.ini: error %2") - .arg(absolutePath()).arg(metaFile.status()); + log::error( + "failed to write {}/meta.ini: error {}", + absolutePath(), metaFile.status()); } } } @@ -425,14 +424,13 @@ bool ModInfoRegular::setName(const QString &name) return false; } if (!modDir.rename(tempName, name)) { - qCritical("rename to final name failed after successful rename to intermediate name"); + log::error("rename to final name failed after successful rename to intermediate name"); modDir.rename(tempName, m_Name); return false; } } else { if (!shellRename(modDir.absoluteFilePath(m_Name), modDir.absoluteFilePath(name))) { - qCritical("failed to rename mod %s (errorcode %d)", - qUtf8Printable(name), ::GetLastError()); + log::error("failed to rename mod {} (errorcode {})", name, ::GetLastError()); return false; } } diff --git a/src/modlist.cpp b/src/modlist.cpp index df25df0d..6ebd0e8b 100644 --- a/src/modlist.cpp +++ b/src/modlist.cpp @@ -271,7 +271,7 @@ QVariant ModList::data(const QModelIndex &modelIndex, int role) const int categoryIdx = categoryFactory.getCategoryIndex(category); return categoryFactory.getCategoryName(categoryIdx); } catch (const std::exception &e) { - qCritical("failed to retrieve category name: %s", e.what()); + log::error("failed to retrieve category name: {}", e.what()); return QString(); } } else { @@ -449,7 +449,7 @@ QVariant ModList::data(const QModelIndex &modelIndex, int role) const try { return modInfo->getDescription(); } catch (const std::exception &e) { - qCritical("invalid mod description: %s", e.what()); + log::error("invalid mod description: {}", e.what()); return QString(); } } else if (column == COL_VERSION) { @@ -488,7 +488,7 @@ QVariant ModList::data(const QModelIndex &modelIndex, int role) const try { categoryString << "" << ToWString(categoryFactory.getCategoryName(categoryFactory.getCategoryIndex(*catIter))) << ""; } catch (const std::exception &e) { - qCritical("failed to generate tooltip: %s", e.what()); + log::error("failed to generate tooltip: {}", e.what()); return QString(); } } @@ -636,9 +636,9 @@ bool ModList::setData(const QModelIndex &index, const QVariant &value, int role) try { m_ModStateChanged(info->name(), newState); } catch (const std::exception &e) { - qCritical("failed to invoke state changed notification: %s", e.what()); + log::error("failed to invoke state changed notification: {}", e.what()); } catch (...) { - qCritical("failed to invoke state changed notification: unknown exception"); + log::error("failed to invoke state changed notification: unknown exception"); } } @@ -834,7 +834,7 @@ void ModList::modInfoChanged(ModInfo::Ptr info) emit dataChanged(index(row, 0), index(row, columnCount())); emit postDataChanged(); } else { - qCritical("modInfoChanged not called after modInfoAboutToChange"); + log::error("modInfoChanged not called after modInfoAboutToChange"); } m_ChangeInfo.name = QString(); } diff --git a/src/modlistsortproxy.cpp b/src/modlistsortproxy.cpp index 1127c7d4..d330e0c2 100644 --- a/src/modlistsortproxy.cpp +++ b/src/modlistsortproxy.cpp @@ -196,7 +196,7 @@ bool ModListSortProxy::lessThan(const QModelIndex &left, QString rightCatName = categories.getCategoryName(categories.getCategoryIndex(rightMod->getPrimaryCategory())); lt = leftCatName < rightCatName; } catch (const std::exception &e) { - qCritical("failed to compare categories: %s", e.what()); + log::error("failed to compare categories: {}", e.what()); } } } diff --git a/src/nexusinterface.cpp b/src/nexusinterface.cpp index 008f3c0d..c797aed6 100644 --- a/src/nexusinterface.cpp +++ b/src/nexusinterface.cpp @@ -41,12 +41,11 @@ using namespace MOShared; void throttledWarning(const APIUserAccount& user) { - qCritical() << - QString( - "You have fewer than %1 requests remaining (%2). Only downloads and " - "login validation are being allowed.") - .arg(APIUserAccount::ThrottleThreshold) - .arg(user.remainingRequests()); + log::error( + "You have fewer than {} requests remaining ({}). Only downloads and " + "login validation are being allowed.", + APIUserAccount::ThrottleThreshold, + user.remainingRequests()); } @@ -344,7 +343,7 @@ QString NexusInterface::getGameURL(QString gameName) const if (game != nullptr) { return "https://www.nexusmods.com/" + game->gameNexusName().toLower(); } else { - qCritical("getGameURL can't find plugin for %s", qUtf8Printable(gameName)); + log::error("getGameURL can't find plugin for {}", gameName); return ""; } } @@ -355,7 +354,7 @@ QString NexusInterface::getOldModsURL(QString gameName) const if (game != nullptr) { return "https://" + game->gameNexusName().toLower() + ".nexusmods.com/mods"; } else { - qCritical("getOldModsURL can't find plugin for %s", qUtf8Printable(gameName)); + log::error("getOldModsURL can't find plugin for {}", gameName); return ""; } } @@ -464,7 +463,7 @@ int NexusInterface::requestUpdates(const int &modID, QObject *receiver, QVariant IPluginGame *game = getGame(gameName); if (game == nullptr) { - qCritical("requestUpdates can't find plugin for %s", qUtf8Printable(gameName)); + log::error("requestUpdates can't find plugin for {}", gameName); return -1; } @@ -521,7 +520,7 @@ int NexusInterface::requestFileInfo(QString gameName, int modID, int fileID, QOb { IPluginGame *gamePlugin = getGame(gameName); if (gamePlugin == nullptr) { - qCritical("requestFileInfo can't find plugin for %s", qUtf8Printable(gameName)); + log::error("requestFileInfo can't find plugin for {}", gameName); return -1; } @@ -687,7 +686,7 @@ void NexusInterface::nextRequest() } else if (getAccessManager()->validateWaiting()) { return; } else { - qCritical() << tr("You must authorize MO2 in Settings -> Nexus to use the Nexus API."); + log::error("{}", tr("You must authorize MO2 in Settings -> Nexus to use the Nexus API.")); } } @@ -949,10 +948,9 @@ void NexusInterface::requestError(QNetworkReply::NetworkError) return; } - qCritical("request (%s) error: %s (%d)", - qUtf8Printable(reply->url().toString()), - qUtf8Printable(reply->errorString()), - reply->error()); + log::error( + "request ({}) error: {} ({})", + reply->url().toString(), reply->errorString(), reply->error()); } diff --git a/src/organizercore.cpp b/src/organizercore.cpp index dbff1a2a..725371e9 100644 --- a/src/organizercore.cpp +++ b/src/organizercore.cpp @@ -224,7 +224,7 @@ bool checkService() } if (serviceConfig->dwStartType == SERVICE_DISABLED) { - qCritical("Windows Event Log service is disabled!"); + log::error("Windows Event Log service is disabled!"); serviceRunning = false; } @@ -242,7 +242,7 @@ bool checkService() } if (serviceStatus->dwCurrentState != SERVICE_RUNNING) { - qCritical("Windows Event Log service is not running"); + log::error("Windows Event Log service is not running"); serviceRunning = false; } } @@ -437,7 +437,7 @@ bool OrganizerCore::testForSteam(bool *found, bool *access) hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hProcessSnap == INVALID_HANDLE_VALUE) { lastError = GetLastError(); - qCritical("unable to get snapshot of processes (error %d)", lastError); + log::error("unable to get snapshot of processes (error {})", lastError); return false; } @@ -446,7 +446,7 @@ bool OrganizerCore::testForSteam(bool *found, bool *access) pe32.dwSize = sizeof(PROCESSENTRY32); if (!Process32First(hProcessSnap, &pe32)) { lastError = GetLastError(); - qCritical("unable to get first process (error %d)", lastError); + log::error("unable to get first process (error {})", lastError); CloseHandle(hProcessSnap); return false; } @@ -486,7 +486,7 @@ return true; void OrganizerCore::updateExecutablesList(QSettings &settings) { if (m_PluginContainer == nullptr) { - qCritical("can't update executables list now"); + log::error("can't update executables list now"); return; } @@ -657,7 +657,7 @@ void OrganizerCore::downloadRequested(QNetworkReply *reply, QString gameName, in } } catch (const std::exception &e) { MessageDialog::showMessage(tr("Download failed"), qApp->activeWindow()); - qCritical("exception starting download: %s", e.what()); + log::error("exception starting download: {}", e.what()); } } @@ -1552,7 +1552,7 @@ HANDLE OrganizerCore::spawnBinaryProcess(const QFileInfo &binary, bool steamFound = true; bool steamAccess = true; if (!testForSteam(&steamFound, &steamAccess)) { - qCritical("unable to determine state of Steam"); + log::error("unable to determine state of Steam"); } if (!steamFound) { @@ -1569,9 +1569,9 @@ HANDLE OrganizerCore::spawnBinaryProcess(const QFileInfo &binary, steamFound = true; steamAccess = true; if (!testForSteam(&steamFound, &steamAccess)) { - qCritical("unable to determine state of Steam"); + log::error("unable to determine state of Steam"); } else if (!steamFound) { - qCritical("could not find Steam"); + log::error("could not find Steam"); } } else if (result == QDialogButtonBox::Cancel) { @@ -1592,14 +1592,14 @@ HANDLE OrganizerCore::spawnBinaryProcess(const QFileInfo &binary, if (result == QDialogButtonBox::Yes) { WCHAR cwd[MAX_PATH]; if (!GetCurrentDirectory(MAX_PATH, cwd)) { - qCritical("unable to get current directory (error %d)", GetLastError()); + log::error("unable to get current directory (error {})", GetLastError()); cwd[0] = L'\0'; } if (!Helper::adminLaunch( qApp->applicationDirPath().toStdWString(), qApp->applicationFilePath().toStdWString(), std::wstring(cwd))) { - qCritical("unable to relaunch MO as admin"); + log::error("unable to relaunch MO as admin"); return INVALID_HANDLE_VALUE; } qApp->exit(0); diff --git a/src/overwriteinfodialog.cpp b/src/overwriteinfodialog.cpp index 5ee8d76c..cc4ae849 100644 --- a/src/overwriteinfodialog.cpp +++ b/src/overwriteinfodialog.cpp @@ -121,18 +121,18 @@ bool OverwriteInfoDialog::recursiveDelete(const QModelIndex &index) QModelIndex childIndex = m_FileSystemModel->index(childRow, 0, index); if (m_FileSystemModel->isDir(childIndex)) { if (!recursiveDelete(childIndex)) { - qCritical("failed to delete %s", m_FileSystemModel->fileName(childIndex).toUtf8().constData()); + log::error("failed to delete {}", m_FileSystemModel->fileName(childIndex)); return false; } } else { if (!m_FileSystemModel->remove(childIndex)) { - qCritical("failed to delete %s", m_FileSystemModel->fileName(childIndex).toUtf8().constData()); + log::error("failed to delete {}", m_FileSystemModel->fileName(childIndex)); return false; } } } if (!m_FileSystemModel->remove(index)) { - qCritical("failed to delete %s", m_FileSystemModel->fileName(index).toUtf8().constData()); + log::error("failed to delete {}", m_FileSystemModel->fileName(index)); return false; } return true; diff --git a/src/persistentcookiejar.cpp b/src/persistentcookiejar.cpp index 1ed463c6..670bf382 100644 --- a/src/persistentcookiejar.cpp +++ b/src/persistentcookiejar.cpp @@ -1,8 +1,10 @@ #include "persistentcookiejar.h" +#include #include #include #include +using namespace MOBase; PersistentCookieJar::PersistentCookieJar(const QString &fileName, QObject *parent) : QNetworkCookieJar(parent), m_FileName(fileName) @@ -24,7 +26,7 @@ void PersistentCookieJar::clear() { void PersistentCookieJar::save() { QTemporaryFile file; if (!file.open()) { - qCritical("failed to save cookies: couldn't create temporary file"); + log::error("failed to save cookies: couldn't create temporary file"); return; } QDataStream data(&file); @@ -40,14 +42,14 @@ void PersistentCookieJar::save() { QFile oldCookies(m_FileName); if (oldCookies.exists()) { if (!oldCookies.remove()) { - qCritical("failed to save cookies: failed to remove %s", qUtf8Printable(m_FileName)); + log::error("failed to save cookies: failed to remove {}", m_FileName); return; } } // if it doesn't exists that's fine } if (!file.copy(m_FileName)) { - qCritical("failed to save cookies: failed to write %s", qUtf8Printable(m_FileName)); + log::error("failed to save cookies: failed to write {}", m_FileName); } } diff --git a/src/plugincontainer.cpp b/src/plugincontainer.cpp index d47fa2c6..36daec52 100644 --- a/src/plugincontainer.cpp +++ b/src/plugincontainer.cpp @@ -291,8 +291,9 @@ void PluginContainer::loadPlugins() std::unique_ptr pluginLoader(new QPluginLoader(pluginName, this)); if (pluginLoader->instance() == nullptr) { m_FailedPlugins.push_back(pluginName); - qCritical("failed to load plugin %s: %s", - qUtf8Printable(pluginName), qUtf8Printable(pluginLoader->errorString())); + log::error( + "failed to load plugin {}: {}", + pluginName, pluginLoader->errorString()); } else { if (registerPlugin(pluginLoader->instance(), pluginName)) { qDebug("loaded plugin \"%s\"", qUtf8Printable(QFileInfo(pluginName).fileName())); diff --git a/src/pluginlist.cpp b/src/pluginlist.cpp index 2fb743d0..e436d7f6 100644 --- a/src/pluginlist.cpp +++ b/src/pluginlist.cpp @@ -309,7 +309,7 @@ int PluginList::findPluginByPriority(int priority) return i; } } - qCritical(QString("No plugin with priority %1").arg(priority).toLocal8Bit()); + log::error("No plugin with priority {}", priority); return -1; } @@ -824,7 +824,7 @@ void PluginList::updateIndices() continue; } if (m_ESPs[i].m_Priority >= static_cast(m_ESPs.size())) { - qCritical("invalid plugin priority: %d", m_ESPs[i].m_Priority); + log::error("invalid plugin priority: {}", m_ESPs[i].m_Priority); continue; } m_ESPsByName[m_ESPs[i].m_Name.toLower()] = i; @@ -1067,9 +1067,9 @@ bool PluginList::setData(const QModelIndex &modIndex, const QVariant &value, int this->index(0, 0), this->index(static_cast(m_ESPs.size()), columnCount())); } catch (const std::exception &e) { - qCritical("failed to invoke state changed notification: %s", e.what()); + log::error("failed to invoke state changed notification: {}", e.what()); } catch (...) { - qCritical("failed to invoke state changed notification: unknown exception"); + log::error("failed to invoke state changed notification: unknown exception"); } } @@ -1368,7 +1368,7 @@ PluginList::ESPInfo::ESPInfo(const QString &name, bool enabled, m_Masters.insert(QString(iter->c_str())); } } catch (const std::exception &e) { - qCritical("failed to parse plugin file %s: %s", qUtf8Printable(fullPath), e.what()); + log::error("failed to parse plugin file {}: {}", fullPath, e.what()); m_IsMaster = false; m_IsLight = false; m_IsLightFlagged = false; diff --git a/src/profile.cpp b/src/profile.cpp index d4778305..555de89a 100644 --- a/src/profile.cpp +++ b/src/profile.cpp @@ -572,7 +572,7 @@ void Profile::setModsEnabled(const QList &modsToEnable, const QLis QList dirtyMods; for (auto idx : modsToEnable) { if (idx >= m_ModStatus.size()) { - qCritical() << tr("invalid mod index: %1").arg(idx); + log::error("invalid mod index: {}", idx); continue; } if (!m_ModStatus[idx].m_Enabled) { @@ -582,7 +582,7 @@ void Profile::setModsEnabled(const QList &modsToEnable, const QLis } for (auto idx : modsToDisable) { if (idx >= m_ModStatus.size()) { - qCritical() << tr("invalid mod index: %1").arg(idx); + log::error("invalid mod index: {}", idx); continue; } if (ModInfo::getByIndex(idx)->alwaysEnabled()) { diff --git a/src/settings.cpp b/src/settings.cpp index 92ae2251..9c303442 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -221,9 +221,7 @@ QString Settings::deObfuscate(const QString key) } else { const auto e = GetLastError(); if (e != ERROR_NOT_FOUND) { - qCritical().nospace() - << "Retrieving encrypted data failed: " - << formatSystemMessageQ(e); + log::error("Retrieving encrypted data failed: {}", formatSystemMessageQ(e)); } } delete[] keyData; @@ -368,11 +366,7 @@ bool Settings::setNexusApiKey(const QString& apiKey) { if (!obfuscate("APIKEY", apiKey)) { const auto e = GetLastError(); - - qCritical().nospace() - << "Storing API key failed: " - << formatSystemMessageQ(e); - + log::error("Storing API key failed: {}", formatSystemMessageQ(e)); return false; } @@ -493,9 +487,7 @@ void Settings::setSteamLogin(QString username, QString password) } if (!obfuscate("steam_password", password)) { const auto e = GetLastError(); - qCritical().nospace() - << "Storing or deleting password failed: " - << formatSystemMessageQ(e); + log::error("Storing or deleting password failed: {}", formatSystemMessageQ(e)); } } diff --git a/src/settingsdialog.cpp b/src/settingsdialog.cpp index 0dae31ac..99943d04 100644 --- a/src/settingsdialog.cpp +++ b/src/settingsdialog.cpp @@ -485,7 +485,6 @@ void SettingsDialog::onValidatorStateChanged( for (auto&& line : log.split("\n")) { addNexusLog(line); } - } updateNexusState(); } diff --git a/src/shared/directoryentry.cpp b/src/shared/directoryentry.cpp index 9d9edd85..2cdbac74 100644 --- a/src/shared/directoryentry.cpp +++ b/src/shared/directoryentry.cpp @@ -21,6 +21,7 @@ along with Mod Organizer. If not, see . #include "windows_error.h" #include "leaktrace.h" #include "error_report.h" +#include #include #include #include @@ -35,6 +36,8 @@ along with Mod Organizer. If not, see . namespace MOShared { +namespace log = MOBase::log; + static const int MAXPATH_UNICODE = 32767; class OriginConnection { @@ -103,7 +106,7 @@ public: m_OriginsNameMap.erase(iter); m_OriginsNameMap[newName] = idx; } else { - vlog("failed to change name lookup from %ls to %ls", oldName.c_str(), newName.c_str()); + log::error("failed to change name lookup from {} to {}", oldName, newName); } } @@ -714,14 +717,14 @@ void DirectoryEntry::removeFile(FileEntry::Index index) if (iter != m_Files.end()) { m_Files.erase(iter); } else { - vlog("file \"%ls\" not in directory \"%ls\"", - m_FileRegister->getFile(index)->getName().c_str(), - this->getName().c_str()); + log::error( + "file \"{}\" not in directory \"{}\"", + m_FileRegister->getFile(index)->getName(), this->getName()); } } else { - vlog("file \"%ls\" not in directory \"%ls\", directory empty", - m_FileRegister->getFile(index)->getName().c_str(), - this->getName().c_str()); + log::error( + "file \"{}\" not in directory \"{}\", directory empty", + m_FileRegister->getFile(index)->getName(), this->getName()); } } @@ -844,7 +847,7 @@ const FileEntry::Ptr DirectoryEntry::searchFile(const std::wstring &path, const DirectoryEntry *temp = findSubDirectory(pathComponent); if (temp != nullptr) { if (len >= path.size()) { - vlog("unexpected end of path"); + log::error("unexpected end of path"); return FileEntry::Ptr(); } return temp->searchFile(path.substr(len + 1), directory); @@ -988,7 +991,7 @@ bool FileRegister::removeFile(FileEntry::Index index) m_Files.erase(index); return true; } else { - vlog("invalid file index for remove: %lu", index); + log::error("invalid file index for remove: {}", index); return false; } } @@ -1002,7 +1005,7 @@ void FileRegister::removeOrigin(FileEntry::Index index, int originID) m_Files.erase(iter); } } else { - vlog("invalid file index for remove (for origin): %lu", index); + log::error("invalid file index for remove (for origin): {}", index); } } diff --git a/src/shared/error_report.h b/src/shared/error_report.h index a003ee09..17b25645 100644 --- a/src/shared/error_report.h +++ b/src/shared/error_report.h @@ -30,5 +30,3 @@ void reportError(LPCSTR format, ...); void reportError(LPCWSTR format, ...); } // namespace MOShared - -void vlog(const char* format, ...); diff --git a/src/syncoverwritedialog.cpp b/src/syncoverwritedialog.cpp index 4ee4716e..b1643b2d 100644 --- a/src/syncoverwritedialog.cpp +++ b/src/syncoverwritedialog.cpp @@ -22,6 +22,7 @@ along with Mod Organizer. If not, see . #include "ui_syncoverwritedialog.h" #include #include +#include #include #include @@ -86,7 +87,7 @@ void SyncOverwriteDialog::readTree(const QString &path, DirectoryEntry *director if (subDir != nullptr) { readTree(fileInfo.absoluteFilePath(), subDir, newItem); } else { - qCritical("no directory structure for %s?", qUtf8Printable(file)); + log::error("no directory structure for {}?", file); delete newItem; newItem = nullptr; } diff --git a/src/texteditor.cpp b/src/texteditor.cpp index 130cd76f..0c0eb1cc 100644 --- a/src/texteditor.cpp +++ b/src/texteditor.cpp @@ -1,7 +1,10 @@ #include "texteditor.h" #include "utility.h" +#include #include +using namespace MOBase; + TextEditor::TextEditor(QWidget* parent) : QPlainTextEdit(parent), m_toolbar(nullptr), m_lineNumbers(nullptr), m_highlighter(nullptr), @@ -249,7 +252,7 @@ QWidget* TextEditor::wrapEditWidget() auto index = splitter->indexOf(this); if (index == -1) { - qCritical( + log::error( "TextEditor: cannot wrap edit widget to display a toolbar, " "parent is a splitter, but widget isn't in it"); @@ -260,7 +263,7 @@ QWidget* TextEditor::wrapEditWidget() } else { // unknown parent - qCritical( + log::error( "TextEditor: cannot wrap edit widget to display a toolbar, " "no parent or parent has no layout"); diff --git a/src/transfersavesdialog.cpp b/src/transfersavesdialog.cpp index 130df14f..1b211fd3 100644 --- a/src/transfersavesdialog.cpp +++ b/src/transfersavesdialog.cpp @@ -24,6 +24,7 @@ along with Mod Organizer. If not, see . #include "isavegame.h" #include "savegameinfo.h" #include +#include #include #include @@ -186,7 +187,7 @@ void TransferSavesDialog::on_moveToLocalBtn_clicked() [this](const QString &source, const QString &destination) -> bool { return shellMove(source, destination, this); }, - "Failed to move %s to %s")) { + "Failed to move {} to {}")) { refreshGlobalSaves(); refreshGlobalCharacters(); refreshLocalSaves(); @@ -203,7 +204,7 @@ void TransferSavesDialog::on_copyToLocalBtn_clicked() [this](const QString &source, const QString &destination) -> bool { return shellCopy(source, destination, this); }, - "Failed to copy %s to %s")) { + "Failed to copy {} to {}")) { refreshLocalSaves(); refreshLocalCharacters(); } @@ -218,7 +219,7 @@ void TransferSavesDialog::on_moveToGlobalBtn_clicked() [this](const QString &source, const QString &destination) -> bool { return shellMove(source, destination, this); }, - "Failed to move %s to %s")) { + "Failed to move {} to {}")) { refreshGlobalSaves(); refreshGlobalCharacters(); refreshLocalSaves(); @@ -235,7 +236,7 @@ void TransferSavesDialog::on_copyToGlobalBtn_clicked() [this](const QString &source, const QString &destination) -> bool { return shellCopy(source, destination, this); }, - "Failed to copy %s to %s")) { + "Failed to copy {} to {}")) { refreshGlobalSaves(); refreshGlobalCharacters(); } @@ -340,9 +341,7 @@ bool TransferSavesDialog::transferCharacters( } if (!method(sourceFile.absoluteFilePath(), destinationFile)) { - qCritical(errmsg, - sourceFile.absoluteFilePath().toUtf8().constData(), - qUtf8Printable(destinationFile)); + log::error(errmsg, sourceFile.absoluteFilePath(), destinationFile); } } } -- cgit v1.3.1 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/categories.cpp | 4 +- src/downloadlistwidget.cpp | 5 ++- src/downloadmanager.cpp | 35 ++++++++--------- src/executableslist.cpp | 4 +- src/filerenamer.cpp | 43 +++++++++++---------- src/installationmanager.cpp | 16 ++++---- src/instancemanager.cpp | 2 +- src/loadmechanism.cpp | 13 ++++--- src/mainwindow.cpp | 37 +++++++----------- src/messagedialog.cpp | 6 ++- src/modinfodialog.cpp | 4 +- src/modinfodialogconflicts.cpp | 24 ++++++++---- src/modinfodialogfiletree.cpp | 12 +++--- src/modinforegular.cpp | 5 ++- src/modlist.cpp | 7 ++-- src/modlistsortproxy.cpp | 2 +- src/nexusinterface.cpp | 8 ++-- src/nxmaccessmanager.cpp | 4 +- src/organizercore.cpp | 41 +++++++++++--------- src/persistentcookiejar.cpp | 2 +- src/plugincontainer.cpp | 14 +++---- src/pluginlist.cpp | 6 +-- src/profile.cpp | 16 ++++---- src/qtgroupingproxy.cpp | 87 +++++++++++++++++------------------------- src/selfupdater.cpp | 18 ++++----- src/settings.cpp | 7 ++-- src/usvfsconnector.cpp | 19 ++++----- 27 files changed, 213 insertions(+), 228 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/categories.cpp b/src/categories.cpp index 7acf6ff5..12b18998 100644 --- a/src/categories.cpp +++ b/src/categories.cpp @@ -360,10 +360,10 @@ unsigned int CategoryFactory::resolveNexusID(int nexusID) const { std::map::const_iterator iter = m_NexusMap.find(nexusID); if (iter != m_NexusMap.end()) { - qDebug("nexus category id %d maps to internal %d", nexusID, iter->second); + log::debug("nexus category id {} maps to internal {}", nexusID, iter->second); return iter->second; } else { - qDebug("nexus category id %d not mapped", nexusID); + log::debug("nexus category id {} not mapped", nexusID); return 0U; } } diff --git a/src/downloadlistwidget.cpp b/src/downloadlistwidget.cpp index e2a6f321..85d27831 100644 --- a/src/downloadlistwidget.cpp +++ b/src/downloadlistwidget.cpp @@ -19,6 +19,7 @@ along with Mod Organizer. If not, see . #include "downloadlist.h" #include "downloadlistwidget.h" +#include #include #include #include @@ -29,6 +30,8 @@ along with Mod Organizer. If not, see . #include #include +using namespace MOBase; + void DownloadProgressDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QModelIndex sourceIndex = m_SortProxy->mapToSource(index); @@ -286,7 +289,7 @@ void DownloadListWidget::issueDelete() void DownloadListWidget::issueRemoveFromView() { - qDebug() << "removing from view: " << m_ContextRow; + log::debug("removing from view: {}", m_ContextRow); emit removeDownload(m_ContextRow, false); } diff --git a/src/downloadmanager.cpp b/src/downloadmanager.cpp index 348b2108..d2556faa 100644 --- a/src/downloadmanager.cpp +++ b/src/downloadmanager.cpp @@ -352,7 +352,7 @@ void DownloadManager::refreshList() } } if (orphans.size() > 0) { - qDebug("%d orphaned meta files will be deleted", orphans.size()); + log::debug("{} orphaned meta files will be deleted", orphans.size()); shellDelete(orphans, true); } @@ -379,7 +379,7 @@ void DownloadManager::refreshList() } //if (m_ActiveDownloads.size() != downloadsBefore) { - qDebug("Downloads after refresh: %d", m_ActiveDownloads.size()); + log::debug("Downloads after refresh: {}", m_ActiveDownloads.size()); //} emit update(-1); @@ -401,7 +401,7 @@ bool DownloadManager::addDownload(const QStringList &URLs, QString gameName, } QUrl preferredUrl = QUrl::fromEncoded(URLs.first().toLocal8Bit()); - qDebug("selected download url: %s", qUtf8Printable(preferredUrl.toString())); + log::debug("selected download url: {}", preferredUrl.toString()); QNetworkRequest request(preferredUrl); request.setHeader(QNetworkRequest::UserAgentHeader, m_NexusInterface->getAccessManager()->userAgent()); return addDownload(m_NexusInterface->getAccessManager()->get(request), URLs, fileName, gameName, modID, fileID, fileInfo); @@ -562,9 +562,9 @@ void DownloadManager::addNXMDownload(const QString &url) break; } } - qDebug("add nxm download: %s", qUtf8Printable(url)); + log::debug("add nxm download: {}", url); if (foundGame == nullptr) { - qDebug("download requested for wrong game (game: %s, url: %s)", qUtf8Printable(m_ManagedGame->gameShortName()), qUtf8Printable(nxmInfo.game())); + log::debug("download requested for wrong game (game: {}, url: {})", m_ManagedGame->gameShortName(), nxmInfo.game()); QMessageBox::information(nullptr, tr("Wrong Game"), tr("The download link is for a mod for \"%1\" but this instance of MO " "has been set up for \"%2\".").arg(nxmInfo.game()).arg(m_ManagedGame->gameShortName()), QMessageBox::Ok); return; @@ -572,13 +572,14 @@ void DownloadManager::addNXMDownload(const QString &url) for (auto tuple : m_PendingDownloads) { if (std::get<0>(tuple).compare(foundGame->gameShortName(), Qt::CaseInsensitive) == 0, std::get<1>(tuple) == nxmInfo.modId() && std::get<2>(tuple) == nxmInfo.fileId()) { - QString debugStr("download requested is already queued (mod: %1, file: %2)"); - QString infoStr(tr("There is already a download queued for this file.\n\nMod %1\nFile %2")); + const auto infoStr = + tr("There is already a download queued for this file.\n\nMod %1\nFile %2") + .arg(nxmInfo.modId()).arg(nxmInfo.fileId()); - debugStr = debugStr.arg(nxmInfo.modId()).arg(nxmInfo.fileId()); - infoStr = infoStr.arg(nxmInfo.modId()).arg(nxmInfo.fileId()); + log::debug( + "download requested is already queued (mod: {}, file: {})", + nxmInfo.modId(), nxmInfo.fileId()); - qDebug(qUtf8Printable(debugStr)); QMessageBox::information(nullptr, tr("Already Queued"), infoStr, QMessageBox::Ok); return; } @@ -622,7 +623,7 @@ void DownloadManager::addNXMDownload(const QString &url) infoStr = infoStr.arg(QStringLiteral("")); } - qDebug(qUtf8Printable(debugStr)); + log::debug("{}", debugStr); QMessageBox::information(nullptr, tr("Already Started"), infoStr, QMessageBox::Ok); return; } @@ -883,7 +884,7 @@ void DownloadManager::resumeDownloadInt(int index) if (info->m_State == STATE_ERROR) { info->m_CurrentUrl = (info->m_CurrentUrl + 1) % info->m_Urls.count(); } - qDebug("request resume from url %s", qUtf8Printable(info->currentURL())); + log::debug("request resume from url {}", info->currentURL()); QNetworkRequest request(QUrl::fromEncoded(info->currentURL().toLocal8Bit())); request.setHeader(QNetworkRequest::UserAgentHeader, m_NexusInterface->getAccessManager()->userAgent()); if (info->m_State != STATE_ERROR) { @@ -896,7 +897,7 @@ void DownloadManager::resumeDownloadInt(int index) std::get<2>(info->m_SpeedDiff) = 0; std::get<3>(info->m_SpeedDiff) = 0; std::get<4>(info->m_SpeedDiff) = 0; - qDebug("resume at %lld bytes", info->m_ResumePos); + log::debug("resume at {} bytes", info->m_ResumePos); startDownload(m_NexusInterface->getAccessManager()->get(request), info, true); } emit update(index); @@ -993,11 +994,11 @@ void DownloadManager::queryInfoMd5(int index) downloadFile.setFileName(m_OrganizerCore->downloadsPath() + "\\" + info->m_FileName); } if (!downloadFile.exists()) { - qDebug("Can't find download file %s", info->m_FileName); + log::debug("Can't find download file {}", info->m_FileName); return; } if (!downloadFile.open(QIODevice::ReadOnly)) { - qDebug("Can't open download file %s", info->m_FileName); + log::debug("Can't open download file {}", info->m_FileName); return; } info->m_Hash = QCryptographicHash::hash(downloadFile.readAll(), QCryptographicHash::Md5); @@ -1384,7 +1385,7 @@ void DownloadManager::setState(DownloadManager::DownloadInfo *info, DownloadMana m_RequestIDs.insert(m_NexusInterface->requestFiles(info->m_FileInfo->gameName, info->m_FileInfo->modID, this, info->m_DownloadID, QString())); } break; case STATE_FETCHINGMODINFO_MD5: { - qDebug(qUtf8Printable(QString("Searching %1 for MD5 of %2").arg(info->m_GamesToQuery[0]).arg(QString(info->m_Hash.toHex())))); + log::debug("Searching {} for MD5 of {}", info->m_GamesToQuery[0], QString(info->m_Hash.toHex())); m_RequestIDs.insert(m_NexusInterface->requestInfoFromMd5(info->m_GamesToQuery[0], info->m_Hash, this, info->m_DownloadID, QString())); } break; case STATE_READY: { @@ -1780,7 +1781,7 @@ void DownloadManager::nxmFileInfoFromMd5Available(QString gameName, QVariant use if (chosenIdx < 0) { chosenIdx = i; //intentional to not break in order to check other results } else { - qDebug("Multiple active files found during MD5 search. Defaulting to time stamps..."); + log::debug("Multiple active files found during MD5 search. Defaulting to time stamps..."); chosenIdx = -1; break; } diff --git a/src/executableslist.cpp b/src/executableslist.cpp index 2408e8f3..3f76bb6f 100644 --- a/src/executableslist.cpp +++ b/src/executableslist.cpp @@ -166,7 +166,7 @@ std::vector ExecutablesList::getPluginExecutables( void ExecutablesList::resetFromPlugin(MOBase::IPluginGame const *game) { - qDebug("resetting plugin executables"); + log::debug("resetting plugin executables"); Q_ASSERT(game != nullptr); @@ -295,7 +295,7 @@ std::optional ExecutablesList::makeNonConflictingTitle( void ExecutablesList::upgradeFromCustom(MOBase::IPluginGame const *game) { - qDebug() << "upgrading executables list"; + log::debug("upgrading executables list"); Q_ASSERT(game != nullptr); diff --git a/src/filerenamer.cpp b/src/filerenamer.cpp index 8835f52f..a97d7742 100644 --- a/src/filerenamer.cpp +++ b/src/filerenamer.cpp @@ -18,10 +18,10 @@ FileRenamer::FileRenamer(QWidget* parent, QFlags flags) FileRenamer::RenameResults FileRenamer::rename(const QString& oldName, const QString& newName) { - qDebug().nospace() << "renaming " << oldName << " to " << newName; + log::debug("renaming {} to {}", oldName, newName); if (QFileInfo(newName).exists()) { - qDebug().nospace() << newName << " already exists"; + log::debug("{} already exists", newName); // target file already exists, confirm replacement auto answer = confirmReplace(newName); @@ -29,24 +29,25 @@ FileRenamer::RenameResults FileRenamer::rename(const QString& oldName, const QSt switch (answer) { case DECISION_SKIP: { // user wants to skip this file - qDebug().nospace() << "skipping " << oldName; + log::debug("skipping {}", oldName); return RESULT_SKIP; } case DECISION_REPLACE: { - qDebug().nospace() << "removing " << newName; + log::debug("removing {}", newName); + // user wants to replace the file, so remove it if (!QFile(newName).remove()) { log::warn("failed to remove '{}'", newName); // removal failed, warn the user and allow canceling if (!removeFailed(newName)) { - qDebug().nospace() << "canceling " << oldName; + log::debug("canceling {}", oldName); // user wants to cancel return RESULT_CANCEL; } // ignore this file and continue on - qDebug().nospace() << "skipping " << oldName; + log::debug("skipping {}", oldName); return RESULT_SKIP; } @@ -56,7 +57,7 @@ FileRenamer::RenameResults FileRenamer::rename(const QString& oldName, const QSt case DECISION_CANCEL: // fall-through default: { // user wants to stop - qDebug().nospace() << "canceling"; + log::debug("canceling"); return RESULT_CANCEL; } } @@ -70,17 +71,17 @@ FileRenamer::RenameResults FileRenamer::rename(const QString& oldName, const QSt // renaming failed, warn the user and allow canceling if (!renameFailed(oldName, newName)) { // user wants to cancel - qDebug().nospace() << "canceling"; + log::debug("canceling"); return RESULT_CANCEL; } // ignore this file and continue on - qDebug().nospace() << "skipping " << oldName; + log::debug("skipping {}", oldName); return RESULT_SKIP; } // everything worked - qDebug().nospace() << "successfully renamed " << oldName << " to " << newName; + log::debug("successfully renamed {} to {}", oldName, newName); return RESULT_OK; } @@ -88,12 +89,12 @@ FileRenamer::RenameDecision FileRenamer::confirmReplace(const QString& newName) { if (m_flags & REPLACE_ALL) { // user wants to silently replace all - qDebug().nospace() << "user has selected replace all"; + log::debug("user has selected replace all"); return DECISION_REPLACE; } else if (m_flags & REPLACE_NONE) { // user wants to silently skip all - qDebug().nospace() << "user has selected replace none"; + log::debug("user has selected replace none"); return DECISION_SKIP; } @@ -117,28 +118,28 @@ FileRenamer::RenameDecision FileRenamer::confirmReplace(const QString& newName) switch (answer) { case QMessageBox::Yes: - qDebug().nospace() << "user wants to replace"; + log::debug("user wants to replace"); return DECISION_REPLACE; case QMessageBox::No: - qDebug().nospace() << "user wants to skip"; + log::debug("user wants to skip"); return DECISION_SKIP; case QMessageBox::YesToAll: - qDebug().nospace() << "user wants to replace all"; + log::debug("user wants to replace all"); // remember the answer m_flags |= REPLACE_ALL; return DECISION_REPLACE; case QMessageBox::NoToAll: - qDebug().nospace() << "user wants to replace none"; + log::debug("user wants to replace none"); // remember the answer m_flags |= REPLACE_NONE; return DECISION_SKIP; case QMessageBox::Cancel: // fall-through default: - qDebug().nospace() << "user wants to cancel"; + log::debug("user wants to cancel"); return DECISION_CANCEL; } } @@ -158,12 +159,12 @@ bool FileRenamer::removeFailed(const QString& name) if (answer == QMessageBox::Cancel) { // user wants to stop - qDebug().nospace() << "user wants to cancel"; + log::debug("user wants to cancel"); return false; } // skip this one and continue - qDebug().nospace() << "user wants to skip"; + log::debug("user wants to skip"); return true; } @@ -182,11 +183,11 @@ bool FileRenamer::renameFailed(const QString& oldName, const QString& newName) if (answer == QMessageBox::Cancel) { // user wants to stop - qDebug().nospace() << "user wants to cancel"; + log::debug("user wants to cancel"); return false; } // skip this one and continue - qDebug().nospace() << "user wants to skip"; + log::debug("user wants to skip"); return true; } diff --git a/src/installationmanager.cpp b/src/installationmanager.cpp index fd971f47..89d0079f 100644 --- a/src/installationmanager.cpp +++ b/src/installationmanager.cpp @@ -398,7 +398,7 @@ bool InstallationManager::isSimpleArchiveTopLayer(const DirectoryTree::Node *nod for (DirectoryTree::const_node_iterator iter = node->nodesBegin(); iter != node->nodesEnd(); ++iter) { if ((bainStyle && InstallationTester::isTopLevelDirectoryBain((*iter)->getData().name)) || (!bainStyle && InstallationTester::isTopLevelDirectory((*iter)->getData().name))) { - qDebug("%s on the top level", (*iter)->getData().name.toUtf8().constData()); + log::debug("{} on the top level", (*iter)->getData().name.toQString()); return true; } } @@ -424,7 +424,7 @@ DirectoryTree::Node *InstallationManager::getSimpleArchiveBase(DirectoryTree *da (currentNode->numNodes() == 1)) { currentNode = *currentNode->nodesBegin(); } else { - qDebug("not a simple archive"); + log::debug("not a simple archive"); return nullptr; } } @@ -576,7 +576,7 @@ bool InstallationManager::doInstall(GuessedValue &modName, QString game QString targetDirectory = QDir(m_ModsDirectory + "/" + modName).canonicalPath(); QString targetDirectoryNative = QDir::toNativeSeparators(targetDirectory); - qDebug("installing to \"%s\"", qUtf8Printable(targetDirectoryNative)); + log::debug("installing to \"{}\"", targetDirectoryNative); m_InstallationProgress = new QProgressDialog(m_ParentWidget); ON_BLOCK_EXIT([this] () { @@ -764,7 +764,7 @@ bool InstallationManager::install(const QString &fileName, if ((modID == 0) && (guessedModID != -1)) { modID = guessedModID; } else if (modID != guessedModID) { - qDebug("passed mod id: %d, guessed id: %d", modID, guessedModID); + log::debug("passed mod id: {}, guessed id: {}", modID, guessedModID); } modName.update(guessedModName, GUESS_GOOD); @@ -774,7 +774,7 @@ bool InstallationManager::install(const QString &fileName, if (fileInfo.dir() == QDir(m_DownloadsDirectory)) { m_CurrentFile = fileInfo.fileName(); } - qDebug("using mod name \"%s\" (id %d) -> %s", qUtf8Printable(modName), modID, qUtf8Printable(m_CurrentFile)); + log::debug("using mod name \"{}\" (id {}) -> {}", QString(modName), modID, m_CurrentFile); //If there's an archive already open, close it. This happens with the bundle //installer when it uncompresses a split archive, then finds it has a real archive @@ -785,9 +785,9 @@ bool InstallationManager::install(const QString &fileName, bool archiveOpen = m_ArchiveHandler->open(fileName, new MethodCallback(this, &InstallationManager::queryPassword)); if (!archiveOpen) { - qDebug("integrated archiver can't open %s: %s (%d)", - qUtf8Printable(fileName), - qUtf8Printable(getErrorString(m_ArchiveHandler->getLastError())), + log::debug("integrated archiver can't open {}: {} ({})", + fileName, + getErrorString(m_ArchiveHandler->getLastError()), m_ArchiveHandler->getLastError()); } ON_BLOCK_EXIT(std::bind(&InstallationManager::postInstallCleanup, this)); diff --git a/src/instancemanager.cpp b/src/instancemanager.cpp index 55ef3fc8..fdc30e22 100644 --- a/src/instancemanager.cpp +++ b/src/instancemanager.cpp @@ -224,7 +224,7 @@ QString InstanceManager::chooseInstance(const QStringList &instanceList) const selection.setWindowFlags(selection.windowFlags() | Qt::WindowStaysOnTopHint); if (selection.exec() == QDialog::Rejected) { - qDebug("rejected"); + log::debug("rejected"); throw MOBase::MyException(QObject::tr("Canceled")); } 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; diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index ad87ba03..e502bdb1 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -867,7 +867,7 @@ void MainWindow::updatePinnedExecutables() exeAction->setStatusTip(exe.binaryInfo().filePath()); if (!connect(exeAction, SIGNAL(triggered()), this, SLOT(startExeAction()))) { - qDebug("failed to connect trigger?"); + log::debug("failed to connect trigger?"); } if (m_linksSeparator) { @@ -1711,7 +1711,7 @@ void MainWindow::on_profileBox_currentIndexChanged(int index) // ensure the new index is valid if (index < 0 || index >= ui->profileBox->count()) { - qDebug("invalid profile index, using last profile"); + log::debug("invalid profile index, using last profile"); ui->profileBox->setCurrentIndex(ui->profileBox->count() - 1); } @@ -2060,7 +2060,7 @@ void MainWindow::refreshSaveList() QDir savesDir = currentSavesDir(); savesDir.setNameFilters(filters); - qDebug("reading save games from %s", qUtf8Printable(savesDir.absolutePath())); + log::debug("reading save games from {}", savesDir.absolutePath()); QFileInfoList files = savesDir.entryInfoList(QDir::Files, QDir::Time); for (const QFileInfo &file : files) { @@ -2261,15 +2261,6 @@ void MainWindow::fixCategories() void MainWindow::setupNetworkProxy(bool activate) { QNetworkProxyFactory::setUseSystemConfiguration(activate); -/* QNetworkProxyQuery query(QUrl("http://www.google.com"), QNetworkProxyQuery::UrlRequest); - query.setProtocolTag("http"); - QList proxies = QNetworkProxyFactory::systemProxyForQuery(query); - if ((proxies.size() > 0) && (proxies.at(0).type() != QNetworkProxy::NoProxy)) { - qDebug("Using proxy: %s", qUtf8Printable(proxies.at(0).hostName())); - QNetworkProxy::setApplicationProxy(proxies[0]); - } else { - qDebug("Not using proxy"); - }*/ } @@ -2456,7 +2447,7 @@ void MainWindow::unlock() { //If you come through here with a null lock pointer, it's a bug! if (m_LockDialog == nullptr) { - qDebug("Unlocking main window when already unlocked"); + log::debug("Unlocking main window when already unlocked"); return; } --m_LockCount; @@ -3259,7 +3250,7 @@ void MainWindow::displayModInformation( ModInfo::Ptr modInfo, unsigned int modIndex, ModInfoTabIDs tabID) { if (!m_OrganizerCore.modList()->modInfoAboutToChange(modInfo)) { - qDebug("A different mod information dialog is open. If this is incorrect, please restart MO"); + log::debug("A different mod information dialog is open. If this is incorrect, please restart MO"); return; } std::vector flags = modInfo->getFlags(); @@ -4325,7 +4316,7 @@ void MainWindow::addRemoveCategories_MenuHandler() { int maxRow = -1; for (const QPersistentModelIndex &idx : selected) { - qDebug("change categories on: %s", qUtf8Printable(idx.data().toString())); + log::debug("change categories on: {}", idx.data().toString()); QModelIndex modIdx = mapToModel(m_OrganizerCore.modList(), idx); if (modIdx.row() != m_ContextIdx.row()) { addRemoveCategoriesFromMenu(menu, modIdx.row(), m_ContextIdx.row()); @@ -4407,7 +4398,7 @@ void MainWindow::saveArchiveList() } } if (archiveFile.commitIfDifferent(m_ArchiveListHash)) { - qDebug("%s saved", qUtf8Printable(QDir::toNativeSeparators(m_OrganizerCore.currentProfile()->getArchivesFileName()))); + log::debug("{} saved", QDir::toNativeSeparators(m_OrganizerCore.currentProfile()->getArchivesFileName())); } } else { log::warn("archive list not initialised"); @@ -5364,7 +5355,7 @@ void MainWindow::installTranslator(const QString &name) QString fileName = name + "_" + m_CurrentLanguage; if (!translator->load(fileName, qApp->applicationDirPath() + "/translations")) { if (m_CurrentLanguage.contains(QRegularExpression("^.*_(EN|en)(-.*)?$"))) { - qDebug("localization file %s not found", qUtf8Printable(fileName)); + log::debug("localization file %s not found", fileName); } // we don't actually expect localization files for English (en, en-us, en-uk, and any variation thereof) } @@ -5389,7 +5380,7 @@ void MainWindow::languageChange(const QString &newLanguage) installTranslator(QFileInfo(fileName).baseName()); } ui->retranslateUi(this); - qDebug("loaded language %s", qUtf8Printable(newLanguage)); + log::debug("loaded language {}", newLanguage); ui->profileBox->setItemText(0, QObject::tr("")); @@ -5634,7 +5625,7 @@ void MainWindow::openDataOriginExplorer_clicked() const auto fullPath = m_ContextItem->data(0, Qt::UserRole).toString(); - qDebug().nospace() << "opening in explorer: " << fullPath; + log::debug("opening in explorer: {}", fullPath); shell::ExploreFile(fullPath); } @@ -6120,7 +6111,7 @@ void MainWindow::nxmDownloadURLs(QString, int, int, QVariant, QVariant resultDat void MainWindow::nxmRequestFailed(QString gameName, int modID, int, QVariant, int, QNetworkReply::NetworkError error, const QString &errorString) { if (error == QNetworkReply::ContentAccessDenied || error == QNetworkReply::ContentNotFoundError) { - qDebug(qUtf8Printable(tr("Mod ID %1 no longer seems to be available on Nexus.").arg(modID))); + log::debug("{}", tr("Mod ID %1 no longer seems to be available on Nexus.").arg(modID)); } else { MessageDialog::showMessage(tr("Request to Nexus failed: %1").arg(errorString), this); } @@ -6587,7 +6578,7 @@ void MainWindow::processLOOTOut(const std::string &lootOut, std::string &errorMe std::string dependency(match[2].first, match[2].second); m_OrganizerCore.pluginList()->addInformation(modName.c_str(), tr("incompatible with \"%1\"").arg(dependency.c_str())); } else { - qDebug("[loot] %s", line.c_str()); + log::debug("[loot] {}", line); } } } @@ -6632,7 +6623,7 @@ void MainWindow::on_bossButton_clicked() try { m_OrganizerCore.prepareVFS(); } catch (const UsvfsConnectorException &e) { - qDebug(e.what()); + log::debug("{}", e.what()); return; } catch (const std::exception &e) { QMessageBox::warning(qApp->activeWindow(), tr("Error"), e.what()); @@ -6662,7 +6653,7 @@ void MainWindow::on_bossButton_clicked() if (isJobHandle) { if (::QueryInformationJobObject(loot, JobObjectBasicProcessIdList, &info, sizeof(info), &retLen) > 0) { if (info.NumberOfProcessIdsInList == 0) { - qDebug("no more processes in job"); + log::debug("no more processes in job"); break; } else { if (lastProcessID != info.ProcessIdList[0]) { diff --git a/src/messagedialog.cpp b/src/messagedialog.cpp index 6c6de3e7..78a5dd4d 100644 --- a/src/messagedialog.cpp +++ b/src/messagedialog.cpp @@ -19,10 +19,13 @@ along with Mod Organizer. If not, see . #include "messagedialog.h" #include "ui_messagedialog.h" +#include #include #include #include +using namespace MOBase; + MessageDialog::MessageDialog(const QString &text, QWidget *reference) : QDialog(reference), ui(new Ui::MessageDialog) @@ -81,7 +84,8 @@ void MessageDialog::resizeEvent(QResizeEvent *event) void MessageDialog::showMessage(const QString &text, QWidget *reference, bool bringToFront) { - qDebug("%s", qUtf8Printable(text)); + log::debug("{}", text); + if (reference != nullptr) { if (bringToFront || (qApp->activeWindow() != nullptr)) { MessageDialog *dialog = new MessageDialog(text, reference); diff --git a/src/modinfodialog.cpp b/src/modinfodialog.cpp index a7a6b0d7..4b1e2f76 100644 --- a/src/modinfodialog.cpp +++ b/src/modinfodialog.cpp @@ -556,9 +556,7 @@ void ModInfoDialog::switchToTab(ModInfoTabIDs id) } // this could happen if the tab is not visible right now - qDebug() - << "can't switch to tab ID " << static_cast(id) - << ", not available"; + log::debug("can't switch to tab ID {}, not available", static_cast(id)); } MOShared::FilesOrigin* ModInfoDialog::getOrigin() diff --git a/src/modinfodialogconflicts.cpp b/src/modinfodialogconflicts.cpp index d16d548c..9a5d9d8d 100644 --- a/src/modinfodialogconflicts.cpp +++ b/src/modinfodialogconflicts.cpp @@ -438,10 +438,18 @@ void ConflictsTab::changeItemsVisibility(QTreeView* tree, bool visible) const auto n = smallSelectionSize(tree); - qDebug().nospace().noquote() - << (visible ? "unhiding" : "hiding") << " " - << (n > max_small_selection ? "a lot of" : QString("%1").arg(n)) - << " conflict files"; + // logging + { + const QString action = (visible ? "unhiding" : "hiding"); + + QString files; + if (n > max_small_selection) + files = "a lot of"; + else + files = QString("%1").arg(n); + + log::debug("{} {} conflict files", action, files); + } QFlags flags = (visible ? FileRenamer::UNHIDE : FileRenamer::HIDE); @@ -467,7 +475,7 @@ void ConflictsTab::changeItemsVisibility(QTreeView* tree, bool visible) if (visible) { if (!item->canUnhide()) { - qDebug().nospace() << "cannot unhide " << item->relativeName() << ", skipping"; + log::debug("cannot unhide {}, skipping", item->relativeName()); return true; } @@ -475,7 +483,7 @@ void ConflictsTab::changeItemsVisibility(QTreeView* tree, bool visible) } else { if (!item->canHide()) { - qDebug().nospace() << "cannot hide " << item->relativeName() << ", skipping"; + log::debug("cannot hide {}, skipping", item->relativeName()); return true; } @@ -504,10 +512,10 @@ void ConflictsTab::changeItemsVisibility(QTreeView* tree, bool visible) return true; }); - qDebug().nospace() << (visible ? "unhiding" : "hiding") << " conflict files done"; + log::debug("{} conflict files done", (visible ? "unhiding" : "hiding")); if (changed) { - qDebug().nospace() << "triggering refresh"; + log::debug("triggering refresh"); if (origin()) { emitOriginModified(); diff --git a/src/modinfodialogfiletree.cpp b/src/modinfodialogfiletree.cpp index 219ddf35..207c792d 100644 --- a/src/modinfodialogfiletree.cpp +++ b/src/modinfodialogfiletree.cpp @@ -257,9 +257,9 @@ void FileTreeTab::changeVisibility(bool visible) bool changed = false; bool stop = false; - qDebug().nospace() - << (visible ? "unhiding" : "hiding") << " " - << selection.size() << " filetree files"; + log::debug( + "{} {} filetree files", + (visible ? "unhiding" : "hiding"), selection.size()); QFlags flags = (visible ? FileRenamer::UNHIDE : FileRenamer::HIDE); @@ -280,13 +280,13 @@ void FileTreeTab::changeVisibility(bool visible) if (visible) { if (!canUnhideFile(false, path)) { - qDebug().nospace() << "cannot unhide " << path << ", skipping"; + log::debug("cannot unhide {}, skipping", path); continue; } result = unhideFile(renamer, path); } else { if (!canHideFile(false, path)) { - qDebug().nospace() << "cannot hide " << path << ", skipping"; + log::debug("cannot hide {}, skipping", path); continue; } result = hideFile(renamer, path); @@ -312,7 +312,7 @@ void FileTreeTab::changeVisibility(bool visible) } } - qDebug().nospace() << (visible ? "unhiding" : "hiding") << " filetree files done"; + log::debug("{} filetree files done", (visible ? "unhiding" : "hiding")); if (changed) { if (origin()) { diff --git a/src/modinforegular.cpp b/src/modinforegular.cpp index 074fa9e2..6e11befc 100644 --- a/src/modinforegular.cpp +++ b/src/modinforegular.cpp @@ -883,8 +883,9 @@ std::vector ModInfoRegular::getIniTweaks() const int numTweaks = metaFile.beginReadArray("INI Tweaks"); if (numTweaks != 0) { - qDebug("%d active ini tweaks in %s", - numTweaks, QDir::toNativeSeparators(metaFileName).toUtf8().constData()); + log::debug( + "{} active ini tweaks in {}", + numTweaks, QDir::toNativeSeparators(metaFileName)); } for (int i = 0; i < numTweaks; ++i) { diff --git a/src/modlist.cpp b/src/modlist.cpp index 6ebd0e8b..39f51d72 100644 --- a/src/modlist.cpp +++ b/src/modlist.cpp @@ -1013,9 +1013,8 @@ bool ModList::dropURLs(const QMimeData *mimeData, int row, const QModelIndex &pa QString overwriteName = ModInfo::getByIndex(overwriteIndex)->name(); for (auto url : mimeData->urls()) { - //qDebug("URL drop requested: %s -> %s", qUtf8Printable(url.url()), qUtf8Printable(modDir.canonicalPath())); if (!url.isLocalFile()) { - qDebug("URL drop ignored: \"%s\" is not a local file", qUtf8Printable(url.url())); + log::debug("URL drop ignored: \"{}\" is not a local file", url.url()); continue; } @@ -1035,7 +1034,7 @@ bool ModList::dropURLs(const QMimeData *mimeData, int row, const QModelIndex &pa originName = overwriteName; relativePath = overwriteDir.relativeFilePath(sourceFile); } else { - qDebug("URL drop ignored: \"%s\" is not a known file to MO", qUtf8Printable(sourceFile)); + log::debug("URL drop ignored: \"{}\" is not a known file to MO", sourceFile); continue; } @@ -1047,7 +1046,7 @@ bool ModList::dropURLs(const QMimeData *mimeData, int row, const QModelIndex &pa if (sourceList.count()) { if (!shellMove(sourceList, targetList)) { - qDebug("Failed to move file (error %d)", ::GetLastError()); + log::debug("Failed to move file (error {})", ::GetLastError()); return false; } } diff --git a/src/modlistsortproxy.cpp b/src/modlistsortproxy.cpp index d330e0c2..77ffad96 100644 --- a/src/modlistsortproxy.cpp +++ b/src/modlistsortproxy.cpp @@ -482,7 +482,7 @@ bool ModListSortProxy::filterAcceptsRow(int row, const QModelIndex &parent) cons QModelIndex idx = sourceModel()->index(row, 0, parent); if (!idx.isValid()) { - qDebug("invalid mod index"); + log::debug("invalid mod index"); return false; } if (sourceModel()->hasChildren(idx)) { diff --git a/src/nexusinterface.cpp b/src/nexusinterface.cpp index c797aed6..0e2bb45b 100644 --- a/src/nexusinterface.cpp +++ b/src/nexusinterface.cpp @@ -316,15 +316,15 @@ void NexusInterface::interpretNexusFileName(const QString &fileName, QString &mo } else { modID = strtol(candidate.c_str(), nullptr, 10); } - qDebug("mod id guessed: %s -> %d", qUtf8Printable(fileName), modID); + log::debug("mod id guessed: {} -> {}", fileName, modID); } else if (std::regex_search(fileNameUTF8.constData(), result, simpleexp)) { - qDebug("simple expression matched, using name only"); + log::debug("simple expression matched, using name only"); modName = QString::fromUtf8(result[1].str().c_str()); modName = modName.replace('_', ' ').trimmed(); modID = -1; } else { - qDebug("no expression matched!"); + log::debug("no expression matched!"); modName.clear(); modID = -1; } @@ -860,7 +860,7 @@ void NexusInterface::requestFinished(std::list::iterator iter) if (nexusError.length() == 0) { nexusError = tr("empty response"); } - qDebug("nexus error: %s", qUtf8Printable(nexusError)); + log::debug("nexus error: {}", nexusError); emit nxmRequestFailed(iter->m_GameName, iter->m_ModID, iter->m_FileID, iter->m_UserData, iter->m_ID, reply->error(), nexusError); } else { QJsonDocument responseDoc = QJsonDocument::fromJson(data); diff --git a/src/nxmaccessmanager.cpp b/src/nxmaccessmanager.cpp index 9f40894e..fd1dc0c1 100644 --- a/src/nxmaccessmanager.cpp +++ b/src/nxmaccessmanager.cpp @@ -600,9 +600,9 @@ void NXMAccessManager::showCookies() const { QUrl url(NexusBaseUrl + "/"); for (const QNetworkCookie &cookie : cookieJar()->cookiesForUrl(url)) { - qDebug("%s - %s (expires: %s)", + log::debug("{} - {} (expires: {})", cookie.name().constData(), cookie.value().constData(), - qUtf8Printable(cookie.expirationDate().toString())); + cookie.expirationDate().toString()); } } diff --git a/src/organizercore.cpp b/src/organizercore.cpp index 725371e9..f6802673 100644 --- a/src/organizercore.cpp +++ b/src/organizercore.cpp @@ -89,9 +89,9 @@ static bool isOnline() if (addresses.count() == 0) { continue; } - qDebug("interface %s seems to be up (address: %s)", - qUtf8Printable(iter->humanReadableName()), - qUtf8Printable(addresses[0].ip().toString())); + log::debug("interface {} seems to be up (address: {})", + iter->humanReadableName(), + addresses[0].ip().toString()); connected = true; } } @@ -543,7 +543,7 @@ void OrganizerCore::setUserInterface(IUserInterface *userInterface, if (isOnline() && !m_Settings.offlineMode()) { m_Updater.testForUpdate(); } else { - qDebug("user doesn't seem to be connected to the internet"); + log::debug("user doesn't seem to be connected to the internet"); } } } @@ -605,7 +605,7 @@ bool OrganizerCore::nexusApi(bool retry) QString apiKey; if (m_Settings.getNexusApiKey(apiKey)) { // credentials stored or user entered them manually - qDebug("attempt to verify nexus api key"); + log::debug("attempt to verify nexus api key"); accessManager->apiCheck(apiKey); return true; } else { @@ -627,7 +627,7 @@ void OrganizerCore::startMOUpdate() void OrganizerCore::downloadRequestedNXM(const QString &url) { - qDebug("download requested: %s", qUtf8Printable(url)); + log::debug("download requested: {}", url); if (nexusApi()) { m_PendingDownloads.append(url); } else { @@ -1208,7 +1208,9 @@ QString OrganizerCore::findJavaInstallation(const QString& jarFile) if (::FindExecutableW(jarFileW.c_str(), nullptr, buffer) > (HINSTANCE)32) { DWORD binaryType = 0UL; if (!::GetBinaryTypeW(buffer, &binaryType)) { - qDebug("failed to determine binary type of \"%ls\": %lu", buffer, ::GetLastError()); + log::debug( + "failed to determine binary type of \"{}\": {}", + QString::fromWCharArray(buffer), ::GetLastError()); } else if (binaryType == SCS_32BIT_BINARY || binaryType == SCS_64BIT_BINARY) { return QString::fromWCharArray(buffer); } @@ -1459,7 +1461,7 @@ void OrganizerCore::spawnBinary(const QFileInfo &binary, // need to remove our stored load order because it may be outdated if a foreign tool changed the // file time. After removing that file, refreshESPList will use the file time as the order if (managedGame()->loadOrderMechanism() == IPluginGame::LoadOrderMechanism::FileTime) { - qDebug("removing loadorder.txt"); + log::debug("removing loadorder.txt"); QFile::remove(m_CurrentProfile->getLoadOrderFileName()); } refreshDirectoryStructure(); @@ -1627,7 +1629,7 @@ HANDLE OrganizerCore::spawnBinaryProcess(const QFileInfo &binary, m_USVFS.updateForcedLibraries(forcedLibraries); } catch (const UsvfsConnectorException &e) { - qDebug(e.what()); + log::debug(e.what()); return INVALID_HANDLE_VALUE; } catch (const std::exception &e) { QMessageBox::warning(window, tr("Error"), e.what()); @@ -1694,17 +1696,16 @@ HANDLE OrganizerCore::spawnBinaryProcess(const QFileInfo &binary, .arg(QDir::toNativeSeparators(cwdPath), QDir::toNativeSeparators(binPath), arguments); - qDebug() << "Spawning proxyed process <" << cmdline << ">"; + log::debug("Spawning proxyed process <{}>", cmdline); return startBinary(QFileInfo(QCoreApplication::applicationFilePath()), cmdline, QCoreApplication::applicationDirPath(), true); } else { - qDebug() << "Spawning direct process <" << binPath << "," << arguments << "," << cwdPath << ">"; + log::debug("Spawning direct process <{}, {}, {}>", binPath, arguments, cwdPath); return startBinary(binary, arguments, currentDirectory, true); } } else { - qDebug("start of \"%s\" canceled by plugin", - qUtf8Printable(binary.absoluteFilePath())); + log::debug("start of \"{}\" canceled by plugin", binary.absoluteFilePath()); return INVALID_HANDLE_VALUE; } } @@ -1872,9 +1873,11 @@ bool OrganizerCore::waitForProcessCompletion(HANDLE handle, LPDWORD exitCode, IL processName += QString(" (%1)").arg(currentPID); if (uilock) uilock->setProcessName(processName); - qDebug() << "Waiting for" - << (originalHandle ? "spawned" : "usvfs") - << "process completion :" << qUtf8Printable(processName); + + log::debug( + "Waiting for {} process completion: {}", + (originalHandle ? "spawned" : "usvfs"), processName); + newHandle = false; } @@ -1943,11 +1946,11 @@ bool OrganizerCore::waitForProcessCompletion(HANDLE handle, LPDWORD exitCode, IL } if (res == WAIT_OBJECT_0) - qDebug() << "Waiting for process completion successfull"; + log::debug("Waiting for process completion successfull"); else if (uiunlocked) - qDebug() << "Waiting for process completion aborted by UI"; + log::debug("Waiting for process completion aborted by UI"); else - qDebug() << "Waiting for process completion not successfull :" << res; + log::debug("Waiting for process completion not successfull: {}", res); if (handle != INVALID_HANDLE_VALUE) ::CloseHandle(handle); diff --git a/src/persistentcookiejar.cpp b/src/persistentcookiejar.cpp index 670bf382..8657f356 100644 --- a/src/persistentcookiejar.cpp +++ b/src/persistentcookiejar.cpp @@ -13,7 +13,7 @@ PersistentCookieJar::PersistentCookieJar(const QString &fileName, QObject *paren } PersistentCookieJar::~PersistentCookieJar() { - qDebug("save %s", qUtf8Printable(m_FileName)); + log::debug("save {}", m_FileName); save(); } diff --git a/src/plugincontainer.cpp b/src/plugincontainer.cpp index 36daec52..62cdff1e 100644 --- a/src/plugincontainer.cpp +++ b/src/plugincontainer.cpp @@ -91,7 +91,7 @@ bool PluginContainer::registerPlugin(QObject *plugin, const QString &fileName) { // generic treatment for all plugins IPlugin *pluginObj = qobject_cast(plugin); if (pluginObj == nullptr) { - qDebug("not an IPlugin"); + log::debug("not an IPlugin"); return false; } plugin->setProperty("filename", fileName); @@ -164,7 +164,7 @@ bool PluginContainer::registerPlugin(QObject *plugin, const QString &fileName) for (QObject *proxiedPlugin : matchingPlugins) { if (proxiedPlugin != nullptr) { if (registerPlugin(proxiedPlugin, pluginName)) { - qDebug("loaded plugin \"%s\"", qUtf8Printable(QFileInfo(pluginName).fileName())); + log::debug("loaded plugin \"{}\"", QFileInfo(pluginName).fileName()); } else { log::warn( @@ -191,7 +191,7 @@ bool PluginContainer::registerPlugin(QObject *plugin, const QString &fileName) } } - qDebug("no matching plugin interface"); + log::debug("no matching plugin interface"); return false; } @@ -225,7 +225,7 @@ void PluginContainer::unloadPlugins() QPluginLoader *loader = m_PluginLoaders.back(); m_PluginLoaders.pop_back(); if ((loader != nullptr) && !loader->unload()) { - qDebug("failed to unload %s: %s", qUtf8Printable(loader->fileName()), qUtf8Printable(loader->errorString())); + log::debug("failed to unload {}: {}", loader->fileName(), loader->errorString()); } delete loader; } @@ -274,13 +274,13 @@ void PluginContainer::loadPlugins() loadCheck.open(QIODevice::WriteOnly); QString pluginPath = qApp->applicationDirPath() + "/" + ToQString(AppConfig::pluginPath()); - qDebug("looking for plugins in %s", QDir::toNativeSeparators(pluginPath).toUtf8().constData()); + log::debug("looking for plugins in {}", QDir::toNativeSeparators(pluginPath)); QDirIterator iter(pluginPath, QDir::Files | QDir::NoDotAndDotDot); while (iter.hasNext()) { iter.next(); if (m_Organizer->settings().pluginBlacklisted(iter.fileName())) { - qDebug("plugin \"%s\" blacklisted", qUtf8Printable(iter.fileName())); + log::debug("plugin \"{}\" blacklisted", iter.fileName()); continue; } loadCheck.write(iter.fileName().toUtf8()); @@ -296,7 +296,7 @@ void PluginContainer::loadPlugins() pluginName, pluginLoader->errorString()); } else { if (registerPlugin(pluginLoader->instance(), pluginName)) { - qDebug("loaded plugin \"%s\"", qUtf8Printable(QFileInfo(pluginName).fileName())); + log::debug("loaded plugin \"{}\"", QFileInfo(pluginName).fileName()); m_PluginLoaders.push_back(pluginLoader.release()); } else { m_FailedPlugins.push_back(pluginName); diff --git a/src/pluginlist.cpp b/src/pluginlist.cpp index e436d7f6..6718641f 100644 --- a/src/pluginlist.cpp +++ b/src/pluginlist.cpp @@ -481,7 +481,7 @@ void PluginList::writeLockedOrder(const QString &fileName) const file->write(QString("%1|%2\r\n").arg(iter->first).arg(iter->second).toUtf8()); } file.commit(); - qDebug("%s saved", qUtf8Printable(QDir::toNativeSeparators(fileName))); + log::debug("{} saved", QDir::toNativeSeparators(fileName)); } @@ -506,7 +506,7 @@ void PluginList::saveTo(const QString &lockedOrderFileName } } if (deleterFile.commitIfDifferent(m_LastSaveHash[deleterFileName])) { - qDebug("%s saved", qUtf8Printable(QDir::toNativeSeparators(deleterFileName))); + log::debug("{} saved", QDir::toNativeSeparators(deleterFileName)); } } else if (QFile::exists(deleterFileName)) { shellDelete(QStringList() << deleterFileName); @@ -521,7 +521,7 @@ bool PluginList::saveLoadOrder(DirectoryEntry &directoryStructure) return true; } - qDebug("setting file times on esps"); + log::debug("setting file times on esps"); for (ESPInfo &esp : m_ESPs) { std::wstring espName = ToWString(esp.m_Name); diff --git a/src/profile.cpp b/src/profile.cpp index 555de89a..27616986 100644 --- a/src/profile.cpp +++ b/src/profile.cpp @@ -40,7 +40,6 @@ along with Mod Organizer. If not, see . #include #include #include // for QStringList -#include // for qDebug, qWarning, etc #include // for qUtf8Printable #include #include @@ -232,7 +231,6 @@ void Profile::doWriteModlist() } for (std::map::const_reverse_iterator iter = m_ModIndexByPriority.crbegin(); iter != m_ModIndexByPriority.crend(); iter++ ) { - //qDebug(QString("write mod %1 to priority %2").arg(iter->first).arg(iter->second).toLocal8Bit()); // the priority order was inverted on load so it has to be inverted again unsigned int index = iter->second; if (index != UINT_MAX) { @@ -253,7 +251,7 @@ void Profile::doWriteModlist() } if (file.commitIfDifferent(m_LastModlistHash)) { - qDebug("%s saved", qUtf8Printable(QDir::toNativeSeparators(fileName))); + log::debug("{} saved", QDir::toNativeSeparators(fileName)); } } catch (const std::exception &e) { reportError(tr("failed to write mod list: %1").arg(e.what())); @@ -292,7 +290,7 @@ void Profile::createTweakedIniFile() .arg(formatSystemMessageQ(e))); } - qDebug("%s saved", qUtf8Printable(QDir::toNativeSeparators(tweakedIni))); + log::debug("{} saved", QDir::toNativeSeparators(tweakedIni)); } // static @@ -364,8 +362,9 @@ void Profile::renameModInList(QFile &modList, const QString &oldName, const QStr } if (renamed) - qDebug("Renamed %d \"%s\" mod to \"%s\" in %s", - renamed, qUtf8Printable(oldName), qUtf8Printable(newName), qUtf8Printable(modList.fileName())); + log::debug( + "Renamed {} \"{}\" mod to \"{}\" in {}", + renamed, oldName, newName, modList.fileName()); } void Profile::refreshModStatus() @@ -431,8 +430,9 @@ void Profile::refreshModStatus() modStatusModified = true; } } else { - qDebug("mod not found: \"%s\" (profile \"%s\")", - qUtf8Printable(modName), qUtf8Printable(m_Directory.path())); + log::debug( + "mod not found: \"{}\" (profile \"{}\")", + modName, m_Directory.path()); // need to rewrite the modlist to fix this modStatusModified = true; } diff --git a/src/qtgroupingproxy.cpp b/src/qtgroupingproxy.cpp index 5fcb84d3..ff9539d7 100644 --- a/src/qtgroupingproxy.cpp +++ b/src/qtgroupingproxy.cpp @@ -18,11 +18,14 @@ #include "qtgroupingproxy.h" +#include #include #include #include +using namespace MOBase; + /*! \class QtGroupingProxy \brief The QtGroupingProxy class will group source model rows by adding a new top tree-level. @@ -86,7 +89,6 @@ QtGroupingProxy::setGroupedColumn( int groupedColumn ) QList QtGroupingProxy::belongsTo( const QModelIndex &idx ) { - //qDebug() << __FILE__ << __FUNCTION__; QList rowDataList; //get all the data for this index from the model @@ -106,7 +108,7 @@ QtGroupingProxy::belongsTo( const QModelIndex &idx ) i.next(); int role = i.key(); QVariant variant = i.value(); - // qDebug() << "role " << role << " : (" << variant.typeName() << ") : "<< variant; + if ( variant.type() == QVariant::List ) { //a list of variants get's expanded to multiple rows @@ -162,7 +164,7 @@ QtGroupingProxy::buildTree() m_parentCreateList.clear(); int max = sourceModel()->rowCount( m_rootNode ); - //qDebug() << QString("building tree with %1 leafs.").arg( max ); + //WARNING: these have to be added in order because the addToGroups function is optimized for //modelRowsInserted(). Failure to do so will result in wrong data shown in the view at best. for( int row = 0; row < max; row++ ) @@ -232,9 +234,6 @@ QtGroupingProxy::addSourceRow( const QModelIndex &idx ) int updatedGroup = -1; if( !data.isEmpty() ) { - // qDebug() << QString("index %1 belongs to group %2").arg( row ) - // .arg( data[0][Qt::DisplayRole].toString() ); - foreach( const RowData &cachedData, m_groupMaps ) { //when this matches the index belongs to an existing group @@ -316,21 +315,12 @@ QtGroupingProxy::indexOfParentCreate( const QModelIndex &parent ) const pc.row = parent.row(); m_parentCreateList << pc; - //dumpParentCreateList(); - // qDebug() << QString( "m_parentCreateList: (%1)" ).arg( m_parentCreateList.size() ); - // for( int i = 0 ; i < m_parentCreateList.size() ; i++ ) - // { - // qDebug() << i << " : " << m_parentCreateList[i].parentCreateIndex << - // " | " << m_parentCreateList[i].row; - // } - return m_parentCreateList.size() - 1; } QModelIndex QtGroupingProxy::index( int row, int column, const QModelIndex &parent ) const { - // qDebug() << "index requested for: (" << row << "," << column << "), " << parent; if( !hasIndex(row, column, parent) ) { return QModelIndex(); } @@ -350,17 +340,15 @@ QtGroupingProxy::index( int row, int column, const QModelIndex &parent ) const QModelIndex QtGroupingProxy::parent( const QModelIndex &index ) const { - //qDebug() << "parent: " << index; if( !index.isValid() ) return QModelIndex(); int parentCreateIndex = index.internalId(); - //qDebug() << "parentCreateIndex: " << parentCreateIndex; if( parentCreateIndex == -1 || parentCreateIndex >= m_parentCreateList.count() ) return QModelIndex(); struct ParentCreate pc = m_parentCreateList[parentCreateIndex]; - //qDebug() << "parentCreate: (" << pc.parentCreateIndex << "," << pc.row << ")"; + //only items at column 0 have children return createIndex( pc.row, 0, pc.parentCreateIndex ); } @@ -368,12 +356,10 @@ QtGroupingProxy::parent( const QModelIndex &index ) const int QtGroupingProxy::rowCount( const QModelIndex &index ) const { - //qDebug() << "rowCount: " << index; if( !index.isValid() ) { //the number of top level groups + the number of non-grouped items int rows = m_groupMaps.count() + m_groupHash.value( std::numeric_limits::max() ).count(); - //qDebug() << rows << " in root group"; return rows; } @@ -382,12 +368,10 @@ QtGroupingProxy::rowCount( const QModelIndex &index ) const { qint64 groupIndex = index.row(); int rows = m_groupHash.value( groupIndex ).count(); - //qDebug() << rows << " in group " << m_groupMaps[groupIndex]; return rows; } else { QModelIndex originalIndex = mapToSource( index ); int rowCount = sourceModel()->rowCount( originalIndex ); - //qDebug() << "original item: rowCount == " << rowCount; return rowCount; } } @@ -447,7 +431,7 @@ QtGroupingProxy::data( const QModelIndex &index, int role ) const { if( !index.isValid() ) return QVariant(); - // qDebug() << __FUNCTION__ << index << " role: " << role; + int row = index.row(); int column = index.column(); if( isGroup( index ) ) @@ -495,11 +479,9 @@ QtGroupingProxy::data( const QModelIndex &index, int role ) const } } - //qDebug() << __FUNCTION__ << "is a group"; //use cached or precalculated data if( m_groupMaps[row][column].contains( Qt::DisplayRole ) ) { - // qDebug() << "Using cached data for " << row << "x" << column << ": " << m_groupMaps[row][column].value(Qt::DisplayRole).toString(); if ((m_flags & FLAG_NOGROUPNAME) != 0) { QModelIndex parentIndex = this->index( row, 0, index.parent() ); QModelIndex childIndex = this->index( 0, column, parentIndex ); @@ -526,18 +508,17 @@ QtGroupingProxy::data( const QModelIndex &index, int role ) const function = mapToSource(childIndex).data(m_aggregateRole).toInt(); } - //qDebug() << __FUNCTION__ << "childCount: " << childCount; //Need a parentIndex with column == 0 because only those have children. QModelIndex parentIndex = this->index( row, 0, index.parent() ); for( int childRow = 0; childRow < childCount; childRow++ ) { QModelIndex childIndex = this->index( childRow, column, parentIndex ); QVariant data = mapToSource( childIndex ).data( role ); - //qDebug() << __FUNCTION__ << data << QVariant::typeToName(data.type()); + if( data.isValid() && !variantsOfChildren.contains( data ) ) variantsOfChildren << data; } - //qDebug() << "gathered this data from children: " << variantsOfChildren; + //saving in cache ItemData roleMap = m_groupMaps[row].value( column ); foreach( const QVariant &variant, variantsOfChildren ) @@ -547,8 +528,6 @@ QtGroupingProxy::data( const QModelIndex &index, int role ) const } } - //qDebug() << QString("roleMap[%1]:").arg(role) << roleMap[role]; - if( variantsOfChildren.count() == 0 ) return QVariant(); @@ -621,34 +600,30 @@ QtGroupingProxy::isGroup( const QModelIndex &index ) const QModelIndex QtGroupingProxy::mapToSource( const QModelIndex &index ) const { - //qDebug() << "mapToSource: " << index; if( !index.isValid() ) { return m_rootNode; } if( isGroup( index ) ) { - //qDebug() << "is a group: " << index.data( Qt::DisplayRole ).toString(); return m_rootNode; } QModelIndex proxyParent = index.parent(); - //qDebug() << "parent: " << proxyParent; QModelIndex originalParent = mapToSource( proxyParent ); - //qDebug() << "originalParent: " << originalParent; + int originalRow = index.row(); if( originalParent == m_rootNode ) { int indexInGroup = index.row(); if( !proxyParent.isValid() ) indexInGroup -= m_groupMaps.count(); - //qDebug() << "indexInGroup" << indexInGroup; + QList childRows = m_groupHash.value( proxyParent.row() ); if( childRows.isEmpty() || indexInGroup >= childRows.count() || indexInGroup < 0 ) return QModelIndex(); originalRow = childRows.at( indexInGroup ); - //qDebug() << "originalRow: " << originalRow; } return sourceModel()->index( originalRow, index.column(), originalParent ); } @@ -674,7 +649,7 @@ QtGroupingProxy::mapFromSource( const QModelIndex &idx ) const QModelIndex proxyParent; QModelIndex sourceParent = idx.parent(); - //qDebug() << "sourceParent: " << sourceParent; + int proxyRow = idx.row(); int sourceRow = idx.row(); @@ -708,15 +683,12 @@ QtGroupingProxy::mapFromSource( const QModelIndex &idx ) const proxyParent = QModelIndex(); // if the proxy item is not in a group it will be below the groups. int groupLength = m_groupMaps.count(); - //qDebug() << "groupNames length: " << groupLength; int i = m_groupHash.value( std::numeric_limits::max() ).indexOf( sourceRow ); - //qDebug() << "index in hash: " << i; + proxyRow = groupLength + i; } } - //qDebug() << "proxyParent: " << proxyParent; - //qDebug() << "proxyRow: " << proxyRow; return this->index( proxyRow, idx.column(), proxyParent ); } @@ -731,9 +703,9 @@ QtGroupingProxy::flags( const QModelIndex &idx ) const return 0; } + //only if the grouped column has the editable flag set allow the //actions leading to setData on the source (edit & drop) - // qDebug() << idx; if( isGroup( idx ) ) { // dumpGroups(); @@ -749,7 +721,7 @@ QtGroupingProxy::flags( const QModelIndex &idx ) const m_rootNode.parent() ); if ( (originalIdx.flags() & Qt::ItemIsUserCheckable) == 0 ) { - qDebug("row %d is not checkable", originalRow); + log::debug("row {} is not checkable", originalRow); checkable = false; } } @@ -892,9 +864,7 @@ QtGroupingProxy::modelRowsAboutToBeInserted( const QModelIndex &parent, int star if( parent != m_rootNode ) { //an item will be added to an original index, remap and pass it on - // qDebug() << parent; QModelIndex proxyParent = mapFromSource( parent ); - // qDebug() << proxyParent; beginInsertRows( proxyParent, start, end ); } } @@ -914,7 +884,12 @@ QtGroupingProxy::modelRowsInserted( const QModelIndex &parent, int start, int en { //an item was added to an original index, remap and pass it on QModelIndex proxyParent = mapFromSource( parent ); - qDebug() << proxyParent; + + QString s; + QDebug debug(&s); + debug << proxyParent; + log::debug("{}", s); + //beginInsertRows had to be called in modelRowsAboutToBeInserted() endInsertRows(); } @@ -951,9 +926,7 @@ QtGroupingProxy::modelRowsAboutToBeRemoved( const QModelIndex &parent, int start else { //child item(s) of an original item will be removed, remap and pass it on - // qDebug() << parent; QModelIndex proxyParent = mapFromSource( parent ); - // qDebug() << proxyParent; beginRemoveRows( proxyParent, start, end ); } } @@ -1044,16 +1017,24 @@ QtGroupingProxy::isAGroupSelected( const QModelIndexList& list ) const void QtGroupingProxy::dumpGroups() const { - qDebug() << "m_groupHash: "; + QString s; + QDebug debug(&s); + + debug << "m_groupHash:\n"; for( int groupIndex = -1; groupIndex < m_groupHash.keys().count() - 1; groupIndex++ ) { - qDebug() << groupIndex << " : " << m_groupHash.value( groupIndex ); + debug << groupIndex << " : " << m_groupHash.value( groupIndex ) << "\n"; } - qDebug() << "m_groupMaps: "; + debug << "m_groupMaps:\n"; for( int groupIndex = 0; groupIndex < m_groupMaps.count(); groupIndex++ ) - qDebug() << m_groupMaps[groupIndex] << ": " << m_groupHash.value( groupIndex ); - qDebug() << m_groupHash.value( std::numeric_limits::max() ); + { + debug << m_groupMaps[groupIndex] << ": " << m_groupHash.value( groupIndex ) << "\n"; + } + + debug << m_groupHash.value( std::numeric_limits::max() ); + + log::debug("{}", s); } diff --git a/src/selfupdater.cpp b/src/selfupdater.cpp index e967b27c..0ca39b19 100644 --- a/src/selfupdater.cpp +++ b/src/selfupdater.cpp @@ -150,23 +150,23 @@ void SelfUpdater::testForUpdate() VersionInfo newestVer(newest["tag_name"].toString()); if (newestVer > this->m_MOVersion) { m_UpdateCandidate = newest; - qDebug("update available: %s -> %s", - qUtf8Printable(this->m_MOVersion.displayString(3)), - qUtf8Printable(newestVer.displayString(3))); + log::debug("update available: {} -> {}", + this->m_MOVersion.displayString(3), + newestVer.displayString(3)); emit updateAvailable(); } else if (newestVer < this->m_MOVersion) { // this could happen if the user switches from using prereleases to // stable builds. Should we downgrade? - qDebug("This version is newer than the latest released one: %s -> %s", - qUtf8Printable(this->m_MOVersion.displayString(3)), - qUtf8Printable(newestVer.displayString(3))); + log::debug("This version is newer than the latest released one: {} -> {}", + this->m_MOVersion.displayString(3), + newestVer.displayString(3)); } } }); } //Catch all is bad by design, should be improved catch (...) { - qDebug("Unable to connect to github.com to check version"); + log::debug("Unable to connect to github.com to check version"); } } @@ -230,7 +230,7 @@ void SelfUpdater::closeProgress() void SelfUpdater::openOutputFile(const QString &fileName) { QString outputPath = QDir::fromNativeSeparators(qApp->property("dataPath").toString()) + "/" + fileName; - qDebug("downloading to %s", qUtf8Printable(outputPath)); + log::debug("downloading to {}", outputPath); m_UpdateFile.setFileName(outputPath); m_UpdateFile.open(QIODevice::WriteOnly); } @@ -312,7 +312,7 @@ void SelfUpdater::downloadFinished() return; } - qDebug("download: %s", m_UpdateFile.fileName().toUtf8().constData()); + log::debug("download: {}", m_UpdateFile.fileName()); try { installUpdate(); diff --git a/src/settings.cpp b/src/settings.cpp index 9c303442..ff5b9976 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -54,7 +54,6 @@ along with Mod Organizer. If not, see . #include #include // for Qt::UserRole, etc -#include // for qDebug, qWarning #include // For ShellExecuteW, HINSTANCE, etc #include // For storage @@ -635,7 +634,7 @@ void Settings::updateServers(const QList &servers) QVariantMap val = m_Settings.value(key).toMap(); QDate lastSeen = val["lastSeen"].toDate(); if (lastSeen.daysTo(now) > 30) { - qDebug("removing server %s since it hasn't been available for downloads in over a month", qUtf8Printable(key)); + log::debug("removing server {} since it hasn't been available for downloads in over a month", key); m_Settings.remove(key); } } @@ -758,10 +757,10 @@ void Settings::query(PluginContainer *pluginContainer, QWidget *parent) if (m_Settings.value(k).toString() != before[k] && !k.contains("username") && !k.contains("password")) { if (first_update) { - qDebug("Changed settings:"); + log::debug("Changed settings:"); first_update = false; } - qDebug(" %s=%s", k.toUtf8().data(), m_Settings.value(k).toString().toUtf8().data()); + log::debug(" {}={}", k, m_Settings.value(k).toString()); } m_Settings.endGroup(); } diff --git a/src/usvfsconnector.cpp b/src/usvfsconnector.cpp index 197955b8..5918c8a5 100644 --- a/src/usvfsconnector.cpp +++ b/src/usvfsconnector.cpp @@ -60,8 +60,7 @@ LogWorker::LogWorker() "yyyy-MM-dd_hh-mm-ss"))) { m_LogFile.open(QIODevice::WriteOnly); - qDebug("usvfs log messages are written to %s", - qUtf8Printable(m_LogFile.fileName())); + log::debug("usvfs log messages are written to {}", m_LogFile.fileName()); } LogWorker::~LogWorker() @@ -129,7 +128,10 @@ UsvfsConnector::UsvfsConnector() USVFSInitParameters(¶ms, SHMID, false, level, dumpType, dumpPath.c_str()); InitLogging(false); - qDebug("Initializing VFS <%s, %d, %d, %s>", params.instanceName, params.logLevel, params.crashDumpsType, params.crashDumpsPath); + log::debug( + "Initializing VFS <{}, {}, {}, {}>", + params.instanceName, static_cast(params.logLevel), + static_cast(params.crashDumpsType), params.crashDumpsPath); CreateVFS(¶ms); @@ -168,7 +170,7 @@ void UsvfsConnector::updateMapping(const MappingType &mapping) int files = 0; int dirs = 0; - qDebug("Updating VFS mappings..."); + log::debug("Updating VFS mappings..."); ClearVirtualMappings(); @@ -196,14 +198,7 @@ void UsvfsConnector::updateMapping(const MappingType &mapping) } } - qDebug("VFS mappings updated ", dirs, files); - /* - size_t dumpSize = 0; - CreateVFSDump(nullptr, &dumpSize); - std::unique_ptr buffer(new char[dumpSize]); - CreateVFSDump(buffer.get(), &dumpSize); - qDebug(buffer.get()); - */ + log::debug("VFS mappings updated ", dirs, files); } void UsvfsConnector::updateParams( -- cgit v1.3.1 From f49efd6d448dccd4100fa46e2ebf1690d97033cc Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Fri, 19 Jul 2019 04:54:47 -0400 Subject: replaced formatSystemMessageQ() with formatSystemMessage() replaced windowsErrorString() with formatSystemMessage() --- src/envmetrics.cpp | 6 +++--- src/envmodule.cpp | 14 +++++++------- src/envsecurity.cpp | 20 ++++++++++---------- src/envshortcut.cpp | 4 ++-- src/envwindows.cpp | 4 ++-- src/main.cpp | 2 +- src/mainwindow.cpp | 25 ++++++++++++++++++------- src/organizercore.cpp | 6 ++++-- src/profile.cpp | 7 +++++-- src/settings.cpp | 6 +++--- 10 files changed, 55 insertions(+), 39 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/envmetrics.cpp b/src/envmetrics.cpp index 784e4baf..b1b9bd2e 100644 --- a/src/envmetrics.cpp +++ b/src/envmetrics.cpp @@ -19,7 +19,7 @@ int getDesktopDpi() if (!dc) { const auto e = GetLastError(); - log::error("can't get desktop DC, {}", formatSystemMessageQ(e)); + log::error("can't get desktop DC, {}", formatSystemMessage(e)); return 0; } @@ -52,7 +52,7 @@ HMONITOR findMonitor(const QString& name) const auto e = GetLastError(); log::error( "GetMonitorInfo() failed for '{}', {}", - data.name, formatSystemMessageQ(e)); + data.name, formatSystemMessage(e)); // error for this monitor, but continue return TRUE; @@ -121,7 +121,7 @@ int getDpi(const QString& monitorDevice) if (FAILED(r)) { log::error( "GetDpiForMonitor() failed for '{}', {}", - monitorDevice, formatSystemMessageQ(r)); + monitorDevice, formatSystemMessage(r)); return 0; } diff --git a/src/envmodule.cpp b/src/envmodule.cpp index aae4e0b1..8cea414a 100644 --- a/src/envmodule.cpp +++ b/src/envmodule.cpp @@ -117,7 +117,7 @@ Module::FileInfo Module::getFileInfo() const log::error( "GetFileVersionInfoSizeW() failed on '{}', {}", - m_path, formatSystemMessageQ(e)); + m_path, formatSystemMessage(e)); return {}; } @@ -130,7 +130,7 @@ Module::FileInfo Module::getFileInfo() const log::error( "GetFileVersionInfoW() failed on '{}', {}", - m_path, formatSystemMessageQ(e)); + m_path, formatSystemMessage(e)); return {}; } @@ -255,7 +255,7 @@ QDateTime Module::getTimestamp(const VS_FIXEDFILEINFO& fi) const log::error( "can't open file '{}' for timestamp, {}", - m_path, formatSystemMessageQ(e)); + m_path, formatSystemMessage(e)); return {}; } @@ -266,7 +266,7 @@ QDateTime Module::getTimestamp(const VS_FIXEDFILEINFO& fi) const log::error( "can't get file time for '{}', {}", - m_path, formatSystemMessageQ(e)); + m_path, formatSystemMessage(e)); return {}; } @@ -328,7 +328,7 @@ std::vector getLoadedModules() if (snapshot.get() == INVALID_HANDLE_VALUE) { const auto e = GetLastError(); - log::error("CreateToolhelp32Snapshot() failed, {}", formatSystemMessageQ(e)); + log::error("CreateToolhelp32Snapshot() failed, {}", formatSystemMessage(e)); return {}; } @@ -339,7 +339,7 @@ std::vector getLoadedModules() if (!Module32First(snapshot.get(), &me)) { const auto e = GetLastError(); - log::error("Module32First() failed, {}", formatSystemMessageQ(e)); + log::error("Module32First() failed, {}", formatSystemMessage(e)); return {}; } @@ -358,7 +358,7 @@ std::vector getLoadedModules() // no more modules is not an error if (e != ERROR_NO_MORE_FILES) { - log::error("Module32Next() failed, {}", formatSystemMessageQ(e)); + log::error("Module32Next() failed, {}", formatSystemMessage(e)); } break; diff --git a/src/envsecurity.cpp b/src/envsecurity.cpp index 015e4000..376be4df 100644 --- a/src/envsecurity.cpp +++ b/src/envsecurity.cpp @@ -58,7 +58,7 @@ public: } if (FAILED(ret)) { - log::error("enum->next() failed, {}", formatSystemMessageQ(ret)); + log::error("enum->next() failed, {}", formatSystemMessage(ret)); break; } @@ -84,7 +84,7 @@ private: if (FAILED(ret) || !rawLocator) { log::error( "CoCreateInstance for WbemLocator failed, {}", - formatSystemMessageQ(ret)); + formatSystemMessage(ret)); throw failed(); } @@ -104,7 +104,7 @@ private: if (FAILED(res) || !rawService) { log::error( "locator->ConnectServer() failed for namespace '{}', {}", - ns, formatSystemMessageQ(res)); + ns, formatSystemMessage(res)); throw failed(); } @@ -120,7 +120,7 @@ private: if (FAILED(ret)) { - log::error("CoSetProxyBlanket() failed, {}", formatSystemMessageQ(ret)); + log::error("CoSetProxyBlanket() failed, {}", formatSystemMessage(ret)); throw failed(); } } @@ -139,7 +139,7 @@ private: if (FAILED(ret) || !rawEnumerator) { - log::error("query '{}' failed, {}", query, formatSystemMessageQ(ret)); + log::error("query '{}' failed, {}", query, formatSystemMessage(ret)); return {}; } @@ -250,7 +250,7 @@ std::vector getSecurityProductsFromWMI() // display name auto ret = o->Get(L"displayName", 0, &prop, 0, 0); if (FAILED(ret)) { - log::error("failed to get displayName, {}", formatSystemMessageQ(ret)); + log::error("failed to get displayName, {}", formatSystemMessage(ret)); return; } @@ -265,7 +265,7 @@ std::vector getSecurityProductsFromWMI() // product state ret = o->Get(L"productState", 0, &prop, 0, 0); if (FAILED(ret)) { - log::error("failed to get productState, {}", formatSystemMessageQ(ret)); + log::error("failed to get productState, {}", formatSystemMessage(ret)); return; } @@ -286,7 +286,7 @@ std::vector getSecurityProductsFromWMI() // guid ret = o->Get(L"instanceGuid", 0, &prop, 0, 0); if (FAILED(ret)) { - log::error("failed to get instanceGuid, {}", formatSystemMessageQ(ret)); + log::error("failed to get instanceGuid, {}", formatSystemMessage(ret)); return; } @@ -349,7 +349,7 @@ std::optional getWindowsFirewall() if (FAILED(hr) || !rawPolicy) { log::error( "CoCreateInstance for NetFwPolicy2 failed, {}", - formatSystemMessageQ(hr)); + formatSystemMessage(hr)); return {}; } @@ -363,7 +363,7 @@ std::optional getWindowsFirewall() hr = policy->get_FirewallEnabled(NET_FW_PROFILE2_PUBLIC, &enabledVariant); if (FAILED(hr)) { - log::error("get_FirewallEnabled failed, {}", formatSystemMessageQ(hr)); + log::error("get_FirewallEnabled failed, {}", formatSystemMessage(hr)); return {}; } } diff --git a/src/envshortcut.cpp b/src/envshortcut.cpp index 1deb9dad..99495c39 100644 --- a/src/envshortcut.cpp +++ b/src/envshortcut.cpp @@ -100,7 +100,7 @@ private: if (FAILED(r)) { throw ShellLinkException(QString("%1, %2") .arg(s) - .arg(formatSystemMessageQ(r))); + .arg(formatSystemMessage(r))); } } @@ -290,7 +290,7 @@ bool Shortcut::remove(Locations loc) log::error( "failed to remove shortcut '{}', {}", - path, formatSystemMessageQ(e)); + path, formatSystemMessage(e)); return false; } diff --git a/src/envwindows.cpp b/src/envwindows.cpp index 8a98036a..3932a9b5 100644 --- a/src/envwindows.cpp +++ b/src/envwindows.cpp @@ -210,7 +210,7 @@ std::optional WindowsInfo::getElevated() const log::error( "while trying to check if process is elevated, " - "OpenProcessToken() failed: {}", formatSystemMessageQ(e)); + "OpenProcessToken() failed: {}", formatSystemMessage(e)); return {}; } @@ -226,7 +226,7 @@ std::optional WindowsInfo::getElevated() const log::error( "while trying to check if process is elevated, " - "GetTokenInformation() failed: {}", formatSystemMessageQ(e)); + "GetTokenInformation() failed: {}", formatSystemMessage(e)); return {}; } diff --git a/src/main.cpp b/src/main.cpp index 5c5ce945..f53a574e 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -464,7 +464,7 @@ void preloadDll(const QString& filename) if (!LoadLibraryW(dllPath.toStdWString().c_str())) { const auto e = GetLastError(); - log::warn("failed to load {}: {}", dllPath, formatSystemMessageQ(e)); + log::warn("failed to load {}: {}", dllPath, formatSystemMessage(e)); } } diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index e502bdb1..8a8a99ef 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -4029,7 +4029,8 @@ void MainWindow::doMoveOverwriteContentToMod(const QString &modAbsolutePath) MessageDialog::showMessage(tr("Move successful."), this); } else { - log::error("Move operation failed: {}", windowsErrorString(::GetLastError())); + const auto e = GetLastError(); + log::error("Move operation failed: {}", formatSystemMessage(e)); } m_OrganizerCore.refreshModList(); @@ -4058,7 +4059,8 @@ void MainWindow::clearOverwrite() updateProblemsButton(); m_OrganizerCore.refreshModList(); } else { - log::error("Delete operation failed: {}", windowsErrorString(::GetLastError())); + const auto e = GetLastError(); + log::error("Delete operation failed: {}", formatSystemMessage(e)); } } } @@ -6819,8 +6821,13 @@ void MainWindow::on_restoreButton_clicked() if (!shellCopy(pluginName + "." + choice, pluginName, true, this) || !shellCopy(loadOrderName + "." + choice, loadOrderName, true, this) || !shellCopy(lockedName + "." + choice, lockedName, true, this)) { - QMessageBox::critical(this, tr("Restore failed"), - tr("Failed to restore the backup. Errorcode: %1").arg(windowsErrorString(::GetLastError()))); + + const auto e = GetLastError(); + + QMessageBox::critical( + this, tr("Restore failed"), + tr("Failed to restore the backup. Errorcode: %1") + .arg(QString::fromStdWString(formatSystemMessage(e)))); } m_OrganizerCore.refreshESPList(true); } @@ -6841,8 +6848,11 @@ void MainWindow::on_restoreModsButton_clicked() QString choice = queryRestore(modlistName); if (!choice.isEmpty()) { if (!shellCopy(modlistName + "." + choice, modlistName, true, this)) { - QMessageBox::critical(this, tr("Restore failed"), - tr("Failed to restore the backup. Errorcode: %1").arg(windowsErrorString(::GetLastError()))); + const auto e = GetLastError(); + QMessageBox::critical( + this, tr("Restore failed"), + tr("Failed to restore the backup. Errorcode: %1") + .arg(formatSystemMessage(e))); } m_OrganizerCore.refreshModList(false); } @@ -6956,7 +6966,8 @@ void MainWindow::dropLocalFile(const QUrl &url, const QString &outputDir, bool m success = shellCopy(file.absoluteFilePath(), target, true, this); } if (!success) { - log::error("file operation failed: {}", windowsErrorString(::GetLastError())); + const auto e = GetLastError(); + log::error("file operation failed: {}", formatSystemMessage(e)); } } diff --git a/src/organizercore.cpp b/src/organizercore.cpp index f6802673..b61ebde8 100644 --- a/src/organizercore.cpp +++ b/src/organizercore.cpp @@ -354,7 +354,7 @@ QString OrganizerCore::commitSettings(const QString &iniFile) // make a second attempt using qt functions but if that fails print the // error from the first attempt if (!renameFile(iniFile + ".new", iniFile)) { - return windowsErrorString(err); + return QString::fromStdWString(formatSystemMessage(err)); } } return QString(); @@ -387,10 +387,12 @@ void OrganizerCore::storeSettings() + QString::fromStdWString(AppConfig::iniFileName()); if (QFileInfo(iniFile).exists()) { if (!shellCopy(iniFile, iniFile + ".new", true, qApp->activeWindow())) { + const auto e = GetLastError(); QMessageBox::critical( qApp->activeWindow(), tr("Failed to write settings"), tr("An error occurred trying to update MO settings to %1: %2") - .arg(iniFile, windowsErrorString(::GetLastError()))); + .arg(iniFile) + .arg(QString::fromStdWString(formatSystemMessage(e)))); return; } } diff --git a/src/profile.cpp b/src/profile.cpp index 27616986..6de1b097 100644 --- a/src/profile.cpp +++ b/src/profile.cpp @@ -265,7 +265,10 @@ void Profile::createTweakedIniFile() QString tweakedIni = m_Directory.absoluteFilePath("initweaks.ini"); if (QFile::exists(tweakedIni) && !shellDeleteQuiet(tweakedIni)) { - reportError(tr("failed to update tweaked ini file, wrong settings may be used: %1").arg(windowsErrorString(::GetLastError()))); + const auto e = GetLastError(); + reportError( + tr("failed to update tweaked ini file, wrong settings may be used: %1") + .arg(QString::fromStdWString(formatSystemMessage(e)))); return; } @@ -287,7 +290,7 @@ void Profile::createTweakedIniFile() if (error) { const auto e = ::GetLastError(); reportError(tr("failed to create tweaked ini: %1") - .arg(formatSystemMessageQ(e))); + .arg(QString::fromStdWString(formatSystemMessage(e)))); } log::debug("{} saved", QDir::toNativeSeparators(tweakedIni)); diff --git a/src/settings.cpp b/src/settings.cpp index ff5b9976..5ad066b2 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -220,7 +220,7 @@ QString Settings::deObfuscate(const QString key) } else { const auto e = GetLastError(); if (e != ERROR_NOT_FOUND) { - log::error("Retrieving encrypted data failed: {}", formatSystemMessageQ(e)); + log::error("Retrieving encrypted data failed: {}", formatSystemMessage(e)); } } delete[] keyData; @@ -365,7 +365,7 @@ bool Settings::setNexusApiKey(const QString& apiKey) { if (!obfuscate("APIKEY", apiKey)) { const auto e = GetLastError(); - log::error("Storing API key failed: {}", formatSystemMessageQ(e)); + log::error("Storing API key failed: {}", formatSystemMessage(e)); return false; } @@ -486,7 +486,7 @@ void Settings::setSteamLogin(QString username, QString password) } if (!obfuscate("steam_password", password)) { const auto e = GetLastError(); - log::error("Storing or deleting password failed: {}", formatSystemMessageQ(e)); + log::error("Storing or deleting password failed: {}", formatSystemMessage(e)); } } -- cgit v1.3.1 From 6b5c9675ae1e8b343dcbc9192d43c63e482a30bd Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sat, 20 Jul 2019 08:43:46 -0400 Subject: moved SettingsTab out of Settings split general tab --- src/CMakeLists.txt | 3 + src/settings.cpp | 204 ++++--------------------------- src/settings.h | 65 ++++------ src/settingsdialog.cpp | 105 ---------------- src/settingsdialog.h | 63 +++------- src/settingsdialoggeneral.cpp | 274 ++++++++++++++++++++++++++++++++++++++++++ src/settingsdialoggeneral.h | 53 ++++++++ 7 files changed, 392 insertions(+), 375 deletions(-) create mode 100644 src/settingsdialoggeneral.cpp create mode 100644 src/settingsdialoggeneral.h (limited to 'src/settings.cpp') diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 9785dc3d..29c419b5 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -37,6 +37,7 @@ SET(organizer_SRCS spawn.cpp singleinstance.cpp settingsdialog.cpp + settingsdialoggeneral.cpp settings.cpp selfupdater.cpp selectiondialog.cpp @@ -151,6 +152,7 @@ SET(organizer_HDRS spawn.h singleinstance.h settingsdialog.h + settingsdialoggeneral.h settings.h selfupdater.h selectiondialog.h @@ -431,6 +433,7 @@ set(profiles set(settings settings settingsdialog + settingsdialoggeneral ) set(utilities diff --git a/src/settings.cpp b/src/settings.cpp index 5ad066b2..0911b155 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -22,6 +22,7 @@ along with Mod Organizer. If not, see . #include "pluginsetting.h" #include "serverinfo.h" #include "settingsdialog.h" +#include "settingsdialoggeneral.h" #include "versioninfo.h" #include "appconfig.h" #include "organizercore.h" @@ -81,6 +82,23 @@ private: }; +SettingsTab::SettingsTab(Settings *m_parent, SettingsDialog &m_dialog) + : m_parent(m_parent) + , m_Settings(m_parent->settingsRef()) + , m_dialog(m_dialog) + , ui(m_dialog.ui) +{ +} + +SettingsTab::~SettingsTab() +{} + +QWidget* SettingsTab::parentWidget() +{ + return &m_dialog; +} + + Settings *Settings::s_Instance = nullptr; @@ -663,63 +681,9 @@ void Settings::writePluginBlacklist() m_Settings.endArray(); } -void Settings::addLanguages(QComboBox *languageBox) -{ - std::vector> languages; - - QDirIterator langIter(QCoreApplication::applicationDirPath() + "/translations", QDir::Files); - QString pattern = ToQString(AppConfig::translationPrefix()) + "_([a-z]{2,3}(_[A-Z]{2,2})?).qm"; - QRegExp exp(pattern); - while (langIter.hasNext()) { - langIter.next(); - QString file = langIter.fileName(); - if (exp.exactMatch(file)) { - QString languageCode = exp.cap(1); - QLocale locale(languageCode); - QString languageString = QString("%1 (%2)").arg(locale.nativeLanguageName()).arg(locale.nativeCountryName()); //QLocale::languageToString(locale.language()); - if (locale.language() == QLocale::Chinese) { - if (languageCode == "zh_TW") { - languageString = "Chinese (traditional)"; - } else { - languageString = "Chinese (simplified)"; - } - } - languages.push_back(std::make_pair(QString("%1").arg(languageString), exp.cap(1))); - //languageBox->addItem(QString("%1").arg(languageString), exp.cap(1)); - } - } - if (!languageBox->findText("English")) { - languages.push_back(std::make_pair(QString("English"), QString("en_US"))); - //languageBox->addItem("English", "en_US"); - } - std::sort(languages.begin(), languages.end()); - for (const auto &lang : languages) { - languageBox->addItem(lang.first, lang.second); - } -} - -void Settings::addStyles(QComboBox *styleBox) -{ - styleBox->addItem("None", ""); - styleBox->addItem("Fusion", "Fusion"); - - QDirIterator langIter(QCoreApplication::applicationDirPath() + "/" + ToQString(AppConfig::stylesheetsPath()), QStringList("*.qss"), QDir::Files); - while (langIter.hasNext()) { - langIter.next(); - QString style = langIter.fileName(); - styleBox->addItem(style, style); - } -} - -void Settings::resetDialogs() -{ - QuestionBoxMemory::resetDialogs(); -} - void Settings::query(PluginContainer *pluginContainer, QWidget *parent) { SettingsDialog dialog(pluginContainer, this, parent); - connect(&dialog, SIGNAL(resetDialogs()), this, SLOT(resetDialogs())); std::vector> tabs; @@ -787,128 +751,6 @@ void Settings::query(PluginContainer *pluginContainer, QWidget *parent) } -Settings::SettingsTab::SettingsTab(Settings *m_parent, SettingsDialog &m_dialog) - : m_parent(m_parent) - , m_Settings(m_parent->m_Settings) - , m_dialog(m_dialog) -{ -} - -Settings::SettingsTab::~SettingsTab() -{} - -Settings::GeneralTab::GeneralTab(Settings *m_parent, SettingsDialog &m_dialog) - : Settings::SettingsTab(m_parent, m_dialog) - , m_languageBox(m_dialog.findChild("languageBox")) - , m_styleBox(m_dialog.findChild("styleBox")) - , m_compactBox(m_dialog.findChild("compactBox")) - , m_showMetaBox(m_dialog.findChild("showMetaBox")) - , m_usePrereleaseBox(m_dialog.findChild("usePrereleaseBox")) - , m_overwritingBtn(m_dialog.findChild("overwritingBtn")) - , m_overwrittenBtn(m_dialog.findChild("overwrittenBtn")) - , m_overwritingArchiveBtn(m_dialog.findChild("overwritingArchiveBtn")) - , m_overwrittenArchiveBtn(m_dialog.findChild("overwrittenArchiveBtn")) - , m_containsBtn(m_dialog.findChild("containsBtn")) - , m_containedBtn(m_dialog.findChild("containedBtn")) - , m_colorSeparatorsBox(m_dialog.findChild("colorSeparatorsBox")) -{ - // FIXME I think 'addLanguages' lives in here not in parent - m_parent->addLanguages(m_languageBox); - { - QString languageCode = m_parent->language(); - int currentID = m_languageBox->findData(languageCode); - // I made a mess. :( Most languages are stored with only the iso country - // code (2 characters like "de") but chinese - // with the exact language variant (zh_TW) so I have to search for both - // variants - if (currentID == -1) { - currentID = m_languageBox->findData(languageCode.mid(0, 2)); - } - if (currentID != -1) { - m_languageBox->setCurrentIndex(currentID); - } - } - - // FIXME I think addStyles lives in here not in parent - m_parent->addStyles(m_styleBox); - { - int currentID = m_styleBox->findData( - m_Settings.value("Settings/style", "").toString()); - if (currentID != -1) { - m_styleBox->setCurrentIndex(currentID); - } - } - /* verision using palette only works with fusion theme for some stupid reason... - m_overwritingBtn->setAutoFillBackground(true); - m_overwrittenBtn->setAutoFillBackground(true); - m_containsBtn->setAutoFillBackground(true); - m_containedBtn->setAutoFillBackground(true); - m_overwritingBtn->setPalette(QPalette(m_parent->modlistOverwritingLooseColor())); - m_overwrittenBtn->setPalette(QPalette(m_parent->modlistOverwrittenLooseColor())); - m_containsBtn->setPalette(QPalette(m_parent->modlistContainsPluginColor())); - m_containedBtn->setPalette(QPalette(m_parent->pluginListContainedColor())); - QPalette palette1 = m_overwritingBtn->palette(); - QPalette palette2 = m_overwrittenBtn->palette(); - QPalette palette3 = m_containsBtn->palette(); - QPalette palette4 = m_containedBtn->palette(); - palette1.setColor(QPalette::Background, m_parent->modlistOverwritingLooseColor()); - palette2.setColor(QPalette::Background, m_parent->modlistOverwrittenLooseColor()); - palette3.setColor(QPalette::Background, m_parent->modlistContainsPluginColor()); - palette4.setColor(QPalette::Background, m_parent->pluginListContainedColor()); - m_overwritingBtn->setPalette(palette1); - m_overwrittenBtn->setPalette(palette2); - m_containsBtn->setPalette(palette3); - m_containedBtn->setPalette(palette4); - */ - - //version with stylesheet - m_dialog.setButtonColor(m_overwritingBtn, m_parent->modlistOverwritingLooseColor()); - m_dialog.setButtonColor(m_overwrittenBtn, m_parent->modlistOverwrittenLooseColor()); - m_dialog.setButtonColor(m_overwritingArchiveBtn, m_parent->modlistOverwritingArchiveColor()); - m_dialog.setButtonColor(m_overwrittenArchiveBtn, m_parent->modlistOverwrittenArchiveColor()); - m_dialog.setButtonColor(m_containsBtn, m_parent->modlistContainsPluginColor()); - m_dialog.setButtonColor(m_containedBtn, m_parent->pluginListContainedColor()); - - m_dialog.setOverwritingColor(m_parent->modlistOverwritingLooseColor()); - m_dialog.setOverwrittenColor(m_parent->modlistOverwrittenLooseColor()); - m_dialog.setOverwritingArchiveColor(m_parent->modlistOverwritingArchiveColor()); - m_dialog.setOverwrittenArchiveColor(m_parent->modlistOverwrittenArchiveColor()); - m_dialog.setContainsColor(m_parent->modlistContainsPluginColor()); - m_dialog.setContainedColor(m_parent->pluginListContainedColor()); - - m_compactBox->setChecked(m_parent->compactDownloads()); - m_showMetaBox->setChecked(m_parent->metaDownloads()); - m_usePrereleaseBox->setChecked(m_parent->usePrereleases()); - m_colorSeparatorsBox->setChecked(m_parent->colorSeparatorScrollbar()); -} - -void Settings::GeneralTab::update() -{ - QString oldLanguage = m_parent->language(); - QString newLanguage = m_languageBox->itemData(m_languageBox->currentIndex()).toString(); - if (newLanguage != oldLanguage) { - m_Settings.setValue("Settings/language", newLanguage); - emit m_parent->languageChanged(newLanguage); - } - - QString oldStyle = m_Settings.value("Settings/style", "").toString(); - QString newStyle = m_styleBox->itemData(m_styleBox->currentIndex()).toString(); - if (oldStyle != newStyle) { - m_Settings.setValue("Settings/style", newStyle); - emit m_parent->styleChanged(newStyle); - } - - m_Settings.setValue("Settings/overwritingLooseFilesColor", m_dialog.getOverwritingColor()); - m_Settings.setValue("Settings/overwrittenLooseFilesColor", m_dialog.getOverwrittenColor()); - m_Settings.setValue("Settings/overwritingArchiveFilesColor", m_dialog.getOverwritingArchiveColor()); - m_Settings.setValue("Settings/overwrittenArchiveFilesColor", m_dialog.getOverwrittenArchiveColor()); - m_Settings.setValue("Settings/containsPluginColor", m_dialog.getContainsColor()); - m_Settings.setValue("Settings/containedColor", m_dialog.getContainedColor()); - m_Settings.setValue("Settings/compact_downloads", m_compactBox->isChecked()); - m_Settings.setValue("Settings/meta_downloads", m_showMetaBox->isChecked()); - m_Settings.setValue("Settings/use_prereleases", m_usePrereleaseBox->isChecked()); - m_Settings.setValue("Settings/colorSeparatorScrollbars", m_colorSeparatorsBox->isChecked()); -} Settings::PathsTab::PathsTab(Settings *parent, SettingsDialog &dialog) : SettingsTab(parent, dialog) @@ -991,7 +833,7 @@ void Settings::PathsTab::update() } Settings::DiagnosticsTab::DiagnosticsTab(Settings *m_parent, SettingsDialog &m_dialog) - : Settings::SettingsTab(m_parent, m_dialog) + : SettingsTab(m_parent, m_dialog) , m_logLevelBox(m_dialog.findChild("logLevelBox")) , m_dumpsTypeBox(m_dialog.findChild("dumpsTypeBox")) , m_dumpsMaxEdit(m_dialog.findChild("dumpsMaxEdit")) @@ -1036,7 +878,7 @@ void Settings::DiagnosticsTab::setLevelsBox() } Settings::NexusTab::NexusTab(Settings *parent, SettingsDialog &dialog) - : Settings::SettingsTab(parent, dialog) + : SettingsTab(parent, dialog) , m_offlineBox(dialog.findChild("offlineBox")) , m_proxyBox(dialog.findChild("proxyBox")) , m_knownServersList(dialog.findChild("knownServersList")) @@ -1114,7 +956,7 @@ void Settings::NexusTab::update() } Settings::SteamTab::SteamTab(Settings *m_parent, SettingsDialog &m_dialog) - : Settings::SettingsTab(m_parent, m_dialog) + : SettingsTab(m_parent, m_dialog) , m_steamUserEdit(m_dialog.findChild("steamUserEdit")) , m_steamPassEdit(m_dialog.findChild("steamPassEdit")) { @@ -1134,7 +976,7 @@ void Settings::SteamTab::update() } Settings::PluginsTab::PluginsTab(Settings *m_parent, SettingsDialog &m_dialog) - : Settings::SettingsTab(m_parent, m_dialog) + : SettingsTab(m_parent, m_dialog) , m_pluginsList(m_dialog.findChild("pluginsList")) , m_pluginBlacklistList(m_dialog.findChild("pluginBlacklist")) { @@ -1181,7 +1023,7 @@ void Settings::PluginsTab::update() Settings::WorkaroundsTab::WorkaroundsTab(Settings *m_parent, SettingsDialog &m_dialog) - : Settings::SettingsTab(m_parent, 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")) diff --git a/src/settings.h b/src/settings.h index c66eb94c..e88080ba 100644 --- a/src/settings.h +++ b/src/settings.h @@ -55,8 +55,30 @@ namespace MOBase { class IPluginGame; } +namespace Ui { + class SettingsDialog; +} + class SettingsDialog; class PluginContainer; +class Settings; + +class SettingsTab +{ +public: + SettingsTab(Settings *m_parent, SettingsDialog &m_dialog); + virtual ~SettingsTab(); + + virtual void update() = 0; + +protected: + Settings *m_parent; + QSettings &m_Settings; + SettingsDialog &m_dialog; + Ui::SettingsDialog* ui; + + QWidget* parentWidget(); +}; /** * manages the settings for Mod Organizer. The settings are not cached @@ -404,6 +426,8 @@ public: */ bool colorSeparatorScrollbar() const; + QSettings& settingsRef() { return m_Settings; } + public slots: void managedGameChanged(MOBase::IPluginGame const *gamePlugin); @@ -414,49 +438,10 @@ private: static bool obfuscate(const QString key, const QString data); static QString deObfuscate(const QString key); - void addLanguages(QComboBox *languageBox); - void addStyles(QComboBox *styleBox); void readPluginBlacklist(); void writePluginBlacklist(); QString getConfigurablePath(const QString &key, const QString &def, bool resolve) const; - class SettingsTab - { - public: - SettingsTab(Settings *m_parent, SettingsDialog &m_dialog); - virtual ~SettingsTab(); - - virtual void update() = 0; - - protected: - Settings *m_parent; - QSettings &m_Settings; - SettingsDialog &m_dialog; - - }; - - /** Display/store the configuration in the 'general' tab of the settings dialogue */ - class GeneralTab : public SettingsTab - { - public: - GeneralTab(Settings *m_parent, SettingsDialog &m_dialog); - - void update(); - - private: - QComboBox *m_languageBox; - QComboBox *m_styleBox; - QCheckBox *m_compactBox; - QCheckBox *m_showMetaBox; - QCheckBox *m_usePrereleaseBox; - QPushButton *m_overwritingBtn; - QPushButton *m_overwrittenBtn; - QPushButton *m_overwritingArchiveBtn; - QPushButton *m_overwrittenArchiveBtn; - QPushButton *m_containsBtn; - QPushButton *m_containedBtn; - QCheckBox *m_colorSeparatorsBox; - }; class PathsTab : public SettingsTab { @@ -554,8 +539,6 @@ private: private slots: - void resetDialogs(); - signals: void languageChanged(const QString &newLanguage); diff --git a/src/settingsdialog.cpp b/src/settingsdialog.cpp index 0dae31ac..f922cfb9 100644 --- a/src/settingsdialog.cpp +++ b/src/settingsdialog.cpp @@ -131,23 +131,6 @@ QString SettingsDialog::getColoredButtonStyleSheet() const "}"); } -void SettingsDialog::setButtonColor(QPushButton *button, const QColor &color) -{ - button->setStyleSheet( - QString("QPushButton {" - "background-color: rgba(%1, %2, %3, %4);" - "color: %5;" - "border: 1px solid;" - "padding: 3px;" - "}") - .arg(color.red()) - .arg(color.green()) - .arg(color.blue()) - .arg(color.alpha()) - .arg(Settings::getIdealTextColor(color).name()) - ); -}; - void SettingsDialog::accept() { QString newModPath = ui->modDirEdit->text(); @@ -181,14 +164,6 @@ bool SettingsDialog::getApiKeyChanged() return m_keyChanged; } -void SettingsDialog::on_categoriesBtn_clicked() -{ - CategoriesDialog dialog(this); - if (dialog.exec() == QDialog::Accepted) { - dialog.commitChanges(); - } -} - void SettingsDialog::on_execBlacklistBtn_clicked() { bool ok = false; @@ -299,86 +274,6 @@ void SettingsDialog::on_browseGameDirBtn_clicked() } } -void SettingsDialog::on_containsBtn_clicked() -{ - QColor result = QColorDialog::getColor(m_ContainsColor, this, "Color Picker: Mod contains selected plugin", QColorDialog::ShowAlphaChannel); - if (result.isValid()) { - m_ContainsColor = result; - setButtonColor(ui->containsBtn, result); - } -} - -void SettingsDialog::on_containedBtn_clicked() -{ - QColor result = QColorDialog::getColor(m_ContainedColor, this, "ColorPicker: Plugin is Contained in selected Mod", QColorDialog::ShowAlphaChannel); - if (result.isValid()) { - m_ContainedColor = result; - setButtonColor(ui->containedBtn, result); - } -} - -void SettingsDialog::on_overwrittenBtn_clicked() -{ - QColor result = QColorDialog::getColor(m_OverwrittenColor, this, "ColorPicker: Is overwritten (loose files)", QColorDialog::ShowAlphaChannel); - if (result.isValid()) { - m_OverwrittenColor = result; - setButtonColor(ui->overwrittenBtn, result); - } -} - -void SettingsDialog::on_overwritingBtn_clicked() -{ - QColor result = QColorDialog::getColor(m_OverwritingColor, this, "ColorPicker: Is overwriting (loose files)", QColorDialog::ShowAlphaChannel); - if (result.isValid()) { - m_OverwritingColor = result; - setButtonColor(ui->overwritingBtn, result); - } -} - -void SettingsDialog::on_overwrittenArchiveBtn_clicked() -{ - QColor result = QColorDialog::getColor(m_OverwrittenArchiveColor, this, "ColorPicker: Is overwritten (archive files)", QColorDialog::ShowAlphaChannel); - if (result.isValid()) { - m_OverwrittenArchiveColor = result; - setButtonColor(ui->overwrittenArchiveBtn, result); - } -} - -void SettingsDialog::on_overwritingArchiveBtn_clicked() -{ - QColor result = QColorDialog::getColor(m_OverwritingArchiveColor, this, "ColorPicker: Is overwriting (archive files)", QColorDialog::ShowAlphaChannel); - if (result.isValid()) { - m_OverwritingArchiveColor = result; - setButtonColor(ui->overwritingArchiveBtn, result); - } -} - -void SettingsDialog::on_resetColorsBtn_clicked() -{ - m_OverwritingColor = QColor(255, 0, 0, 64); - m_OverwrittenColor = QColor(0, 255, 0, 64); - m_OverwritingArchiveColor = QColor(255, 0, 255, 64); - m_OverwrittenArchiveColor = QColor(0, 255, 255, 64); - m_ContainsColor = QColor(0, 0, 255, 64); - m_ContainedColor = QColor(0, 0, 255, 64); - - setButtonColor(ui->overwritingBtn, m_OverwritingColor); - setButtonColor(ui->overwrittenBtn, m_OverwrittenColor); - setButtonColor(ui->overwritingArchiveBtn, m_OverwritingArchiveColor); - setButtonColor(ui->overwrittenArchiveBtn, m_OverwrittenArchiveColor); - setButtonColor(ui->containsBtn, m_ContainsColor); - setButtonColor(ui->containedBtn, m_ContainedColor); -} - -void SettingsDialog::on_resetDialogsButton_clicked() -{ - if (QMessageBox::question(this, tr("Confirm?"), - tr("This will make all dialogs show up again where you checked the \"Remember selection\"-box. Continue?"), - QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { - emit resetDialogs(); - } -} - void SettingsDialog::on_nexusConnect_clicked() { if (m_nexusLogin && m_nexusLogin->isActive()) { diff --git a/src/settingsdialog.h b/src/settingsdialog.h index c5f487fd..01a0afa2 100644 --- a/src/settingsdialog.h +++ b/src/settingsdialog.h @@ -54,7 +54,7 @@ public: */ QString getColoredButtonStyleSheet() const; - void setButtonColor(QPushButton *button, const QColor &color); + Ui::SettingsDialog *ui; public slots: @@ -62,7 +62,6 @@ public slots: signals: - void resetDialogs(); void retryApiConnection(); private: @@ -71,73 +70,41 @@ private: void normalizePath(QLineEdit *lineEdit); public: - - QColor getOverwritingColor() { return m_OverwritingColor; } - QColor getOverwrittenColor() { return m_OverwrittenColor; } - QColor getOverwritingArchiveColor() { return m_OverwritingArchiveColor; } - QColor getOverwrittenArchiveColor() { return m_OverwrittenArchiveColor; } - QColor getContainsColor() { return m_ContainsColor; } - QColor getContainedColor() { return m_ContainedColor; } QString getExecutableBlacklist() { return m_ExecutableBlacklist; } + void setExecutableBlacklist(QString blacklist) { m_ExecutableBlacklist = blacklist; } bool getResetGeometries(); bool getApiKeyChanged(); - void setOverwritingColor(QColor col) { m_OverwritingColor = col; } - void setOverwrittenColor(QColor col) { m_OverwrittenColor = col; } - void setOverwritingArchiveColor(QColor col) { m_OverwritingArchiveColor = col; } - void setOverwrittenArchiveColor(QColor col) { m_OverwrittenArchiveColor = col; } - void setContainsColor(QColor col) { m_ContainsColor = col; } - void setContainedColor(QColor col) { m_ContainedColor = col; } - void setExecutableBlacklist(QString blacklist) { m_ExecutableBlacklist = blacklist; } - - private slots: - void on_categoriesBtn_clicked(); - void on_execBlacklistBtn_clicked(); - void on_bsaDateBtn_clicked(); - void on_browseDownloadDirBtn_clicked(); - void on_browseModDirBtn_clicked(); - void on_browseCacheDirBtn_clicked(); - void on_resetDialogsButton_clicked(); - void on_pluginsList_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous); void on_associateButton_clicked(); - void on_clearCacheButton_clicked(); - void on_nexusDisconnect_clicked(); + void on_baseDirEdit_editingFinished(); void on_browseBaseDirBtn_clicked(); + void on_browseCacheDirBtn_clicked(); + void on_browseDownloadDirBtn_clicked(); + void on_browseGameDirBtn_clicked(); + void on_browseModDirBtn_clicked(); void on_browseOverwriteDirBtn_clicked(); void on_browseProfilesDirBtn_clicked(); - void on_browseGameDirBtn_clicked(); - void on_overwritingBtn_clicked(); - void on_overwrittenBtn_clicked(); - void on_overwritingArchiveBtn_clicked(); - void on_overwrittenArchiveBtn_clicked(); - void on_containsBtn_clicked(); - void on_containedBtn_clicked(); - void on_resetColorsBtn_clicked(); - void on_baseDirEdit_editingFinished(); + void on_bsaDateBtn_clicked(); + void on_cacheDirEdit_editingFinished(); + void on_clearCacheButton_clicked(); void on_downloadDirEdit_editingFinished(); + void on_execBlacklistBtn_clicked(); void on_modDirEdit_editingFinished(); - void on_cacheDirEdit_editingFinished(); - void on_profilesDirEdit_editingFinished(); - void on_overwriteDirEdit_editingFinished(); void on_nexusConnect_clicked(); + void on_nexusDisconnect_clicked(); void on_nexusManualKey_clicked(); + void on_overwriteDirEdit_editingFinished(); + void on_pluginsList_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous); + void on_profilesDirEdit_editingFinished(); void on_resetGeometryBtn_clicked(); void deleteBlacklistItem(); private: - Ui::SettingsDialog *ui; Settings* m_settings; PluginContainer *m_PluginContainer; - QColor m_OverwritingColor; - QColor m_OverwrittenColor; - QColor m_OverwritingArchiveColor; - QColor m_OverwrittenArchiveColor; - QColor m_ContainsColor; - QColor m_ContainedColor; - bool m_GeometriesReset; bool m_keyChanged; diff --git a/src/settingsdialoggeneral.cpp b/src/settingsdialoggeneral.cpp new file mode 100644 index 00000000..b22b04fd --- /dev/null +++ b/src/settingsdialoggeneral.cpp @@ -0,0 +1,274 @@ +#include "settingsdialoggeneral.h" +#include "ui_settingsdialog.h" +#include "appconfig.h" +#include "categoriesdialog.h" +#include + +using MOBase::QuestionBoxMemory; + +GeneralTab::GeneralTab(Settings *m_parent, SettingsDialog &m_dialog) + : SettingsTab(m_parent, m_dialog) +{ + addLanguages(); + { + QString languageCode = m_parent->language(); + int currentID = ui->languageBox->findData(languageCode); + // I made a mess. :( Most languages are stored with only the iso country + // code (2 characters like "de") but chinese + // with the exact language variant (zh_TW) so I have to search for both + // variants + if (currentID == -1) { + currentID = ui->languageBox->findData(languageCode.mid(0, 2)); + } + if (currentID != -1) { + ui->languageBox->setCurrentIndex(currentID); + } + } + + addStyles(); + { + int currentID = ui->styleBox->findData( + m_Settings.value("Settings/style", "").toString()); + if (currentID != -1) { + ui->styleBox->setCurrentIndex(currentID); + } + } + /* verision using palette only works with fusion theme for some stupid reason... + m_overwritingBtn->setAutoFillBackground(true); + m_overwrittenBtn->setAutoFillBackground(true); + m_containsBtn->setAutoFillBackground(true); + m_containedBtn->setAutoFillBackground(true); + m_overwritingBtn->setPalette(QPalette(m_parent->modlistOverwritingLooseColor())); + m_overwrittenBtn->setPalette(QPalette(m_parent->modlistOverwrittenLooseColor())); + m_containsBtn->setPalette(QPalette(m_parent->modlistContainsPluginColor())); + m_containedBtn->setPalette(QPalette(m_parent->pluginListContainedColor())); + QPalette palette1 = m_overwritingBtn->palette(); + QPalette palette2 = m_overwrittenBtn->palette(); + QPalette palette3 = m_containsBtn->palette(); + QPalette palette4 = m_containedBtn->palette(); + palette1.setColor(QPalette::Background, m_parent->modlistOverwritingLooseColor()); + palette2.setColor(QPalette::Background, m_parent->modlistOverwrittenLooseColor()); + palette3.setColor(QPalette::Background, m_parent->modlistContainsPluginColor()); + palette4.setColor(QPalette::Background, m_parent->pluginListContainedColor()); + m_overwritingBtn->setPalette(palette1); + m_overwrittenBtn->setPalette(palette2); + m_containsBtn->setPalette(palette3); + m_containedBtn->setPalette(palette4); + */ + + //version with stylesheet + setButtonColor(ui->overwritingBtn, m_parent->modlistOverwritingLooseColor()); + setButtonColor(ui->overwrittenBtn, m_parent->modlistOverwrittenLooseColor()); + setButtonColor(ui->overwritingArchiveBtn, m_parent->modlistOverwritingArchiveColor()); + setButtonColor(ui->overwrittenArchiveBtn, m_parent->modlistOverwrittenArchiveColor()); + setButtonColor(ui->containsBtn, m_parent->modlistContainsPluginColor()); + setButtonColor(ui->containedBtn, m_parent->pluginListContainedColor()); + + setOverwritingColor(m_parent->modlistOverwritingLooseColor()); + setOverwrittenColor(m_parent->modlistOverwrittenLooseColor()); + setOverwritingArchiveColor(m_parent->modlistOverwritingArchiveColor()); + setOverwrittenArchiveColor(m_parent->modlistOverwrittenArchiveColor()); + setContainsColor(m_parent->modlistContainsPluginColor()); + setContainedColor(m_parent->pluginListContainedColor()); + + ui->compactBox->setChecked(m_parent->compactDownloads()); + ui->showMetaBox->setChecked(m_parent->metaDownloads()); + ui->usePrereleaseBox->setChecked(m_parent->usePrereleases()); + ui->colorSeparatorsBox->setChecked(m_parent->colorSeparatorScrollbar()); + + QObject::connect(ui->overwritingArchiveBtn, &QPushButton::clicked, [&]{ on_overwritingArchiveBtn_clicked(); }); + QObject::connect(ui->overwritingBtn, &QPushButton::clicked, [&]{ on_overwritingBtn_clicked(); }); + QObject::connect(ui->overwrittenArchiveBtn, &QPushButton::clicked, [&]{ on_overwrittenArchiveBtn_clicked(); }); + QObject::connect(ui->overwrittenBtn, &QPushButton::clicked, [&]{ on_overwrittenBtn_clicked(); }); + QObject::connect(ui->containedBtn, &QPushButton::clicked, [&]{ on_containedBtn_clicked(); }); + QObject::connect(ui->containsBtn, &QPushButton::clicked, [&]{ on_containsBtn_clicked(); }); + QObject::connect(ui->categoriesBtn, &QPushButton::clicked, [&]{ on_categoriesBtn_clicked(); }); + QObject::connect(ui->resetColorsBtn, &QPushButton::clicked, [&]{ on_resetColorsBtn_clicked(); }); + QObject::connect(ui->resetDialogsButton, &QPushButton::clicked, [&]{ on_resetDialogsButton_clicked(); }); +} + +void GeneralTab::update() +{ + QString oldLanguage = m_parent->language(); + QString newLanguage = ui->languageBox->itemData(ui->languageBox->currentIndex()).toString(); + if (newLanguage != oldLanguage) { + m_Settings.setValue("Settings/language", newLanguage); + emit m_parent->languageChanged(newLanguage); + } + + QString oldStyle = m_Settings.value("Settings/style", "").toString(); + QString newStyle = ui->styleBox->itemData(ui->styleBox->currentIndex()).toString(); + if (oldStyle != newStyle) { + m_Settings.setValue("Settings/style", newStyle); + emit m_parent->styleChanged(newStyle); + } + + m_Settings.setValue("Settings/overwritingLooseFilesColor", getOverwritingColor()); + m_Settings.setValue("Settings/overwrittenLooseFilesColor", getOverwrittenColor()); + m_Settings.setValue("Settings/overwritingArchiveFilesColor", getOverwritingArchiveColor()); + m_Settings.setValue("Settings/overwrittenArchiveFilesColor", getOverwrittenArchiveColor()); + m_Settings.setValue("Settings/containsPluginColor", getContainsColor()); + m_Settings.setValue("Settings/containedColor", getContainedColor()); + m_Settings.setValue("Settings/compact_downloads", ui->compactBox->isChecked()); + m_Settings.setValue("Settings/meta_downloads", ui->showMetaBox->isChecked()); + m_Settings.setValue("Settings/use_prereleases", ui->usePrereleaseBox->isChecked()); + m_Settings.setValue("Settings/colorSeparatorScrollbars", ui->colorSeparatorsBox->isChecked()); +} + +void GeneralTab::addLanguages() +{ + std::vector> languages; + + QDirIterator langIter(QCoreApplication::applicationDirPath() + "/translations", QDir::Files); + QString pattern = QString::fromStdWString(AppConfig::translationPrefix()) + "_([a-z]{2,3}(_[A-Z]{2,2})?).qm"; + QRegExp exp(pattern); + while (langIter.hasNext()) { + langIter.next(); + QString file = langIter.fileName(); + if (exp.exactMatch(file)) { + QString languageCode = exp.cap(1); + QLocale locale(languageCode); + QString languageString = QString("%1 (%2)").arg(locale.nativeLanguageName()).arg(locale.nativeCountryName()); //QLocale::languageToString(locale.language()); + if (locale.language() == QLocale::Chinese) { + if (languageCode == "zh_TW") { + languageString = "Chinese (traditional)"; + } else { + languageString = "Chinese (simplified)"; + } + } + languages.push_back(std::make_pair(QString("%1").arg(languageString), exp.cap(1))); + //languageBox->addItem(QString("%1").arg(languageString), exp.cap(1)); + } + } + if (!ui->languageBox->findText("English")) { + languages.push_back(std::make_pair(QString("English"), QString("en_US"))); + //languageBox->addItem("English", "en_US"); + } + std::sort(languages.begin(), languages.end()); + for (const auto &lang : languages) { + ui->languageBox->addItem(lang.first, lang.second); + } +} + +void GeneralTab::addStyles() +{ + ui->styleBox->addItem("None", ""); + ui->styleBox->addItem("Fusion", "Fusion"); + + QDirIterator langIter(QCoreApplication::applicationDirPath() + "/" + QString::fromStdWString(AppConfig::stylesheetsPath()), QStringList("*.qss"), QDir::Files); + while (langIter.hasNext()) { + langIter.next(); + QString style = langIter.fileName(); + ui->styleBox->addItem(style, style); + } +} + +void GeneralTab::resetDialogs() +{ + QuestionBoxMemory::resetDialogs(); +} + +void GeneralTab::setButtonColor(QPushButton *button, const QColor &color) +{ + button->setStyleSheet( + QString("QPushButton {" + "background-color: rgba(%1, %2, %3, %4);" + "color: %5;" + "border: 1px solid;" + "padding: 3px;" + "}") + .arg(color.red()) + .arg(color.green()) + .arg(color.blue()) + .arg(color.alpha()) + .arg(Settings::getIdealTextColor(color).name()) + ); +}; + +void GeneralTab::on_containsBtn_clicked() +{ + QColor result = QColorDialog::getColor(m_ContainsColor, parentWidget(), "Color Picker: Mod contains selected plugin", QColorDialog::ShowAlphaChannel); + if (result.isValid()) { + m_ContainsColor = result; + setButtonColor(ui->containsBtn, result); + } +} + +void GeneralTab::on_containedBtn_clicked() +{ + QColor result = QColorDialog::getColor(m_ContainedColor, parentWidget(), "ColorPicker: Plugin is Contained in selected Mod", QColorDialog::ShowAlphaChannel); + if (result.isValid()) { + m_ContainedColor = result; + setButtonColor(ui->containedBtn, result); + } +} + +void GeneralTab::on_overwrittenBtn_clicked() +{ + QColor result = QColorDialog::getColor(m_OverwrittenColor, parentWidget(), "ColorPicker: Is overwritten (loose files)", QColorDialog::ShowAlphaChannel); + if (result.isValid()) { + m_OverwrittenColor = result; + setButtonColor(ui->overwrittenBtn, result); + } +} + +void GeneralTab::on_overwritingBtn_clicked() +{ + QColor result = QColorDialog::getColor(m_OverwritingColor, parentWidget(), "ColorPicker: Is overwriting (loose files)", QColorDialog::ShowAlphaChannel); + if (result.isValid()) { + m_OverwritingColor = result; + setButtonColor(ui->overwritingBtn, result); + } +} + +void GeneralTab::on_overwrittenArchiveBtn_clicked() +{ + QColor result = QColorDialog::getColor(m_OverwrittenArchiveColor, parentWidget(), "ColorPicker: Is overwritten (archive files)", QColorDialog::ShowAlphaChannel); + if (result.isValid()) { + m_OverwrittenArchiveColor = result; + setButtonColor(ui->overwrittenArchiveBtn, result); + } +} + +void GeneralTab::on_overwritingArchiveBtn_clicked() +{ + QColor result = QColorDialog::getColor(m_OverwritingArchiveColor, parentWidget(), "ColorPicker: Is overwriting (archive files)", QColorDialog::ShowAlphaChannel); + if (result.isValid()) { + m_OverwritingArchiveColor = result; + setButtonColor(ui->overwritingArchiveBtn, result); + } +} + +void GeneralTab::on_resetColorsBtn_clicked() +{ + m_OverwritingColor = QColor(255, 0, 0, 64); + m_OverwrittenColor = QColor(0, 255, 0, 64); + m_OverwritingArchiveColor = QColor(255, 0, 255, 64); + m_OverwrittenArchiveColor = QColor(0, 255, 255, 64); + m_ContainsColor = QColor(0, 0, 255, 64); + m_ContainedColor = QColor(0, 0, 255, 64); + + setButtonColor(ui->overwritingBtn, m_OverwritingColor); + setButtonColor(ui->overwrittenBtn, m_OverwrittenColor); + setButtonColor(ui->overwritingArchiveBtn, m_OverwritingArchiveColor); + setButtonColor(ui->overwrittenArchiveBtn, m_OverwrittenArchiveColor); + setButtonColor(ui->containsBtn, m_ContainsColor); + setButtonColor(ui->containedBtn, m_ContainedColor); +} + +void GeneralTab::on_resetDialogsButton_clicked() +{ + if (QMessageBox::question(parentWidget(), QObject::tr("Confirm?"), + QObject::tr("This will make all dialogs show up again where you checked the \"Remember selection\"-box. Continue?"), + QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { + resetDialogs(); + } +} + +void GeneralTab::on_categoriesBtn_clicked() +{ + CategoriesDialog dialog(parentWidget()); + if (dialog.exec() == QDialog::Accepted) { + dialog.commitChanges(); + } +} diff --git a/src/settingsdialoggeneral.h b/src/settingsdialoggeneral.h new file mode 100644 index 00000000..1f1b4637 --- /dev/null +++ b/src/settingsdialoggeneral.h @@ -0,0 +1,53 @@ +#ifndef SETTINGSDIALOGGENERAL_H +#define SETTINGSDIALOGGENERAL_H + +#include "settingsdialog.h" +#include "settings.h" + +class GeneralTab : public SettingsTab +{ +public: + GeneralTab(Settings *m_parent, SettingsDialog &m_dialog); + + void update(); + +private: + QColor m_OverwritingColor; + QColor m_OverwrittenColor; + QColor m_OverwritingArchiveColor; + QColor m_OverwrittenArchiveColor; + QColor m_ContainsColor; + QColor m_ContainedColor; + + void addLanguages(); + void addStyles(); + void resetDialogs(); + void setButtonColor(QPushButton *button, const QColor &color); + + QColor getOverwritingColor() { return m_OverwritingColor; } + QColor getOverwrittenColor() { return m_OverwrittenColor; } + QColor getOverwritingArchiveColor() { return m_OverwritingArchiveColor; } + QColor getOverwrittenArchiveColor() { return m_OverwrittenArchiveColor; } + QColor getContainsColor() { return m_ContainsColor; } + QColor getContainedColor() { return m_ContainedColor; } + + void setOverwritingColor(QColor col) { m_OverwritingColor = col; } + void setOverwrittenColor(QColor col) { m_OverwrittenColor = col; } + void setOverwritingArchiveColor(QColor col) { m_OverwritingArchiveColor = col; } + void setOverwrittenArchiveColor(QColor col) { m_OverwrittenArchiveColor = col; } + void setContainsColor(QColor col) { m_ContainsColor = col; } + void setContainedColor(QColor col) { m_ContainedColor = col; } + + void on_overwritingArchiveBtn_clicked(); + void on_overwritingBtn_clicked(); + void on_overwrittenArchiveBtn_clicked(); + void on_overwrittenBtn_clicked(); + void on_containedBtn_clicked(); + void on_containsBtn_clicked(); + + void on_categoriesBtn_clicked(); + void on_resetColorsBtn_clicked(); + void on_resetDialogsButton_clicked(); +}; + +#endif // SETTINGSDIALOGGENERAL_H -- cgit v1.3.1 From 0a5ce34b1a80694fbfe6a4d6b4f032b9c11a5376 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sat, 20 Jul 2019 09:02:03 -0400 Subject: split paths tab --- src/CMakeLists.txt | 3 + src/settings.cpp | 81 +---------------- src/settings.h | 17 +--- src/settingsdialog.cpp | 113 ------------------------ src/settingsdialog.h | 14 --- src/settingsdialogpaths.cpp | 205 ++++++++++++++++++++++++++++++++++++++++++++ src/settingsdialogpaths.h | 33 +++++++ 7 files changed, 243 insertions(+), 223 deletions(-) create mode 100644 src/settingsdialogpaths.cpp create mode 100644 src/settingsdialogpaths.h (limited to 'src/settings.cpp') diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 29c419b5..98d59996 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -38,6 +38,7 @@ SET(organizer_SRCS singleinstance.cpp settingsdialog.cpp settingsdialoggeneral.cpp + settingsdialogpaths.cpp settings.cpp selfupdater.cpp selectiondialog.cpp @@ -153,6 +154,7 @@ SET(organizer_HDRS singleinstance.h settingsdialog.h settingsdialoggeneral.h + settingsdialogpaths.h settings.h selfupdater.h selectiondialog.h @@ -434,6 +436,7 @@ set(settings settings settingsdialog settingsdialoggeneral + settingsdialogpaths ) set(utilities diff --git a/src/settings.cpp b/src/settings.cpp index 0911b155..bed8e789 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -23,6 +23,7 @@ along with Mod Organizer. If not, see . #include "serverinfo.h" #include "settingsdialog.h" #include "settingsdialoggeneral.h" +#include "settingsdialogpaths.h" #include "versioninfo.h" #include "appconfig.h" #include "organizercore.h" @@ -752,86 +753,6 @@ void Settings::query(PluginContainer *pluginContainer, QWidget *parent) } -Settings::PathsTab::PathsTab(Settings *parent, SettingsDialog &dialog) - : SettingsTab(parent, dialog) - , m_baseDirEdit(m_dialog.findChild("baseDirEdit")) - , m_downloadDirEdit(m_dialog.findChild("downloadDirEdit")) - , m_modDirEdit(m_dialog.findChild("modDirEdit")) - , m_cacheDirEdit(m_dialog.findChild("cacheDirEdit")) - , m_profilesDirEdit(m_dialog.findChild("profilesDirEdit")) - , m_overwriteDirEdit(m_dialog.findChild("overwriteDirEdit")) - , m_managedGameDirEdit(m_dialog.findChild("managedGameDirEdit")) -{ - m_baseDirEdit->setText(m_parent->getBaseDirectory()); - m_managedGameDirEdit->setText(m_parent->m_GamePlugin->gameDirectory().absoluteFilePath(m_parent->m_GamePlugin->binaryName())); - QString basePath = parent->getBaseDirectory(); - QDir baseDir(basePath); - for (const auto &dir : { - std::make_pair(m_downloadDirEdit, m_parent->getDownloadDirectory(false)), - std::make_pair(m_modDirEdit, m_parent->getModDirectory(false)), - std::make_pair(m_cacheDirEdit, m_parent->getCacheDirectory(false)), - std::make_pair(m_profilesDirEdit, m_parent->getProfileDirectory(false)), - std::make_pair(m_overwriteDirEdit, m_parent->getOverwriteDirectory(false)) - }) { - QString storePath = baseDir.relativeFilePath(dir.second); - storePath = dir.second; - dir.first->setText(storePath); - } -} - -void Settings::PathsTab::update() -{ - typedef std::tuple Directory; - - QString basePath = m_parent->getBaseDirectory(); - - for (const Directory &dir :{ - Directory{m_downloadDirEdit->text(), "download_directory", AppConfig::downloadPath()}, - Directory{m_cacheDirEdit->text(), "cache_directory", AppConfig::cachePath()}, - Directory{m_modDirEdit->text(), "mod_directory", AppConfig::modsPath()}, - Directory{m_overwriteDirEdit->text(), "overwrite_directory", AppConfig::overwritePath()}, - Directory{m_profilesDirEdit->text(), "profiles_directory", AppConfig::profilesPath()} - }) { - QString path, settingsKey; - std::wstring defaultName; - std::tie(path, settingsKey, defaultName) = dir; - - settingsKey = QString("Settings/%1").arg(settingsKey); - - QString realPath = path; - realPath.replace("%BASE_DIR%", m_baseDirEdit->text()); - - if (!QDir(realPath).exists()) { - if (!QDir().mkpath(realPath)) { - QMessageBox::warning(qApp->activeWindow(), tr("Error"), - tr("Failed to create \"%1\", you may not have the " - "necessary permission. path remains unchanged.") - .arg(realPath)); - } - } - - if (QFileInfo(realPath) - != QFileInfo(basePath + "/" + QString::fromStdWString(defaultName))) { - m_Settings.setValue(settingsKey, path); - } else { - m_Settings.remove(settingsKey); - } - } - - if (QFileInfo(m_baseDirEdit->text()) != - QFileInfo(qApp->property("dataPath").toString())) { - m_Settings.setValue("Settings/base_directory", m_baseDirEdit->text()); - } else { - m_Settings.remove("Settings/base_directory"); - } - - QFileInfo oldGameExe(m_parent->m_GamePlugin->gameDirectory().absoluteFilePath(m_parent->m_GamePlugin->binaryName())); - QFileInfo newGameExe(m_managedGameDirEdit->text()); - if (oldGameExe != newGameExe) { - m_Settings.setValue("gamePath", newGameExe.absolutePath()); - } -} - Settings::DiagnosticsTab::DiagnosticsTab(Settings *m_parent, SettingsDialog &m_dialog) : SettingsTab(m_parent, m_dialog) , m_logLevelBox(m_dialog.findChild("logLevelBox")) diff --git a/src/settings.h b/src/settings.h index e88080ba..6f75562b 100644 --- a/src/settings.h +++ b/src/settings.h @@ -427,6 +427,7 @@ public: bool colorSeparatorScrollbar() const; QSettings& settingsRef() { return m_Settings; } + MOBase::IPluginGame const *gamePlugin() { return m_GamePlugin; } public slots: @@ -443,22 +444,6 @@ private: QString getConfigurablePath(const QString &key, const QString &def, bool resolve) const; - class PathsTab : public SettingsTab - { - public: - PathsTab(Settings *parent, SettingsDialog &dialog); - - void update(); - - private: - QLineEdit *m_baseDirEdit; - QLineEdit *m_downloadDirEdit; - QLineEdit *m_modDirEdit; - QLineEdit *m_cacheDirEdit; - QLineEdit *m_profilesDirEdit; - QLineEdit *m_overwriteDirEdit; - QLineEdit *m_managedGameDirEdit; - }; class DiagnosticsTab : public SettingsTab { diff --git a/src/settingsdialog.cpp b/src/settingsdialog.cpp index f922cfb9..bfa285bf 100644 --- a/src/settingsdialog.cpp +++ b/src/settingsdialog.cpp @@ -200,80 +200,6 @@ void SettingsDialog::on_bsaDateBtn_clicked() dir.absolutePath().toStdWString()); } -void SettingsDialog::on_browseBaseDirBtn_clicked() -{ - QString temp = QFileDialog::getExistingDirectory( - this, tr("Select base directory"), ui->baseDirEdit->text()); - if (!temp.isEmpty()) { - ui->baseDirEdit->setText(temp); - } -} - -void SettingsDialog::on_browseDownloadDirBtn_clicked() -{ - QString searchPath = ui->downloadDirEdit->text(); - searchPath.replace("%BASE_DIR%", ui->baseDirEdit->text()); - - QString temp = QFileDialog::getExistingDirectory(this, tr("Select download directory"), searchPath); - if (!temp.isEmpty()) { - ui->downloadDirEdit->setText(temp); - } -} - -void SettingsDialog::on_browseModDirBtn_clicked() -{ - QString searchPath = ui->modDirEdit->text(); - searchPath.replace("%BASE_DIR%", ui->baseDirEdit->text()); - - QString temp = QFileDialog::getExistingDirectory(this, tr("Select mod directory"), searchPath); - if (!temp.isEmpty()) { - ui->modDirEdit->setText(temp); - } -} - -void SettingsDialog::on_browseCacheDirBtn_clicked() -{ - QString searchPath = ui->cacheDirEdit->text(); - searchPath.replace("%BASE_DIR%", ui->baseDirEdit->text()); - - QString temp = QFileDialog::getExistingDirectory(this, tr("Select cache directory"), searchPath); - if (!temp.isEmpty()) { - ui->cacheDirEdit->setText(temp); - } -} - -void SettingsDialog::on_browseProfilesDirBtn_clicked() -{ - QString searchPath = ui->profilesDirEdit->text(); - searchPath.replace("%BASE_DIR%", ui->baseDirEdit->text()); - - QString temp = QFileDialog::getExistingDirectory(this, tr("Select profiles directory"), searchPath); - if (!temp.isEmpty()) { - ui->profilesDirEdit->setText(temp); - } -} - -void SettingsDialog::on_browseOverwriteDirBtn_clicked() -{ - QString searchPath = ui->overwriteDirEdit->text(); - searchPath.replace("%BASE_DIR%", ui->baseDirEdit->text()); - - QString temp = QFileDialog::getExistingDirectory(this, tr("Select overwrite directory"), searchPath); - if (!temp.isEmpty()) { - ui->overwriteDirEdit->setText(temp); - } -} - -void SettingsDialog::on_browseGameDirBtn_clicked() -{ - QFileInfo oldGameExe(ui->managedGameDirEdit->text()); - - QString temp = QFileDialog::getOpenFileName(this, tr("Select game executable"), oldGameExe.absolutePath(), oldGameExe.fileName()); - if (!temp.isEmpty()) { - ui->managedGameDirEdit->setText(temp); - } -} - void SettingsDialog::on_nexusConnect_clicked() { if (m_nexusLogin && m_nexusLogin->isActive()) { @@ -555,45 +481,6 @@ void SettingsDialog::on_clearCacheButton_clicked() NexusInterface::instance(m_PluginContainer)->clearCache(); } -void SettingsDialog::normalizePath(QLineEdit *lineEdit) -{ - QString text = lineEdit->text(); - while (text.endsWith('/') || text.endsWith('\\')) { - text.chop(1); - } - lineEdit->setText(text); -} - -void SettingsDialog::on_baseDirEdit_editingFinished() -{ - normalizePath(ui->baseDirEdit); -} - -void SettingsDialog::on_downloadDirEdit_editingFinished() -{ - normalizePath(ui->downloadDirEdit); -} - -void SettingsDialog::on_modDirEdit_editingFinished() -{ - normalizePath(ui->modDirEdit); -} - -void SettingsDialog::on_cacheDirEdit_editingFinished() -{ - normalizePath(ui->cacheDirEdit); -} - -void SettingsDialog::on_profilesDirEdit_editingFinished() -{ - normalizePath(ui->profilesDirEdit); -} - -void SettingsDialog::on_overwriteDirEdit_editingFinished() -{ - normalizePath(ui->overwriteDirEdit); -} - void SettingsDialog::on_resetGeometryBtn_clicked() { m_GeometriesReset = true; diff --git a/src/settingsdialog.h b/src/settingsdialog.h index 01a0afa2..68e72529 100644 --- a/src/settingsdialog.h +++ b/src/settingsdialog.h @@ -67,7 +67,6 @@ signals: private: void storeSettings(QListWidgetItem *pluginItem); - void normalizePath(QLineEdit *lineEdit); public: QString getExecutableBlacklist() { return m_ExecutableBlacklist; } @@ -77,26 +76,13 @@ public: private slots: void on_associateButton_clicked(); - void on_baseDirEdit_editingFinished(); - void on_browseBaseDirBtn_clicked(); - void on_browseCacheDirBtn_clicked(); - void on_browseDownloadDirBtn_clicked(); - void on_browseGameDirBtn_clicked(); - void on_browseModDirBtn_clicked(); - void on_browseOverwriteDirBtn_clicked(); - void on_browseProfilesDirBtn_clicked(); void on_bsaDateBtn_clicked(); - void on_cacheDirEdit_editingFinished(); void on_clearCacheButton_clicked(); - void on_downloadDirEdit_editingFinished(); void on_execBlacklistBtn_clicked(); - void on_modDirEdit_editingFinished(); void on_nexusConnect_clicked(); void on_nexusDisconnect_clicked(); void on_nexusManualKey_clicked(); - void on_overwriteDirEdit_editingFinished(); void on_pluginsList_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous); - void on_profilesDirEdit_editingFinished(); void on_resetGeometryBtn_clicked(); void deleteBlacklistItem(); diff --git a/src/settingsdialogpaths.cpp b/src/settingsdialogpaths.cpp new file mode 100644 index 00000000..303d1562 --- /dev/null +++ b/src/settingsdialogpaths.cpp @@ -0,0 +1,205 @@ +#include "settingsdialogpaths.h" +#include "ui_settingsdialog.h" +#include "appconfig.h" +#include + +PathsTab::PathsTab(Settings *parent, SettingsDialog &dialog) + : SettingsTab(parent, dialog) +{ + ui->baseDirEdit->setText(m_parent->getBaseDirectory()); + ui->managedGameDirEdit->setText(m_parent->gamePlugin()->gameDirectory().absoluteFilePath(m_parent->gamePlugin()->binaryName())); + QString basePath = parent->getBaseDirectory(); + QDir baseDir(basePath); + for (const auto &dir : { + std::make_pair(ui->downloadDirEdit, m_parent->getDownloadDirectory(false)), + std::make_pair(ui->modDirEdit, m_parent->getModDirectory(false)), + std::make_pair(ui->cacheDirEdit, m_parent->getCacheDirectory(false)), + std::make_pair(ui->profilesDirEdit, m_parent->getProfileDirectory(false)), + std::make_pair(ui->overwriteDirEdit, m_parent->getOverwriteDirectory(false)) + }) { + QString storePath = baseDir.relativeFilePath(dir.second); + storePath = dir.second; + dir.first->setText(storePath); + } + + QObject::connect(ui->browseBaseDirBtn, &QPushButton::clicked, [&]{ on_browseBaseDirBtn_clicked(); }); + QObject::connect(ui->browseCacheDirBtn, &QPushButton::clicked, [&]{ on_browseCacheDirBtn_clicked(); }); + QObject::connect(ui->browseDownloadDirBtn, &QPushButton::clicked, [&]{ on_browseDownloadDirBtn_clicked(); }); + QObject::connect(ui->browseGameDirBtn, &QPushButton::clicked, [&]{ on_browseGameDirBtn_clicked(); }); + QObject::connect(ui->browseModDirBtn, &QPushButton::clicked, [&]{ on_browseModDirBtn_clicked(); }); + QObject::connect(ui->browseOverwriteDirBtn, &QPushButton::clicked, [&]{ on_browseOverwriteDirBtn_clicked(); }); + QObject::connect(ui->browseProfilesDirBtn, &QPushButton::clicked, [&]{ on_browseProfilesDirBtn_clicked(); }); + + QObject::connect(ui->baseDirEdit, &QLineEdit::editingFinished, [&]{ on_baseDirEdit_editingFinished(); }); + QObject::connect(ui->cacheDirEdit, &QLineEdit::editingFinished, [&]{ on_cacheDirEdit_editingFinished(); }); + QObject::connect(ui->downloadDirEdit, &QLineEdit::editingFinished, [&]{ on_downloadDirEdit_editingFinished(); }); + QObject::connect(ui->modDirEdit, &QLineEdit::editingFinished, [&]{ on_modDirEdit_editingFinished(); }); + QObject::connect(ui->overwriteDirEdit, &QLineEdit::editingFinished, [&]{ on_overwriteDirEdit_editingFinished(); }); + QObject::connect(ui->profilesDirEdit, &QLineEdit::editingFinished, [&]{ on_profilesDirEdit_editingFinished(); }); +} + +void PathsTab::update() +{ + typedef std::tuple Directory; + + QString basePath = m_parent->getBaseDirectory(); + + for (const Directory &dir :{ + Directory{ui->downloadDirEdit->text(), "download_directory", AppConfig::downloadPath()}, + Directory{ui->cacheDirEdit->text(), "cache_directory", AppConfig::cachePath()}, + Directory{ui->modDirEdit->text(), "mod_directory", AppConfig::modsPath()}, + Directory{ui->overwriteDirEdit->text(), "overwrite_directory", AppConfig::overwritePath()}, + Directory{ui->profilesDirEdit->text(), "profiles_directory", AppConfig::profilesPath()} + }) { + QString path, settingsKey; + std::wstring defaultName; + std::tie(path, settingsKey, defaultName) = dir; + + settingsKey = QString("Settings/%1").arg(settingsKey); + + QString realPath = path; + realPath.replace("%BASE_DIR%", ui->baseDirEdit->text()); + + if (!QDir(realPath).exists()) { + if (!QDir().mkpath(realPath)) { + QMessageBox::warning(qApp->activeWindow(), QObject::tr("Error"), + QObject::tr("Failed to create \"%1\", you may not have the " + "necessary permission. path remains unchanged.") + .arg(realPath)); + } + } + + if (QFileInfo(realPath) + != QFileInfo(basePath + "/" + QString::fromStdWString(defaultName))) { + m_Settings.setValue(settingsKey, path); + } else { + m_Settings.remove(settingsKey); + } + } + + if (QFileInfo(ui->baseDirEdit->text()) != + QFileInfo(qApp->property("dataPath").toString())) { + m_Settings.setValue("Settings/base_directory", ui->baseDirEdit->text()); + } else { + m_Settings.remove("Settings/base_directory"); + } + + QFileInfo oldGameExe(m_parent->gamePlugin()->gameDirectory().absoluteFilePath(m_parent->gamePlugin()->binaryName())); + QFileInfo newGameExe(ui->managedGameDirEdit->text()); + if (oldGameExe != newGameExe) { + m_Settings.setValue("gamePath", newGameExe.absolutePath()); + } +} + +void PathsTab::on_browseBaseDirBtn_clicked() +{ + QString temp = QFileDialog::getExistingDirectory( + parentWidget(), QObject::tr("Select base directory"), ui->baseDirEdit->text()); + if (!temp.isEmpty()) { + ui->baseDirEdit->setText(temp); + } +} + +void PathsTab::on_browseDownloadDirBtn_clicked() +{ + QString searchPath = ui->downloadDirEdit->text(); + searchPath.replace("%BASE_DIR%", ui->baseDirEdit->text()); + + QString temp = QFileDialog::getExistingDirectory(parentWidget(), QObject::tr("Select download directory"), searchPath); + if (!temp.isEmpty()) { + ui->downloadDirEdit->setText(temp); + } +} + +void PathsTab::on_browseModDirBtn_clicked() +{ + QString searchPath = ui->modDirEdit->text(); + searchPath.replace("%BASE_DIR%", ui->baseDirEdit->text()); + + QString temp = QFileDialog::getExistingDirectory(parentWidget(), QObject::tr("Select mod directory"), searchPath); + if (!temp.isEmpty()) { + ui->modDirEdit->setText(temp); + } +} + +void PathsTab::on_browseCacheDirBtn_clicked() +{ + QString searchPath = ui->cacheDirEdit->text(); + searchPath.replace("%BASE_DIR%", ui->baseDirEdit->text()); + + QString temp = QFileDialog::getExistingDirectory(parentWidget(), QObject::tr("Select cache directory"), searchPath); + if (!temp.isEmpty()) { + ui->cacheDirEdit->setText(temp); + } +} + +void PathsTab::on_browseProfilesDirBtn_clicked() +{ + QString searchPath = ui->profilesDirEdit->text(); + searchPath.replace("%BASE_DIR%", ui->baseDirEdit->text()); + + QString temp = QFileDialog::getExistingDirectory(parentWidget(), QObject::tr("Select profiles directory"), searchPath); + if (!temp.isEmpty()) { + ui->profilesDirEdit->setText(temp); + } +} + +void PathsTab::on_browseOverwriteDirBtn_clicked() +{ + QString searchPath = ui->overwriteDirEdit->text(); + searchPath.replace("%BASE_DIR%", ui->baseDirEdit->text()); + + QString temp = QFileDialog::getExistingDirectory(parentWidget(), QObject::tr("Select overwrite directory"), searchPath); + if (!temp.isEmpty()) { + ui->overwriteDirEdit->setText(temp); + } +} + +void PathsTab::on_browseGameDirBtn_clicked() +{ + QFileInfo oldGameExe(ui->managedGameDirEdit->text()); + + QString temp = QFileDialog::getOpenFileName(parentWidget(), QObject::tr("Select game executable"), oldGameExe.absolutePath(), oldGameExe.fileName()); + if (!temp.isEmpty()) { + ui->managedGameDirEdit->setText(temp); + } +} + +void PathsTab::on_baseDirEdit_editingFinished() +{ + normalizePath(ui->baseDirEdit); +} + +void PathsTab::on_downloadDirEdit_editingFinished() +{ + normalizePath(ui->downloadDirEdit); +} + +void PathsTab::on_modDirEdit_editingFinished() +{ + normalizePath(ui->modDirEdit); +} + +void PathsTab::on_cacheDirEdit_editingFinished() +{ + normalizePath(ui->cacheDirEdit); +} + +void PathsTab::on_profilesDirEdit_editingFinished() +{ + normalizePath(ui->profilesDirEdit); +} + +void PathsTab::on_overwriteDirEdit_editingFinished() +{ + normalizePath(ui->overwriteDirEdit); +} + +void PathsTab::normalizePath(QLineEdit *lineEdit) +{ + QString text = lineEdit->text(); + while (text.endsWith('/') || text.endsWith('\\')) { + text.chop(1); + } + lineEdit->setText(text); +} diff --git a/src/settingsdialogpaths.h b/src/settingsdialogpaths.h new file mode 100644 index 00000000..dac402b1 --- /dev/null +++ b/src/settingsdialogpaths.h @@ -0,0 +1,33 @@ +#ifndef SETTINGSDIALOGPATHS_H +#define SETTINGSDIALOGPATHS_H + +#include "settings.h" +#include "settingsdialog.h" + +class PathsTab : public SettingsTab +{ +public: + PathsTab(Settings *parent, SettingsDialog &dialog); + + void update(); + +private: + void on_browseBaseDirBtn_clicked(); + void on_browseCacheDirBtn_clicked(); + void on_browseDownloadDirBtn_clicked(); + void on_browseGameDirBtn_clicked(); + void on_browseModDirBtn_clicked(); + void on_browseOverwriteDirBtn_clicked(); + void on_browseProfilesDirBtn_clicked(); + + void on_baseDirEdit_editingFinished(); + void on_cacheDirEdit_editingFinished(); + void on_downloadDirEdit_editingFinished(); + void on_modDirEdit_editingFinished(); + void on_overwriteDirEdit_editingFinished(); + void on_profilesDirEdit_editingFinished(); + + void normalizePath(QLineEdit *lineEdit); +}; + +#endif // SETTINGSDIALOGPATHS_H -- cgit v1.3.1 From af95b3b8637d28517f69a70f13b901cc7f43d121 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sat, 20 Jul 2019 09:31:38 -0400 Subject: renamed tab classes, clashing with mod info dialog split nexus tab --- src/CMakeLists.txt | 3 + src/settings.cpp | 114 +------------ src/settings.h | 16 -- src/settingsdialog.cpp | 278 +------------------------------ src/settingsdialog.h | 34 +--- src/settingsdialoggeneral.cpp | 30 ++-- src/settingsdialoggeneral.h | 4 +- src/settingsdialognexus.cpp | 374 ++++++++++++++++++++++++++++++++++++++++++ src/settingsdialognexus.h | 40 +++++ src/settingsdialogpaths.cpp | 32 ++-- src/settingsdialogpaths.h | 4 +- 11 files changed, 460 insertions(+), 469 deletions(-) create mode 100644 src/settingsdialognexus.cpp create mode 100644 src/settingsdialognexus.h (limited to 'src/settings.cpp') diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 98d59996..b2407e17 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -38,6 +38,7 @@ SET(organizer_SRCS singleinstance.cpp settingsdialog.cpp settingsdialoggeneral.cpp + settingsdialognexus.cpp settingsdialogpaths.cpp settings.cpp selfupdater.cpp @@ -154,6 +155,7 @@ SET(organizer_HDRS singleinstance.h settingsdialog.h settingsdialoggeneral.h + settingsdialognexus.h settingsdialogpaths.h settings.h selfupdater.h @@ -436,6 +438,7 @@ set(settings settings settingsdialog settingsdialoggeneral + settingsdialognexus settingsdialogpaths ) diff --git a/src/settings.cpp b/src/settings.cpp index bed8e789..bded470c 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -23,6 +23,7 @@ along with Mod Organizer. If not, see . #include "serverinfo.h" #include "settingsdialog.h" #include "settingsdialoggeneral.h" +#include "settingsdialognexus.h" #include "settingsdialogpaths.h" #include "versioninfo.h" #include "appconfig.h" @@ -69,19 +70,6 @@ along with Mod Organizer. If not, see . using namespace MOBase; -template -class QListWidgetItemEx : public QListWidgetItem { -public: - QListWidgetItemEx(const QString &text, int sortRole = Qt::DisplayRole, QListWidget *parent = 0, int type = Type) - : QListWidgetItem(text, parent, type), m_SortRole(sortRole) {} - - virtual bool operator< ( const QListWidgetItem & other ) const { - return this->data(m_SortRole).value() < other.data(m_SortRole).value(); - } -private: - int m_SortRole; -}; - SettingsTab::SettingsTab(Settings *m_parent, SettingsDialog &m_dialog) : m_parent(m_parent) @@ -688,10 +676,10 @@ void Settings::query(PluginContainer *pluginContainer, QWidget *parent) std::vector> tabs; - tabs.push_back(std::unique_ptr(new GeneralTab(this, dialog))); - tabs.push_back(std::unique_ptr(new PathsTab(this, dialog))); + tabs.push_back(std::unique_ptr(new GeneralSettingsTab(this, dialog))); + tabs.push_back(std::unique_ptr(new PathsSettingsTab(this, dialog))); tabs.push_back(std::unique_ptr(new DiagnosticsTab(this, dialog))); - tabs.push_back(std::unique_ptr(new NexusTab(this, dialog))); + tabs.push_back(std::unique_ptr(new NexusSettingsTab(this, dialog))); tabs.push_back(std::unique_ptr(new SteamTab(this, dialog))); tabs.push_back(std::unique_ptr(new PluginsTab(this, dialog))); tabs.push_back(std::unique_ptr(new WorkaroundsTab(this, dialog))); @@ -781,100 +769,6 @@ void Settings::DiagnosticsTab::update() m_Settings.setValue("Settings/crash_dumps_max", m_dumpsMaxEdit->value()); } -void Settings::DiagnosticsTab::setLevelsBox() -{ - m_logLevelBox->clear(); - - m_logLevelBox->addItem(tr("Debug"), log::Debug); - m_logLevelBox->addItem(tr("Info (recommended)"), log::Info); - m_logLevelBox->addItem(tr("Warning"), log::Warning); - m_logLevelBox->addItem(tr("Error"), log::Error); - - for (int i=0; icount(); ++i) { - if (m_logLevelBox->itemData(i) == m_parent->logLevel()) { - m_logLevelBox->setCurrentIndex(i); - break; - } - } -} - -Settings::NexusTab::NexusTab(Settings *parent, SettingsDialog &dialog) - : SettingsTab(parent, dialog) - , m_offlineBox(dialog.findChild("offlineBox")) - , m_proxyBox(dialog.findChild("proxyBox")) - , m_knownServersList(dialog.findChild("knownServersList")) - , m_preferredServersList( - dialog.findChild("preferredServersList")) - , m_endorsementBox(dialog.findChild("endorsementBox")) - , m_hideAPICounterBox(dialog.findChild("hideAPICounterBox")) -{ - m_offlineBox->setChecked(parent->offlineMode()); - m_proxyBox->setChecked(parent->useProxy()); - m_endorsementBox->setChecked(parent->endorsementIntegration()); - m_hideAPICounterBox->setChecked(parent->hideAPICounter()); - - // display server preferences - m_Settings.beginGroup("Servers"); - for (const QString &key : m_Settings.childKeys()) { - QVariantMap val = m_Settings.value(key).toMap(); - QString descriptor = key; - if (!descriptor.compare("CDN", Qt::CaseInsensitive)) { - descriptor += QStringLiteral(" (automatic)"); - } - if (val.contains("downloadSpeed") && val.contains("downloadCount") && (val["downloadCount"].toInt() > 0)) { - int bps = static_cast(val["downloadSpeed"].toDouble() / val["downloadCount"].toInt()); - descriptor += QString(" (%1 kbps)").arg(bps / 1024); - } - - QListWidgetItem *newItem = new QListWidgetItemEx(descriptor, Qt::UserRole + 1); - - newItem->setData(Qt::UserRole, key); - newItem->setData(Qt::UserRole + 1, val["preferred"].toInt()); - if (val["preferred"].toInt() > 0) { - m_preferredServersList->addItem(newItem); - } else { - m_knownServersList->addItem(newItem); - } - m_preferredServersList->sortItems(Qt::DescendingOrder); - } - m_Settings.endGroup(); -} - -void Settings::NexusTab::update() -{ - /* - if (m_loginCheckBox->isChecked()) { - m_Settings.setValue("Settings/nexus_login", true); - m_Settings.setValue("Settings/nexus_username", m_usernameEdit->text()); - m_Settings.setValue("Settings/nexus_password", obfuscate(m_passwordEdit->text())); - } else { - m_Settings.setValue("Settings/nexus_login", false); - m_Settings.remove("Settings/nexus_username"); - m_Settings.remove("Settings/nexus_password"); - } - */ - m_Settings.setValue("Settings/offline_mode", m_offlineBox->isChecked()); - m_Settings.setValue("Settings/use_proxy", m_proxyBox->isChecked()); - m_Settings.setValue("Settings/endorsement_integration", m_endorsementBox->isChecked()); - m_Settings.setValue("Settings/hide_api_counter", m_hideAPICounterBox->isChecked()); - - // store server preference - m_Settings.beginGroup("Servers"); - for (int i = 0; i < m_knownServersList->count(); ++i) { - QString key = m_knownServersList->item(i)->data(Qt::UserRole).toString(); - QVariantMap val = m_Settings.value(key).toMap(); - val["preferred"] = 0; - m_Settings.setValue(key, val); - } - int count = m_preferredServersList->count(); - for (int i = 0; i < count; ++i) { - QString key = m_preferredServersList->item(i)->data(Qt::UserRole).toString(); - QVariantMap val = m_Settings.value(key).toMap(); - val["preferred"] = count - i; - m_Settings.setValue(key, val); - } - m_Settings.endGroup(); -} Settings::SteamTab::SteamTab(Settings *m_parent, SettingsDialog &m_dialog) : SettingsTab(m_parent, m_dialog) diff --git a/src/settings.h b/src/settings.h index 6f75562b..b9383ce4 100644 --- a/src/settings.h +++ b/src/settings.h @@ -461,22 +461,6 @@ private: void setLevelsBox(); }; - /** Display/store the configuration in the 'nexus' tab of the settings dialogue */ - class NexusTab : public SettingsTab - { - public: - NexusTab(Settings *m_parent, SettingsDialog &m_dialog); - void update(); - - private: - QCheckBox *m_offlineBox; - QCheckBox *m_proxyBox; - QListWidget *m_knownServersList; - QListWidget *m_preferredServersList; - QCheckBox *m_endorsementBox; - QCheckBox *m_hideAPICounterBox; - }; - /** Display/store the configuration in the 'steam' tab of the settings dialogue */ class SteamTab : public SettingsTab { diff --git a/src/settingsdialog.cpp b/src/settingsdialog.cpp index bfa285bf..6d5a8cc0 100644 --- a/src/settingsdialog.cpp +++ b/src/settingsdialog.cpp @@ -20,7 +20,6 @@ along with Mod Organizer. If not, see . #include "settingsdialog.h" #include "ui_settingsdialog.h" -#include "ui_nexusmanualkey.h" #include "categoriesdialog.h" #include "helper.h" #include "noeditdelegate.h" @@ -48,62 +47,14 @@ along with Mod Organizer. If not, see . using namespace MOBase; -class NexusManualKeyDialog : public QDialog -{ -public: - NexusManualKeyDialog(QWidget* parent) - : QDialog(parent), ui(new Ui::NexusManualKeyDialog) - { - ui->setupUi(this); - ui->key->setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont)); - - connect(ui->openBrowser, &QPushButton::clicked, [&]{ openBrowser(); }); - connect(ui->paste, &QPushButton::clicked, [&]{ paste(); }); - connect(ui->clear, &QPushButton::clicked, [&]{ clear(); }); - } - - void accept() override - { - m_key = ui->key->toPlainText(); - QDialog::accept(); - } - - const QString& key() const - { - return m_key; - } - - void openBrowser() - { - shell::OpenLink(QUrl("https://www.nexusmods.com/users/myaccount?tab=api")); - } - - void paste() - { - const auto text = QApplication::clipboard()->text(); - if (!text.isEmpty()) { - ui->key->setPlainText(text); - } - } - - void clear() - { - ui->key->clear(); - } - -private: - std::unique_ptr ui; - QString m_key; -}; - SettingsDialog::SettingsDialog(PluginContainer *pluginContainer, Settings* settings, QWidget *parent) : TutorableDialog("SettingsDialog", parent) , ui(new Ui::SettingsDialog) , m_settings(settings) , m_PluginContainer(pluginContainer) - , m_keyChanged(false) , m_GeometriesReset(false) + , m_keyChanged(false) { ui->setupUi(this); ui->pluginSettingsList->setStyleSheet("QTreeWidget::item {padding-right: 10px;}"); @@ -111,8 +62,6 @@ SettingsDialog::SettingsDialog(PluginContainer *pluginContainer, Settings* setti QShortcut *delShortcut = new QShortcut( QKeySequence(Qt::Key_Delete), ui->pluginBlacklist); connect(delShortcut, SIGNAL(activated()), this, SLOT(deleteBlacklistItem())); - - updateNexusState(); } SettingsDialog::~SettingsDialog() @@ -200,220 +149,6 @@ void SettingsDialog::on_bsaDateBtn_clicked() dir.absolutePath().toStdWString()); } -void SettingsDialog::on_nexusConnect_clicked() -{ - if (m_nexusLogin && m_nexusLogin->isActive()) { - m_nexusLogin->cancel(); - return; - } - - if (!m_nexusLogin) { - m_nexusLogin.reset(new NexusSSOLogin); - - m_nexusLogin->keyChanged = [&](auto&& s){ - onSSOKeyChanged(s); - }; - - m_nexusLogin->stateChanged = [&](auto&& s, auto&& e){ - onSSOStateChanged(s, e); - }; - } - - ui->nexusLog->clear(); - m_nexusLogin->start(); - updateNexusState(); -} - -void SettingsDialog::on_nexusManualKey_clicked() -{ - if (m_nexusValidator && m_nexusValidator->isActive()) { - m_nexusValidator->cancel(); - return; - } - - NexusManualKeyDialog dialog(this); - if (dialog.exec() != QDialog::Accepted) { - return; - } - - const auto key = dialog.key(); - if (key.isEmpty()) { - clearKey(); - return; - } - - ui->nexusLog->clear(); - validateKey(key); -} - -void SettingsDialog::on_nexusDisconnect_clicked() -{ - clearKey(); - ui->nexusLog->clear(); - addNexusLog(tr("Disconnected.")); -} - -void SettingsDialog::validateKey(const QString& key) -{ - if (!m_nexusValidator) { - m_nexusValidator.reset(new NexusKeyValidator( - *NexusInterface::instance(m_PluginContainer)->getAccessManager())); - - m_nexusValidator->stateChanged = [&](auto&& s, auto&& e){ - onValidatorStateChanged(s, e); - }; - - m_nexusValidator->finished = [&](auto&& user) { - onValidatorFinished(user); - }; - } - - addNexusLog(tr("Checking API key...")); - m_nexusValidator->start(key); -} - -void SettingsDialog::onSSOKeyChanged(const QString& key) -{ - if (key.isEmpty()) { - clearKey(); - } else { - addNexusLog(tr("Received API key.")); - validateKey(key); - } -} - -void SettingsDialog::onSSOStateChanged(NexusSSOLogin::States s, const QString& e) -{ - if (s != NexusSSOLogin::Finished) { - // finished state is handled in onSSOKeyChanged() - const auto log = NexusSSOLogin::stateToString(s, e); - - for (auto&& line : log.split("\n")) { - addNexusLog(line); - } - } - - updateNexusState(); -} - -void SettingsDialog::onValidatorStateChanged( - NexusKeyValidator::States s, const QString& e) -{ - if (s != NexusKeyValidator::Finished) { - // finished state is handled in onValidatorFinished() - const auto log = NexusKeyValidator::stateToString(s, e); - - for (auto&& line : log.split("\n")) { - addNexusLog(line); - } - } - - updateNexusState(); -} - -void SettingsDialog::onValidatorFinished(const APIUserAccount& user) -{ - NexusInterface::instance(m_PluginContainer)->setUserAccount(user); - - if (!user.apiKey().isEmpty()) { - if (setKey(user.apiKey())) { - addNexusLog(tr("Linked with Nexus successfully.")); - } - } -} - -void SettingsDialog::addNexusLog(const QString& s) -{ - ui->nexusLog->addItem(s); - ui->nexusLog->scrollToBottom(); -} - -bool SettingsDialog::setKey(const QString& key) -{ - m_keyChanged = true; - const bool ret = m_settings->setNexusApiKey(key); - updateNexusState(); - return ret; -} - -bool SettingsDialog::clearKey() -{ - m_keyChanged = true; - const auto ret = m_settings->clearNexusApiKey(); - - NexusInterface::instance(m_PluginContainer)->getAccessManager()->clearApiKey(); - updateNexusState(); - - return ret; -} - -void SettingsDialog::updateNexusState() -{ - updateNexusButtons(); - updateNexusData(); -} - -void SettingsDialog::updateNexusButtons() -{ - if (m_nexusLogin && m_nexusLogin->isActive()) { - // api key is in the process of being retrieved - ui->nexusConnect->setText(tr("Cancel")); - ui->nexusConnect->setEnabled(true); - ui->nexusDisconnect->setEnabled(false); - ui->nexusManualKey->setText(tr("Enter API Key Manually")); - ui->nexusManualKey->setEnabled(false); - } - else if (m_nexusValidator && m_nexusValidator->isActive()) { - // api key is in the process of being tested - ui->nexusConnect->setText(tr("Connect to Nexus")); - ui->nexusConnect->setEnabled(false); - ui->nexusDisconnect->setEnabled(false); - ui->nexusManualKey->setText(tr("Cancel")); - ui->nexusManualKey->setEnabled(true); - } - else if (m_settings->hasNexusApiKey()) { - // api key is present - ui->nexusConnect->setText(tr("Connect to Nexus")); - ui->nexusConnect->setEnabled(false); - ui->nexusDisconnect->setEnabled(true); - ui->nexusManualKey->setText(tr("Enter API Key Manually")); - ui->nexusManualKey->setEnabled(false); - } else { - // api key not present - ui->nexusConnect->setText(tr("Connect to Nexus")); - ui->nexusConnect->setEnabled(true); - ui->nexusDisconnect->setEnabled(false); - ui->nexusManualKey->setText(tr("Enter API Key Manually")); - ui->nexusManualKey->setEnabled(true); - } -} - -void SettingsDialog::updateNexusData() -{ - const auto user = NexusInterface::instance(m_PluginContainer) - ->getAPIUserAccount(); - - if (user.isValid()) { - ui->nexusUserID->setText(user.id()); - ui->nexusName->setText(user.name()); - ui->nexusAccount->setText(localizedUserAccountType(user.type())); - - ui->nexusDailyRequests->setText(QString("%1/%2") - .arg(user.limits().remainingDailyRequests) - .arg(user.limits().maxDailyRequests)); - - ui->nexusHourlyRequests->setText(QString("%1/%2") - .arg(user.limits().remainingHourlyRequests) - .arg(user.limits().maxHourlyRequests)); - } else { - ui->nexusUserID->setText(tr("N/A")); - ui->nexusName->setText(tr("N/A")); - ui->nexusAccount->setText(tr("N/A")); - ui->nexusDailyRequests->setText(tr("N/A")); - ui->nexusHourlyRequests->setText(tr("N/A")); - } -} - void SettingsDialog::storeSettings(QListWidgetItem *pluginItem) { if (pluginItem != nullptr) { @@ -470,17 +205,6 @@ void SettingsDialog::deleteBlacklistItem() ui->pluginBlacklist->takeItem(ui->pluginBlacklist->currentIndex().row()); } -void SettingsDialog::on_associateButton_clicked() -{ - Settings::instance().registerAsNXMHandler(true); -} - -void SettingsDialog::on_clearCacheButton_clicked() -{ - QDir(Settings::instance().getCacheDirectory()).removeRecursively(); - NexusInterface::instance(m_PluginContainer)->clearCache(); -} - void SettingsDialog::on_resetGeometryBtn_clicked() { m_GeometriesReset = true; diff --git a/src/settingsdialog.h b/src/settingsdialog.h index 68e72529..df5d0ad8 100644 --- a/src/settingsdialog.h +++ b/src/settingsdialog.h @@ -54,18 +54,15 @@ public: */ QString getColoredButtonStyleSheet() const; + // temp Ui::SettingsDialog *ui; + bool m_keyChanged; + PluginContainer *m_PluginContainer; public slots: - virtual void accept(); -signals: - - void retryApiConnection(); - private: - void storeSettings(QListWidgetItem *pluginItem); public: @@ -75,13 +72,8 @@ public: bool getApiKeyChanged(); private slots: - void on_associateButton_clicked(); void on_bsaDateBtn_clicked(); - void on_clearCacheButton_clicked(); void on_execBlacklistBtn_clicked(); - void on_nexusConnect_clicked(); - void on_nexusDisconnect_clicked(); - void on_nexusManualKey_clicked(); void on_pluginsList_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous); void on_resetGeometryBtn_clicked(); @@ -89,30 +81,10 @@ private slots: private: Settings* m_settings; - PluginContainer *m_PluginContainer; bool m_GeometriesReset; - bool m_keyChanged; QString m_ExecutableBlacklist; - std::unique_ptr m_nexusLogin; - std::unique_ptr m_nexusValidator; - - void validateKey(const QString& key); - bool setKey(const QString& key); - bool clearKey(); - - void updateNexusState(); - void updateNexusButtons(); - void updateNexusData(); - - void onSSOKeyChanged(const QString& key); - void onSSOStateChanged(NexusSSOLogin::States s, const QString& e); - - void onValidatorStateChanged(NexusKeyValidator::States s, const QString& e); - void onValidatorFinished(const APIUserAccount& user); - - void addNexusLog(const QString& s); }; #endif // SETTINGSDIALOG_H diff --git a/src/settingsdialoggeneral.cpp b/src/settingsdialoggeneral.cpp index b22b04fd..cd98dfdc 100644 --- a/src/settingsdialoggeneral.cpp +++ b/src/settingsdialoggeneral.cpp @@ -6,7 +6,7 @@ using MOBase::QuestionBoxMemory; -GeneralTab::GeneralTab(Settings *m_parent, SettingsDialog &m_dialog) +GeneralSettingsTab::GeneralSettingsTab(Settings *m_parent, SettingsDialog &m_dialog) : SettingsTab(m_parent, m_dialog) { addLanguages(); @@ -87,7 +87,7 @@ GeneralTab::GeneralTab(Settings *m_parent, SettingsDialog &m_dialog) QObject::connect(ui->resetDialogsButton, &QPushButton::clicked, [&]{ on_resetDialogsButton_clicked(); }); } -void GeneralTab::update() +void GeneralSettingsTab::update() { QString oldLanguage = m_parent->language(); QString newLanguage = ui->languageBox->itemData(ui->languageBox->currentIndex()).toString(); @@ -115,7 +115,7 @@ void GeneralTab::update() m_Settings.setValue("Settings/colorSeparatorScrollbars", ui->colorSeparatorsBox->isChecked()); } -void GeneralTab::addLanguages() +void GeneralSettingsTab::addLanguages() { std::vector> languages; @@ -150,7 +150,7 @@ void GeneralTab::addLanguages() } } -void GeneralTab::addStyles() +void GeneralSettingsTab::addStyles() { ui->styleBox->addItem("None", ""); ui->styleBox->addItem("Fusion", "Fusion"); @@ -163,12 +163,12 @@ void GeneralTab::addStyles() } } -void GeneralTab::resetDialogs() +void GeneralSettingsTab::resetDialogs() { QuestionBoxMemory::resetDialogs(); } -void GeneralTab::setButtonColor(QPushButton *button, const QColor &color) +void GeneralSettingsTab::setButtonColor(QPushButton *button, const QColor &color) { button->setStyleSheet( QString("QPushButton {" @@ -185,7 +185,7 @@ void GeneralTab::setButtonColor(QPushButton *button, const QColor &color) ); }; -void GeneralTab::on_containsBtn_clicked() +void GeneralSettingsTab::on_containsBtn_clicked() { QColor result = QColorDialog::getColor(m_ContainsColor, parentWidget(), "Color Picker: Mod contains selected plugin", QColorDialog::ShowAlphaChannel); if (result.isValid()) { @@ -194,7 +194,7 @@ void GeneralTab::on_containsBtn_clicked() } } -void GeneralTab::on_containedBtn_clicked() +void GeneralSettingsTab::on_containedBtn_clicked() { QColor result = QColorDialog::getColor(m_ContainedColor, parentWidget(), "ColorPicker: Plugin is Contained in selected Mod", QColorDialog::ShowAlphaChannel); if (result.isValid()) { @@ -203,7 +203,7 @@ void GeneralTab::on_containedBtn_clicked() } } -void GeneralTab::on_overwrittenBtn_clicked() +void GeneralSettingsTab::on_overwrittenBtn_clicked() { QColor result = QColorDialog::getColor(m_OverwrittenColor, parentWidget(), "ColorPicker: Is overwritten (loose files)", QColorDialog::ShowAlphaChannel); if (result.isValid()) { @@ -212,7 +212,7 @@ void GeneralTab::on_overwrittenBtn_clicked() } } -void GeneralTab::on_overwritingBtn_clicked() +void GeneralSettingsTab::on_overwritingBtn_clicked() { QColor result = QColorDialog::getColor(m_OverwritingColor, parentWidget(), "ColorPicker: Is overwriting (loose files)", QColorDialog::ShowAlphaChannel); if (result.isValid()) { @@ -221,7 +221,7 @@ void GeneralTab::on_overwritingBtn_clicked() } } -void GeneralTab::on_overwrittenArchiveBtn_clicked() +void GeneralSettingsTab::on_overwrittenArchiveBtn_clicked() { QColor result = QColorDialog::getColor(m_OverwrittenArchiveColor, parentWidget(), "ColorPicker: Is overwritten (archive files)", QColorDialog::ShowAlphaChannel); if (result.isValid()) { @@ -230,7 +230,7 @@ void GeneralTab::on_overwrittenArchiveBtn_clicked() } } -void GeneralTab::on_overwritingArchiveBtn_clicked() +void GeneralSettingsTab::on_overwritingArchiveBtn_clicked() { QColor result = QColorDialog::getColor(m_OverwritingArchiveColor, parentWidget(), "ColorPicker: Is overwriting (archive files)", QColorDialog::ShowAlphaChannel); if (result.isValid()) { @@ -239,7 +239,7 @@ void GeneralTab::on_overwritingArchiveBtn_clicked() } } -void GeneralTab::on_resetColorsBtn_clicked() +void GeneralSettingsTab::on_resetColorsBtn_clicked() { m_OverwritingColor = QColor(255, 0, 0, 64); m_OverwrittenColor = QColor(0, 255, 0, 64); @@ -256,7 +256,7 @@ void GeneralTab::on_resetColorsBtn_clicked() setButtonColor(ui->containedBtn, m_ContainedColor); } -void GeneralTab::on_resetDialogsButton_clicked() +void GeneralSettingsTab::on_resetDialogsButton_clicked() { if (QMessageBox::question(parentWidget(), QObject::tr("Confirm?"), QObject::tr("This will make all dialogs show up again where you checked the \"Remember selection\"-box. Continue?"), @@ -265,7 +265,7 @@ void GeneralTab::on_resetDialogsButton_clicked() } } -void GeneralTab::on_categoriesBtn_clicked() +void GeneralSettingsTab::on_categoriesBtn_clicked() { CategoriesDialog dialog(parentWidget()); if (dialog.exec() == QDialog::Accepted) { diff --git a/src/settingsdialoggeneral.h b/src/settingsdialoggeneral.h index 1f1b4637..c7fcae36 100644 --- a/src/settingsdialoggeneral.h +++ b/src/settingsdialoggeneral.h @@ -4,10 +4,10 @@ #include "settingsdialog.h" #include "settings.h" -class GeneralTab : public SettingsTab +class GeneralSettingsTab : public SettingsTab { public: - GeneralTab(Settings *m_parent, SettingsDialog &m_dialog); + GeneralSettingsTab(Settings *m_parent, SettingsDialog &m_dialog); void update(); diff --git a/src/settingsdialognexus.cpp b/src/settingsdialognexus.cpp new file mode 100644 index 00000000..7d4414fd --- /dev/null +++ b/src/settingsdialognexus.cpp @@ -0,0 +1,374 @@ +#include "settingsdialognexus.h" +#include "ui_settingsdialog.h" +#include "ui_nexusmanualkey.h" +#include "nexusinterface.h" +#include + +namespace shell = MOBase::shell; + +template +class ServerItem : public QListWidgetItem { +public: + ServerItem(const QString &text, int sortRole = Qt::DisplayRole, QListWidget *parent = 0, int type = Type) + : QListWidgetItem(text, parent, type), m_SortRole(sortRole) {} + + virtual bool operator< ( const QListWidgetItem & other ) const { + return this->data(m_SortRole).value() < other.data(m_SortRole).value(); + } +private: + int m_SortRole; +}; + + +class NexusManualKeyDialog : public QDialog +{ +public: + NexusManualKeyDialog(QWidget* parent) + : QDialog(parent), ui(new Ui::NexusManualKeyDialog) + { + ui->setupUi(this); + ui->key->setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont)); + + connect(ui->openBrowser, &QPushButton::clicked, [&]{ openBrowser(); }); + connect(ui->paste, &QPushButton::clicked, [&]{ paste(); }); + connect(ui->clear, &QPushButton::clicked, [&]{ clear(); }); + } + + void accept() override + { + m_key = ui->key->toPlainText(); + QDialog::accept(); + } + + const QString& key() const + { + return m_key; + } + + void openBrowser() + { + shell::OpenLink(QUrl("https://www.nexusmods.com/users/myaccount?tab=api")); + } + + void paste() + { + const auto text = QApplication::clipboard()->text(); + if (!text.isEmpty()) { + ui->key->setPlainText(text); + } + } + + void clear() + { + ui->key->clear(); + } + +private: + std::unique_ptr ui; + QString m_key; +}; + + +NexusSettingsTab::NexusSettingsTab(Settings *parent, SettingsDialog &dialog) + : SettingsTab(parent, dialog) +{ + ui->offlineBox->setChecked(parent->offlineMode()); + ui->proxyBox->setChecked(parent->useProxy()); + ui->endorsementBox->setChecked(parent->endorsementIntegration()); + ui->hideAPICounterBox->setChecked(parent->hideAPICounter()); + + // display server preferences + m_Settings.beginGroup("Servers"); + for (const QString &key : m_Settings.childKeys()) { + QVariantMap val = m_Settings.value(key).toMap(); + QString descriptor = key; + if (!descriptor.compare("CDN", Qt::CaseInsensitive)) { + descriptor += QStringLiteral(" (automatic)"); + } + if (val.contains("downloadSpeed") && val.contains("downloadCount") && (val["downloadCount"].toInt() > 0)) { + int bps = static_cast(val["downloadSpeed"].toDouble() / val["downloadCount"].toInt()); + descriptor += QString(" (%1 kbps)").arg(bps / 1024); + } + + QListWidgetItem *newItem = new ServerItem(descriptor, Qt::UserRole + 1); + + newItem->setData(Qt::UserRole, key); + newItem->setData(Qt::UserRole + 1, val["preferred"].toInt()); + if (val["preferred"].toInt() > 0) { + ui->preferredServersList->addItem(newItem); + } else { + ui->knownServersList->addItem(newItem); + } + ui->preferredServersList->sortItems(Qt::DescendingOrder); + } + m_Settings.endGroup(); + + QObject::connect(ui->nexusConnect, &QPushButton::clicked, [&]{ on_nexusConnect_clicked(); }); + QObject::connect(ui->nexusManualKey, &QPushButton::clicked, [&]{ on_nexusManualKey_clicked(); }); + QObject::connect(ui->nexusDisconnect, &QPushButton::clicked, [&]{ on_nexusDisconnect_clicked(); }); + QObject::connect(ui->clearCacheButton, &QPushButton::clicked, [&]{ on_clearCacheButton_clicked(); }); + QObject::connect(ui->associateButton, &QPushButton::clicked, [&]{ on_associateButton_clicked(); }); + + updateNexusState(); +} + +void NexusSettingsTab::update() +{ + /* + if (m_loginCheckBox->isChecked()) { + m_Settings.setValue("Settings/nexus_login", true); + m_Settings.setValue("Settings/nexus_username", m_usernameEdit->text()); + m_Settings.setValue("Settings/nexus_password", obfuscate(m_passwordEdit->text())); + } else { + m_Settings.setValue("Settings/nexus_login", false); + m_Settings.remove("Settings/nexus_username"); + m_Settings.remove("Settings/nexus_password"); + } + */ + m_Settings.setValue("Settings/offline_mode", ui->offlineBox->isChecked()); + m_Settings.setValue("Settings/use_proxy", ui->proxyBox->isChecked()); + m_Settings.setValue("Settings/endorsement_integration", ui->endorsementBox->isChecked()); + m_Settings.setValue("Settings/hide_api_counter", ui->hideAPICounterBox->isChecked()); + + // store server preference + m_Settings.beginGroup("Servers"); + for (int i = 0; i < ui->knownServersList->count(); ++i) { + QString key = ui->knownServersList->item(i)->data(Qt::UserRole).toString(); + QVariantMap val = m_Settings.value(key).toMap(); + val["preferred"] = 0; + m_Settings.setValue(key, val); + } + int count = ui->preferredServersList->count(); + for (int i = 0; i < count; ++i) { + QString key = ui->preferredServersList->item(i)->data(Qt::UserRole).toString(); + QVariantMap val = m_Settings.value(key).toMap(); + val["preferred"] = count - i; + m_Settings.setValue(key, val); + } + m_Settings.endGroup(); +} + +void NexusSettingsTab::on_nexusConnect_clicked() +{ + if (m_nexusLogin && m_nexusLogin->isActive()) { + m_nexusLogin->cancel(); + return; + } + + if (!m_nexusLogin) { + m_nexusLogin.reset(new NexusSSOLogin); + + m_nexusLogin->keyChanged = [&](auto&& s){ + onSSOKeyChanged(s); + }; + + m_nexusLogin->stateChanged = [&](auto&& s, auto&& e){ + onSSOStateChanged(s, e); + }; + } + + ui->nexusLog->clear(); + m_nexusLogin->start(); + updateNexusState(); +} + +void NexusSettingsTab::on_nexusManualKey_clicked() +{ + if (m_nexusValidator && m_nexusValidator->isActive()) { + m_nexusValidator->cancel(); + return; + } + + NexusManualKeyDialog dialog(parentWidget()); + if (dialog.exec() != QDialog::Accepted) { + return; + } + + const auto key = dialog.key(); + if (key.isEmpty()) { + clearKey(); + return; + } + + ui->nexusLog->clear(); + validateKey(key); +} + +void NexusSettingsTab::on_nexusDisconnect_clicked() +{ + clearKey(); + ui->nexusLog->clear(); + addNexusLog(QObject::tr("Disconnected.")); +} + +void NexusSettingsTab::on_clearCacheButton_clicked() +{ + QDir(Settings::instance().getCacheDirectory()).removeRecursively(); + NexusInterface::instance(m_dialog.m_PluginContainer)->clearCache(); +} + +void NexusSettingsTab::on_associateButton_clicked() +{ + Settings::instance().registerAsNXMHandler(true); +} + +void NexusSettingsTab::validateKey(const QString& key) +{ + if (!m_nexusValidator) { + m_nexusValidator.reset(new NexusKeyValidator( + *NexusInterface::instance(m_dialog.m_PluginContainer)->getAccessManager())); + + m_nexusValidator->stateChanged = [&](auto&& s, auto&& e){ + onValidatorStateChanged(s, e); + }; + + m_nexusValidator->finished = [&](auto&& user) { + onValidatorFinished(user); + }; + } + + addNexusLog(QObject::tr("Checking API key...")); + m_nexusValidator->start(key); +} + +void NexusSettingsTab::onSSOKeyChanged(const QString& key) +{ + if (key.isEmpty()) { + clearKey(); + } else { + addNexusLog(QObject::tr("Received API key.")); + validateKey(key); + } +} + +void NexusSettingsTab::onSSOStateChanged(NexusSSOLogin::States s, const QString& e) +{ + if (s != NexusSSOLogin::Finished) { + // finished state is handled in onSSOKeyChanged() + const auto log = NexusSSOLogin::stateToString(s, e); + + for (auto&& line : log.split("\n")) { + addNexusLog(line); + } + } + + updateNexusState(); +} + +void NexusSettingsTab::onValidatorStateChanged( + NexusKeyValidator::States s, const QString& e) +{ + if (s != NexusKeyValidator::Finished) { + // finished state is handled in onValidatorFinished() + const auto log = NexusKeyValidator::stateToString(s, e); + + for (auto&& line : log.split("\n")) { + addNexusLog(line); + } + } + + updateNexusState(); +} + +void NexusSettingsTab::onValidatorFinished(const APIUserAccount& user) +{ + NexusInterface::instance(m_dialog.m_PluginContainer)->setUserAccount(user); + + if (!user.apiKey().isEmpty()) { + if (setKey(user.apiKey())) { + addNexusLog(QObject::tr("Linked with Nexus successfully.")); + } + } +} + +void NexusSettingsTab::addNexusLog(const QString& s) +{ + ui->nexusLog->addItem(s); + ui->nexusLog->scrollToBottom(); +} + +bool NexusSettingsTab::setKey(const QString& key) +{ + m_dialog.m_keyChanged = true; + const bool ret = m_parent->setNexusApiKey(key); + updateNexusState(); + return ret; +} + +bool NexusSettingsTab::clearKey() +{ + m_dialog.m_keyChanged = true; + const auto ret = m_parent->clearNexusApiKey(); + + NexusInterface::instance(m_dialog.m_PluginContainer)->getAccessManager()->clearApiKey(); + updateNexusState(); + + return ret; +} + +void NexusSettingsTab::updateNexusState() +{ + updateNexusButtons(); + updateNexusData(); +} + +void NexusSettingsTab::updateNexusButtons() +{ + if (m_nexusLogin && m_nexusLogin->isActive()) { + // api key is in the process of being retrieved + ui->nexusConnect->setText(QObject::tr("Cancel")); + ui->nexusConnect->setEnabled(true); + ui->nexusDisconnect->setEnabled(false); + ui->nexusManualKey->setText(QObject::tr("Enter API Key Manually")); + ui->nexusManualKey->setEnabled(false); + } + else if (m_nexusValidator && m_nexusValidator->isActive()) { + // api key is in the process of being tested + ui->nexusConnect->setText(QObject::tr("Connect to Nexus")); + ui->nexusConnect->setEnabled(false); + ui->nexusDisconnect->setEnabled(false); + ui->nexusManualKey->setText(QObject::tr("Cancel")); + ui->nexusManualKey->setEnabled(true); + } + else if (m_parent->hasNexusApiKey()) { + // api key is present + ui->nexusConnect->setText(QObject::tr("Connect to Nexus")); + ui->nexusConnect->setEnabled(false); + ui->nexusDisconnect->setEnabled(true); + ui->nexusManualKey->setText(QObject::tr("Enter API Key Manually")); + ui->nexusManualKey->setEnabled(false); + } else { + // api key not present + ui->nexusConnect->setText(QObject::tr("Connect to Nexus")); + ui->nexusConnect->setEnabled(true); + ui->nexusDisconnect->setEnabled(false); + ui->nexusManualKey->setText(QObject::tr("Enter API Key Manually")); + ui->nexusManualKey->setEnabled(true); + } +} + +void NexusSettingsTab::updateNexusData() +{ + const auto user = NexusInterface::instance(m_dialog.m_PluginContainer) + ->getAPIUserAccount(); + + if (user.isValid()) { + ui->nexusUserID->setText(user.id()); + ui->nexusName->setText(user.name()); + ui->nexusAccount->setText(localizedUserAccountType(user.type())); + + ui->nexusDailyRequests->setText(QString("%1/%2") + .arg(user.limits().remainingDailyRequests) + .arg(user.limits().maxDailyRequests)); + + ui->nexusHourlyRequests->setText(QString("%1/%2") + .arg(user.limits().remainingHourlyRequests) + .arg(user.limits().maxHourlyRequests)); + } else { + ui->nexusUserID->setText(QObject::tr("N/A")); + ui->nexusName->setText(QObject::tr("N/A")); + ui->nexusAccount->setText(QObject::tr("N/A")); + ui->nexusDailyRequests->setText(QObject::tr("N/A")); + ui->nexusHourlyRequests->setText(QObject::tr("N/A")); + } +} diff --git a/src/settingsdialognexus.h b/src/settingsdialognexus.h new file mode 100644 index 00000000..5c01f61f --- /dev/null +++ b/src/settingsdialognexus.h @@ -0,0 +1,40 @@ +#ifndef SETTINGSDIALOGNEXUS_H +#define SETTINGSDIALOGNEXUS_H + +#include "settings.h" +#include "settingsdialog.h" + +class NexusSettingsTab : public SettingsTab +{ +public: + NexusSettingsTab(Settings *m_parent, SettingsDialog &m_dialog); + void update(); + +private: + std::unique_ptr m_nexusLogin; + std::unique_ptr m_nexusValidator; + + void on_nexusConnect_clicked(); + void on_nexusManualKey_clicked(); + void on_nexusDisconnect_clicked(); + void on_clearCacheButton_clicked(); + void on_associateButton_clicked(); + + void validateKey(const QString& key); + bool setKey(const QString& key); + bool clearKey(); + + void updateNexusState(); + void updateNexusButtons(); + void updateNexusData(); + + void onSSOKeyChanged(const QString& key); + void onSSOStateChanged(NexusSSOLogin::States s, const QString& e); + + void onValidatorStateChanged(NexusKeyValidator::States s, const QString& e); + void onValidatorFinished(const APIUserAccount& user); + + void addNexusLog(const QString& s); +}; + +#endif // SETTINGSDIALOGNEXUS_H diff --git a/src/settingsdialogpaths.cpp b/src/settingsdialogpaths.cpp index 303d1562..6e8fe994 100644 --- a/src/settingsdialogpaths.cpp +++ b/src/settingsdialogpaths.cpp @@ -3,7 +3,7 @@ #include "appconfig.h" #include -PathsTab::PathsTab(Settings *parent, SettingsDialog &dialog) +PathsSettingsTab::PathsSettingsTab(Settings *parent, SettingsDialog &dialog) : SettingsTab(parent, dialog) { ui->baseDirEdit->setText(m_parent->getBaseDirectory()); @@ -38,7 +38,7 @@ PathsTab::PathsTab(Settings *parent, SettingsDialog &dialog) QObject::connect(ui->profilesDirEdit, &QLineEdit::editingFinished, [&]{ on_profilesDirEdit_editingFinished(); }); } -void PathsTab::update() +void PathsSettingsTab::update() { typedef std::tuple Directory; @@ -91,7 +91,7 @@ void PathsTab::update() } } -void PathsTab::on_browseBaseDirBtn_clicked() +void PathsSettingsTab::on_browseBaseDirBtn_clicked() { QString temp = QFileDialog::getExistingDirectory( parentWidget(), QObject::tr("Select base directory"), ui->baseDirEdit->text()); @@ -100,7 +100,7 @@ void PathsTab::on_browseBaseDirBtn_clicked() } } -void PathsTab::on_browseDownloadDirBtn_clicked() +void PathsSettingsTab::on_browseDownloadDirBtn_clicked() { QString searchPath = ui->downloadDirEdit->text(); searchPath.replace("%BASE_DIR%", ui->baseDirEdit->text()); @@ -111,7 +111,7 @@ void PathsTab::on_browseDownloadDirBtn_clicked() } } -void PathsTab::on_browseModDirBtn_clicked() +void PathsSettingsTab::on_browseModDirBtn_clicked() { QString searchPath = ui->modDirEdit->text(); searchPath.replace("%BASE_DIR%", ui->baseDirEdit->text()); @@ -122,7 +122,7 @@ void PathsTab::on_browseModDirBtn_clicked() } } -void PathsTab::on_browseCacheDirBtn_clicked() +void PathsSettingsTab::on_browseCacheDirBtn_clicked() { QString searchPath = ui->cacheDirEdit->text(); searchPath.replace("%BASE_DIR%", ui->baseDirEdit->text()); @@ -133,7 +133,7 @@ void PathsTab::on_browseCacheDirBtn_clicked() } } -void PathsTab::on_browseProfilesDirBtn_clicked() +void PathsSettingsTab::on_browseProfilesDirBtn_clicked() { QString searchPath = ui->profilesDirEdit->text(); searchPath.replace("%BASE_DIR%", ui->baseDirEdit->text()); @@ -144,7 +144,7 @@ void PathsTab::on_browseProfilesDirBtn_clicked() } } -void PathsTab::on_browseOverwriteDirBtn_clicked() +void PathsSettingsTab::on_browseOverwriteDirBtn_clicked() { QString searchPath = ui->overwriteDirEdit->text(); searchPath.replace("%BASE_DIR%", ui->baseDirEdit->text()); @@ -155,7 +155,7 @@ void PathsTab::on_browseOverwriteDirBtn_clicked() } } -void PathsTab::on_browseGameDirBtn_clicked() +void PathsSettingsTab::on_browseGameDirBtn_clicked() { QFileInfo oldGameExe(ui->managedGameDirEdit->text()); @@ -165,37 +165,37 @@ void PathsTab::on_browseGameDirBtn_clicked() } } -void PathsTab::on_baseDirEdit_editingFinished() +void PathsSettingsTab::on_baseDirEdit_editingFinished() { normalizePath(ui->baseDirEdit); } -void PathsTab::on_downloadDirEdit_editingFinished() +void PathsSettingsTab::on_downloadDirEdit_editingFinished() { normalizePath(ui->downloadDirEdit); } -void PathsTab::on_modDirEdit_editingFinished() +void PathsSettingsTab::on_modDirEdit_editingFinished() { normalizePath(ui->modDirEdit); } -void PathsTab::on_cacheDirEdit_editingFinished() +void PathsSettingsTab::on_cacheDirEdit_editingFinished() { normalizePath(ui->cacheDirEdit); } -void PathsTab::on_profilesDirEdit_editingFinished() +void PathsSettingsTab::on_profilesDirEdit_editingFinished() { normalizePath(ui->profilesDirEdit); } -void PathsTab::on_overwriteDirEdit_editingFinished() +void PathsSettingsTab::on_overwriteDirEdit_editingFinished() { normalizePath(ui->overwriteDirEdit); } -void PathsTab::normalizePath(QLineEdit *lineEdit) +void PathsSettingsTab::normalizePath(QLineEdit *lineEdit) { QString text = lineEdit->text(); while (text.endsWith('/') || text.endsWith('\\')) { diff --git a/src/settingsdialogpaths.h b/src/settingsdialogpaths.h index dac402b1..f661b624 100644 --- a/src/settingsdialogpaths.h +++ b/src/settingsdialogpaths.h @@ -4,10 +4,10 @@ #include "settings.h" #include "settingsdialog.h" -class PathsTab : public SettingsTab +class PathsSettingsTab : public SettingsTab { public: - PathsTab(Settings *parent, SettingsDialog &dialog); + PathsSettingsTab(Settings *parent, SettingsDialog &dialog); void update(); -- cgit v1.3.1 From d91d0caba5fac3b2b27698a5e6ab4a9b60efbf53 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sat, 20 Jul 2019 09:47:09 -0400 Subject: removed incorrect warning that steam password is unencrypted split steam tab --- src/CMakeLists.txt | 3 +++ src/settings.cpp | 36 +++++----------------------- src/settings.h | 13 ---------- src/settingsdialog.ui | 58 ++++++++++++++++----------------------------- src/settingsdialogsteam.cpp | 17 +++++++++++++ src/settingsdialogsteam.h | 17 +++++++++++++ 6 files changed, 64 insertions(+), 80 deletions(-) create mode 100644 src/settingsdialogsteam.cpp create mode 100644 src/settingsdialogsteam.h (limited to 'src/settings.cpp') diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index b2407e17..a1adf2db 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -40,6 +40,7 @@ SET(organizer_SRCS settingsdialoggeneral.cpp settingsdialognexus.cpp settingsdialogpaths.cpp + settingsdialogsteam.cpp settings.cpp selfupdater.cpp selectiondialog.cpp @@ -157,6 +158,7 @@ SET(organizer_HDRS settingsdialoggeneral.h settingsdialognexus.h settingsdialogpaths.h + settingsdialogsteam.h settings.h selfupdater.h selectiondialog.h @@ -440,6 +442,7 @@ set(settings settingsdialoggeneral settingsdialognexus settingsdialogpaths + settingsdialogsteam ) set(utilities diff --git a/src/settings.cpp b/src/settings.cpp index bded470c..26c9720a 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -25,6 +25,7 @@ along with Mod Organizer. If not, see . #include "settingsdialoggeneral.h" #include "settingsdialognexus.h" #include "settingsdialogpaths.h" +#include "settingsdialogsteam.h" #include "versioninfo.h" #include "appconfig.h" #include "organizercore.h" @@ -391,15 +392,10 @@ bool Settings::hasNexusApiKey() const bool Settings::getSteamLogin(QString &username, QString &password) const { - if (m_Settings.contains("Settings/steam_username")) { - QString tempPass = deObfuscate("steam_password"); - if (!tempPass.isEmpty()) { - username = m_Settings.value("Settings/steam_username").toString(); - password = tempPass; - return true; - } - } - return false; + username = m_Settings.value("Settings/steam_username", "").toString(); + password = deObfuscate("steam_password"); + + return !username.isEmpty() && !password.isEmpty(); } bool Settings::compactDownloads() const { @@ -680,7 +676,7 @@ void Settings::query(PluginContainer *pluginContainer, QWidget *parent) tabs.push_back(std::unique_ptr(new PathsSettingsTab(this, dialog))); tabs.push_back(std::unique_ptr(new DiagnosticsTab(this, dialog))); tabs.push_back(std::unique_ptr(new NexusSettingsTab(this, dialog))); - tabs.push_back(std::unique_ptr(new SteamTab(this, dialog))); + tabs.push_back(std::unique_ptr(new SteamSettingsTab(this, dialog))); tabs.push_back(std::unique_ptr(new PluginsTab(this, dialog))); tabs.push_back(std::unique_ptr(new WorkaroundsTab(this, dialog))); @@ -770,26 +766,6 @@ void Settings::DiagnosticsTab::update() } -Settings::SteamTab::SteamTab(Settings *m_parent, SettingsDialog &m_dialog) - : SettingsTab(m_parent, m_dialog) - , m_steamUserEdit(m_dialog.findChild("steamUserEdit")) - , m_steamPassEdit(m_dialog.findChild("steamPassEdit")) -{ - if (m_Settings.contains("Settings/steam_username")) { - m_steamUserEdit->setText(m_Settings.value("Settings/steam_username", "").toString()); - QString password = deObfuscate("steam_password"); - if (!password.isEmpty()) { - m_steamPassEdit->setText(password); - } - } -} - -void Settings::SteamTab::update() -{ - //FIXME this should be inlined here? - m_parent->setSteamLogin(m_steamUserEdit->text(), m_steamPassEdit->text()); -} - Settings::PluginsTab::PluginsTab(Settings *m_parent, SettingsDialog &m_dialog) : SettingsTab(m_parent, m_dialog) , m_pluginsList(m_dialog.findChild("pluginsList")) diff --git a/src/settings.h b/src/settings.h index b9383ce4..5bf705d1 100644 --- a/src/settings.h +++ b/src/settings.h @@ -461,19 +461,6 @@ private: void setLevelsBox(); }; - /** Display/store the configuration in the 'steam' tab of the settings dialogue */ - class SteamTab : public SettingsTab - { - public: - SteamTab(Settings *m_parent, SettingsDialog &m_dialog); - - void update(); - - private: - QLineEdit *m_steamUserEdit; - QLineEdit *m_steamPassEdit; - }; - /** Display/store the configuration in the 'plugins' tab of the settings dialogue */ class PluginsTab : public SettingsTab { diff --git a/src/settingsdialog.ui b/src/settingsdialog.ui index 1e94bcde..3ad525e1 100644 --- a/src/settingsdialog.ui +++ b/src/settingsdialog.ui @@ -828,71 +828,55 @@ If you use pre-releases, never contact me directly by e-mail or via private mess Steam - + Username - - - - - - - Password - - - - - - - QLineEdit::Password - - - - - + + Qt::Vertical - QSizePolicy::Minimum + QSizePolicy::Expanding 20 - 40 + 232 - + + + + - If you save your steam user ID and password here, they will be used when logging into steam. Note, however, your password will be stored unencrypted, so make sure your computer is secure. + <html><head/><body><p>If you save your steam user ID and password here, they will be used when logging into steam.</p></body></html> true - - - - Qt::Vertical - - - QSizePolicy::Expanding + + + + Password - - - 20 - 232 - + + + + + + QLineEdit::Password - + diff --git a/src/settingsdialogsteam.cpp b/src/settingsdialogsteam.cpp new file mode 100644 index 00000000..34c2d76b --- /dev/null +++ b/src/settingsdialogsteam.cpp @@ -0,0 +1,17 @@ +#include "settingsdialogsteam.h" +#include "ui_settingsdialog.h" + +SteamSettingsTab::SteamSettingsTab(Settings *m_parent, SettingsDialog &m_dialog) + : SettingsTab(m_parent, m_dialog) +{ + QString username, password; + m_parent->getSteamLogin(username, password); + + ui->steamUserEdit->setText(username); + ui->steamPassEdit->setText(password); +} + +void SteamSettingsTab::update() +{ + m_parent->setSteamLogin(ui->steamUserEdit->text(), ui->steamPassEdit->text()); +} diff --git a/src/settingsdialogsteam.h b/src/settingsdialogsteam.h new file mode 100644 index 00000000..dbd85151 --- /dev/null +++ b/src/settingsdialogsteam.h @@ -0,0 +1,17 @@ +#ifndef SETTINGSDIALOGSTEAM_H +#define SETTINGSDIALOGSTEAM_H + +#include "settings.h" +#include "settingsdialog.h" + +class SteamSettingsTab : public SettingsTab +{ +public: + SteamSettingsTab(Settings *m_parent, SettingsDialog &m_dialog); + + void update(); + +private: +}; + +#endif // SETTINGSDIALOGSTEAM_H -- cgit v1.3.1 From 55eafd62dd3c96f363cde4537061e7f03ae8fd0a Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sat, 20 Jul 2019 10:10:49 -0400 Subject: split plugins tab --- src/CMakeLists.txt | 3 ++ src/settings.cpp | 54 +++------------------ src/settings.h | 25 +++------- src/settingsdialog.cpp | 52 -------------------- src/settingsdialog.h | 4 -- src/settingsdialogplugins.cpp | 110 ++++++++++++++++++++++++++++++++++++++++++ src/settingsdialogplugins.h | 20 ++++++++ 7 files changed, 146 insertions(+), 122 deletions(-) create mode 100644 src/settingsdialogplugins.cpp create mode 100644 src/settingsdialogplugins.h (limited to 'src/settings.cpp') diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index a1adf2db..a8ded510 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -40,6 +40,7 @@ SET(organizer_SRCS settingsdialoggeneral.cpp settingsdialognexus.cpp settingsdialogpaths.cpp + settingsdialogplugins.cpp settingsdialogsteam.cpp settings.cpp selfupdater.cpp @@ -158,6 +159,7 @@ SET(organizer_HDRS settingsdialoggeneral.h settingsdialognexus.h settingsdialogpaths.h + settingsdialogplugins.h settingsdialogsteam.h settings.h selfupdater.h @@ -442,6 +444,7 @@ set(settings settingsdialoggeneral settingsdialognexus settingsdialogpaths + settingsdialogplugins settingsdialogsteam ) diff --git a/src/settings.cpp b/src/settings.cpp index 26c9720a..bc45b720 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -25,6 +25,7 @@ along with Mod Organizer. If not, see . #include "settingsdialoggeneral.h" #include "settingsdialognexus.h" #include "settingsdialogpaths.h" +#include "settingsdialogplugins.h" #include "settingsdialogsteam.h" #include "versioninfo.h" #include "appconfig.h" @@ -677,7 +678,7 @@ void Settings::query(PluginContainer *pluginContainer, QWidget *parent) tabs.push_back(std::unique_ptr(new DiagnosticsTab(this, dialog))); 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 PluginsTab(this, dialog))); + tabs.push_back(std::unique_ptr(new PluginsSettingsTab(this, dialog))); tabs.push_back(std::unique_ptr(new WorkaroundsTab(this, dialog))); @@ -687,6 +688,11 @@ void Settings::query(PluginContainer *pluginContainer, QWidget *parent) } if (dialog.exec() == QDialog::Accepted) { + + for (auto&& tab : tabs) { + tab->closing(); + } + // remember settings before change QMap before; m_Settings.beginGroup("Settings"); @@ -766,52 +772,6 @@ void Settings::DiagnosticsTab::update() } -Settings::PluginsTab::PluginsTab(Settings *m_parent, SettingsDialog &m_dialog) - : SettingsTab(m_parent, m_dialog) - , m_pluginsList(m_dialog.findChild("pluginsList")) - , m_pluginBlacklistList(m_dialog.findChild("pluginBlacklist")) -{ - // display plugin settings - QSet handledNames; - for (IPlugin *plugin : m_parent->m_Plugins) { - if (handledNames.contains(plugin->name())) - continue; - QListWidgetItem *listItem = new QListWidgetItem(plugin->name(), m_pluginsList); - listItem->setData(Qt::UserRole, QVariant::fromValue((void*)plugin)); - listItem->setData(Qt::UserRole + 1, m_parent->m_PluginSettings[plugin->name()]); - listItem->setData(Qt::UserRole + 2, m_parent->m_PluginDescriptions[plugin->name()]); - m_pluginsList->addItem(listItem); - handledNames.insert(plugin->name()); - } - - // display plugin blacklist - for (const QString &pluginName : m_parent->m_PluginBlacklist) { - m_pluginBlacklistList->addItem(pluginName); - } -} - -void Settings::PluginsTab::update() -{ - // transfer plugin settings to in-memory structure - for (int i = 0; i < m_pluginsList->count(); ++i) { - QListWidgetItem *item = m_pluginsList->item(i); - m_parent->m_PluginSettings[item->text()] = item->data(Qt::UserRole + 1).toMap(); - } - // store plugin settings on disc - for (auto iterPlugins = m_parent->m_PluginSettings.begin(); iterPlugins != m_parent->m_PluginSettings.end(); ++iterPlugins) { - for (auto iterSettings = iterPlugins->begin(); iterSettings != iterPlugins->end(); ++iterSettings) { - m_Settings.setValue("Plugins/" + iterPlugins.key() + "/" + iterSettings.key(), iterSettings.value()); - } - } - - // store plugin blacklist - m_parent->m_PluginBlacklist.clear(); - for (QListWidgetItem *item : m_pluginBlacklistList->findItems("*", Qt::MatchWildcard)) { - m_parent->m_PluginBlacklist.insert(item->text()); - } - m_parent->writePluginBlacklist(); -} - Settings::WorkaroundsTab::WorkaroundsTab(Settings *m_parent, SettingsDialog &m_dialog) : SettingsTab(m_parent, m_dialog) diff --git a/src/settings.h b/src/settings.h index 5bf705d1..5298103a 100644 --- a/src/settings.h +++ b/src/settings.h @@ -70,6 +70,7 @@ public: virtual ~SettingsTab(); virtual void update() = 0; + virtual void closing() {} protected: Settings *m_parent; @@ -426,8 +427,13 @@ public: */ bool colorSeparatorScrollbar() const; + // temp QSettings& settingsRef() { return m_Settings; } MOBase::IPluginGame const *gamePlugin() { return m_GamePlugin; } + QMap m_PluginSettings; + QMap m_PluginDescriptions; + QSet m_PluginBlacklist; + void writePluginBlacklist(); public slots: @@ -440,7 +446,6 @@ private: static QString deObfuscate(const QString key); void readPluginBlacklist(); - void writePluginBlacklist(); QString getConfigurablePath(const QString &key, const QString &def, bool resolve) const; @@ -461,19 +466,6 @@ private: void setLevelsBox(); }; - /** Display/store the configuration in the 'plugins' tab of the settings dialogue */ - class PluginsTab : public SettingsTab - { - public: - PluginsTab(Settings *m_parent, SettingsDialog &m_dialog); - - void update(); - - private: - QListWidget *m_pluginsList; - QListWidget *m_pluginBlacklistList; - }; - /** Display/store the configuration in the 'workarounds' tab of the settings dialogue */ class WorkaroundsTab : public SettingsTab { @@ -512,11 +504,6 @@ private: std::vector m_Plugins; - QMap m_PluginSettings; - QMap m_PluginDescriptions; - - QSet m_PluginBlacklist; - }; #endif // SETTINGS_H diff --git a/src/settingsdialog.cpp b/src/settingsdialog.cpp index 6d5a8cc0..f43f7ae8 100644 --- a/src/settingsdialog.cpp +++ b/src/settingsdialog.cpp @@ -99,7 +99,6 @@ void SettingsDialog::accept() return; } - storeSettings(ui->pluginsList->currentItem()); TutorableDialog::accept(); } @@ -149,57 +148,6 @@ void SettingsDialog::on_bsaDateBtn_clicked() dir.absolutePath().toStdWString()); } -void SettingsDialog::storeSettings(QListWidgetItem *pluginItem) -{ - if (pluginItem != nullptr) { - QVariantMap settings = pluginItem->data(Qt::UserRole + 1).toMap(); - - for (int i = 0; i < ui->pluginSettingsList->topLevelItemCount(); ++i) { - const QTreeWidgetItem *item = ui->pluginSettingsList->topLevelItem(i); - settings[item->text(0)] = item->data(1, Qt::DisplayRole); - } - - pluginItem->setData(Qt::UserRole + 1, settings); - } -} - -void SettingsDialog::on_pluginsList_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous) -{ - storeSettings(previous); - - ui->pluginSettingsList->clear(); - IPlugin *plugin = static_cast(current->data(Qt::UserRole).value()); - ui->authorLabel->setText(plugin->author()); - ui->versionLabel->setText(plugin->version().canonicalString()); - ui->descriptionLabel->setText(plugin->description()); - - QVariantMap settings = current->data(Qt::UserRole + 1).toMap(); - QVariantMap descriptions = current->data(Qt::UserRole + 2).toMap(); - ui->pluginSettingsList->setEnabled(settings.count() != 0); - for (auto iter = settings.begin(); iter != settings.end(); ++iter) { - QTreeWidgetItem *newItem = new QTreeWidgetItem(QStringList(iter.key())); - QVariant value = *iter; - QString description; - { - auto descriptionIter = descriptions.find(iter.key()); - if (descriptionIter != descriptions.end()) { - description = descriptionIter->toString(); - } - } - - ui->pluginSettingsList->setItemDelegateForColumn(0, new NoEditDelegate()); - newItem->setData(1, Qt::DisplayRole, value); - newItem->setData(1, Qt::EditRole, value); - newItem->setToolTip(1, description); - - newItem->setFlags(newItem->flags() | Qt::ItemIsEditable); - ui->pluginSettingsList->addTopLevelItem(newItem); - } - - ui->pluginSettingsList->resizeColumnToContents(0); - ui->pluginSettingsList->resizeColumnToContents(1); -} - void SettingsDialog::deleteBlacklistItem() { ui->pluginBlacklist->takeItem(ui->pluginBlacklist->currentIndex().row()); diff --git a/src/settingsdialog.h b/src/settingsdialog.h index df5d0ad8..319e6ed8 100644 --- a/src/settingsdialog.h +++ b/src/settingsdialog.h @@ -62,9 +62,6 @@ public: public slots: virtual void accept(); -private: - void storeSettings(QListWidgetItem *pluginItem); - public: QString getExecutableBlacklist() { return m_ExecutableBlacklist; } void setExecutableBlacklist(QString blacklist) { m_ExecutableBlacklist = blacklist; } @@ -74,7 +71,6 @@ public: private slots: void on_bsaDateBtn_clicked(); void on_execBlacklistBtn_clicked(); - void on_pluginsList_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous); void on_resetGeometryBtn_clicked(); void deleteBlacklistItem(); diff --git a/src/settingsdialogplugins.cpp b/src/settingsdialogplugins.cpp new file mode 100644 index 00000000..32269344 --- /dev/null +++ b/src/settingsdialogplugins.cpp @@ -0,0 +1,110 @@ +#include "settingsdialogplugins.h" +#include "ui_settingsdialog.h" +#include "noeditdelegate.h" +#include + +using MOBase::IPlugin; + +PluginsSettingsTab::PluginsSettingsTab(Settings *m_parent, SettingsDialog &m_dialog) + : SettingsTab(m_parent, m_dialog) +{ + // display plugin settings + QSet handledNames; + for (IPlugin *plugin : m_parent->plugins()) { + if (handledNames.contains(plugin->name())) + continue; + QListWidgetItem *listItem = new QListWidgetItem(plugin->name(), ui->pluginsList); + listItem->setData(Qt::UserRole, QVariant::fromValue((void*)plugin)); + listItem->setData(Qt::UserRole + 1, m_parent->m_PluginSettings[plugin->name()]); + listItem->setData(Qt::UserRole + 2, m_parent->m_PluginDescriptions[plugin->name()]); + ui->pluginsList->addItem(listItem); + handledNames.insert(plugin->name()); + } + + // display plugin blacklist + for (const QString &pluginName : m_parent->m_PluginBlacklist) { + ui->pluginBlacklist->addItem(pluginName); + } + + QObject::connect( + ui->pluginsList, &QListWidget::currentItemChanged, + [&](auto* current, auto* previous) { on_pluginsList_currentItemChanged(current, previous); }); +} + +void PluginsSettingsTab::update() +{ + // transfer plugin settings to in-memory structure + for (int i = 0; i < ui->pluginsList->count(); ++i) { + QListWidgetItem *item = ui->pluginsList->item(i); + m_parent->m_PluginSettings[item->text()] = item->data(Qt::UserRole + 1).toMap(); + } + // store plugin settings on disc + for (auto iterPlugins = m_parent->m_PluginSettings.begin(); iterPlugins != m_parent->m_PluginSettings.end(); ++iterPlugins) { + for (auto iterSettings = iterPlugins->begin(); iterSettings != iterPlugins->end(); ++iterSettings) { + m_Settings.setValue("Plugins/" + iterPlugins.key() + "/" + iterSettings.key(), iterSettings.value()); + } + } + + // store plugin blacklist + m_parent->m_PluginBlacklist.clear(); + for (QListWidgetItem *item : ui->pluginBlacklist->findItems("*", Qt::MatchWildcard)) { + m_parent->m_PluginBlacklist.insert(item->text()); + } + m_parent->writePluginBlacklist(); +} + +void PluginsSettingsTab::closing() +{ + storeSettings(ui->pluginsList->currentItem()); +} + +void PluginsSettingsTab::on_pluginsList_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous) +{ + storeSettings(previous); + + ui->pluginSettingsList->clear(); + IPlugin *plugin = static_cast(current->data(Qt::UserRole).value()); + ui->authorLabel->setText(plugin->author()); + ui->versionLabel->setText(plugin->version().canonicalString()); + ui->descriptionLabel->setText(plugin->description()); + + QVariantMap settings = current->data(Qt::UserRole + 1).toMap(); + QVariantMap descriptions = current->data(Qt::UserRole + 2).toMap(); + ui->pluginSettingsList->setEnabled(settings.count() != 0); + for (auto iter = settings.begin(); iter != settings.end(); ++iter) { + QTreeWidgetItem *newItem = new QTreeWidgetItem(QStringList(iter.key())); + QVariant value = *iter; + QString description; + { + auto descriptionIter = descriptions.find(iter.key()); + if (descriptionIter != descriptions.end()) { + description = descriptionIter->toString(); + } + } + + ui->pluginSettingsList->setItemDelegateForColumn(0, new NoEditDelegate()); + newItem->setData(1, Qt::DisplayRole, value); + newItem->setData(1, Qt::EditRole, value); + newItem->setToolTip(1, description); + + newItem->setFlags(newItem->flags() | Qt::ItemIsEditable); + ui->pluginSettingsList->addTopLevelItem(newItem); + } + + ui->pluginSettingsList->resizeColumnToContents(0); + ui->pluginSettingsList->resizeColumnToContents(1); +} + +void PluginsSettingsTab::storeSettings(QListWidgetItem *pluginItem) +{ + if (pluginItem != nullptr) { + QVariantMap settings = pluginItem->data(Qt::UserRole + 1).toMap(); + + for (int i = 0; i < ui->pluginSettingsList->topLevelItemCount(); ++i) { + const QTreeWidgetItem *item = ui->pluginSettingsList->topLevelItem(i); + settings[item->text(0)] = item->data(1, Qt::DisplayRole); + } + + pluginItem->setData(Qt::UserRole + 1, settings); + } +} diff --git a/src/settingsdialogplugins.h b/src/settingsdialogplugins.h new file mode 100644 index 00000000..48d61858 --- /dev/null +++ b/src/settingsdialogplugins.h @@ -0,0 +1,20 @@ +#ifndef SETTINGSDIALOGPLUGINS_H +#define SETTINGSDIALOGPLUGINS_H + +#include "settings.h" +#include "settingsdialog.h" + +class PluginsSettingsTab : public SettingsTab +{ +public: + PluginsSettingsTab(Settings *m_parent, SettingsDialog &m_dialog); + + void update(); + void closing() override; + +private: + void on_pluginsList_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous); + void storeSettings(QListWidgetItem *pluginItem); +}; + +#endif // SETTINGSDIALOGPLUGINS_H -- 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/settings.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 e8d7930edacdc04a4607ecd59fc402f2f04ea39d Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sat, 20 Jul 2019 10:59:07 -0400 Subject: split diagnostics tab fixed log and crash dump directory links in label not working --- src/CMakeLists.txt | 3 +++ src/settings.cpp | 32 ++------------------------------ src/settings.h | 18 ------------------ src/settingsdialog.ui | 3 +++ src/settingsdialogdiagnostics.cpp | 28 ++++++++++++++++++++++++++++ src/settingsdialogdiagnostics.h | 17 +++++++++++++++++ 6 files changed, 53 insertions(+), 48 deletions(-) create mode 100644 src/settingsdialogdiagnostics.cpp create mode 100644 src/settingsdialogdiagnostics.h (limited to 'src/settings.cpp') diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 86ef9721..d8316e7e 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -37,6 +37,7 @@ SET(organizer_SRCS spawn.cpp singleinstance.cpp settingsdialog.cpp + settingsdialogdiagnostics.cpp settingsdialoggeneral.cpp settingsdialognexus.cpp settingsdialogpaths.cpp @@ -157,6 +158,7 @@ SET(organizer_HDRS spawn.h singleinstance.h settingsdialog.h + settingsdialogdiagnostics.h settingsdialoggeneral.h settingsdialognexus.h settingsdialogpaths.h @@ -443,6 +445,7 @@ set(profiles set(settings settings settingsdialog + settingsdialogdiagnostics settingsdialoggeneral settingsdialognexus settingsdialogpaths diff --git a/src/settings.cpp b/src/settings.cpp index 515ff907..725b7e06 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -22,6 +22,7 @@ along with Mod Organizer. If not, see . #include "pluginsetting.h" #include "serverinfo.h" #include "settingsdialog.h" +#include "settingsdialogdiagnostics.h" #include "settingsdialoggeneral.h" #include "settingsdialognexus.h" #include "settingsdialogpaths.h" @@ -676,7 +677,7 @@ void Settings::query(PluginContainer *pluginContainer, QWidget *parent) tabs.push_back(std::unique_ptr(new GeneralSettingsTab(this, dialog))); tabs.push_back(std::unique_ptr(new PathsSettingsTab(this, dialog))); - tabs.push_back(std::unique_ptr(new DiagnosticsTab(this, dialog))); + tabs.push_back(std::unique_ptr(new DiagnosticsSettingsTab(this, dialog))); 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))); @@ -742,32 +743,3 @@ void Settings::query(PluginContainer *pluginContainer, QWidget *parent) } } - - -Settings::DiagnosticsTab::DiagnosticsTab(Settings *m_parent, SettingsDialog &m_dialog) - : SettingsTab(m_parent, m_dialog) - , m_logLevelBox(m_dialog.findChild("logLevelBox")) - , m_dumpsTypeBox(m_dialog.findChild("dumpsTypeBox")) - , m_dumpsMaxEdit(m_dialog.findChild("dumpsMaxEdit")) - , m_diagnosticsExplainedLabel(m_dialog.findChild("diagnosticsExplainedLabel")) -{ - setLevelsBox(); - m_dumpsTypeBox->setCurrentIndex(m_parent->crashDumpsType()); - m_dumpsMaxEdit->setValue(m_parent->crashDumpsMax()); - QString logsPath = qApp->property("dataPath").toString() - + "/" + QString::fromStdWString(AppConfig::logPath()); - m_diagnosticsExplainedLabel->setText( - m_diagnosticsExplainedLabel->text() - .replace("LOGS_FULL_PATH", logsPath) - .replace("LOGS_DIR", QString::fromStdWString(AppConfig::logPath())) - .replace("DUMPS_FULL_PATH", QString::fromStdWString(OrganizerCore::crashDumpsPath())) - .replace("DUMPS_DIR", QString::fromStdWString(AppConfig::dumpsDir())) - ); -} - -void Settings::DiagnosticsTab::update() -{ - m_Settings.setValue("Settings/log_level", m_logLevelBox->currentData().toInt()); - m_Settings.setValue("Settings/crash_dumps_type", m_dumpsTypeBox->currentIndex()); - m_Settings.setValue("Settings/crash_dumps_max", m_dumpsMaxEdit->value()); -} diff --git a/src/settings.h b/src/settings.h index 64068173..71fbcbc1 100644 --- a/src/settings.h +++ b/src/settings.h @@ -449,24 +449,6 @@ private: void readPluginBlacklist(); QString getConfigurablePath(const QString &key, const QString &def, bool resolve) const; - - - class DiagnosticsTab : public SettingsTab - { - public: - DiagnosticsTab(Settings *parent, SettingsDialog &dialog); - - void update(); - - private: - QComboBox *m_logLevelBox; - QComboBox *m_dumpsTypeBox; - QSpinBox *m_dumpsMaxEdit; - QLabel *m_diagnosticsExplainedLabel; - - void setLevelsBox(); - }; - private slots: signals: diff --git a/src/settingsdialog.ui b/src/settingsdialog.ui index 3ad525e1..1deac400 100644 --- a/src/settingsdialog.ui +++ b/src/settingsdialog.ui @@ -1325,6 +1325,9 @@ programs you are intentionally running. true + + true + diff --git a/src/settingsdialogdiagnostics.cpp b/src/settingsdialogdiagnostics.cpp new file mode 100644 index 00000000..2ea4d478 --- /dev/null +++ b/src/settingsdialogdiagnostics.cpp @@ -0,0 +1,28 @@ +#include "settingsdialogdiagnostics.h" +#include "ui_settingsdialog.h" +#include "appconfig.h" +#include "organizercore.h" + +DiagnosticsSettingsTab::DiagnosticsSettingsTab(Settings *m_parent, SettingsDialog &m_dialog) + : SettingsTab(m_parent, m_dialog) +{ + ui->logLevelBox->setCurrentIndex(m_parent->logLevel()); + ui->dumpsTypeBox->setCurrentIndex(m_parent->crashDumpsType()); + ui->dumpsMaxEdit->setValue(m_parent->crashDumpsMax()); + QString logsPath = qApp->property("dataPath").toString() + + "/" + QString::fromStdWString(AppConfig::logPath()); + ui->diagnosticsExplainedLabel->setText( + ui->diagnosticsExplainedLabel->text() + .replace("LOGS_FULL_PATH", logsPath) + .replace("LOGS_DIR", QString::fromStdWString(AppConfig::logPath())) + .replace("DUMPS_FULL_PATH", QString::fromStdWString(OrganizerCore::crashDumpsPath())) + .replace("DUMPS_DIR", QString::fromStdWString(AppConfig::dumpsDir())) + ); +} + +void DiagnosticsSettingsTab::update() +{ + m_Settings.setValue("Settings/log_level", ui->logLevelBox->currentIndex()); + m_Settings.setValue("Settings/crash_dumps_type", ui->dumpsTypeBox->currentIndex()); + m_Settings.setValue("Settings/crash_dumps_max", ui->dumpsMaxEdit->value()); +} diff --git a/src/settingsdialogdiagnostics.h b/src/settingsdialogdiagnostics.h new file mode 100644 index 00000000..2341c253 --- /dev/null +++ b/src/settingsdialogdiagnostics.h @@ -0,0 +1,17 @@ +#ifndef SETTINGSDIALOGDIAGNOSTICS_H +#define SETTINGSDIALOGDIAGNOSTICS_H + +#include "settings.h" +#include "settingsdialog.h" + +class DiagnosticsSettingsTab : public SettingsTab +{ +public: + DiagnosticsSettingsTab(Settings *parent, SettingsDialog &dialog); + + void update(); + +private: +}; + +#endif // SETTINGSDIALOGDIAGNOSTICS_H -- cgit v1.3.1 From 107b396902be52f8ae305f58d4e7d85a86779051 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sat, 20 Jul 2019 11:12:28 -0400 Subject: moved tabs to SettingsDialog removed Settings::query(), main window now deals with SettingsDialog directly --- src/mainwindow.cpp | 5 +- src/settings.cpp | 100 ---------------------------------------- src/settings.h | 55 +--------------------- src/settingsdialog.cpp | 105 +++++++++++++++++++++++++++++++++++++++++- src/settingsdialog.h | 26 +++++++++-- src/settingsdialogplugins.cpp | 2 + 6 files changed, 133 insertions(+), 160 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 7c73bc8a..28405819 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -72,6 +72,7 @@ along with Mod Organizer. If not, see . #include "previewdialog.h" #include "browserdialog.h" #include "aboutdialog.h" +#include "settingsdialog.h" #include #include "nxmaccessmanager.h" #include "appconfig.h" @@ -5217,7 +5218,9 @@ void MainWindow::on_actionSettings_triggered() bool proxy = settings.useProxy(); DownloadManager *dlManager = m_OrganizerCore.downloadManager(); - settings.query(&m_PluginContainer, this); + + SettingsDialog dialog(&m_PluginContainer, &settings, this); + dialog.exec(); if (oldManagedGameDirectory != settings.getManagedGameDirectory()) { QMessageBox::about(this, tr("Restarting MO"), diff --git a/src/settings.cpp b/src/settings.cpp index 725b7e06..dc07e107 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -21,14 +21,6 @@ along with Mod Organizer. If not, see . #include "pluginsetting.h" #include "serverinfo.h" -#include "settingsdialog.h" -#include "settingsdialogdiagnostics.h" -#include "settingsdialoggeneral.h" -#include "settingsdialognexus.h" -#include "settingsdialogpaths.h" -#include "settingsdialogplugins.h" -#include "settingsdialogsteam.h" -#include "settingsdialogworkarounds.h" #include "versioninfo.h" #include "appconfig.h" #include "organizercore.h" @@ -75,23 +67,6 @@ along with Mod Organizer. If not, see . using namespace MOBase; -SettingsTab::SettingsTab(Settings *m_parent, SettingsDialog &m_dialog) - : m_parent(m_parent) - , m_Settings(m_parent->settingsRef()) - , m_dialog(m_dialog) - , ui(m_dialog.ui) -{ -} - -SettingsTab::~SettingsTab() -{} - -QWidget* SettingsTab::parentWidget() -{ - return &m_dialog; -} - - Settings *Settings::s_Instance = nullptr; @@ -668,78 +643,3 @@ void Settings::writePluginBlacklist() m_Settings.endArray(); } - -void Settings::query(PluginContainer *pluginContainer, QWidget *parent) -{ - SettingsDialog dialog(pluginContainer, this, parent); - - std::vector> tabs; - - tabs.push_back(std::unique_ptr(new GeneralSettingsTab(this, dialog))); - tabs.push_back(std::unique_ptr(new PathsSettingsTab(this, dialog))); - tabs.push_back(std::unique_ptr(new DiagnosticsSettingsTab(this, dialog))); - 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 WorkaroundsSettingsTab(this, dialog))); - - - QString key = QString("geometry/%1").arg(dialog.objectName()); - if (m_Settings.contains(key)) { - dialog.restoreGeometry(m_Settings.value(key).toByteArray()); - } - - if (dialog.exec() == QDialog::Accepted) { - - for (auto&& tab : tabs) { - tab->closing(); - } - - // remember settings before change - QMap before; - m_Settings.beginGroup("Settings"); - for (auto k : m_Settings.allKeys()) - before[k] = m_Settings.value(k).toString(); - m_Settings.endGroup(); - - // transfer modified settings to configuration file - for (std::unique_ptr const &tab: tabs) { - tab->update(); - } - - // print "changed" settings - m_Settings.beginGroup("Settings"); - bool first_update = true; - for (auto k : m_Settings.allKeys()) - if (m_Settings.value(k).toString() != before[k] && !k.contains("username") && !k.contains("password")) - { - if (first_update) { - log::debug("Changed settings:"); - first_update = false; - } - log::debug(" {}={}", k, m_Settings.value(k).toString()); - } - m_Settings.endGroup(); - } - m_Settings.setValue(key, dialog.saveGeometry()); - - // These changes happen regardless of accepted or rejected - bool restartNeeded = false; - if (dialog.getApiKeyChanged()) { - restartNeeded = true; - } - if (dialog.getResetGeometries()) { - restartNeeded = true; - m_Settings.setValue("reset_geometry", true); - } - if (restartNeeded) { - if (QMessageBox::question(nullptr, - tr("Restart Mod Organizer?"), - tr("In order to finish configuration changes, MO must be restarted.\n" - "Restart it now?"), - QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { - qApp->exit(INT_MAX); - } - } - -} diff --git a/src/settings.h b/src/settings.h index 71fbcbc1..899baaa3 100644 --- a/src/settings.h +++ b/src/settings.h @@ -26,60 +26,21 @@ along with Mod Organizer. If not, see . #include #include #include -#include #include #include #include #include #include -#include - -#include //for uint - #include #include -class QCheckBox; -class QComboBox; -class QLineEdit; -class QSpinBox; -class QListWidget; -class QWidget; -class QLabel; -class QPushButton; - -struct ServerInfo; - namespace MOBase { class IPlugin; class IPluginGame; } -namespace Ui { - class SettingsDialog; -} - -class SettingsDialog; class PluginContainer; -class Settings; - -class SettingsTab -{ -public: - SettingsTab(Settings *m_parent, SettingsDialog &m_dialog); - virtual ~SettingsTab(); - - virtual void update() = 0; - virtual void closing() {} - -protected: - Settings *m_parent; - QSettings &m_Settings; - SettingsDialog &m_dialog; - Ui::SettingsDialog* ui; - - QWidget* parentWidget(); -}; +struct ServerInfo; /** * manages the settings for Mod Organizer. The settings are not cached @@ -87,17 +48,11 @@ protected: **/ class Settings : public QObject { - Q_OBJECT public: - - /** - * @brief constructor - **/ Settings(const QSettings &settingsSource); - - virtual ~Settings(); + ~Settings(); static Settings &instance(); @@ -113,12 +68,6 @@ public: */ void registerPlugin(MOBase::IPlugin *plugin); - /** - * displays a SettingsDialog that allows the user to change settings. If the - * user accepts the changes, the settings are immediately written - **/ - void query(PluginContainer *pluginContainer, QWidget *parent); - /** * set up the settings for the specified plugins **/ diff --git a/src/settingsdialog.cpp b/src/settingsdialog.cpp index 76b0a146..8c5b2678 100644 --- a/src/settingsdialog.cpp +++ b/src/settingsdialog.cpp @@ -29,6 +29,14 @@ along with Mod Organizer. If not, see . #include "nexusinterface.h" #include "plugincontainer.h" +#include "settingsdialogdiagnostics.h" +#include "settingsdialoggeneral.h" +#include "settingsdialognexus.h" +#include "settingsdialogpaths.h" +#include "settingsdialogplugins.h" +#include "settingsdialogsteam.h" +#include "settingsdialogworkarounds.h" + #include #include @@ -47,7 +55,6 @@ along with Mod Organizer. If not, see . using namespace MOBase; - SettingsDialog::SettingsDialog(PluginContainer *pluginContainer, Settings* settings, QWidget *parent) : TutorableDialog("SettingsDialog", parent) , ui(new Ui::SettingsDialog) @@ -57,7 +64,84 @@ SettingsDialog::SettingsDialog(PluginContainer *pluginContainer, Settings* setti , m_keyChanged(false) { ui->setupUi(this); - ui->pluginSettingsList->setStyleSheet("QTreeWidget::item {padding-right: 10px;}"); + + m_tabs.push_back(std::unique_ptr(new GeneralSettingsTab(settings, *this))); + m_tabs.push_back(std::unique_ptr(new PathsSettingsTab(settings, *this))); + m_tabs.push_back(std::unique_ptr(new DiagnosticsSettingsTab(settings, *this))); + m_tabs.push_back(std::unique_ptr(new NexusSettingsTab(settings, *this))); + m_tabs.push_back(std::unique_ptr(new SteamSettingsTab(settings, *this))); + m_tabs.push_back(std::unique_ptr(new PluginsSettingsTab(settings, *this))); + m_tabs.push_back(std::unique_ptr(new WorkaroundsSettingsTab(settings, *this))); + + auto& qsettings = settings->directInterface(); + + QString key = QString("geometry/%1").arg(objectName()); + if (qsettings.contains(key)) { + restoreGeometry(qsettings.value(key).toByteArray()); + } +} + +int SettingsDialog::exec() +{ + auto& qsettings = m_settings->directInterface(); + auto ret = TutorableDialog::exec(); + + if (ret == QDialog::Accepted) { + + for (auto&& tab : m_tabs) { + tab->closing(); + } + + // remember settings before change + QMap before; + qsettings.beginGroup("Settings"); + for (auto k : qsettings.allKeys()) + before[k] = qsettings.value(k).toString(); + qsettings.endGroup(); + + // transfer modified settings to configuration file + for (std::unique_ptr const &tab: m_tabs) { + tab->update(); + } + + // print "changed" settings + qsettings.beginGroup("Settings"); + bool first_update = true; + for (auto k : qsettings.allKeys()) + if (qsettings.value(k).toString() != before[k] && !k.contains("username") && !k.contains("password")) + { + if (first_update) { + qDebug("Changed settings:"); + first_update = false; + } + qDebug(" %s=%s", k.toUtf8().data(), qsettings.value(k).toString().toUtf8().data()); + } + qsettings.endGroup(); + } + + QString key = QString("geometry/%1").arg(objectName()); + qsettings.setValue(key, saveGeometry()); + + // These changes happen regardless of accepted or rejected + bool restartNeeded = false; + if (getApiKeyChanged()) { + restartNeeded = true; + } + if (getResetGeometries()) { + restartNeeded = true; + qsettings.setValue("reset_geometry", true); + } + if (restartNeeded) { + if (QMessageBox::question(nullptr, + tr("Restart Mod Organizer?"), + tr("In order to finish configuration changes, MO must be restarted.\n" + "Restart it now?"), + QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { + qApp->exit(INT_MAX); + } + } + + return ret; } SettingsDialog::~SettingsDialog() @@ -107,3 +191,20 @@ bool SettingsDialog::getApiKeyChanged() { return m_keyChanged; } + + +SettingsTab::SettingsTab(Settings *m_parent, SettingsDialog &m_dialog) + : m_parent(m_parent) + , m_Settings(m_parent->settingsRef()) + , m_dialog(m_dialog) + , ui(m_dialog.ui) +{ +} + +SettingsTab::~SettingsTab() +{} + +QWidget* SettingsTab::parentWidget() +{ + return &m_dialog; +} diff --git a/src/settingsdialog.h b/src/settingsdialog.h index 81c17f44..f2367315 100644 --- a/src/settingsdialog.h +++ b/src/settingsdialog.h @@ -27,10 +27,26 @@ along with Mod Organizer. If not, see . class PluginContainer; class Settings; +class SettingsDialog; +namespace Ui { class SettingsDialog; } -namespace Ui { - class SettingsDialog; -} +class SettingsTab +{ +public: + SettingsTab(Settings *m_parent, SettingsDialog &m_dialog); + virtual ~SettingsTab(); + + virtual void update() = 0; + virtual void closing() {} + +protected: + Settings *m_parent; + QSettings &m_Settings; + SettingsDialog &m_dialog; + Ui::SettingsDialog* ui; + + QWidget* parentWidget(); +}; /** @@ -60,6 +76,8 @@ public: bool m_GeometriesReset; PluginContainer *m_PluginContainer; + int exec() override; + public slots: virtual void accept(); @@ -69,7 +87,7 @@ public: private: Settings* m_settings; - + std::vector> m_tabs; }; diff --git a/src/settingsdialogplugins.cpp b/src/settingsdialogplugins.cpp index 33bc1563..53b28fcc 100644 --- a/src/settingsdialogplugins.cpp +++ b/src/settingsdialogplugins.cpp @@ -8,6 +8,8 @@ using MOBase::IPlugin; PluginsSettingsTab::PluginsSettingsTab(Settings *m_parent, SettingsDialog &m_dialog) : SettingsTab(m_parent, m_dialog) { + ui->pluginSettingsList->setStyleSheet("QTreeWidget::item {padding-right: 10px;}"); + // display plugin settings QSet handledNames; for (IPlugin *plugin : m_parent->plugins()) { -- cgit v1.3.1 From a05862aaa13b028e2f250347daa7a2e0f64c2380 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sat, 20 Jul 2019 11:20:27 -0400 Subject: cleaned up includes removed commented out code reordered member functions in Settings --- src/settings.cpp | 44 ------------------------------------------- src/settings.h | 36 +++++++---------------------------- src/settingsdialog.cpp | 26 ------------------------- src/settingsdialog.h | 4 +--- src/settingsdialoggeneral.cpp | 24 ----------------------- src/settingsdialognexus.cpp | 11 ----------- src/settingsdialognexus.h | 1 + 7 files changed, 9 insertions(+), 137 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/settings.cpp b/src/settings.cpp index dc07e107..e7a853a2 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -18,58 +18,16 @@ along with Mod Organizer. If not, see . */ #include "settings.h" - -#include "pluginsetting.h" #include "serverinfo.h" -#include "versioninfo.h" #include "appconfig.h" -#include "organizercore.h" #include -#include #include -#include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include // for Qt::UserRole, etc - -#include // For ShellExecuteW, HINSTANCE, etc -#include // For storage - -#include // for sort -#include -#include // for runtime_error -#include -#include // for pair, make_pair - - using namespace MOBase; - Settings *Settings::s_Instance = nullptr; - Settings::Settings(const QSettings &settingsSource) : m_Settings(settingsSource.fileName(), settingsSource.format()) { @@ -80,13 +38,11 @@ Settings::Settings(const QSettings &settingsSource) } } - Settings::~Settings() { s_Instance = nullptr; } - Settings &Settings::instance() { if (s_Instance == nullptr) { diff --git a/src/settings.h b/src/settings.h index 899baaa3..b20e78d0 100644 --- a/src/settings.h +++ b/src/settings.h @@ -23,17 +23,6 @@ along with Mod Organizer. If not, see . #include "loadmechanism.h" #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - namespace MOBase { class IPlugin; class IPluginGame; @@ -376,6 +365,8 @@ public: */ bool colorSeparatorScrollbar() const; + static QColor getIdealTextColor(const QColor& rBackgroundColor); + // temp QSettings& settingsRef() { return m_Settings; } MOBase::IPluginGame const *gamePlugin() { return m_GamePlugin; } @@ -386,37 +377,24 @@ public: const LoadMechanism& loadMechanism() const { return m_LoadMechanism; } public slots: - void managedGameChanged(MOBase::IPluginGame const *gamePlugin); -public: - static QColor getIdealTextColor(const QColor& rBackgroundColor); -private: - - static bool obfuscate(const QString key, const QString data); - static QString deObfuscate(const QString key); - - void readPluginBlacklist(); - QString getConfigurablePath(const QString &key, const QString &def, bool resolve) const; - -private slots: signals: - void languageChanged(const QString &newLanguage); void styleChanged(const QString &newStyle); private: - static Settings *s_Instance; - MOBase::IPluginGame const *m_GamePlugin; - QSettings m_Settings; - LoadMechanism m_LoadMechanism; - std::vector m_Plugins; + static bool obfuscate(const QString key, const QString data); + static QString deObfuscate(const QString key); + + void readPluginBlacklist(); + QString getConfigurablePath(const QString &key, const QString &def, bool resolve) const; }; #endif // SETTINGS_H diff --git a/src/settingsdialog.cpp b/src/settingsdialog.cpp index 8c5b2678..e008086a 100644 --- a/src/settingsdialog.cpp +++ b/src/settingsdialog.cpp @@ -18,17 +18,7 @@ along with Mod Organizer. If not, see . */ #include "settingsdialog.h" - #include "ui_settingsdialog.h" -#include "categoriesdialog.h" -#include "helper.h" -#include "noeditdelegate.h" -#include "iplugingame.h" -#include "settings.h" -#include "instancemanager.h" -#include "nexusinterface.h" -#include "plugincontainer.h" - #include "settingsdialogdiagnostics.h" #include "settingsdialoggeneral.h" #include "settingsdialognexus.h" @@ -37,22 +27,6 @@ along with Mod Organizer. If not, see . #include "settingsdialogsteam.h" #include "settingsdialogworkarounds.h" -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#define WIN32_LEAN_AND_MEAN -#include - - using namespace MOBase; SettingsDialog::SettingsDialog(PluginContainer *pluginContainer, Settings* settings, QWidget *parent) diff --git a/src/settingsdialog.h b/src/settingsdialog.h index f2367315..03bba7cf 100644 --- a/src/settingsdialog.h +++ b/src/settingsdialog.h @@ -21,15 +21,13 @@ along with Mod Organizer. If not, see . #define SETTINGSDIALOG_H #include "tutorabledialog.h" -#include "nxmaccessmanager.h" -#include -#include class PluginContainer; class Settings; class SettingsDialog; namespace Ui { class SettingsDialog; } + class SettingsTab { public: diff --git a/src/settingsdialoggeneral.cpp b/src/settingsdialoggeneral.cpp index cd98dfdc..324dc4f4 100644 --- a/src/settingsdialoggeneral.cpp +++ b/src/settingsdialoggeneral.cpp @@ -33,28 +33,6 @@ GeneralSettingsTab::GeneralSettingsTab(Settings *m_parent, SettingsDialog &m_dia ui->styleBox->setCurrentIndex(currentID); } } - /* verision using palette only works with fusion theme for some stupid reason... - m_overwritingBtn->setAutoFillBackground(true); - m_overwrittenBtn->setAutoFillBackground(true); - m_containsBtn->setAutoFillBackground(true); - m_containedBtn->setAutoFillBackground(true); - m_overwritingBtn->setPalette(QPalette(m_parent->modlistOverwritingLooseColor())); - m_overwrittenBtn->setPalette(QPalette(m_parent->modlistOverwrittenLooseColor())); - m_containsBtn->setPalette(QPalette(m_parent->modlistContainsPluginColor())); - m_containedBtn->setPalette(QPalette(m_parent->pluginListContainedColor())); - QPalette palette1 = m_overwritingBtn->palette(); - QPalette palette2 = m_overwrittenBtn->palette(); - QPalette palette3 = m_containsBtn->palette(); - QPalette palette4 = m_containedBtn->palette(); - palette1.setColor(QPalette::Background, m_parent->modlistOverwritingLooseColor()); - palette2.setColor(QPalette::Background, m_parent->modlistOverwrittenLooseColor()); - palette3.setColor(QPalette::Background, m_parent->modlistContainsPluginColor()); - palette4.setColor(QPalette::Background, m_parent->pluginListContainedColor()); - m_overwritingBtn->setPalette(palette1); - m_overwrittenBtn->setPalette(palette2); - m_containsBtn->setPalette(palette3); - m_containedBtn->setPalette(palette4); - */ //version with stylesheet setButtonColor(ui->overwritingBtn, m_parent->modlistOverwritingLooseColor()); @@ -137,12 +115,10 @@ void GeneralSettingsTab::addLanguages() } } languages.push_back(std::make_pair(QString("%1").arg(languageString), exp.cap(1))); - //languageBox->addItem(QString("%1").arg(languageString), exp.cap(1)); } } if (!ui->languageBox->findText("English")) { languages.push_back(std::make_pair(QString("English"), QString("en_US"))); - //languageBox->addItem("English", "en_US"); } std::sort(languages.begin(), languages.end()); for (const auto &lang : languages) { diff --git a/src/settingsdialognexus.cpp b/src/settingsdialognexus.cpp index 7d4414fd..575f54d0 100644 --- a/src/settingsdialognexus.cpp +++ b/src/settingsdialognexus.cpp @@ -114,17 +114,6 @@ NexusSettingsTab::NexusSettingsTab(Settings *parent, SettingsDialog &dialog) void NexusSettingsTab::update() { - /* - if (m_loginCheckBox->isChecked()) { - m_Settings.setValue("Settings/nexus_login", true); - m_Settings.setValue("Settings/nexus_username", m_usernameEdit->text()); - m_Settings.setValue("Settings/nexus_password", obfuscate(m_passwordEdit->text())); - } else { - m_Settings.setValue("Settings/nexus_login", false); - m_Settings.remove("Settings/nexus_username"); - m_Settings.remove("Settings/nexus_password"); - } - */ m_Settings.setValue("Settings/offline_mode", ui->offlineBox->isChecked()); m_Settings.setValue("Settings/use_proxy", ui->proxyBox->isChecked()); m_Settings.setValue("Settings/endorsement_integration", ui->endorsementBox->isChecked()); diff --git a/src/settingsdialognexus.h b/src/settingsdialognexus.h index 5c01f61f..cca2e1b5 100644 --- a/src/settingsdialognexus.h +++ b/src/settingsdialognexus.h @@ -3,6 +3,7 @@ #include "settings.h" #include "settingsdialog.h" +#include "nxmaccessmanager.h" class NexusSettingsTab : public SettingsTab { -- 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/settings.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 b6b01a52db1877b16531137289641fb9be9833aa Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Fri, 2 Aug 2019 23:24:27 -0400 Subject: removed mentions of QSettings from main.cpp added necessary member functions in Settings --- src/filedialogmemory.cpp | 1 + src/filedialogmemory.h | 1 + src/main.cpp | 185 +++++++++++++++++++++-------------------------- src/mainwindow.cpp | 6 +- src/mainwindow.h | 3 +- src/organizercore.cpp | 4 +- src/organizercore.h | 2 +- src/settings.cpp | 77 +++++++++++++++++++- src/settings.h | 22 +++++- 9 files changed, 188 insertions(+), 113 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/filedialogmemory.cpp b/src/filedialogmemory.cpp index 0e3e9793..308a175e 100644 --- a/src/filedialogmemory.cpp +++ b/src/filedialogmemory.cpp @@ -18,6 +18,7 @@ along with Mod Organizer. If not, see . */ #include "filedialogmemory.h" +#include "settings.h" #include diff --git a/src/filedialogmemory.h b/src/filedialogmemory.h index 81d7ba40..1a72b289 100644 --- a/src/filedialogmemory.h +++ b/src/filedialogmemory.h @@ -26,6 +26,7 @@ along with Mod Organizer. If not, see . #include #include +class Settings; class FileDialogMemory { diff --git a/src/main.cpp b/src/main.cpp index 911f11c3..720ecbf9 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -245,9 +245,10 @@ static bool HaveWriteAccess(const std::wstring &path) } -QString determineProfile(QStringList &arguments, const QSettings &settings) +QString determineProfile(QStringList &arguments, const Settings &settings) { - QString selectedProfileName = QString::fromUtf8(settings.value("selected_profile", "").toByteArray()); + QString selectedProfileName = settings.getSelectedProfileName(); + { // see if there is a profile on the command line int profileIndex = arguments.indexOf("-p", 1); if ((profileIndex != -1) && (profileIndex < arguments.size() - 1)) { @@ -257,6 +258,7 @@ QString determineProfile(QStringList &arguments, const QSettings &settings) arguments.removeAt(profileIndex); arguments.removeAt(profileIndex); } + if (selectedProfileName.isEmpty()) { log::debug("no configured profile"); selectedProfileName = "Default"; @@ -267,46 +269,50 @@ QString determineProfile(QStringList &arguments, const QSettings &settings) return selectedProfileName; } -MOBase::IPluginGame *selectGame(QSettings &settings, QDir const &gamePath, MOBase::IPluginGame *game) +MOBase::IPluginGame *selectGame( + Settings &settings, QDir const &gamePath, MOBase::IPluginGame *game) { - settings.setValue("gameName", game->gameName()); - //Sadly, hookdll needs gamePath in order to run. So following code block is - //commented out - /*if (gamePath == game->gameDirectory()) { - settings.remove("gamePath"); - } else*/ { - QString gameDir = gamePath.absolutePath(); - game->setGamePath(gameDir); - settings.setValue("gamePath", QDir::toNativeSeparators(gameDir).toUtf8().constData()); - } - return game; //Woot + settings.setManagedGameName(game->gameName()); + + QString gameDir = gamePath.absolutePath(); + game->setGamePath(gameDir); + + settings.setManagedGameDirectory(gameDir); + + return game; } -MOBase::IPluginGame *determineCurrentGame(QString const &moPath, QSettings &settings, PluginContainer const &plugins) +MOBase::IPluginGame *determineCurrentGame( + QString const &moPath, Settings &settings, PluginContainer const &plugins) { //Determine what game we are running where. Be very paranoid in case the //user has done something odd. //If the game name has been set up, try to use that. - QString gameName = settings.value("gameName", "").toString(); + const QString gameName = settings.getManagedGameName(); bool gameConfigured = !gameName.isEmpty(); + if (gameConfigured) { MOBase::IPluginGame *game = plugins.managedGame(gameName); if (game == nullptr) { reportError(QObject::tr("Plugin to handle %1 no longer installed").arg(gameName)); return nullptr; } - QString gamePath = QString::fromUtf8(settings.value("gamePath", "").toByteArray()); + + QString gamePath = settings.getManagedGameDirectory(); if (gamePath == "") { gamePath = game->gameDirectory().absolutePath(); } + QDir gameDir(gamePath); QFileInfo directoryInfo(gameDir.path()); + if (directoryInfo.isSymLink()) { reportError(QObject::tr("The configured path to the game directory (%1) appears to be a symbolic (or other) link. " "This setup is incompatible with MO2's VFS and will not run correctly.").arg(gamePath)); } + if (game->looksValid(gameDir)) { return selectGame(settings, gameDir, game); } @@ -315,7 +321,7 @@ MOBase::IPluginGame *determineCurrentGame(QString const &moPath, QSettings &sett //If we've made it this far and the instance is already configured for a game, something has gone wrong. //Tell the user about it. if (gameConfigured) { - QString gamePath = QString::fromUtf8(settings.value("gamePath", "").toByteArray()); + const QString gamePath = settings.getManagedGameDirectory(); reportError(QObject::tr("Could not use configuration settings for game \"%1\", path \"%2\"."). arg(gameName).arg(gamePath)); } @@ -480,27 +486,6 @@ static QString getVersionDisplayString() return createVersionInfo().displayString(3); } -void dumpSettings(QSettings& settings) -{ - static const QStringList ignore({ - "username", "password", "nexus_api_key" - }); - - log::debug("settings:"); - - settings.beginGroup("Settings"); - - for (auto k : settings.allKeys()) { - if (ignore.contains(k, Qt::CaseInsensitive)) { - continue; - } - - log::debug(" . {}={}", k, settings.value(k).toString()); - } - - settings.endGroup(); -} - void checkMissingFiles() { // files that are likely to be eaten @@ -557,7 +542,7 @@ int runApplication(MOApplication &application, SingleInstance &instance, log::warn("no ssl support"); } - QString dataPath = application.property("dataPath").toString(); + const QString dataPath = application.property("dataPath").toString(); log::info("data path: {}", dataPath); if (!bootstrap()) { @@ -573,11 +558,7 @@ int runApplication(MOApplication &application, SingleInstance &instance, try { log::info("working directory: {}", QDir::currentPath()); - QSettings initSettings( - dataPath + "/" + QString::fromStdWString(AppConfig::iniFileName()), - QSettings::IniFormat); - - Settings settings(initSettings); + Settings settings(dataPath + "/" + QString::fromStdWString(AppConfig::iniFileName())); log::getDefault().setLevel(settings.logLevel()); // global crashDumpType sits in OrganizerCore to make a bit less ugly to @@ -587,7 +568,7 @@ int runApplication(MOApplication &application, SingleInstance &instance, env::Environment env; env.dump(); - dumpSettings(initSettings); + settings.dump(); sanityChecks(env); log::debug("initializing core"); @@ -602,7 +583,8 @@ int runApplication(MOApplication &application, SingleInstance &instance, pluginContainer.loadPlugins(); MOBase::IPluginGame *game = determineCurrentGame( - application.applicationDirPath(), initSettings, pluginContainer); + application.applicationDirPath(), settings, pluginContainer); + if (game == nullptr) { InstanceManager &instance = InstanceManager::instance(); QString instanceName = instance.currentInstance(); @@ -612,6 +594,7 @@ int runApplication(MOApplication &application, SingleInstance &instance, } return 1; } + if (splashPath.startsWith(':')) { // currently using MO splash, see if the plugin contains one QString pluginSplash @@ -625,7 +608,7 @@ int runApplication(MOApplication &application, SingleInstance &instance, organizer.setManagedGame(game); organizer.createDefaultProfile(); - if (!initSettings.contains("game_edition")) { + if (settings.getManagedGameEdition() == "") { QStringList editions = game->gameVariants(); if (editions.size() > 1) { SelectionDialog selection( @@ -641,78 +624,76 @@ int runApplication(MOApplication &application, SingleInstance &instance, if (selection.exec() == QDialog::Rejected) { return 1; } else { - initSettings.setValue("game_edition", selection.getChoiceString()); + settings.setManagedGameEdition(selection.getChoiceString()); } } } - game->setGameVariant(initSettings.value("game_edition").toString()); + + game->setGameVariant(settings.getManagedGameEdition()); log::info("managing game at {}", game->gameDirectory().absolutePath()); - organizer.updateExecutablesList(initSettings); + organizer.updateExecutablesList(); - QString selectedProfileName = determineProfile(arguments, initSettings); + QString selectedProfileName = determineProfile(arguments, settings); organizer.setCurrentProfile(selectedProfileName); // if we have a command line parameter, it is either a nxm link or // a binary to start - if (arguments.size() > 1) { - if (MOShortcut shortcut{ arguments.at(1) }) { - if (shortcut.hasExecutable()) { - try { - organizer.runShortcut(shortcut); - return 0; - } - catch (const std::exception &e) { - reportError( - QObject::tr("failed to start shortcut: %1").arg(e.what())); - return 1; - } - } - } - else if (OrganizerCore::isNxmLink(arguments.at(1))) { - log::debug("starting download from command line: {}", arguments.at(1)); - organizer.externalMessage(arguments.at(1)); - } - else { - QString exeName = arguments.at(1); - log::debug("starting {} from command line", exeName); - arguments.removeFirst(); // remove application name (ModOrganizer.exe) - arguments.removeFirst(); // remove binary name - // pass the remaining parameters to the binary - try { - organizer.startApplication(exeName, arguments, QString(), QString()); - return 0; - } - catch (const std::exception &e) { - reportError( - QObject::tr("failed to start application: %1").arg(e.what())); - return 1; - } - } - } + if (arguments.size() > 1) { + if (MOShortcut shortcut{ arguments.at(1) }) { + if (shortcut.hasExecutable()) { + try { + organizer.runShortcut(shortcut); + return 0; + } + catch (const std::exception &e) { + reportError( + QObject::tr("failed to start shortcut: %1").arg(e.what())); + return 1; + } + } + } + else if (OrganizerCore::isNxmLink(arguments.at(1))) { + log::debug("starting download from command line: {}", arguments.at(1)); + organizer.externalMessage(arguments.at(1)); + } + else { + QString exeName = arguments.at(1); + log::debug("starting {} from command line", exeName); + arguments.removeFirst(); // remove application name (ModOrganizer.exe) + arguments.removeFirst(); // remove binary name + // pass the remaining parameters to the binary + try { + organizer.startApplication(exeName, arguments, QString(), QString()); + return 0; + } + catch (const std::exception &e) { + reportError( + QObject::tr("failed to start application: %1").arg(e.what())); + return 1; + } + } + } QPixmap pixmap(splashPath); QSplashScreen splash(pixmap); - if (initSettings.contains("window_monitor")) { - const int monitor = initSettings.value("window_monitor").toInt(); - - if (monitor != -1 && QGuiApplication::screens().size() > monitor) { - QGuiApplication::screens().at(monitor)->geometry().center(); - const QPoint center = QGuiApplication::screens().at(monitor)->geometry().center(); - splash.move(center - splash.rect().center()); - } else { - const QPoint center = QGuiApplication::primaryScreen()->geometry().center(); - splash.move(center - splash.rect().center()); - } + const int monitor = settings.getMainWindowMonitor(); + if (monitor != -1 && QGuiApplication::screens().size() > monitor) { + QGuiApplication::screens().at(monitor)->geometry().center(); + const QPoint center = QGuiApplication::screens().at(monitor)->geometry().center(); + splash.move(center - splash.rect().center()); + } else { + const QPoint center = QGuiApplication::primaryScreen()->geometry().center(); + splash.move(center - splash.rect().center()); } splash.show(); splash.activateWindow(); QString apiKey; - if (organizer.settings().getNexusApiKey(apiKey)) { + if (settings.getNexusApiKey(apiKey)) { NexusInterface::instance(&pluginContainer)->getAccessManager()->apiCheck(apiKey); } @@ -722,15 +703,15 @@ int runApplication(MOApplication &application, SingleInstance &instance, + QString::fromStdWString(AppConfig::tutorialsPath()) + "/", &organizer); - if (!application.setStyleFile(initSettings.value("Settings/style", "").toString())) { + if (!application.setStyleFile(settings.getStyleName())) { // disable invalid stylesheet - initSettings.setValue("Settings/style", ""); + settings.setStyleName(""); } int res = 1; { // scope to control lifetime of mainwindow // set up main window and its data structures - MainWindow mainWindow(initSettings, organizer, pluginContainer); + MainWindow mainWindow(settings, organizer, pluginContainer); NexusInterface::instance(&pluginContainer) ->getAccessManager()->setTopLevelWidget(&mainWindow); diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 28405819..7f7ded80 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -291,7 +291,7 @@ public: }; -MainWindow::MainWindow(QSettings &initSettings +MainWindow::MainWindow(Settings &settings , OrganizerCore &organizerCore , PluginContainer &pluginContainer , QWidget *parent) @@ -540,8 +540,8 @@ MainWindow::MainWindow(QSettings &initSettings connect(&m_SaveMetaTimer, SIGNAL(timeout()), this, SLOT(saveModMetas())); m_SaveMetaTimer.start(5000); - setCategoryListVisible(initSettings.value("categorylist_visible", true).toBool()); - FileDialogMemory::restore(initSettings); + setCategoryListVisible(settings.isCategoryListVisible()); + FileDialogMemory::restore(settings.directInterface()); fixCategories(); diff --git a/src/mainwindow.h b/src/mainwindow.h index aa49205d..7326425a 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -103,6 +103,7 @@ namespace Ui { class MainWindow; } +class Settings; class MainWindow : public QMainWindow, public IUserInterface @@ -113,7 +114,7 @@ class MainWindow : public QMainWindow, public IUserInterface public: - explicit MainWindow(QSettings &initSettings, + explicit MainWindow(Settings &settings, OrganizerCore &organizerCore, PluginContainer &pluginContainer, QWidget *parent = 0); ~MainWindow(); diff --git a/src/organizercore.cpp b/src/organizercore.cpp index 1e164525..72c8dab5 100644 --- a/src/organizercore.cpp +++ b/src/organizercore.cpp @@ -480,14 +480,14 @@ return true; } -void OrganizerCore::updateExecutablesList(QSettings &settings) +void OrganizerCore::updateExecutablesList() { if (m_PluginContainer == nullptr) { log::error("can't update executables list now"); return; } - m_ExecutablesList.load(managedGame(), settings); + m_ExecutablesList.load(managedGame(), m_Settings.directInterface()); // TODO this has nothing to do with executables list move to an appropriate // function! diff --git a/src/organizercore.h b/src/organizercore.h index 2aa7e707..926a21f0 100644 --- a/src/organizercore.h +++ b/src/organizercore.h @@ -107,7 +107,7 @@ public: void setManagedGame(MOBase::IPluginGame *game); - void updateExecutablesList(QSettings &settings); + void updateExecutablesList(); void startMOUpdate(); diff --git a/src/settings.cpp b/src/settings.cpp index 77db6918..5d103267 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -28,8 +28,8 @@ using namespace MOBase; Settings *Settings::s_Instance = nullptr; -Settings::Settings(const QSettings &settingsSource) - : m_Settings(settingsSource.fileName(), settingsSource.format()) +Settings::Settings(const QString& path) + : m_Settings(path, QSettings::IniFormat) { if (s_Instance != nullptr) { throw std::runtime_error("second instance of \"Settings\" created"); @@ -280,7 +280,57 @@ QString Settings::getModDirectory(bool resolve) const QString Settings::getManagedGameDirectory() const { - return m_Settings.value("gamePath", "").toString(); + return QString::fromUtf8(m_Settings.value("gamePath", "").toByteArray()); +} + +void Settings::setManagedGameDirectory(const QString& path) +{ + m_Settings.setValue("gamePath", QDir::toNativeSeparators(path).toUtf8()); +} + +QString Settings::getManagedGameName() const +{ + return m_Settings.value("gameName", "").toString(); +} + +void Settings::setManagedGameName(const QString& name) +{ + m_Settings.setValue("gameName", name); +} + +QString Settings::getManagedGameEdition() const +{ + return m_Settings.value("game_edition", "").toString(); +} + +void Settings::setManagedGameEdition(const QString& name) +{ + m_Settings.setValue("game_edition", name); +} + +QString Settings::getSelectedProfileName() const +{ + return QString::fromUtf8(m_Settings.value("selected_profile", "").toByteArray()); +} + +int Settings::getMainWindowMonitor() const +{ + return m_Settings.value("window_monitor", -1).toInt(); +} + +QString Settings::getStyleName() const +{ + return m_Settings.value("Settings/style", "").toString(); +} + +void Settings::setStyleName(const QString& name) +{ + m_Settings.setValue("Settings/style", name); +} + +bool Settings::isCategoryListVisible() const +{ + return m_Settings.value("categorylist_visible", true).toBool(); } QString Settings::getProfileDirectory(bool resolve) const @@ -608,3 +658,24 @@ void Settings::writePluginBlacklist() m_Settings.endArray(); } + +void Settings::dump() const +{ + static const QStringList ignore({ + "username", "password", "nexus_api_key" + }); + + log::debug("settings:"); + + m_Settings.beginGroup("Settings"); + + for (auto k : m_Settings.allKeys()) { + if (ignore.contains(k, Qt::CaseInsensitive)) { + continue; + } + + log::debug(" . {}={}", k, m_Settings.value(k).toString()); + } + + m_Settings.endGroup(); +} diff --git a/src/settings.h b/src/settings.h index 63718089..f06aece9 100644 --- a/src/settings.h +++ b/src/settings.h @@ -40,7 +40,7 @@ class Settings : public QObject Q_OBJECT public: - Settings(const QSettings &settingsSource); + Settings(const QString& path); ~Settings(); static Settings &instance(); @@ -123,6 +123,24 @@ public: * retrieve the directory where the managed game is stored (with native separators) **/ QString getManagedGameDirectory() const; + void setManagedGameDirectory(const QString& path); + + QString getManagedGameName() const; + void setManagedGameName(const QString& name); + + QString getManagedGameEdition() const; + void setManagedGameEdition(const QString& name); + + QString getSelectedProfileName() const; + + // returns -1 if not set + // + int getMainWindowMonitor() const; + + QString getStyleName() const; + void setStyleName(const QString& name); + + bool isCategoryListVisible() const; /** * retrieve the directory where profiles stored (with native separators) @@ -370,6 +388,8 @@ public: MOBase::IPluginGame const *gamePlugin() { return m_GamePlugin; } const LoadMechanism& loadMechanism() const { return m_LoadMechanism; } + void dump() const; + // temp QMap m_PluginSettings; QMap m_PluginDescriptions; -- cgit v1.3.1 From 07f1ac7a96dcf4c91a24bb1d30af92851ecda78f Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sat, 3 Aug 2019 01:55:21 -0400 Subject: split into GeometrySettings removed most of storeSettings() from OrganizerCore: QSettings handles saving by itself, no need for that removed topLevelSplitter from ui, unused since the log widget is in a dock removed QSettings from MainWindow::readSettings() replaced return values for some of the new getters in Settings to std::optional --- src/executableslist.cpp | 9 ++- src/executableslist.h | 5 +- src/filedialogmemory.cpp | 8 ++- src/filedialogmemory.h | 5 +- src/iuserinterface.h | 4 +- src/main.cpp | 96 +++++++++++++++---------- src/mainwindow.cpp | 116 ++++++++++++++---------------- src/mainwindow.h | 4 +- src/mainwindow.ui | 5 -- src/organizercore.cpp | 90 +++++------------------- src/organizercore.h | 4 -- src/settings.cpp | 180 +++++++++++++++++++++++++++++++++++++++++++---- src/settings.h | 55 ++++++++++++--- 13 files changed, 359 insertions(+), 222 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/executableslist.cpp b/src/executableslist.cpp index 3f76bb6f..2b3219df 100644 --- a/src/executableslist.cpp +++ b/src/executableslist.cpp @@ -21,6 +21,7 @@ along with Mod Organizer. If not, see . #include "iplugingame.h" #include "utility.h" +#include "settings.h" #include #include @@ -64,7 +65,7 @@ bool ExecutablesList::empty() const return m_Executables.empty(); } -void ExecutablesList::load(const MOBase::IPluginGame* game, QSettings& settings) +void ExecutablesList::load(const MOBase::IPluginGame* game, const Settings& s) { log::debug("loading executables"); @@ -74,6 +75,8 @@ void ExecutablesList::load(const MOBase::IPluginGame* game, QSettings& settings) // executables from 2.2.0, see upgradeFromCustom() bool needsUpgrade = false; + auto& settings = const_cast(s.directInterface()); + int numCustomExecutables = settings.beginReadArray("customExecutables"); for (int i = 0; i < numCustomExecutables; ++i) { settings.setArrayIndex(i); @@ -108,8 +111,10 @@ void ExecutablesList::load(const MOBase::IPluginGame* game, QSettings& settings) dump(); } -void ExecutablesList::store(QSettings& settings) +void ExecutablesList::store(Settings& s) { + auto& settings = s.directInterface(); + settings.remove("customExecutables"); settings.beginWriteArray("customExecutables"); diff --git a/src/executableslist.h b/src/executableslist.h index eda2034e..23cf3cfe 100644 --- a/src/executableslist.h +++ b/src/executableslist.h @@ -29,6 +29,7 @@ along with Mod Organizer. If not, see . #include namespace MOBase { class IPluginGame; class ExecutableInfo; } +class Settings; /*! * @brief Information about an executable @@ -103,7 +104,7 @@ public: /** * @brief initializes the list from the settings and the given plugin **/ - void load(const MOBase::IPluginGame* game, QSettings& settings); + void load(const MOBase::IPluginGame* game, const Settings& settings); /** * @brief re-adds all the executables from the plugin and renames existing @@ -114,7 +115,7 @@ public: /** * @brief writes the current list to the settings */ - void store(QSettings& settings); + void store(Settings& settings); /** * @brief get an executable by name diff --git a/src/filedialogmemory.cpp b/src/filedialogmemory.cpp index 308a175e..48828563 100644 --- a/src/filedialogmemory.cpp +++ b/src/filedialogmemory.cpp @@ -27,8 +27,10 @@ FileDialogMemory::FileDialogMemory() } -void FileDialogMemory::save(QSettings &settings) +void FileDialogMemory::save(Settings& s) { + auto& settings = s.directInterface(); + settings.remove("recentDirectories"); settings.beginWriteArray("recentDirectories"); int index = 0; @@ -42,8 +44,10 @@ void FileDialogMemory::save(QSettings &settings) } -void FileDialogMemory::restore(QSettings &settings) +void FileDialogMemory::restore(const Settings& s) { + auto& settings = const_cast(s.directInterface()); + int size = settings.beginReadArray("recentDirectories"); for (int i = 0; i < size; ++i) { settings.setArrayIndex(i); diff --git a/src/filedialogmemory.h b/src/filedialogmemory.h index 1a72b289..d214a8e6 100644 --- a/src/filedialogmemory.h +++ b/src/filedialogmemory.h @@ -23,7 +23,6 @@ along with Mod Organizer. If not, see . #include #include -#include #include class Settings; @@ -31,8 +30,8 @@ class Settings; class FileDialogMemory { public: - static void save(QSettings &settings); - static void restore(QSettings &settings); + static void save(Settings& settings); + static void restore(const Settings& settings); static QString getOpenFileName( const QString &dirID, QWidget *parent = 0, const QString &caption = QString(), diff --git a/src/iuserinterface.h b/src/iuserinterface.h index bba8de2b..7205f982 100644 --- a/src/iuserinterface.h +++ b/src/iuserinterface.h @@ -10,13 +10,13 @@ #include -class QSettings; +class Settings; class IUserInterface { public: - virtual void storeSettings(QSettings &settings) = 0; + virtual void storeSettings(Settings &settings) = 0; virtual void registerPluginTool(MOBase::IPluginTool *tool, QString name = QString(), QMenu *menu = nullptr) = 0; virtual void registerPluginTools(std::vector toolPlugins) = 0; diff --git a/src/main.cpp b/src/main.cpp index 720ecbf9..3e26ea17 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -62,7 +62,6 @@ along with Mod Organizer. If not, see . #include #include #include -#include #include #include #include @@ -116,7 +115,7 @@ bool bootstrap() shellDelete(QStringList(backupDirectory)); } - // cycle logfile + // cycle log file removeOldFiles(qApp->property("dataPath").toString() + "/" + QString::fromStdWString(AppConfig::logPath()), "usvfs*.log", 5, QDir::Name); @@ -247,7 +246,7 @@ static bool HaveWriteAccess(const std::wstring &path) QString determineProfile(QStringList &arguments, const Settings &settings) { - QString selectedProfileName = settings.getSelectedProfileName(); + auto selectedProfileName = settings.getSelectedProfileName(); { // see if there is a profile on the command line int profileIndex = arguments.indexOf("-p", 1); @@ -259,14 +258,14 @@ QString determineProfile(QStringList &arguments, const Settings &settings) arguments.removeAt(profileIndex); } - if (selectedProfileName.isEmpty()) { + if (!selectedProfileName) { log::debug("no configured profile"); selectedProfileName = "Default"; } else { - log::debug("configured profile: {}", selectedProfileName); + log::debug("configured profile: {}", *selectedProfileName); } - return selectedProfileName; + return *selectedProfileName; } MOBase::IPluginGame *selectGame( @@ -290,27 +289,27 @@ MOBase::IPluginGame *determineCurrentGame( //user has done something odd. //If the game name has been set up, try to use that. - const QString gameName = settings.getManagedGameName(); - bool gameConfigured = !gameName.isEmpty(); + const auto gameName = settings.getManagedGameName(); + const bool gameConfigured = (gameName.has_value() && *gameName != ""); if (gameConfigured) { - MOBase::IPluginGame *game = plugins.managedGame(gameName); + MOBase::IPluginGame *game = plugins.managedGame(*gameName); if (game == nullptr) { - reportError(QObject::tr("Plugin to handle %1 no longer installed").arg(gameName)); + reportError(QObject::tr("Plugin to handle %1 no longer installed").arg(*gameName)); return nullptr; } - QString gamePath = settings.getManagedGameDirectory(); - if (gamePath == "") { + auto gamePath = settings.getManagedGameDirectory(); + if (!gamePath || *gamePath == "") { gamePath = game->gameDirectory().absolutePath(); } - QDir gameDir(gamePath); + QDir gameDir(*gamePath); QFileInfo directoryInfo(gameDir.path()); if (directoryInfo.isSymLink()) { reportError(QObject::tr("The configured path to the game directory (%1) appears to be a symbolic (or other) link. " - "This setup is incompatible with MO2's VFS and will not run correctly.").arg(gamePath)); + "This setup is incompatible with MO2's VFS and will not run correctly.").arg(*gamePath)); } if (game->looksValid(gameDir)) { @@ -321,17 +320,20 @@ MOBase::IPluginGame *determineCurrentGame( //If we've made it this far and the instance is already configured for a game, something has gone wrong. //Tell the user about it. if (gameConfigured) { - const QString gamePath = settings.getManagedGameDirectory(); - reportError(QObject::tr("Could not use configuration settings for game \"%1\", path \"%2\"."). - arg(gameName).arg(gamePath)); + const auto gamePath = settings.getManagedGameDirectory(); + + reportError( + QObject::tr("Could not use configuration settings for game \"%1\", path \"%2\".") + .arg(*gameName).arg(gamePath ? *gamePath : "")); } - SelectionDialog selection(gameConfigured ? QObject::tr("Please select the installation of %1 to manage").arg(gameName) - : QObject::tr("Please select the game to manage"), nullptr, QSize(32, 32)); + SelectionDialog selection(gameConfigured ? + QObject::tr("Please select the installation of %1 to manage").arg(*gameName) : + QObject::tr("Please select the game to manage"), nullptr, QSize(32, 32)); for (IPluginGame *game : plugins.plugins()) { //If a game is already configured, skip any plugins that are not for that game - if (gameConfigured && gameName.compare(game->gameName(), Qt::CaseInsensitive) != 0) + if (gameConfigured && gameName->compare(game->gameName(), Qt::CaseInsensitive) != 0) continue; //Only add games that are installed @@ -355,9 +357,11 @@ MOBase::IPluginGame *determineCurrentGame( return selectGame(settings, game->gameDirectory(), game); } - gamePath = QFileDialog::getExistingDirectory(nullptr, gameConfigured ? QObject::tr("Please select the installation of %1 to manage").arg(gameName) - : QObject::tr("Please select the game to manage"), - QString(), QFileDialog::ShowDirsOnly); + gamePath = QFileDialog::getExistingDirectory(nullptr, gameConfigured ? + QObject::tr("Please select the installation of %1 to manage").arg(*gameName) : + QObject::tr("Please select the game to manage"), + QString(), QFileDialog::ShowDirsOnly); + if (!gamePath.isEmpty()) { QDir gameDir(gamePath); QFileInfo directoryInfo(gamePath); @@ -368,7 +372,7 @@ MOBase::IPluginGame *determineCurrentGame( QList possibleGames; for (IPluginGame * const game : plugins.plugins()) { //If a game is already configured, skip any plugins that are not for that game - if (gameConfigured && gameName.compare(game->gameName(), Qt::CaseInsensitive) != 0) + if (gameConfigured && gameName->compare(game->gameName(), Qt::CaseInsensitive) != 0) continue; //Only try plugins that look valid for this directory @@ -376,24 +380,31 @@ MOBase::IPluginGame *determineCurrentGame( possibleGames.append(game); } } + if (possibleGames.count() > 1) { - SelectionDialog browseSelection(gameConfigured ? QObject::tr("Please select the installation of %1 to manage").arg(gameName) - : QObject::tr("Please select the game to manage"), - nullptr, QSize(32, 32)); + SelectionDialog browseSelection(gameConfigured ? + QObject::tr("Please select the installation of %1 to manage").arg(*gameName) : + QObject::tr("Please select the game to manage"), + nullptr, QSize(32, 32)); + for (IPluginGame *game : possibleGames) { browseSelection.addChoice(game->gameIcon(), game->gameName(), gamePath, QVariant::fromValue(game)); } + if (browseSelection.exec() == QDialog::Accepted) { return selectGame(settings, gameDir, browseSelection.getChoiceData().value()); } else { - reportError(gameConfigured ? QObject::tr("Canceled finding %1 in \"%2\".").arg(gameName).arg(gamePath) - : QObject::tr("Canceled finding game in \"%1\".").arg(gamePath)); + reportError(gameConfigured ? + QObject::tr("Canceled finding %1 in \"%2\".").arg(*gameName).arg(gamePath) : + QObject::tr("Canceled finding game in \"%1\".").arg(gamePath)); } } else if(possibleGames.count() == 1) { return selectGame(settings, gameDir, possibleGames[0]); } else { if (gameConfigured) { - reportError(QObject::tr("%1 not identified in \"%2\". The directory is required to contain the game binary.").arg(gameName).arg(gamePath)); + reportError( + QObject::tr("%1 not identified in \"%2\". The directory is required to contain the game binary.") + .arg(*gameName).arg(gamePath)); } else { QString supportedGames; @@ -608,7 +619,11 @@ int runApplication(MOApplication &application, SingleInstance &instance, organizer.setManagedGame(game); organizer.createDefaultProfile(); - if (settings.getManagedGameEdition() == "") { + QString edition; + + if (auto v=settings.getManagedGameEdition()) { + edition = *v; + } else { QStringList editions = game->gameVariants(); if (editions.size() > 1) { SelectionDialog selection( @@ -624,12 +639,15 @@ int runApplication(MOApplication &application, SingleInstance &instance, if (selection.exec() == QDialog::Rejected) { return 1; } else { - settings.setManagedGameEdition(selection.getChoiceString()); + edition = selection.getChoiceString(); + settings.setManagedGameEdition(edition); } } } - game->setGameVariant(settings.getManagedGameEdition()); + Q_ASSERT(!edition.isEmpty()); + + game->setGameVariant(edition); log::info("managing game at {}", game->gameDirectory().absolutePath()); @@ -679,10 +697,10 @@ int runApplication(MOApplication &application, SingleInstance &instance, QPixmap pixmap(splashPath); QSplashScreen splash(pixmap); - const int monitor = settings.getMainWindowMonitor(); - if (monitor != -1 && QGuiApplication::screens().size() > monitor) { - QGuiApplication::screens().at(monitor)->geometry().center(); - const QPoint center = QGuiApplication::screens().at(monitor)->geometry().center(); + const auto monitor = settings.geometry().getMainWindowMonitor(); + if (monitor && QGuiApplication::screens().size() > *monitor) { + QGuiApplication::screens().at(*monitor)->geometry().center(); + const QPoint center = QGuiApplication::screens().at(*monitor)->geometry().center(); splash.move(center - splash.rect().center()); } else { const QPoint center = QGuiApplication::primaryScreen()->geometry().center(); @@ -703,7 +721,7 @@ int runApplication(MOApplication &application, SingleInstance &instance, + QString::fromStdWString(AppConfig::tutorialsPath()) + "/", &organizer); - if (!application.setStyleFile(settings.getStyleName())) { + if (!application.setStyleFile(settings.getStyleName().value_or(""))) { // disable invalid stylesheet settings.setStyleName(""); } @@ -726,7 +744,7 @@ int runApplication(MOApplication &application, SingleInstance &instance, // this must be before readSettings(), see DockFixer in mainwindow.cpp splash.finish(&mainWindow); - mainWindow.readSettings(); + mainWindow.readSettings(settings); log::debug("displaying main window"); mainWindow.show(); diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 7f7ded80..e77d08b1 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -216,26 +216,24 @@ const QSize LargeToolbarSize(42, 36); class DockFixer { public: - static void save(MainWindow* mw, QSettings& settings) + static void save(MainWindow* mw, Settings& settings) { - const auto docks = mw->findChildren(); - // saves the size of each dock - for (int i=0; ifindChildren()) { int size = 0; // save the width for horizontal docks, or the height for vertical - if (orientation(mw, docks[i]) == Qt::Horizontal) { - size = docks[i]->size().width(); + if (orientation(mw, dock) == Qt::Horizontal) { + size = dock->size().width(); } else { - size = docks[i]->size().height(); + size = dock->size().height(); } - settings.setValue(settingName(docks[i]), size); + settings.geometry().setDockSize(dock->objectName(), size); } } - static void restore(MainWindow* mw, const QSettings& settings) + static void restore(MainWindow* mw, const Settings& settings) { struct DockInfo { @@ -246,16 +244,11 @@ public: std::vector dockInfos; - const auto docks = mw->findChildren(); - // for each dock - for (int i=0; ifindChildren()) { + if (auto size=settings.geometry().getDockSize(dock->objectName())) { // remember this dock, its size and orientation - const auto size = settings.value(name).toInt(); - dockInfos.push_back({docks[i], size, orientation(mw, docks[i])}); + dockInfos.push_back({dock, *size, orientation(mw, dock)}); } } @@ -264,30 +257,25 @@ public: // // some people said a single processEvents() call is enough, but it doesn't // look like it - QTimer::singleShot(1, [=] { + QTimer::singleShot(5, [=] { for (const auto& info : dockInfos) { mw->resizeDocks({info.d}, {info.size}, info.ori); } - }); + }); } - static Qt::Orientation orientation(QMainWindow* mw, QDockWidget* d) + static Qt::Orientation orientation(QMainWindow* mw, const QDockWidget* d) { // docks in these areas are horizontal const auto horizontalAreas = Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea; - if (mw->dockWidgetArea(d) & horizontalAreas) { + if (mw->dockWidgetArea(const_cast(d)) & horizontalAreas) { return Qt::Horizontal; } else { return Qt::Vertical; } } - - static QString settingName(QDockWidget* d) - { - return "geometry/" + d->objectName() + "_size"; - } }; @@ -359,9 +347,6 @@ MainWindow::MainWindow(Settings &settings ui->logList->setCore(m_OrganizerCore); - int splitterSize = this->size().height(); // actually total window size, but the splitter doesn't seem to return the true value - ui->topLevelSplitter->setSizes(QList() << splitterSize - 100 << 100); - updateProblemsButton(); setupToolbar(); @@ -540,8 +525,7 @@ MainWindow::MainWindow(Settings &settings connect(&m_SaveMetaTimer, SIGNAL(timeout()), this, SLOT(saveModMetas())); m_SaveMetaTimer.start(5000); - setCategoryListVisible(settings.isCategoryListVisible()); - FileDialogMemory::restore(settings.directInterface()); + FileDialogMemory::restore(settings); fixCategories(); @@ -2247,52 +2231,50 @@ void MainWindow::activateProxy(bool activate) busyDialog.hide(); } -void MainWindow::readSettings() +void MainWindow::readSettings(const Settings& settings) { - QSettings settings(qApp->property("dataPath").toString() + "/" + QString::fromStdWString(AppConfig::iniFileName()), QSettings::IniFormat); - - if (settings.contains("window_geometry")) { - restoreGeometry(settings.value("window_geometry").toByteArray()); + if (auto v=settings.geometry().getMainWindow()) { + restoreGeometry(*v); } - if (settings.contains("window_state")) { - restoreState(settings.value("window_state").toByteArray()); + if (auto v=settings.geometry().getMainWindowState()) { + restoreState(*v); } - if (settings.contains("toolbar_size")) { - setToolbarSize(settings.value("toolbar_size").toSize()); + if (auto v=settings.geometry().getToolbarSize()) { + setToolbarSize(*v); } - if (settings.contains("toolbar_button_style")) { - setToolbarButtonStyle(static_cast( - settings.value("toolbar_button_style").toInt())); + if (auto v=settings.geometry().getToolbarButtonStyle()) { + setToolbarButtonStyle(*v); } - if (settings.contains("menubar_visible")) { - showMenuBar(settings.value("menubar_visible").toBool()); + if (auto v=settings.geometry().getMenubarVisible()) { + showMenuBar(*v); } - if (settings.contains("statusbar_visible")) { - showStatusBar(settings.value("statusbar_visible").toBool()); + if (auto v=settings.geometry().getStatusbarVisible()) { + showStatusBar(*v); } - if (settings.contains("window_split")) { - ui->splitter->restoreState(settings.value("window_split").toByteArray()); + if (auto v=settings.geometry().getMainSplitterState()) { + ui->splitter->restoreState(*v); } - if (settings.contains("log_split")) { - ui->topLevelSplitter->restoreState(settings.value("log_split").toByteArray()); + { + auto v = settings.geometry().getFiltersVisible().value_or(false); + setCategoryListVisible(v); + ui->displayCategoriesBtn->setChecked(v); } - bool filtersVisible = settings.value("filters_visible", false).toBool(); - setCategoryListVisible(filtersVisible); - ui->displayCategoriesBtn->setChecked(filtersVisible); - - int selectedExecutable = settings.value("selected_executable").toInt(); - setExecutableIndex(selectedExecutable); + if (auto v=settings.getSelectedExecutable()) { + setExecutableIndex(*v); + } - if (settings.value("Settings/use_proxy", false).toBool()) { - activateProxy(true); + if (auto v=settings.getUseProxy()) { + if (*v) { + activateProxy(true); + } } DockFixer::restore(this, settings); @@ -2335,6 +2317,12 @@ void MainWindow::processUpdates() { ui->downloadView->header()->hideSection(i); } } + if (lastVersion < QVersionNumber(2, 2, 2)) { + QSettings &instance = Settings::instance().directInterface(); + + // log splitter is gone, it's a dock now + instance.remove("log_split"); + } } if (currentVersion > lastVersion) { @@ -2354,7 +2342,9 @@ void MainWindow::processUpdates() { settings.setValue("version", currentVersion.toString()); } -void MainWindow::storeSettings(QSettings &settings) { +void MainWindow::storeSettings(Settings& s) { + auto& settings = s.directInterface(); + settings.setValue("group_state", ui->groupCombo->currentIndex()); settings.setValue("selected_executable", ui->executablesListBox->currentIndex()); @@ -2367,7 +2357,6 @@ void MainWindow::storeSettings(QSettings &settings) { settings.remove("menubar_visible"); settings.remove("window_split"); settings.remove("window_monitor"); - settings.remove("log_split"); settings.remove("filters_visible"); settings.remove("browser_geometry"); settings.remove("geometry"); @@ -2383,7 +2372,6 @@ void MainWindow::storeSettings(QSettings &settings) { QScreen *screen = this->window()->windowHandle()->screen(); int screenId = QGuiApplication::screens().indexOf(screen); settings.setValue("window_monitor", screenId); - settings.setValue("log_split", ui->topLevelSplitter->saveState()); settings.setValue("browser_geometry", m_IntegratedBrowser.saveGeometry()); settings.setValue("filters_visible", ui->displayCategoriesBtn->isChecked()); @@ -2392,7 +2380,7 @@ void MainWindow::storeSettings(QSettings &settings) { settings.setValue(key, kv.second->saveState()); } - DockFixer::save(this, settings); + DockFixer::save(this, s); } } @@ -5213,7 +5201,7 @@ void MainWindow::on_actionSettings_triggered() QString oldModDirectory(settings.getModDirectory()); QString oldCacheDirectory(settings.getCacheDirectory()); QString oldProfilesDirectory(settings.getProfileDirectory()); - QString oldManagedGameDirectory(settings.getManagedGameDirectory()); + QString oldManagedGameDirectory(settings.getManagedGameDirectory().value_or("")); bool oldDisplayForeign(settings.displayForeign()); bool proxy = settings.useProxy(); DownloadManager *dlManager = m_OrganizerCore.downloadManager(); diff --git a/src/mainwindow.h b/src/mainwindow.h index 7326425a..d4513c0f 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -119,8 +119,8 @@ public: QWidget *parent = 0); ~MainWindow(); - void storeSettings(QSettings &settings) override; - void readSettings(); + void storeSettings(Settings& settings) override; + void readSettings(const Settings& settings); void processUpdates(); virtual ILockedWaitingForProcess* lock() override; diff --git a/src/mainwindow.ui b/src/mainwindow.ui index 6c6d0bca..e9910b83 100644 --- a/src/mainwindow.ui +++ b/src/mainwindow.ui @@ -47,10 +47,6 @@ 0 - - - Qt::Vertical - @@ -1286,7 +1282,6 @@ p, li { white-space: pre-wrap; } - diff --git a/src/organizercore.cpp b/src/organizercore.cpp index 72c8dab5..a64d93b4 100644 --- a/src/organizercore.cpp +++ b/src/organizercore.cpp @@ -94,15 +94,6 @@ static bool isOnline() return false; } -static bool renameFile(const QString &oldName, const QString &newName, - bool overwrite = true) -{ - if (overwrite && QFile::exists(newName)) { - QFile::remove(newName); - } - return QFile::rename(oldName, newName); -} - static std::wstring getProcessName(HANDLE process) { wchar_t buffer[MAX_PATH]; @@ -342,80 +333,37 @@ OrganizerCore::~OrganizerCore() delete m_DirectoryStructure; } -QString OrganizerCore::commitSettings(const QString &iniFile) -{ - if (!shellRename(iniFile + ".new", iniFile, true, qApp->activeWindow())) { - DWORD err = ::GetLastError(); - // make a second attempt using qt functions but if that fails print the - // error from the first attempt - if (!renameFile(iniFile + ".new", iniFile)) { - return QString::fromStdWString(formatSystemMessage(err)); - } - } - return QString(); -} - -QSettings::Status OrganizerCore::storeSettings(const QString &fileName) +void OrganizerCore::storeSettings() { - QSettings settings(fileName, QSettings::IniFormat); - if (m_UserInterface != nullptr) { - m_UserInterface->storeSettings(settings); + m_UserInterface->storeSettings(m_Settings); } if (m_CurrentProfile != nullptr) { - settings.setValue("selected_profile", - m_CurrentProfile->name().toUtf8().constData()); + m_Settings.setSelectedProfileName(m_CurrentProfile->name()); } - m_ExecutablesList.store(settings); - - FileDialogMemory::save(settings); + m_ExecutablesList.store(m_Settings); - settings.sync(); - return settings.status(); -} - -void OrganizerCore::storeSettings() -{ - QString iniFile = qApp->property("dataPath").toString() + "/" - + QString::fromStdWString(AppConfig::iniFileName()); - if (QFileInfo(iniFile).exists()) { - if (!shellCopy(iniFile, iniFile + ".new", true, qApp->activeWindow())) { - const auto e = GetLastError(); - QMessageBox::critical( - qApp->activeWindow(), tr("Failed to write settings"), - tr("An error occurred trying to update MO settings to %1: %2") - .arg(iniFile) - .arg(QString::fromStdWString(formatSystemMessage(e)))); - return; - } - } + FileDialogMemory::save(m_Settings); - QString writeTarget = iniFile + ".new"; + const auto result = m_Settings.sync(); - QSettings::Status result = storeSettings(writeTarget); + if (result != QSettings::NoError) { + QString reason; - if (result == QSettings::NoError) { - QString errMsg = commitSettings(iniFile); - if (!errMsg.isEmpty()) { - log::warn( - "settings file not writable, may be locked by another " - "application, trying direct write"); - writeTarget = iniFile; - result = storeSettings(iniFile); + if (result == QSettings::AccessError) { + reason = tr("File is write protected"); + } else if (result == QSettings::FormatError) { + reason = tr("Invalid file format (probably a bug)"); + } else { + reason = tr("Unknown error %1").arg(result); } - } - if (result != QSettings::NoError) { - QString reason = result == QSettings::AccessError - ? tr("File is write protected") - : result == QSettings::FormatError - ? tr("Invalid file format (probably a bug)") - : tr("Unknown error %1").arg(result); + QMessageBox::critical( - qApp->activeWindow(), tr("Failed to write settings"), - tr("An error occurred trying to write back MO settings to %1: %2") - .arg(writeTarget, reason)); + qApp->activeWindow(), tr("Failed to write settings"), + tr("An error occurred trying to write back MO settings to %1: %2") + .arg(m_Settings.getFilename(), reason)); } } @@ -487,7 +435,7 @@ void OrganizerCore::updateExecutablesList() return; } - m_ExecutablesList.load(managedGame(), m_Settings.directInterface()); + m_ExecutablesList.load(managedGame(), m_Settings); // TODO this has nothing to do with executables list move to an appropriate // function! diff --git a/src/organizercore.h b/src/organizercore.h index 926a21f0..4bcfe745 100644 --- a/src/organizercore.h +++ b/src/organizercore.h @@ -288,10 +288,6 @@ private: void storeSettings(); - QSettings::Status storeSettings(const QString &fileName); - - QString commitSettings(const QString &iniFile); - bool queryApi(QString &apiKey); void updateModActiveState(int index, bool active); diff --git a/src/settings.cpp b/src/settings.cpp index 5d103267..d843a0db 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -26,10 +26,56 @@ along with Mod Organizer. If not, see . using namespace MOBase; +template +T convertVariant(const QVariant& v); + +template <> +QByteArray convertVariant(const QVariant& v) +{ + return v.toByteArray(); +} + +template <> +QString convertVariant(const QVariant& v) +{ + return v.toString(); +} + +template <> +int convertVariant(const QVariant& v) +{ + return v.toInt(); +} + +template <> +bool convertVariant(const QVariant& v) +{ + return v.toBool(); +} + +template <> +QSize convertVariant(const QVariant& v) +{ + return v.toSize(); +} + + + +template +std::optional getOptional(const QSettings& s, const QString& name) +{ + if (s.contains(name)) { + return convertVariant(s.value(name)); + } + + return {}; +} + + Settings *Settings::s_Instance = nullptr; Settings::Settings(const QString& path) - : m_Settings(path, QSettings::IniFormat) + : m_Settings(path, QSettings::IniFormat), m_Geometry(m_Settings) { if (s_Instance != nullptr) { throw std::runtime_error("second instance of \"Settings\" created"); @@ -51,6 +97,11 @@ Settings &Settings::instance() return *s_Instance; } +QString Settings::getFilename() const +{ + return m_Settings.fileName(); +} + void Settings::clearPlugins() { m_Plugins.clear(); @@ -278,9 +329,13 @@ QString Settings::getModDirectory(bool resolve) const return getConfigurablePath("mod_directory", ToQString(AppConfig::modsPath()), resolve); } -QString Settings::getManagedGameDirectory() const +std::optional Settings::getManagedGameDirectory() const { - return QString::fromUtf8(m_Settings.value("gamePath", "").toByteArray()); + if (auto v=getOptional(m_Settings, "gamePath")) { + return QString::fromUtf8(*v); + } + + return {}; } void Settings::setManagedGameDirectory(const QString& path) @@ -288,9 +343,9 @@ void Settings::setManagedGameDirectory(const QString& path) m_Settings.setValue("gamePath", QDir::toNativeSeparators(path).toUtf8()); } -QString Settings::getManagedGameName() const +std::optional Settings::getManagedGameName() const { - return m_Settings.value("gameName", "").toString(); + return getOptional(m_Settings, "gameName"); } void Settings::setManagedGameName(const QString& name) @@ -298,9 +353,9 @@ void Settings::setManagedGameName(const QString& name) m_Settings.setValue("gameName", name); } -QString Settings::getManagedGameEdition() const +std::optional Settings::getManagedGameEdition() const { - return m_Settings.value("game_edition", "").toString(); + return getOptional(m_Settings, "game_edition"); } void Settings::setManagedGameEdition(const QString& name) @@ -308,19 +363,23 @@ void Settings::setManagedGameEdition(const QString& name) m_Settings.setValue("game_edition", name); } -QString Settings::getSelectedProfileName() const +std::optional Settings::getSelectedProfileName() const { - return QString::fromUtf8(m_Settings.value("selected_profile", "").toByteArray()); + if (auto v=getOptional(m_Settings, "selected_profile")) { + return QString::fromUtf8(*v); + } + + return {}; } -int Settings::getMainWindowMonitor() const +void Settings::setSelectedProfileName(const QString& name) { - return m_Settings.value("window_monitor", -1).toInt(); + m_Settings.setValue("selected_profile", name.toUtf8()); } -QString Settings::getStyleName() const +std::optional Settings::getStyleName() const { - return m_Settings.value("Settings/style", "").toString(); + return getOptional(m_Settings, "Settings/style"); } void Settings::setStyleName(const QString& name) @@ -328,9 +387,14 @@ void Settings::setStyleName(const QString& name) m_Settings.setValue("Settings/style", name); } -bool Settings::isCategoryListVisible() const +std::optional Settings::getSelectedExecutable() const { - return m_Settings.value("categorylist_visible", true).toBool(); + return getOptional(m_Settings, "selected_executable"); +} + +std::optional Settings::getUseProxy() const +{ + return getOptional(m_Settings, "Settings/use_proxy"); } QString Settings::getProfileDirectory(bool resolve) const @@ -659,6 +723,22 @@ void Settings::writePluginBlacklist() m_Settings.endArray(); } +GeometrySettings& Settings::geometry() +{ + return m_Geometry; +} + +const GeometrySettings& Settings::geometry() const +{ + return m_Geometry; +} + +QSettings::Status Settings::sync() const +{ + m_Settings.sync(); + return m_Settings.status(); +} + void Settings::dump() const { static const QStringList ignore({ @@ -679,3 +759,73 @@ void Settings::dump() const m_Settings.endGroup(); } + + +GeometrySettings::GeometrySettings(QSettings& s) + : m_Settings(s) +{ +} + +std::optional GeometrySettings::getMainWindow() const +{ + return getOptional(m_Settings, "window_geometry"); +} + +std::optional GeometrySettings::getMainWindowState() const +{ + return getOptional(m_Settings, "window_state"); +} + +std::optional GeometrySettings::getToolbarSize() const +{ + return getOptional(m_Settings, "toolbar_size"); +} + +std::optional GeometrySettings::getToolbarButtonStyle() const +{ + if (auto v=getOptional(m_Settings, "toolbar_button_style")) { + return static_cast(*v); + } + + return {}; +} + +std::optional GeometrySettings::getMenubarVisible() const +{ + return getOptional(m_Settings, "menubar_visible"); +} + +std::optional GeometrySettings::getStatusbarVisible() const +{ + return getOptional(m_Settings, "statusbar_visible"); +} + +std::optional GeometrySettings::getMainSplitterState() const +{ + return getOptional(m_Settings, "window_split"); +} + +std::optional GeometrySettings::getFiltersVisible() const +{ + return getOptional(m_Settings, "filters_visible"); +} + +std::optional GeometrySettings::getMainWindowMonitor() const +{ + return getOptional(m_Settings, "window_monitor"); +} + +void GeometrySettings::setDockSize(const QString& name, int size) +{ + m_Settings.setValue("geometry/" + name + "_size", size); +} + +std::optional GeometrySettings::getDockSize(const QString& name) const +{ + return getOptional(m_Settings, "geometry/" + name + "_size"); +} + +std::optional GeometrySettings::isCategoryListVisible() const +{ + return getOptional(m_Settings, "categorylist_visible"); +} diff --git a/src/settings.h b/src/settings.h index f06aece9..066843c2 100644 --- a/src/settings.h +++ b/src/settings.h @@ -31,13 +31,40 @@ namespace MOBase { class PluginContainer; struct ServerInfo; + +class GeometrySettings +{ +public: + GeometrySettings(QSettings& s); + + std::optional getMainWindow() const; + std::optional getMainWindowState() const; + std::optional getToolbarSize() const; + std::optional getToolbarButtonStyle() const; + std::optional getMenubarVisible() const; + std::optional getStatusbarVisible() const; + std::optional getMainSplitterState() const; + std::optional getFiltersVisible() const; + + std::optional getMainWindowMonitor() const; + void setDockSize(const QString& name, int size); + + std::optional getDockSize(const QString& name) const; + + std::optional isCategoryListVisible() const; + +private: + QSettings& m_Settings; +}; + + /** * manages the settings for Mod Organizer. The settings are not cached * inside the class but read/written directly from/to disc **/ class Settings : public QObject { - Q_OBJECT + Q_OBJECT; public: Settings(const QString& path); @@ -45,6 +72,8 @@ public: static Settings &instance(); + QString getFilename() const; + /** * unregister all plugins from settings */ @@ -122,25 +151,26 @@ public: /** * retrieve the directory where the managed game is stored (with native separators) **/ - QString getManagedGameDirectory() const; + std::optional getManagedGameDirectory() const; void setManagedGameDirectory(const QString& path); - QString getManagedGameName() const; + std::optional getManagedGameName() const; void setManagedGameName(const QString& name); - QString getManagedGameEdition() const; + std::optional getManagedGameEdition() const; void setManagedGameEdition(const QString& name); - QString getSelectedProfileName() const; - - // returns -1 if not set - // - int getMainWindowMonitor() const; + std::optional getSelectedProfileName() const; + void setSelectedProfileName(const QString& name); - QString getStyleName() const; + std::optional getStyleName() const; void setStyleName(const QString& name); - bool isCategoryListVisible() const; + std::optional getSelectedExecutable() const; + std::optional getUseProxy() const; + + GeometrySettings& geometry(); + const GeometrySettings& geometry() const; /** * retrieve the directory where profiles stored (with native separators) @@ -388,6 +418,8 @@ public: MOBase::IPluginGame const *gamePlugin() { return m_GamePlugin; } const LoadMechanism& loadMechanism() const { return m_LoadMechanism; } + QSettings::Status sync() const; + void dump() const; // temp @@ -407,6 +439,7 @@ private: static Settings *s_Instance; MOBase::IPluginGame const *m_GamePlugin; mutable QSettings m_Settings; + GeometrySettings m_Geometry; LoadMechanism m_LoadMechanism; std::vector m_Plugins; -- cgit v1.3.1 From e4418b95fa24f9caea32adfe9d957ce37e46f127 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sat, 3 Aug 2019 02:30:20 -0400 Subject: moved settings updates to Settings::processUpdates() --- src/main.cpp | 2 +- src/mainwindow.cpp | 44 ++++++++++++-------------------------------- src/mainwindow.h | 2 +- src/settings.cpp | 46 ++++++++++++++++++++++++++++++++++++++++++++++ src/settings.h | 7 +++++++ 5 files changed, 67 insertions(+), 34 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/main.cpp b/src/main.cpp index 3e26ea17..506c6270 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -739,7 +739,7 @@ int runApplication(MOApplication &application, SingleInstance &instance, QObject::connect(&instance, SIGNAL(messageSent(QString)), &organizer, SLOT(externalMessage(QString))); - mainWindow.processUpdates(); + mainWindow.processUpdates(settings); // this must be before readSettings(), see DockFixer in mainwindow.cpp splash.finish(&mainWindow); diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index e77d08b1..0618f949 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -2280,11 +2280,15 @@ void MainWindow::readSettings(const Settings& settings) DockFixer::restore(this, settings); } -void MainWindow::processUpdates() { - QSettings settings(qApp->property("dataPath").toString() + "/" + QString::fromStdWString(AppConfig::iniFileName()), QSettings::IniFormat); - QVersionNumber lastVersion = QVersionNumber::fromString(settings.value("version", "2.1.2").toString()).normalized(); - QVersionNumber currentVersion = QVersionNumber::fromString(m_OrganizerCore.getVersion().displayString()).normalized(); - if (!m_OrganizerCore.settings().directInterface().value("first_start", true).toBool()) { +void MainWindow::processUpdates(Settings& settings) { + const auto earliest = QVersionNumber::fromString("2.1.2").normalized(); + + const auto lastVersion = settings.getVersion().value_or(earliest); + const auto currentVersion = m_OrganizerCore.getVersion().asQVersionNumber(); + + settings.processUpdates(currentVersion, lastVersion); + + if (!settings.getFirstStart()) { if (lastVersion < QVersionNumber(2, 1, 3)) { bool lastHidden = true; for (int i = ModList::COL_GAME; i < ui->modList->model()->columnCount(); ++i) { @@ -2293,41 +2297,20 @@ void MainWindow::processUpdates() { lastHidden = hidden; } } + if (lastVersion < QVersionNumber(2, 1, 6)) { ui->modList->header()->setSectionHidden(ModList::COL_NOTES, true); } - if (lastVersion < QVersionNumber(2, 2, 0)) { - QSettings &instance = Settings::instance().directInterface(); - instance.beginGroup("Settings"); - instance.remove("steam_password"); - instance.remove("nexus_username"); - instance.remove("nexus_password"); - instance.remove("nexus_login"); - instance.remove("nexus_api_key"); - instance.remove("ask_for_nexuspw"); - instance.remove("nmm_version"); - instance.endGroup(); - instance.beginGroup("Servers"); - instance.remove(""); - instance.endGroup(); - } + if (lastVersion < QVersionNumber(2, 2, 1)) { // hide new columns by default for (int i=DownloadList::COL_MODNAME; idownloadView->header()->hideSection(i); } } - if (lastVersion < QVersionNumber(2, 2, 2)) { - QSettings &instance = Settings::instance().directInterface(); - - // log splitter is gone, it's a dock now - instance.remove("log_split"); - } } - if (currentVersion > lastVersion) { - //NOP - } else if (currentVersion < lastVersion) { + if (currentVersion < lastVersion) { const auto text = tr( "Notice: Your current MO version (%1) is lower than the previously used one (%2). " "The GUI may not downgrade gracefully, so you may experience oddities. " @@ -2337,9 +2320,6 @@ void MainWindow::processUpdates() { log::warn("{}", text); } - - //save version in all case - settings.setValue("version", currentVersion.toString()); } void MainWindow::storeSettings(Settings& s) { diff --git a/src/mainwindow.h b/src/mainwindow.h index d4513c0f..e8f60211 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -121,7 +121,7 @@ public: void storeSettings(Settings& settings) override; void readSettings(const Settings& settings); - void processUpdates(); + void processUpdates(Settings& settings); virtual ILockedWaitingForProcess* lock() override; virtual void unlock() override; diff --git a/src/settings.cpp b/src/settings.cpp index d843a0db..35be1298 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -97,6 +97,38 @@ Settings &Settings::instance() return *s_Instance; } +void Settings::processUpdates( + const QVersionNumber& currentVersion, const QVersionNumber& lastVersion) +{ + if (getFirstStart()) { + return; + } + + if (lastVersion < QVersionNumber(2, 2, 0)) { + m_Settings.beginGroup("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"); + m_Settings.endGroup(); + + m_Settings.beginGroup("Servers"); + m_Settings.remove(""); + m_Settings.endGroup(); + } + + if (lastVersion < QVersionNumber(2, 2, 2)) { + // log splitter is gone, it's a dock now + m_Settings.remove("log_split"); + } + + //save version in all case + m_Settings.setValue("version", currentVersion.toString()); +} + QString Settings::getFilename() const { return m_Settings.fileName(); @@ -397,6 +429,20 @@ std::optional Settings::getUseProxy() const return getOptional(m_Settings, "Settings/use_proxy"); } +std::optional Settings::getVersion() const +{ + if (auto v=getOptional(m_Settings, "version")) { + return QVersionNumber::fromString(*v).normalized(); + } + + return {}; +} + +bool Settings::getFirstStart() const +{ + return getOptional(m_Settings, "first_start").value_or(true); +} + QString Settings::getProfileDirectory(bool resolve) const { return getConfigurablePath("profiles_directory", ToQString(AppConfig::profilesPath()), resolve); diff --git a/src/settings.h b/src/settings.h index 066843c2..bf66c0dd 100644 --- a/src/settings.h +++ b/src/settings.h @@ -72,6 +72,9 @@ public: static Settings &instance(); + void processUpdates( + const QVersionNumber& currentVersion, const QVersionNumber& lastVersion); + QString getFilename() const; /** @@ -169,9 +172,13 @@ public: std::optional getSelectedExecutable() const; std::optional getUseProxy() const; + std::optional getVersion() const; + bool getFirstStart() const; + GeometrySettings& geometry(); const GeometrySettings& geometry() const; + /** * retrieve the directory where profiles stored (with native separators) **/ -- cgit v1.3.1 From e40245abf46f133292636909fbacf10fc0712932 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sat, 3 Aug 2019 02:42:16 -0400 Subject: moved geometry handling to EditExecutablesDialog itself --- src/editexecutablesdialog.cpp | 14 ++++++++++++++ src/editexecutablesdialog.h | 4 ++++ src/mainwindow.cpp | 9 +-------- src/settings.cpp | 10 ++++++++++ src/settings.h | 2 ++ 5 files changed, 31 insertions(+), 8 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/editexecutablesdialog.cpp b/src/editexecutablesdialog.cpp index 3ec3d64f..9c5ae44a 100644 --- a/src/editexecutablesdialog.cpp +++ b/src/editexecutablesdialog.cpp @@ -65,6 +65,20 @@ EditExecutablesDialog::EditExecutablesDialog(OrganizerCore& oc, QWidget* parent) EditExecutablesDialog::~EditExecutablesDialog() = default; +int EditExecutablesDialog::exec() +{ + auto& settings = m_organizerCore.settings(); + + if (auto v=settings.geometry().getExecutablesDialog()) { + restoreGeometry(*v); + } + + const int r = QDialog::exec(); + + settings.geometry().setExecutablesDialog(saveGeometry()); + + return r; +} void EditExecutablesDialog::loadCustomOverwrites() { diff --git a/src/editexecutablesdialog.h b/src/editexecutablesdialog.h index 9715489e..494f0651 100644 --- a/src/editexecutablesdialog.h +++ b/src/editexecutablesdialog.h @@ -151,6 +151,10 @@ public: ~EditExecutablesDialog(); + // also saves and restores geometry + // + int exec() override; + ExecutablesList getExecutablesList() const; const CustomOverwrites& getCustomOverwrites() const; const ForcedLibraries& getForcedLibraries() const; diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 0618f949..7ef0c9b9 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -2480,21 +2480,14 @@ bool MainWindow::modifyExecutablesDialog() EditExecutablesDialog dialog(m_OrganizerCore, this); - QSettings &settings = m_OrganizerCore.settings().directInterface(); - QString key = QString("geometry/%1").arg(dialog.objectName()); - - if (settings.contains(key)) { - dialog.restoreGeometry(settings.value(key).toByteArray()); - } - result = (dialog.exec() == QDialog::Accepted); - settings.setValue(key, dialog.saveGeometry()); refreshExecutablesList(); updatePinnedExecutables(); } catch (const std::exception &e) { reportError(e.what()); } + return result; } diff --git a/src/settings.cpp b/src/settings.cpp index 35be1298..834bd1d8 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -856,6 +856,16 @@ std::optional GeometrySettings::getFiltersVisible() const return getOptional(m_Settings, "filters_visible"); } +std::optional GeometrySettings::getExecutablesDialog() const +{ + return getOptional(m_Settings, "geometry/EditExecutablesDialog"); +} + +void GeometrySettings::setExecutablesDialog(const QByteArray& v) +{ + m_Settings.setValue("geometry/EditExecutablesDialog", v); +} + std::optional GeometrySettings::getMainWindowMonitor() const { return getOptional(m_Settings, "window_monitor"); diff --git a/src/settings.h b/src/settings.h index bf66c0dd..0cdccd87 100644 --- a/src/settings.h +++ b/src/settings.h @@ -45,6 +45,8 @@ public: std::optional getStatusbarVisible() const; std::optional getMainSplitterState() const; std::optional getFiltersVisible() const; + std::optional getExecutablesDialog() const; + void setExecutablesDialog(const QByteArray& v); std::optional getMainWindowMonitor() const; void setDockSize(const QString& name, int size); -- cgit v1.3.1 From 7eed0450e84cc465b0d163a64ebb4d410db688c4 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sat, 3 Aug 2019 02:52:55 -0400 Subject: moved geometry handling to ProfilesDialog --- src/mainwindow.cpp | 8 ++------ src/profilesdialog.cpp | 15 +++++++++++++++ src/profilesdialog.h | 4 ++++ src/settings.cpp | 10 ++++++++++ src/settings.h | 4 ++++ 5 files changed, 35 insertions(+), 6 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 7ef0c9b9..ac86d9d8 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -2554,17 +2554,13 @@ void MainWindow::on_actionAdd_Profile_triggered() ProfilesDialog profilesDialog(m_OrganizerCore.currentProfile()->name(), m_OrganizerCore.managedGame(), this); - QSettings &settings = m_OrganizerCore.settings().directInterface(); - QString key = QString("geometry/%1").arg(profilesDialog.objectName()); - if (settings.contains(key)) { - profilesDialog.restoreGeometry(settings.value(key).toByteArray()); - } + // workaround: need to disable monitoring of the saves directory, otherwise the active // profile directory is locked stopMonitorSaves(); profilesDialog.exec(); - settings.setValue(key, profilesDialog.saveGeometry()); refreshSaveList(); // since the save list may now be outdated we have to refresh it completely + if (refreshProfiles() && !profilesDialog.failed()) { break; } diff --git a/src/profilesdialog.cpp b/src/profilesdialog.cpp index d7863fc8..25fff2b2 100644 --- a/src/profilesdialog.cpp +++ b/src/profilesdialog.cpp @@ -84,6 +84,21 @@ ProfilesDialog::~ProfilesDialog() delete ui; } +int ProfilesDialog::exec() +{ + auto& settings = Settings::instance(); + + if (auto v=settings.geometry().getProfilesDialog()) { + restoreGeometry(*v); + } + + const int r = QDialog::exec(); + + settings.geometry().setProfilesDialog(saveGeometry()); + + return r; +} + void ProfilesDialog::showEvent(QShowEvent *event) { TutorableDialog::showEvent(event); diff --git a/src/profilesdialog.h b/src/profilesdialog.h index a328ce40..a47367be 100644 --- a/src/profilesdialog.h +++ b/src/profilesdialog.h @@ -51,6 +51,10 @@ public: explicit ProfilesDialog(const QString &profileName, MOBase::IPluginGame const *game, QWidget *parent = 0); ~ProfilesDialog(); + // also saves and restores geometry + // + int exec() override; + /** * @return true if creation of a new profile failed * @todo the notion of a fail state makes little sense in the current dialog diff --git a/src/settings.cpp b/src/settings.cpp index 834bd1d8..1f5abb2a 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -866,6 +866,16 @@ void GeometrySettings::setExecutablesDialog(const QByteArray& v) m_Settings.setValue("geometry/EditExecutablesDialog", v); } +std::optional GeometrySettings::getProfilesDialog() const +{ + return getOptional(m_Settings, "geometry/ProfilesDialog"); +} + +void GeometrySettings::setProfilesDialog(const QByteArray& v) +{ + m_Settings.setValue("geometry/ProfilesDialog", v); +} + std::optional GeometrySettings::getMainWindowMonitor() const { return getOptional(m_Settings, "window_monitor"); diff --git a/src/settings.h b/src/settings.h index 0cdccd87..6d51c610 100644 --- a/src/settings.h +++ b/src/settings.h @@ -45,9 +45,13 @@ public: std::optional getStatusbarVisible() const; std::optional getMainSplitterState() const; std::optional getFiltersVisible() const; + std::optional getExecutablesDialog() const; void setExecutablesDialog(const QByteArray& v); + std::optional getProfilesDialog() const; + void setProfilesDialog(const QByteArray& v); + std::optional getMainWindowMonitor() const; void setDockSize(const QString& name, int size); -- cgit v1.3.1 From cc3a16c6e9d58ed68a31be52f9fe2ef1d514ff5f Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sat, 3 Aug 2019 03:28:33 -0400 Subject: moved geometry handling to mod info and overwrite dialogs --- src/mainwindow.cpp | 18 +----------- src/modinfodialog.cpp | 72 +++++++++++++-------------------------------- src/modinfodialog.h | 26 ++++++++-------- src/overwriteinfodialog.cpp | 19 ++++++++++++ src/overwriteinfodialog.h | 11 ++++++- src/settings.cpp | 66 +++++++++++++++++++++++++++++++++++++++++ src/settings.h | 9 ++++++ 7 files changed, 137 insertions(+), 84 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index ac86d9d8..32f728d8 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -3165,9 +3165,6 @@ void MainWindow::overwriteClosed(int) OverwriteInfoDialog *dialog = this->findChild("__overwriteDialog"); if (dialog != nullptr) { m_OrganizerCore.modList()->modInfoChanged(dialog->modInfo()); - QSettings &settings = m_OrganizerCore.settings().directInterface(); - QString key = QString("geometry/%1").arg(dialog->objectName()); - settings.setValue(key, dialog->saveGeometry()); dialog->deleteLater(); } m_OrganizerCore.refreshDirectoryStructure(); @@ -3191,11 +3188,7 @@ void MainWindow::displayModInformation( } else { qobject_cast(dialog)->setModInfo(modInfo); } - QSettings &settings = m_OrganizerCore.settings().directInterface(); - QString key = QString("geometry/%1").arg(dialog->objectName()); - if (settings.contains(key)) { - dialog->restoreGeometry(settings.value(key).toByteArray()); - } + dialog->show(); dialog->raise(); dialog->activateWindow(); @@ -3214,16 +3207,7 @@ void MainWindow::displayModInformation( dialog.selectTab(tabID); } - dialog.restoreState(m_OrganizerCore.settings()); - QSettings &settings = m_OrganizerCore.settings().directInterface(); - QString key = QString("geometry/%1").arg(dialog.objectName()); - if (settings.contains(key)) { - dialog.restoreGeometry(settings.value(key).toByteArray()); - } - dialog.exec(); - dialog.saveState(m_OrganizerCore.settings()); - settings.setValue(key, dialog.saveGeometry()); modInfo->saveMeta(); emit modInfoDisplayed(); diff --git a/src/modinfodialog.cpp b/src/modinfodialog.cpp index 4b1e2f76..5e614358 100644 --- a/src/modinfodialog.cpp +++ b/src/modinfodialog.cpp @@ -210,6 +210,11 @@ void ModInfoDialog::createTabs() int ModInfoDialog::exec() { + restoreState(); + if (auto v=m_core->settings().geometry().getModInfoDialog()) { + restoreGeometry(*v); + } + // whether to select the first tab; if the main window requested a specific // tab, it is selected when encountered in update() const auto selectFirst = (m_initialTab == ModInfoTabIDs::None); @@ -220,7 +225,12 @@ int ModInfoDialog::exec() ui->tabWidget->setCurrentIndex(0); } - return TutorableDialog::exec(); + const int r = TutorableDialog::exec(); + + saveState(); + m_core->settings().geometry().setModInfoDialog(saveGeometry()); + + return r; } void ModInfoDialog::setMod(ModInfo::Ptr mod) @@ -356,7 +366,7 @@ void ModInfoDialog::setTabsVisibility(bool firstTime) if (!firstTime) { // but don't do it the first time visibility is set because the tabs are // in the default order, which will clobber the current settings - saveTabOrder(Settings::instance()); + saveTabOrder(); } // remember selection, if any @@ -375,7 +385,7 @@ void ModInfoDialog::reAddTabs( Q_ASSERT(visibility.size() == m_tabs.size()); // ordered tab names from settings - const auto orderedNames = getOrderedTabNames(); + const auto orderedNames = m_core->settings().geometry().getModInfoTabOrder(); // whether the tabs can be sorted; if the object name of a tab widget is not // found in orderedNames, the list cannot be sorted safely @@ -575,37 +585,28 @@ MOShared::FilesOrigin* ModInfoDialog::getOrigin() return origin; } -void ModInfoDialog::saveState(Settings& s) const +void ModInfoDialog::saveState() const { - saveTabOrder(s); - - // remove 2.2.0 settings - s.directInterface().remove("mod_info_tabs"); - s.directInterface().remove("mod_info_conflict_expanders"); - s.directInterface().remove("mod_info_conflicts"); - s.directInterface().remove("mod_info_advanced_conflicts"); - s.directInterface().remove("mod_info_conflicts_overwrite"); - s.directInterface().remove("mod_info_conflicts_noconflict"); - s.directInterface().remove("mod_info_conflicts_overwritten"); + saveTabOrder(); // save state for each tab for (const auto& tabInfo : m_tabs) { - tabInfo.tab->saveState(s); + tabInfo.tab->saveState(m_core->settings()); } } -void ModInfoDialog::restoreState(const Settings& s) +void ModInfoDialog::restoreState() { // tab order is not restored here, it will be picked up if tabs have to be // removed and re-added // restore state for each tab for (const auto& tabInfo : m_tabs) { - tabInfo.tab->restoreState(s); + tabInfo.tab->restoreState(m_core->settings()); } } -void ModInfoDialog::saveTabOrder(Settings& s) const +void ModInfoDialog::saveTabOrder() const { if (static_cast(m_tabs.size()) != ui->tabWidget->count()) { // only save tab state when all tabs are visible @@ -629,40 +630,7 @@ void ModInfoDialog::saveTabOrder(Settings& s) const names += ui->tabWidget->widget(i)->objectName(); } - s.directInterface().setValue("mod_info_tab_order", names); -} - -std::vector ModInfoDialog::getOrderedTabNames() const -{ - const auto& settings = Settings::instance().directInterface(); - - std::vector v; - - if (settings.contains("mod_info_tabs")) { - // old byte array from 2.2.0 - QDataStream stream(settings.value("mod_info_tabs").toByteArray()); - - int count = 0; - stream >> count; - - for (int i=0; i> s; - v.emplace_back(std::move(s)); - } - } else { - // string list - QString string = settings.value("mod_info_tab_order").toString(); - QTextStream stream(&string); - - while (!stream.atEnd()) { - QString s; - stream >> s; - v.emplace_back(std::move(s)); - } - } - - return v; + m_core->settings().geometry().setModInfoTabOrder(names); } void ModInfoDialog::onOriginModified(int originID) diff --git a/src/modinfodialog.h b/src/modinfodialog.h index 34555b0c..48680ca4 100644 --- a/src/modinfodialog.h +++ b/src/modinfodialog.h @@ -61,18 +61,11 @@ public: // void selectTab(ModInfoTabIDs id); - // updates all tabs, selects the initial tab and opens the dialog + // updates all tabs, selects the initial tab, opens the dialog and + // saves/restores geometry // int exec() override; - // saves the dialog state and calls saveState() on all tabs - // - void saveState(Settings& s) const; - - // restores the dialog state and calls restoreState() on all tabs - // - void restoreState(const Settings& s); - signals: // emitted when a tab changes the origin // @@ -146,6 +139,15 @@ private: void createTabs(); + // saves the dialog state and calls saveState() on all tabs + // + void saveState() const; + + // restores the dialog state and calls restoreState() on all tabs + // + void restoreState(); + + // sets the currently selected mod; resets first activation, but doesn't // update anything // @@ -213,11 +215,7 @@ private: // setTabsVisibility() to make sure any changes to order are saved before // re-adding tabs // - void saveTabOrder(Settings& s) const; - - // returns a list of tab names in the order they should appear on the widget - // - std::vector getOrderedTabNames() const; + void saveTabOrder() const; // asks all the tabs if they accept closing the dialog, returns false if one // objected diff --git a/src/overwriteinfodialog.cpp b/src/overwriteinfodialog.cpp index 715e11e3..f3ae0ff5 100644 --- a/src/overwriteinfodialog.cpp +++ b/src/overwriteinfodialog.cpp @@ -104,6 +104,25 @@ OverwriteInfoDialog::~OverwriteInfoDialog() delete ui; } +void OverwriteInfoDialog::showEvent(QShowEvent* e) +{ + const auto& settings = Settings::instance(); + + if (auto v=settings.geometry().getOverwriteDialog()) { + restoreGeometry(*v); + } + + QDialog::showEvent(e); +} + +void OverwriteInfoDialog::done(int r) +{ + auto& settings = Settings::instance(); + settings.geometry().setOverwriteDialog(saveGeometry()); + + QDialog::done(r); +} + void OverwriteInfoDialog::setModInfo(ModInfo::Ptr modInfo) { m_ModInfo = modInfo; diff --git a/src/overwriteinfodialog.h b/src/overwriteinfodialog.h index 4b731736..bedb779a 100644 --- a/src/overwriteinfodialog.h +++ b/src/overwriteinfodialog.h @@ -31,7 +31,7 @@ class OverwriteInfoDialog; class OverwriteInfoDialog : public QDialog { Q_OBJECT - + public: explicit OverwriteInfoDialog(ModInfo::Ptr modInfo, QWidget *parent = 0); @@ -39,8 +39,17 @@ public: ModInfo::Ptr modInfo() const { return m_ModInfo; } + // saves geometry + // + void done(int r) override; + void setModInfo(ModInfo::Ptr modInfo); +protected: + // restores geometry + // + void showEvent(QShowEvent* e) override; + private: void openFile(const QModelIndex &index); diff --git a/src/settings.cpp b/src/settings.cpp index 1f5abb2a..73595ac9 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -120,6 +120,16 @@ void Settings::processUpdates( m_Settings.endGroup(); } + 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"); + } + if (lastVersion < QVersionNumber(2, 2, 2)) { // log splitter is gone, it's a dock now m_Settings.remove("log_split"); @@ -876,6 +886,62 @@ void GeometrySettings::setProfilesDialog(const QByteArray& v) m_Settings.setValue("geometry/ProfilesDialog", v); } +std::optional GeometrySettings::getOverwriteDialog() const +{ + return getOptional(m_Settings, "geometry/__overwriteDialog"); +} + +void GeometrySettings::setOverwriteDialog(const QByteArray& v) +{ + m_Settings.setValue("geometry/__overwriteDialog", v); +} + +std::optional GeometrySettings::getModInfoDialog() const +{ + return getOptional(m_Settings, "geometry/ModInfoDialog"); +} + +void GeometrySettings::setModInfoDialog(const QByteArray& v) const +{ + m_Settings.setValue("geometry/ModInfoDialog", v); +} + +QStringList GeometrySettings::getModInfoTabOrder() const +{ + QStringList v; + + if (m_Settings.contains("mod_info_tabs")) { + // old byte array from 2.2.0 + QDataStream stream(m_Settings.value("mod_info_tabs").toByteArray()); + + int count = 0; + stream >> count; + + for (int i=0; i> s; + v.push_back(s); + } + } else { + // string list since 2.2.1 + QString string = m_Settings.value("mod_info_tab_order").toString(); + QTextStream stream(&string); + + while (!stream.atEnd()) { + QString s; + stream >> s; + v.push_back(s); + } + } + + return v; +} + +void GeometrySettings::setModInfoTabOrder(const QString& names) +{ + m_Settings.setValue("mod_info_tab_order", names); +} + std::optional GeometrySettings::getMainWindowMonitor() const { return getOptional(m_Settings, "window_monitor"); diff --git a/src/settings.h b/src/settings.h index 6d51c610..f4e36b2a 100644 --- a/src/settings.h +++ b/src/settings.h @@ -52,6 +52,15 @@ public: std::optional getProfilesDialog() const; void setProfilesDialog(const QByteArray& v); + std::optional getOverwriteDialog() const; + void setOverwriteDialog(const QByteArray& v); + + std::optional getModInfoDialog() const; + void setModInfoDialog(const QByteArray& v) const; + + QStringList getModInfoTabOrder() const; + void setModInfoTabOrder(const QString& names); + std::optional getMainWindowMonitor() const; void setDockSize(const QString& name, int size); -- cgit v1.3.1 From 37502f388422b2fdb60c2564d733ec015f579831 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sat, 3 Aug 2019 03:39:22 -0400 Subject: removed convertVariant(), turns out value() does it separator colors to settings --- src/mainwindow.cpp | 30 ++++++++++++++++------------ src/settings.cpp | 57 ++++++++++++++++++++---------------------------------- src/settings.h | 4 ++++ 3 files changed, 43 insertions(+), 48 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 32f728d8..f98da391 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -3786,32 +3786,37 @@ void MainWindow::createSeparator_clicked() { m_OrganizerCore.modList()->changeModPriority(ModInfo::getIndex(name), newPriority); } - QSettings &settings = m_OrganizerCore.settings().directInterface(); - QColor previousColor = settings.value("previousSeparatorColor", QColor()).value(); - if (previousColor.isValid()) { - ModInfo::getByIndex(ModInfo::getIndex(name))->setColor(previousColor); - } + if (auto c=m_OrganizerCore.settings().getPreviousSeparatorColor()) { + ModInfo::getByIndex(ModInfo::getIndex(name))->setColor(*c); + } } void MainWindow::setColor_clicked() { - QSettings &settings = m_OrganizerCore.settings().directInterface(); + auto& settings = m_OrganizerCore.settings(); ModInfo::Ptr modInfo = ModInfo::getByIndex(m_ContextRow); + QColorDialog dialog(this); dialog.setOption(QColorDialog::ShowAlphaChannel); + QColor currentColor = modInfo->getColor(); - QColor previousColor = settings.value("previousSeparatorColor", QColor()).value(); - if (currentColor.isValid()) + if (currentColor.isValid()) { dialog.setCurrentColor(currentColor); - else - dialog.setCurrentColor(previousColor); + } + else if (auto c=settings.getPreviousSeparatorColor()) { + dialog.setCurrentColor(*c); + } + if (!dialog.exec()) return; + currentColor = dialog.currentColor(); if (!currentColor.isValid()) return; - settings.setValue("previousSeparatorColor", currentColor); + + settings.setPreviousSeparatorColor(currentColor); + QItemSelectionModel *selection = ui->modList->selectionModel(); if (selection->hasSelection() && selection->selectedRows().count() > 1) { for (QModelIndex idx : selection->selectedRows()) { @@ -3846,7 +3851,8 @@ void MainWindow::resetColor_clicked() else { modInfo->setColor(color); } - Settings::instance().directInterface().remove("previousSeparatorColor"); + + m_OrganizerCore.settings().removePreviousSeparatorColor(); } void MainWindow::createModFromOverwrite() diff --git a/src/settings.cpp b/src/settings.cpp index 73595ac9..f980e0be 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -26,46 +26,11 @@ along with Mod Organizer. If not, see . using namespace MOBase; -template -T convertVariant(const QVariant& v); - -template <> -QByteArray convertVariant(const QVariant& v) -{ - return v.toByteArray(); -} - -template <> -QString convertVariant(const QVariant& v) -{ - return v.toString(); -} - -template <> -int convertVariant(const QVariant& v) -{ - return v.toInt(); -} - -template <> -bool convertVariant(const QVariant& v) -{ - return v.toBool(); -} - -template <> -QSize convertVariant(const QVariant& v) -{ - return v.toSize(); -} - - - template std::optional getOptional(const QSettings& s, const QString& name) { if (s.contains(name)) { - return convertVariant(s.value(name)); + return s.value(name).value(); } return {}; @@ -453,6 +418,26 @@ bool Settings::getFirstStart() const return getOptional(m_Settings, "first_start").value_or(true); } +std::optional Settings::getPreviousSeparatorColor() const +{ + const auto c = getOptional(m_Settings, "previousSeparatorColor"); + if (c && c->isValid()) { + return c; + } + + return {}; +} + +void Settings::setPreviousSeparatorColor(const QColor& c) const +{ + m_Settings.setValue("previousSeparatorColor", c); +} + +void Settings::removePreviousSeparatorColor() +{ + m_Settings.remove("previousSeparatorColor"); +} + QString Settings::getProfileDirectory(bool resolve) const { return getConfigurablePath("profiles_directory", ToQString(AppConfig::profilesPath()), resolve); diff --git a/src/settings.h b/src/settings.h index f4e36b2a..fff684b8 100644 --- a/src/settings.h +++ b/src/settings.h @@ -190,6 +190,10 @@ public: std::optional getVersion() const; bool getFirstStart() const; + std::optional getPreviousSeparatorColor() const; + void setPreviousSeparatorColor(const QColor& c) const; + void removePreviousSeparatorColor(); + GeometrySettings& geometry(); const GeometrySettings& geometry() const; -- cgit v1.3.1 From 61ad96cb54a20ce9f8e5380d67ba4bb26e19cc8e Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sat, 3 Aug 2019 03:47:35 -0400 Subject: moved geometry handling to ListDialog --- src/listdialog.cpp | 16 ++++++++++++++++ src/listdialog.h | 4 ++++ src/mainwindow.cpp | 8 -------- src/settings.cpp | 10 ++++++++++ src/settings.h | 3 +++ 5 files changed, 33 insertions(+), 8 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/listdialog.cpp b/src/listdialog.cpp index b9857070..0fdcdb5f 100644 --- a/src/listdialog.cpp +++ b/src/listdialog.cpp @@ -17,6 +17,7 @@ along with Mod Organizer. If not, see . #include "listdialog.h" #include "ui_listdialog.h" +#include "settings.h" ListDialog::ListDialog(QWidget *parent) : QDialog(parent) @@ -32,6 +33,21 @@ ListDialog::~ListDialog() delete ui; } +int ListDialog::exec() +{ + auto& settings = Settings::instance(); + + if (auto v=settings.geometry().getListDialog()) { + restoreGeometry(*v); + } + + const int r = QDialog::exec(); + + settings.geometry().setListDialog(saveGeometry()); + + return r; +} + void ListDialog::setChoices(QStringList choices) { m_Choices = choices; diff --git a/src/listdialog.h b/src/listdialog.h index 7b5a5461..d0594bd7 100644 --- a/src/listdialog.h +++ b/src/listdialog.h @@ -15,6 +15,10 @@ public: explicit ListDialog(QWidget *parent = nullptr); ~ListDialog(); + // also saves and restores geometry + // + int exec() override; + void setChoices(QStringList choices); QString getChoice() const; diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index f98da391..f41bde17 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -3898,17 +3898,10 @@ void MainWindow::moveOverwriteContentToExistingMod() } ListDialog dialog(this); - QSettings &settings = m_OrganizerCore.settings().directInterface(); - QString key = QString("geometry/%1").arg(dialog.objectName()); - dialog.setWindowTitle("Select a mod..."); dialog.setChoices(mods); - if (settings.contains(key)) { - dialog.restoreGeometry(settings.value(key).toByteArray()); - } if (dialog.exec() == QDialog::Accepted) { - QString result = dialog.getChoice(); if (!result.isEmpty()) { @@ -3930,7 +3923,6 @@ void MainWindow::moveOverwriteContentToExistingMod() doMoveOverwriteContentToMod(modAbsolutePath); } } - settings.setValue(key, dialog.saveGeometry()); } void MainWindow::doMoveOverwriteContentToMod(const QString &modAbsolutePath) diff --git a/src/settings.cpp b/src/settings.cpp index f980e0be..c36585b3 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -927,6 +927,16 @@ void GeometrySettings::setModInfoTabOrder(const QString& names) m_Settings.setValue("mod_info_tab_order", names); } +std::optional GeometrySettings::getListDialog() const +{ + return getOptional(m_Settings, "geometry/ListDialog"); +} + +void GeometrySettings::setListDialog(const QByteArray& v) +{ + m_Settings.setValue("geometry/ListDialog", v); +} + std::optional GeometrySettings::getMainWindowMonitor() const { return getOptional(m_Settings, "window_monitor"); diff --git a/src/settings.h b/src/settings.h index fff684b8..989ea1c6 100644 --- a/src/settings.h +++ b/src/settings.h @@ -61,6 +61,9 @@ public: QStringList getModInfoTabOrder() const; void setModInfoTabOrder(const QString& names); + std::optional getListDialog() const; + void setListDialog(const QByteArray& v); + std::optional getMainWindowMonitor() const; void setDockSize(const QString& name, int size); -- cgit v1.3.1 From 3d86f150ca3a0992ddaca5055a270b7204c0682a Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sun, 4 Aug 2019 06:30:37 -0400 Subject: moved geometry handling to ProblemsDialog and CategoriesDialog --- src/categoriesdialog.cpp | 16 ++++++++++++++++ src/categoriesdialog.h | 6 +++++- src/mainwindow.cpp | 26 ++++++++------------------ src/problemsdialog.cpp | 15 +++++++++++++++ src/problemsdialog.h | 4 ++++ src/settings.cpp | 20 ++++++++++++++++++++ src/settings.h | 6 ++++++ 7 files changed, 74 insertions(+), 19 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/categoriesdialog.cpp b/src/categoriesdialog.cpp index 881179a4..91df5cae 100644 --- a/src/categoriesdialog.cpp +++ b/src/categoriesdialog.cpp @@ -21,6 +21,7 @@ along with Mod Organizer. If not, see . #include "ui_categoriesdialog.h" #include "categories.h" #include "utility.h" +#include "settings.h" #include #include #include @@ -109,6 +110,21 @@ CategoriesDialog::~CategoriesDialog() delete ui; } +int CategoriesDialog::exec() +{ + auto& settings = Settings::instance(); + + if (auto v=settings.geometry().getCategoriesDialog()) { + restoreGeometry(*v); + } + + const int r = QDialog::exec(); + + settings.geometry().setCategoriesDialog(saveGeometry()); + + return r; +} + void CategoriesDialog::cellChanged(int row, int) { diff --git a/src/categoriesdialog.h b/src/categoriesdialog.h index 72d2154d..c743c157 100644 --- a/src/categoriesdialog.h +++ b/src/categoriesdialog.h @@ -33,12 +33,16 @@ class CategoriesDialog; class CategoriesDialog : public MOBase::TutorableDialog { Q_OBJECT - + public: explicit CategoriesDialog(QWidget *parent = 0); ~CategoriesDialog(); + // also saves and restores geometry + // + int exec() override; + /** * @brief store changes here to the global categories store (categories.h) * diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index f41bde17..26398630 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -6164,24 +6164,20 @@ void MainWindow::on_bsaList_itemChanged(QTreeWidgetItem*, int) void MainWindow::on_actionNotifications_triggered() { updateProblemsButton(); - ProblemsDialog problems(m_PluginContainer.plugins(), this); - QSettings &settings = m_OrganizerCore.settings().directInterface(); - QString key = QString("geometry/%1").arg(problems.objectName()); - if (settings.contains(key)) { - problems.restoreGeometry(settings.value(key).toByteArray()); - } + ProblemsDialog problems(m_PluginContainer.plugins(), this); problems.exec(); - settings.setValue(key, problems.saveGeometry()); + updateProblemsButton(); } void MainWindow::on_actionChange_Game_triggered() { - if (QMessageBox::question(this, tr("Are you sure?"), - tr("This will restart MO, continue?"), - QMessageBox::Yes | QMessageBox::Cancel) - == QMessageBox::Yes) { + const auto r = QMessageBox::question( + this, tr("Are you sure?"), tr("This will restart MO, continue?"), + QMessageBox::Yes | QMessageBox::Cancel); + + if (r == QMessageBox::Yes) { InstanceManager::instance().clearCurrentInstance(); qApp->exit(INT_MAX); } @@ -6206,16 +6202,10 @@ void MainWindow::on_displayCategoriesBtn_toggled(bool checked) void MainWindow::editCategories() { CategoriesDialog dialog(this); - QSettings &settings = m_OrganizerCore.settings().directInterface(); - QString key = QString("geometry/%1").arg(dialog.objectName()); - if (settings.contains(key)) { - dialog.restoreGeometry(settings.value(key).toByteArray()); - } + if (dialog.exec() == QDialog::Accepted) { dialog.commitChanges(); } - settings.setValue(key, dialog.saveGeometry()); - } void MainWindow::deselectFilters() diff --git a/src/problemsdialog.cpp b/src/problemsdialog.cpp index da09935b..99cc9833 100644 --- a/src/problemsdialog.cpp +++ b/src/problemsdialog.cpp @@ -29,6 +29,21 @@ ProblemsDialog::~ProblemsDialog() delete ui; } +int ProblemsDialog::exec() +{ + auto& settings = Settings::instance(); + + if (auto v=settings.geometry().getProblemsDialog()) { + restoreGeometry(*v); + } + + const int r = QDialog::exec(); + + settings.geometry().setProblemsDialog(saveGeometry()); + + return r; +} + void ProblemsDialog::runDiagnosis() { m_hasProblems = false; diff --git a/src/problemsdialog.h b/src/problemsdialog.h index c211e4f5..a30c8d48 100644 --- a/src/problemsdialog.h +++ b/src/problemsdialog.h @@ -20,6 +20,10 @@ public: explicit ProblemsDialog(std::vector pluginObjects, QWidget *parent = 0); ~ProblemsDialog(); + // also saves and restores geometry + // + int exec() override; + bool hasProblems() const; private: diff --git a/src/settings.cpp b/src/settings.cpp index c36585b3..da3b42a0 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -937,6 +937,26 @@ void GeometrySettings::setListDialog(const QByteArray& v) m_Settings.setValue("geometry/ListDialog", v); } +std::optional GeometrySettings::getProblemsDialog() const +{ + return getOptional(m_Settings, "geometry/ProblemsDialog"); +} + +void GeometrySettings::setProblemsDialog(const QByteArray& v) +{ + m_Settings.setValue("geometry/ProblemsDialog", v); +} + +std::optional GeometrySettings::getCategoriesDialog() const +{ + return getOptional(m_Settings, "geometry/CategoriesDialog"); +} + +void GeometrySettings::setCategoriesDialog(const QByteArray& v) +{ + m_Settings.setValue("geometry/CategoriesDialog", v); +} + std::optional GeometrySettings::getMainWindowMonitor() const { return getOptional(m_Settings, "window_monitor"); diff --git a/src/settings.h b/src/settings.h index 989ea1c6..217c8db6 100644 --- a/src/settings.h +++ b/src/settings.h @@ -64,6 +64,12 @@ public: std::optional getListDialog() const; void setListDialog(const QByteArray& v); + std::optional getProblemsDialog() const; + void setProblemsDialog(const QByteArray& v); + + std::optional getCategoriesDialog() const; + void setCategoriesDialog(const QByteArray& v); + std::optional getMainWindowMonitor() const; void setDockSize(const QString& name, int size); -- cgit v1.3.1 From ea3840a39deacf269c1859389c3b1847bcbdb93b Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sun, 4 Aug 2019 07:14:06 -0400 Subject: removed registerWidgetState(), was used just for header list headers, now saved and restored directly --- src/mainwindow.cpp | 73 +++++++++++++++++++----------------------------------- src/mainwindow.h | 9 +------ src/settings.cpp | 40 ++++++++++++++++++++++++++++++ src/settings.h | 12 +++++++++ 4 files changed, 79 insertions(+), 55 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index d4673701..95aa0b38 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -368,18 +368,24 @@ MainWindow::MainWindow(Settings &settings initDownloadView(); - bool pluginListAdjusted = registerWidgetState( - ui->espList->objectName(), ui->espList->header(), "plugin_list_state"); + bool pluginListAdjusted = false; + if (auto v=m_OrganizerCore.settings().geometry().getPluginListHeader()) { + ui->espList->header()->restoreState(*v); + pluginListAdjusted = true; + } - registerWidgetState(ui->dataTree->objectName(), ui->dataTree->header()); + if (auto v=m_OrganizerCore.settings().geometry().getDataTreeHeader()) { + ui->dataTree->header()->restoreState(*v); + } - registerWidgetState( - ui->downloadView->objectName(), ui->downloadView->header()); + if (auto v=m_OrganizerCore.settings().geometry().getDownloadViewHeader()) { + ui->downloadView->header()->restoreState(*v); + } ui->splitter->setStretchFactor(0, 3); ui->splitter->setStretchFactor(1, 2); - resizeLists(modListAdjusted, pluginListAdjusted); + resizeLists(pluginListAdjusted); QMenu *linkMenu = new QMenu(this); m_LinkToolbar = linkMenu->addAction(QIcon(":/MO/gui/link"), tr("Toolbar and Menu"), this, SLOT(linkToolbar())); @@ -581,10 +587,9 @@ void MainWindow::setupModList() ui->modList->header()->installEventFilter(m_OrganizerCore.modList()); - const bool modListAdjusted = registerWidgetState( - ui->modList->objectName(), ui->modList->header(), "mod_list_state"); + if (auto v=m_OrganizerCore.settings().geometry().getModListHeader()) { + ui->modList->header()->restoreState(*v); - if (modListAdjusted) { // hack: force the resize-signal to be triggered because restoreState doesn't seem to do that for (int column = 0; column <= ModList::COL_LASTCOLUMN; ++column) { int sectionSize = ui->modList->header()->sectionSize(column); @@ -598,6 +603,13 @@ void MainWindow::setupModList() ui->modList->header()->setSectionHidden(ModList::COL_GAME, true); ui->modList->header()->setSectionHidden(ModList::COL_INSTALLTIME, true); ui->modList->header()->setSectionHidden(ModList::COL_NOTES, true); + + // resize mod list to fit content + for (int i = 0; i < ui->modList->header()->count(); ++i) { + ui->modList->header()->setSectionResizeMode(i, QHeaderView::ResizeToContents); + } + + ui->modList->header()->setSectionResizeMode(ModList::COL_NAME, QHeaderView::Stretch); } // prevent the name-column from being hidden @@ -720,16 +732,8 @@ void MainWindow::disconnectPlugins() } -void MainWindow::resizeLists(bool modListCustom, bool pluginListCustom) +void MainWindow::resizeLists(bool pluginListCustom) { - if (!modListCustom) { - // resize mod list to fit content - for (int i = 0; i < ui->modList->header()->count(); ++i) { - ui->modList->header()->setSectionResizeMode(i, QHeaderView::ResizeToContents); - } - ui->modList->header()->setSectionResizeMode(ModList::COL_NAME, QHeaderView::Stretch); - } - // ensure the columns aren't so small you can't see them any more for (int i = 0; i < ui->modList->header()->count(); ++i) { if (ui->modList->header()->sectionSize(i) < 10) { @@ -2391,10 +2395,10 @@ void MainWindow::storeSettings(Settings& s) { settings.setValue("browser_geometry", m_IntegratedBrowser.saveGeometry()); settings.setValue("filters_visible", ui->displayCategoriesBtn->isChecked()); - for (const std::pair kv : m_PersistedGeometry) { - QString key = QString("geometry/") + kv.first; - settings.setValue(key, kv.second->saveState()); - } + s.geometry().setPluginListHeader(ui->espList->header()->saveState()); + s.geometry().setDataTreeHeader(ui->dataTree->header()->saveState()); + s.geometry().setDownloadViewHeader(ui->downloadView->header()->saveState()); + s.geometry().setModListHeader(ui->modList->header()->saveState()); DockFixer::save(this, s); } @@ -6892,31 +6896,6 @@ void MainWindow::dropLocalFile(const QUrl &url, const QString &outputDir, bool m } } -bool MainWindow::registerWidgetState(const QString &name, QHeaderView *view, const char *oldSettingName) { - // register the view so it's geometry gets saved at exit - m_PersistedGeometry.push_back(std::make_pair(name, view)); - - // also, restore the geometry if it was saved before - QSettings &settings = m_OrganizerCore.settings().directInterface(); - - QString key = QString("geometry/%1").arg(name); - QByteArray data; - - if ((oldSettingName != nullptr) && settings.contains(oldSettingName)) { - data = settings.value(oldSettingName).toByteArray(); - settings.remove(oldSettingName); - } else if (settings.contains(key)) { - data = settings.value(key).toByteArray(); - } - - if (!data.isEmpty()) { - view->restoreState(data); - return true; - } else { - return false; - } -} - void MainWindow::dropEvent(QDropEvent *event) { Qt::DropAction action = event->proposedAction(); diff --git a/src/mainwindow.h b/src/mainwindow.h index 5ddb9bef..46f04784 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -316,8 +316,6 @@ private: void dropLocalFile(const QUrl &url, const QString &outputDir, bool move); - bool registerWidgetState(const QString &name, QHeaderView *view, const char *oldSettingName = nullptr); - void sendSelectedModsToPriority(int newPriority); void sendSelectedPluginsToPriority(int newPriority); @@ -405,8 +403,6 @@ private: bool m_showArchiveData{ true }; - std::vector> m_PersistedGeometry; - MOBase::DelayedFileWriter m_ArchiveListWriter; QAction* m_LinkToolbar; @@ -604,10 +600,7 @@ private slots: void expandModList(const QModelIndex &index); - /** - * @brief resize columns in mod list and plugin list to content - */ - void resizeLists(bool modListCustom, bool pluginListCustom); + void resizeLists(bool pluginListCustom); /** * @brief allow columns in mod list and plugin list to be resized diff --git a/src/settings.cpp b/src/settings.cpp index da3b42a0..d9440aa4 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -957,6 +957,46 @@ void GeometrySettings::setCategoriesDialog(const QByteArray& v) m_Settings.setValue("geometry/CategoriesDialog", v); } +std::optional GeometrySettings::getPluginListHeader() const +{ + return getOptional(m_Settings, "geometry/espList"); +} + +void GeometrySettings::setPluginListHeader(const QByteArray& v) const +{ + m_Settings.setValue("geometry/espList", v); +} + +std::optional GeometrySettings::getDataTreeHeader() const +{ + return getOptional(m_Settings, "geometry/dataTree"); +} + +void GeometrySettings::setDataTreeHeader(const QByteArray& v) const +{ + m_Settings.setValue("geometry/dataTree", v); +} + +std::optional GeometrySettings::getDownloadViewHeader() const +{ + return getOptional(m_Settings, "geometry/downloadView"); +} + +void GeometrySettings::setDownloadViewHeader(const QByteArray& v) const +{ + m_Settings.setValue("geometry/downloadView", v); +} + +std::optional GeometrySettings::getModListHeader() const +{ + return getOptional(m_Settings, "geometry/modList"); +} + +void GeometrySettings::setModListHeader(const QByteArray& v) const +{ + m_Settings.setValue("geometry/modList", v); +} + std::optional GeometrySettings::getMainWindowMonitor() const { return getOptional(m_Settings, "window_monitor"); diff --git a/src/settings.h b/src/settings.h index 217c8db6..110cfa76 100644 --- a/src/settings.h +++ b/src/settings.h @@ -70,6 +70,18 @@ public: std::optional getCategoriesDialog() const; void setCategoriesDialog(const QByteArray& v); + std::optional getPluginListHeader() const; + void setPluginListHeader(const QByteArray& v) const; + + std::optional getDataTreeHeader() const; + void setDataTreeHeader(const QByteArray& v) const; + + std::optional getDownloadViewHeader() const; + void setDownloadViewHeader(const QByteArray& v) const; + + std::optional getModListHeader() const; + void setModListHeader(const QByteArray& v) const; + std::optional getMainWindowMonitor() const; void setDockSize(const QString& name, int size); -- cgit v1.3.1 From 89415ca5c3903ced870d3bf5698dfa0e53122520 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sun, 4 Aug 2019 07:32:12 -0400 Subject: moved geometry handling to PreviewDialog fixed dialogs not having a parent --- src/mainwindow.h | 1 - src/organizercore.cpp | 23 +++-------------------- src/previewdialog.cpp | 16 ++++++++++++++++ src/previewdialog.h | 4 ++++ src/settings.cpp | 10 ++++++++++ src/settings.h | 3 +++ 6 files changed, 36 insertions(+), 21 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/mainwindow.h b/src/mainwindow.h index 46f04784..7460019d 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -83,7 +83,6 @@ class QProgressDialog; class QTranslator; class QTreeWidgetItem; class QUrl; -class QSettings; class QWidget; #ifndef Q_MOC_RUN diff --git a/src/organizercore.cpp b/src/organizercore.cpp index a64d93b4..2d11dafd 100644 --- a/src/organizercore.cpp +++ b/src/organizercore.cpp @@ -1297,7 +1297,8 @@ bool OrganizerCore::previewFileWithAlternatives( } // set up preview dialog - PreviewDialog preview(fileName); + PreviewDialog preview(fileName, parent); + auto addFunc = [&](int originId) { FilesOrigin &origin = directoryStructure()->getOriginByID(originId); QString filePath = QDir::fromNativeSeparators(ToQString(origin.getPath())) + "/" + fileName; @@ -1352,16 +1353,7 @@ bool OrganizerCore::previewFileWithAlternatives( } if (preview.numVariants() > 0) { - QSettings &s = settings().directInterface(); - QString key = QString("geometry/%1").arg(preview.objectName()); - if (s.contains(key)) { - preview.restoreGeometry(s.value(key).toByteArray()); - } - preview.exec(); - - s.setValue(key, preview.saveGeometry()); - return true; } else { @@ -1381,7 +1373,7 @@ bool OrganizerCore::previewFile( return false; } - PreviewDialog preview(path); + PreviewDialog preview(path, parent); QWidget *wid = m_PluginContainer->previewGenerator().genPreview(path); if (wid == nullptr) { @@ -1390,17 +1382,8 @@ bool OrganizerCore::previewFile( } preview.addVariant(originName, wid); - - QSettings &s = settings().directInterface(); - QString key = QString("geometry/%1").arg(preview.objectName()); - if (s.contains(key)) { - preview.restoreGeometry(s.value(key).toByteArray()); - } - preview.exec(); - s.setValue(key, preview.saveGeometry()); - return true; } diff --git a/src/previewdialog.cpp b/src/previewdialog.cpp index de33cdd0..06dcd674 100644 --- a/src/previewdialog.cpp +++ b/src/previewdialog.cpp @@ -1,5 +1,6 @@ #include "previewdialog.h" #include "ui_previewdialog.h" +#include "settings.h" #include PreviewDialog::PreviewDialog(const QString &fileName, QWidget *parent) : @@ -17,6 +18,21 @@ PreviewDialog::~PreviewDialog() delete ui; } +int PreviewDialog::exec() +{ + auto& settings = Settings::instance(); + + if (auto v=settings.geometry().getPreviewDialog()) { + restoreGeometry(*v); + } + + const int r = QDialog::exec(); + + settings.geometry().setPreviewDialog(saveGeometry()); + + return r; +} + void PreviewDialog::addVariant(const QString &modName, QWidget *widget) { widget->setProperty("modName", modName); diff --git a/src/previewdialog.h b/src/previewdialog.h index 0011bc50..9525f127 100644 --- a/src/previewdialog.h +++ b/src/previewdialog.h @@ -15,6 +15,10 @@ public: explicit PreviewDialog(const QString &fileName, QWidget *parent = 0); ~PreviewDialog(); + // also saves and restores geometry + // + int exec() override; + void addVariant(const QString &modName, QWidget *widget); int numVariants() const; diff --git a/src/settings.cpp b/src/settings.cpp index d9440aa4..44aa56ba 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -957,6 +957,16 @@ void GeometrySettings::setCategoriesDialog(const QByteArray& v) m_Settings.setValue("geometry/CategoriesDialog", v); } +std::optional GeometrySettings::getPreviewDialog() const +{ + return getOptional(m_Settings, "geometry/PreviewDialog"); +} + +void GeometrySettings::setPreviewDialog(const QByteArray& v) +{ + m_Settings.setValue("geometry/PreviewDialog", v); +} + std::optional GeometrySettings::getPluginListHeader() const { return getOptional(m_Settings, "geometry/espList"); diff --git a/src/settings.h b/src/settings.h index 110cfa76..615cdcbe 100644 --- a/src/settings.h +++ b/src/settings.h @@ -70,6 +70,9 @@ public: std::optional getCategoriesDialog() const; void setCategoriesDialog(const QByteArray& v); + std::optional getPreviewDialog() const; + void setPreviewDialog(const QByteArray& v); + std::optional getPluginListHeader() const; void setPluginListHeader(const QByteArray& v) const; -- cgit v1.3.1 From ab14a8bac3368fc2c1005bcc33009b65a0c728f2 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sun, 4 Aug 2019 07:51:12 -0400 Subject: moved recent directories to Settings use global cache variable instead of an instance inside a function --- src/filedialogmemory.cpp | 53 ++++++++---------------------------------------- src/filedialogmemory.h | 8 ++------ src/settings.cpp | 39 +++++++++++++++++++++++++++++++++++ src/settings.h | 3 +++ 4 files changed, 53 insertions(+), 50 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/filedialogmemory.cpp b/src/filedialogmemory.cpp index 48828563..96587ac7 100644 --- a/src/filedialogmemory.cpp +++ b/src/filedialogmemory.cpp @@ -21,46 +21,18 @@ along with Mod Organizer. If not, see . #include "settings.h" #include - -FileDialogMemory::FileDialogMemory() -{ -} - +static std::map g_Cache; void FileDialogMemory::save(Settings& s) { - auto& settings = s.directInterface(); - - settings.remove("recentDirectories"); - settings.beginWriteArray("recentDirectories"); - int index = 0; - for (std::map::const_iterator iter = instance().m_Cache.begin(); - iter != instance().m_Cache.end(); ++iter) { - settings.setArrayIndex(index++); - settings.setValue("name", iter->first); - settings.setValue("directory", iter->second); - } - settings.endArray(); + s.setRecentDirectories(g_Cache); } - void FileDialogMemory::restore(const Settings& s) { - auto& settings = const_cast(s.directInterface()); - - int size = settings.beginReadArray("recentDirectories"); - for (int i = 0; i < size; ++i) { - settings.setArrayIndex(i); - QVariant name = settings.value("name"); - QVariant dir = settings.value("directory"); - if (name.isValid() && dir.isValid()) { - instance().m_Cache.insert(std::make_pair(name.toString(), dir.toString())); - } - } - settings.endArray(); + g_Cache = s.getRecentDirectories(); } - QString FileDialogMemory::getOpenFileName( const QString &dirID, QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedFilter, @@ -69,8 +41,8 @@ QString FileDialogMemory::getOpenFileName( QString currentDir = dir; if (currentDir.isEmpty()) { - auto itor = instance().m_Cache.find(dirID); - if (itor != instance().m_Cache.end()) { + auto itor = g_Cache.find(dirID); + if (itor != g_Cache.end()) { currentDir = itor->second; } } @@ -79,7 +51,7 @@ QString FileDialogMemory::getOpenFileName( parent, caption, currentDir, filter, selectedFilter, options); if (!result.isNull()) { - instance().m_Cache[dirID] = QFileInfo(result).path(); + g_Cache[dirID] = QFileInfo(result).path(); } return result; @@ -93,8 +65,8 @@ QString FileDialogMemory::getExistingDirectory( QString currentDir = dir; if (currentDir.isEmpty()) { - auto itor = instance().m_Cache.find(dirID); - if (itor != instance().m_Cache.end()) { + auto itor = g_Cache.find(dirID); + if (itor != g_Cache.end()) { currentDir = itor->second; } } @@ -103,15 +75,8 @@ QString FileDialogMemory::getExistingDirectory( parent, caption, currentDir, options); if (!result.isNull()) { - instance().m_Cache[dirID] = QFileInfo(result).path(); + g_Cache[dirID] = result; } return result; } - - -FileDialogMemory &FileDialogMemory::instance() -{ - static FileDialogMemory instance; - return instance; -} diff --git a/src/filedialogmemory.h b/src/filedialogmemory.h index d214a8e6..8b8a3b76 100644 --- a/src/filedialogmemory.h +++ b/src/filedialogmemory.h @@ -30,6 +30,8 @@ class Settings; class FileDialogMemory { public: + FileDialogMemory() = delete; + static void save(Settings& settings); static void restore(const Settings& settings); @@ -42,12 +44,6 @@ public: const QString &dirID, QWidget *parent = 0, const QString &caption = QString(), const QString &dir = QString(), QFileDialog::Options options = QFileDialog::ShowDirsOnly); - -private: - std::map m_Cache; - - FileDialogMemory(); - static FileDialogMemory &instance(); }; #endif // FILEDIALOGMEMORY_H diff --git a/src/settings.cpp b/src/settings.cpp index 44aa56ba..cfc5c1d7 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -764,6 +764,45 @@ void Settings::writePluginBlacklist() m_Settings.endArray(); } +std::map Settings::getRecentDirectories() const +{ + std::map map; + + const int size = m_Settings.beginReadArray("recentDirectories"); + + for (int i=0; i& map) +{ + m_Settings.remove("recentDirectories"); + m_Settings.beginWriteArray("recentDirectories"); + + int index = 0; + for (auto&& p : map) { + m_Settings.setArrayIndex(index); + m_Settings.setValue("name", p.first); + m_Settings.setValue("directory", p.second); + + ++index; + } + + m_Settings.endArray(); +} + GeometrySettings& Settings::geometry() { return m_Geometry; diff --git a/src/settings.h b/src/settings.h index 615cdcbe..5b02ca67 100644 --- a/src/settings.h +++ b/src/settings.h @@ -218,6 +218,9 @@ public: void setPreviousSeparatorColor(const QColor& c) const; void removePreviousSeparatorColor(); + std::map getRecentDirectories() const; + void setRecentDirectories(const std::map& map); + GeometrySettings& geometry(); const GeometrySettings& geometry() const; -- cgit v1.3.1 From 4d4f25d1774659e0dfae8e60e13c494cab0f0a44 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Mon, 5 Aug 2019 13:10:21 -0400 Subject: moved getting and setting executables to Settings --- src/executableslist.cpp | 54 +++++++++++++++++++++---------------------------- src/settings.cpp | 44 ++++++++++++++++++++++++++++++++++++++++ src/settings.h | 3 +++ 3 files changed, 70 insertions(+), 31 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/executableslist.cpp b/src/executableslist.cpp index 2b3219df..f2df2d6d 100644 --- a/src/executableslist.cpp +++ b/src/executableslist.cpp @@ -75,34 +75,29 @@ void ExecutablesList::load(const MOBase::IPluginGame* game, const Settings& s) // executables from 2.2.0, see upgradeFromCustom() bool needsUpgrade = false; - auto& settings = const_cast(s.directInterface()); - - int numCustomExecutables = settings.beginReadArray("customExecutables"); - for (int i = 0; i < numCustomExecutables; ++i) { - settings.setArrayIndex(i); - + for (auto& map : s.getExecutables()) { Executable::Flags flags; - if (settings.value("toolbar", false).toBool()) + + if (map["toolbar"].toBool()) flags |= Executable::ShowInToolbar; - if (settings.value("ownicon", false).toBool()) + + if (map["ownicon"].toBool()) flags |= Executable::UseApplicationIcon; - if (settings.contains("custom")) { + if (map.contains("custom")) { // the "custom" setting only exists in older versions needsUpgrade = true; } setExecutable(Executable() - .title(settings.value("title").toString()) - .binaryInfo(settings.value("binary").toString()) - .arguments(settings.value("arguments").toString()) - .steamAppID(settings.value("steamAppID", "").toString()) - .workingDirectory(settings.value("workingDirectory", "").toString()) + .title(map["title"].toString()) + .binaryInfo(map["binary"].toString()) + .arguments(map["arguments"].toString()) + .steamAppID(map["steamAppID"].toString()) + .workingDirectory(map["workingDirectory"].toString()) .flags(flags)); } - settings.endArray(); - addFromPlugin(game, IgnoreExisting); if (needsUpgrade) @@ -113,26 +108,23 @@ void ExecutablesList::load(const MOBase::IPluginGame* game, const Settings& s) void ExecutablesList::store(Settings& s) { - auto& settings = s.directInterface(); + std::vector> v; - settings.remove("customExecutables"); - settings.beginWriteArray("customExecutables"); + for (const auto& item : *this) { + std::map map; - int count = 0; + map["title"] = item.title(); + map["toolbar"] = item.isShownOnToolbar(); + map["ownicon"] = item.usesOwnIcon(); + map["binary"] = item.binaryInfo().absoluteFilePath(); + map["arguments"] = item.arguments(); + map["workingDirectory"] = item.workingDirectory(); + map["steamAppID"] = item.steamAppID(); - for (const auto& item : *this) { - settings.setArrayIndex(count++); - - settings.setValue("title", item.title()); - settings.setValue("toolbar", item.isShownOnToolbar()); - settings.setValue("ownicon", item.usesOwnIcon()); - settings.setValue("binary", item.binaryInfo().absoluteFilePath()); - settings.setValue("arguments", item.arguments()); - settings.setValue("workingDirectory", item.workingDirectory()); - settings.setValue("steamAppID", item.steamAppID()); + v.push_back(std::move(map)); } - settings.endArray(); + s.setExecutables(v); } std::vector ExecutablesList::getPluginExecutables( diff --git a/src/settings.cpp b/src/settings.cpp index cfc5c1d7..a8dcfa39 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -19,6 +19,7 @@ along with Mod Organizer. If not, see . #include "settings.h" #include "serverinfo.h" +#include "executableslist.h" #include "appconfig.h" #include #include @@ -803,6 +804,49 @@ void Settings::setRecentDirectories(const std::map& map) m_Settings.endArray(); } +std::vector> Settings::getExecutables() const +{ + const int count = m_Settings.beginReadArray("customExecutables"); + std::vector> v; + + for (int i=0; i map; + + const auto keys = m_Settings.childKeys(); + for (auto&& key : keys) { + map[key] = m_Settings.value(key); + } + + v.push_back(map); + } + + m_Settings.endArray(); + + return v; +} + +void Settings::setExecutables(const std::vector>& v) +{ + m_Settings.remove("customExecutables"); + m_Settings.beginWriteArray("customExecutables"); + + int i = 0; + + for (const auto& map : v) { + m_Settings.setArrayIndex(i); + + for (auto&& p : map) { + m_Settings.setValue(p.first, p.second); + } + + ++i; + } + + m_Settings.endArray(); +} + GeometrySettings& Settings::geometry() { return m_Geometry; diff --git a/src/settings.h b/src/settings.h index 5b02ca67..2c4c7ca6 100644 --- a/src/settings.h +++ b/src/settings.h @@ -221,6 +221,9 @@ public: std::map getRecentDirectories() const; void setRecentDirectories(const std::map& map); + std::vector> getExecutables() const; + void setExecutables(const std::vector>& v); + GeometrySettings& geometry(); const GeometrySettings& geometry() const; -- cgit v1.3.1 From 799ddb1b2477434252d06975fd4c68106dc3826f Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Fri, 16 Aug 2019 06:03:05 -0400 Subject: added GeometrySaver removed widget-specific functions in GeometrySettings, now using generic functions in Settings removed some unused member variables in MainWindow --- src/categoriesdialog.cpp | 13 +-- src/editexecutablesdialog.cpp | 13 +-- src/listdialog.cpp | 13 +-- src/mainwindow.cpp | 49 ++++------ src/mainwindow.h | 4 - src/modinfodialog.cpp | 6 +- src/overwriteinfodialog.cpp | 11 +-- src/previewdialog.cpp | 13 +-- src/problemsdialog.cpp | 13 +-- src/profilesdialog.cpp | 13 +-- src/settings.cpp | 218 +++++++++++++++++++----------------------- src/settings.h | 64 +++++-------- 12 files changed, 158 insertions(+), 272 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/categoriesdialog.cpp b/src/categoriesdialog.cpp index 91df5cae..b5194bf0 100644 --- a/src/categoriesdialog.cpp +++ b/src/categoriesdialog.cpp @@ -112,17 +112,8 @@ CategoriesDialog::~CategoriesDialog() int CategoriesDialog::exec() { - auto& settings = Settings::instance(); - - if (auto v=settings.geometry().getCategoriesDialog()) { - restoreGeometry(*v); - } - - const int r = QDialog::exec(); - - settings.geometry().setCategoriesDialog(saveGeometry()); - - return r; + GeometrySaver gs(Settings::instance(), this); + return QDialog::exec(); } diff --git a/src/editexecutablesdialog.cpp b/src/editexecutablesdialog.cpp index 9c5ae44a..7823fadc 100644 --- a/src/editexecutablesdialog.cpp +++ b/src/editexecutablesdialog.cpp @@ -67,17 +67,8 @@ EditExecutablesDialog::~EditExecutablesDialog() = default; int EditExecutablesDialog::exec() { - auto& settings = m_organizerCore.settings(); - - if (auto v=settings.geometry().getExecutablesDialog()) { - restoreGeometry(*v); - } - - const int r = QDialog::exec(); - - settings.geometry().setExecutablesDialog(saveGeometry()); - - return r; + GeometrySaver gs(Settings::instance(), this); + return QDialog::exec(); } void EditExecutablesDialog::loadCustomOverwrites() diff --git a/src/listdialog.cpp b/src/listdialog.cpp index 0fdcdb5f..2ad88408 100644 --- a/src/listdialog.cpp +++ b/src/listdialog.cpp @@ -35,17 +35,8 @@ ListDialog::~ListDialog() int ListDialog::exec() { - auto& settings = Settings::instance(); - - if (auto v=settings.geometry().getListDialog()) { - restoreGeometry(*v); - } - - const int r = QDialog::exec(); - - settings.geometry().setListDialog(saveGeometry()); - - return r; + GeometrySaver gs(Settings::instance(), this); + return QDialog::exec(); } void ListDialog::setChoices(QStringList choices) diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 532914a5..85be8563 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -290,7 +290,6 @@ MainWindow::MainWindow(Settings &settings , m_linksSeparator(nullptr) , m_Tutorial(this, "MainWindow") , m_OldProfileIndex(-1) - , m_ModListGroupingProxy(nullptr) , m_ModListSortProxy(nullptr) , m_OldExecutableIndex(-1) , m_CategoryFactory(CategoryFactory::instance()) @@ -309,8 +308,8 @@ MainWindow::MainWindow(Settings &settings { QWebEngineProfile::defaultProfile()->setPersistentCookiesPolicy(QWebEngineProfile::NoPersistentCookies); QWebEngineProfile::defaultProfile()->setHttpCacheMaximumSize(52428800); - QWebEngineProfile::defaultProfile()->setCachePath(m_OrganizerCore.settings().getCacheDirectory()); - QWebEngineProfile::defaultProfile()->setPersistentStoragePath(m_OrganizerCore.settings().getCacheDirectory()); + QWebEngineProfile::defaultProfile()->setCachePath(settings.getCacheDirectory()); + QWebEngineProfile::defaultProfile()->setPersistentStoragePath(settings.getCacheDirectory()); ui->setupUi(this); m_statusBar.reset(new StatusBar(statusBar(), ui)); @@ -340,7 +339,7 @@ MainWindow::MainWindow(Settings &settings m_statusBar->setAPI(ni->getAPIStats(), ni->getAPIUserAccount()); } - languageChange(m_OrganizerCore.settings().language()); + languageChange(settings.language()); m_CategoryFactory.loadCategories(); @@ -367,19 +366,9 @@ MainWindow::MainWindow(Settings &settings initDownloadView(); - bool pluginListAdjusted = false; - if (auto v=m_OrganizerCore.settings().geometry().getPluginListHeader()) { - ui->espList->header()->restoreState(*v); - pluginListAdjusted = true; - } - - if (auto v=m_OrganizerCore.settings().geometry().getDataTreeHeader()) { - ui->dataTree->header()->restoreState(*v); - } - - if (auto v=m_OrganizerCore.settings().geometry().getDownloadViewHeader()) { - ui->downloadView->header()->restoreState(*v); - } + const bool pluginListAdjusted = settings.restoreState(ui->espList->header()); + settings.restoreState(ui->dataTree->header()); + settings.restoreState(ui->downloadView->header()); ui->splitter->setStretchFactor(0, 3); ui->splitter->setStretchFactor(1, 2); @@ -586,9 +575,7 @@ void MainWindow::setupModList() ui->modList->header()->installEventFilter(m_OrganizerCore.modList()); - if (auto v=m_OrganizerCore.settings().geometry().getModListHeader()) { - ui->modList->header()->restoreState(*v); - + if (m_OrganizerCore.settings().restoreState(ui->modList->header())) { // hack: force the resize-signal to be triggered because restoreState doesn't seem to do that for (int column = 0; column <= ModList::COL_LASTCOLUMN; ++column) { int sectionSize = ui->modList->header()->sectionSize(column); @@ -2272,13 +2259,8 @@ void MainWindow::activateProxy(bool activate) void MainWindow::readSettings(const Settings& settings) { - if (auto v=settings.geometry().getMainWindow()) { - restoreGeometry(*v); - } - - if (auto v=settings.geometry().getMainWindowState()) { - restoreState(*v); - } + settings.restoreGeometry(this); + settings.restoreState(this); if (auto v=settings.geometry().getToolbarSize()) { setToolbarSize(*v); @@ -2381,8 +2363,9 @@ void MainWindow::storeSettings(Settings& s) { settings.remove("geometry"); settings.remove("reset_geometry"); } else { - settings.setValue("window_geometry", saveGeometry()); - settings.setValue("window_state", saveState()); + s.saveState(this); + s.saveGeometry(this); + settings.setValue("toolbar_size", ui->toolBar->iconSize()); settings.setValue("toolbar_button_style", static_cast(ui->toolBar->toolButtonStyle())); settings.setValue("menubar_visible", m_menuBarVisible); @@ -2394,10 +2377,10 @@ void MainWindow::storeSettings(Settings& s) { settings.setValue("browser_geometry", m_IntegratedBrowser.saveGeometry()); settings.setValue("filters_visible", ui->displayCategoriesBtn->isChecked()); - s.geometry().setPluginListHeader(ui->espList->header()->saveState()); - s.geometry().setDataTreeHeader(ui->dataTree->header()->saveState()); - s.geometry().setDownloadViewHeader(ui->downloadView->header()->saveState()); - s.geometry().setModListHeader(ui->modList->header()->saveState()); + s.saveState(ui->espList->header()); + s.saveState(ui->dataTree->header()); + s.saveState(ui->downloadView->header()); + s.saveState(ui->modList->header()); DockFixer::save(this, s); } diff --git a/src/mainwindow.h b/src/mainwindow.h index 7460019d..946a341b 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -347,11 +347,9 @@ private: int m_OldProfileIndex; std::vector m_ModNameList; // the mod-list to go with the directory structure - bool m_Refreshing; QStringList m_DefaultArchives; - QAbstractItemModel *m_ModListGroupingProxy; ModListSortProxy *m_ModListSortProxy; PluginListSortProxy *m_PluginListSortProxy; @@ -367,8 +365,6 @@ private: CategoryFactory &m_CategoryFactory; - bool m_LoginAttempted; - QTimer m_CheckBSATimer; QTimer m_SaveMetaTimer; QTimer m_UpdateProblemsTimer; diff --git a/src/modinfodialog.cpp b/src/modinfodialog.cpp index 5e614358..f3840230 100644 --- a/src/modinfodialog.cpp +++ b/src/modinfodialog.cpp @@ -210,10 +210,8 @@ void ModInfoDialog::createTabs() int ModInfoDialog::exec() { + GeometrySaver gs(Settings::instance(), this); restoreState(); - if (auto v=m_core->settings().geometry().getModInfoDialog()) { - restoreGeometry(*v); - } // whether to select the first tab; if the main window requested a specific // tab, it is selected when encountered in update() @@ -226,9 +224,7 @@ int ModInfoDialog::exec() } const int r = TutorableDialog::exec(); - saveState(); - m_core->settings().geometry().setModInfoDialog(saveGeometry()); return r; } diff --git a/src/overwriteinfodialog.cpp b/src/overwriteinfodialog.cpp index f3ae0ff5..47416311 100644 --- a/src/overwriteinfodialog.cpp +++ b/src/overwriteinfodialog.cpp @@ -106,20 +106,13 @@ OverwriteInfoDialog::~OverwriteInfoDialog() void OverwriteInfoDialog::showEvent(QShowEvent* e) { - const auto& settings = Settings::instance(); - - if (auto v=settings.geometry().getOverwriteDialog()) { - restoreGeometry(*v); - } - + Settings::instance().restoreGeometry(this); QDialog::showEvent(e); } void OverwriteInfoDialog::done(int r) { - auto& settings = Settings::instance(); - settings.geometry().setOverwriteDialog(saveGeometry()); - + Settings::instance().saveGeometry(this); QDialog::done(r); } diff --git a/src/previewdialog.cpp b/src/previewdialog.cpp index 06dcd674..91a5f13e 100644 --- a/src/previewdialog.cpp +++ b/src/previewdialog.cpp @@ -20,17 +20,8 @@ PreviewDialog::~PreviewDialog() int PreviewDialog::exec() { - auto& settings = Settings::instance(); - - if (auto v=settings.geometry().getPreviewDialog()) { - restoreGeometry(*v); - } - - const int r = QDialog::exec(); - - settings.geometry().setPreviewDialog(saveGeometry()); - - return r; + GeometrySaver gs(Settings::instance(), this); + return QDialog::exec(); } void PreviewDialog::addVariant(const QString &modName, QWidget *widget) diff --git a/src/problemsdialog.cpp b/src/problemsdialog.cpp index 99cc9833..63d58295 100644 --- a/src/problemsdialog.cpp +++ b/src/problemsdialog.cpp @@ -31,17 +31,8 @@ ProblemsDialog::~ProblemsDialog() int ProblemsDialog::exec() { - auto& settings = Settings::instance(); - - if (auto v=settings.geometry().getProblemsDialog()) { - restoreGeometry(*v); - } - - const int r = QDialog::exec(); - - settings.geometry().setProblemsDialog(saveGeometry()); - - return r; + GeometrySaver gs(Settings::instance(), this); + return QDialog::exec(); } void ProblemsDialog::runDiagnosis() diff --git a/src/profilesdialog.cpp b/src/profilesdialog.cpp index 25fff2b2..2f1bd059 100644 --- a/src/profilesdialog.cpp +++ b/src/profilesdialog.cpp @@ -86,17 +86,8 @@ ProfilesDialog::~ProfilesDialog() int ProfilesDialog::exec() { - auto& settings = Settings::instance(); - - if (auto v=settings.geometry().getProfilesDialog()) { - restoreGeometry(*v); - } - - const int r = QDialog::exec(); - - settings.geometry().setProfilesDialog(saveGeometry()); - - return r; + GeometrySaver gs(Settings::instance(), this); + return QDialog::exec(); } void ProfilesDialog::showEvent(QShowEvent *event) diff --git a/src/settings.cpp b/src/settings.cpp index a8dcfa39..91e667d5 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -884,94 +884,146 @@ void Settings::dump() const m_Settings.endGroup(); } +QString widgetNameWithTopLevel(const QWidget* widget) +{ + QStringList components; -GeometrySettings::GeometrySettings(QSettings& s) - : m_Settings(s) + auto* tl = widget->window(); + + if (tl == widget) { + // this is a top level widget, such as a dialog + components.push_back(widget->objectName()); + } else { + // this is a widget + const auto toplevelName = tl->objectName(); + if (!toplevelName.isEmpty()) { + components.push_back(toplevelName); + } + + const auto widgetName = widget->objectName(); + if (!widgetName.isEmpty()) { + components.push_back(widgetName); + } + } + + if (components.isEmpty()) { + // can't do much + return "unknown_widget"; + } + + return components.join("_"); +} + +QString widgetName(const QMainWindow* w) { + return w->objectName(); } -std::optional GeometrySettings::getMainWindow() const +QString widgetName(const QHeaderView* w) { - return getOptional(m_Settings, "window_geometry"); + return widgetNameWithTopLevel(w->parentWidget()); } -std::optional GeometrySettings::getMainWindowState() const +QString widgetName(const QWidget* w) { - return getOptional(m_Settings, "window_state"); + return widgetNameWithTopLevel(w); } -std::optional GeometrySettings::getToolbarSize() const +template +QString geoSettingName(const Widget* widget) { - return getOptional(m_Settings, "toolbar_size"); + return "geometry/" + widgetName(widget) + "_geometry"; } -std::optional GeometrySettings::getToolbarButtonStyle() const +template +QString stateSettingName(const Widget* widget) { - if (auto v=getOptional(m_Settings, "toolbar_button_style")) { - return static_cast(*v); - } + return "geometry/" + widgetName(widget) + "_state"; +} - return {}; +void Settings::saveGeometry(const QWidget* w) +{ + m_Settings.setValue(geoSettingName(w), w->saveGeometry()); } -std::optional GeometrySettings::getMenubarVisible() const +bool Settings::restoreGeometry(QWidget* w) const { - return getOptional(m_Settings, "menubar_visible"); + if (auto v=getOptional(m_Settings, geoSettingName(w))) { + w->restoreGeometry(*v); + return true; + } + + return false; } -std::optional GeometrySettings::getStatusbarVisible() const +void Settings::saveState(const QMainWindow* w) { - return getOptional(m_Settings, "statusbar_visible"); + m_Settings.setValue(stateSettingName(w), w->saveGeometry()); } -std::optional GeometrySettings::getMainSplitterState() const +bool Settings::restoreState(QMainWindow* w) const { - return getOptional(m_Settings, "window_split"); + if (auto v=getOptional(m_Settings, stateSettingName(w))) { + w->restoreState(*v); + return true; + } + + return false; } -std::optional GeometrySettings::getFiltersVisible() const +void Settings::saveState(const QHeaderView* w) { - return getOptional(m_Settings, "filters_visible"); + m_Settings.setValue(stateSettingName(w), w->saveState()); } -std::optional GeometrySettings::getExecutablesDialog() const +bool Settings::restoreState(QHeaderView* w) const { - return getOptional(m_Settings, "geometry/EditExecutablesDialog"); + if (auto v=getOptional(m_Settings, stateSettingName(w))) { + w->restoreState(*v); + return true; + } + + return false; } -void GeometrySettings::setExecutablesDialog(const QByteArray& v) + +GeometrySettings::GeometrySettings(QSettings& s) + : m_Settings(s) { - m_Settings.setValue("geometry/EditExecutablesDialog", v); } -std::optional GeometrySettings::getProfilesDialog() const +std::optional GeometrySettings::getToolbarSize() const { - return getOptional(m_Settings, "geometry/ProfilesDialog"); + return getOptional(m_Settings, "toolbar_size"); } -void GeometrySettings::setProfilesDialog(const QByteArray& v) +std::optional GeometrySettings::getToolbarButtonStyle() const { - m_Settings.setValue("geometry/ProfilesDialog", v); + if (auto v=getOptional(m_Settings, "toolbar_button_style")) { + return static_cast(*v); + } + + return {}; } -std::optional GeometrySettings::getOverwriteDialog() const +std::optional GeometrySettings::getMenubarVisible() const { - return getOptional(m_Settings, "geometry/__overwriteDialog"); + return getOptional(m_Settings, "menubar_visible"); } -void GeometrySettings::setOverwriteDialog(const QByteArray& v) +std::optional GeometrySettings::getStatusbarVisible() const { - m_Settings.setValue("geometry/__overwriteDialog", v); + return getOptional(m_Settings, "statusbar_visible"); } -std::optional GeometrySettings::getModInfoDialog() const +std::optional GeometrySettings::getMainSplitterState() const { - return getOptional(m_Settings, "geometry/ModInfoDialog"); + return getOptional(m_Settings, "window_split"); } -void GeometrySettings::setModInfoDialog(const QByteArray& v) const +std::optional GeometrySettings::getFiltersVisible() const { - m_Settings.setValue("geometry/ModInfoDialog", v); + return getOptional(m_Settings, "filters_visible"); } QStringList GeometrySettings::getModInfoTabOrder() const @@ -1010,86 +1062,6 @@ void GeometrySettings::setModInfoTabOrder(const QString& names) m_Settings.setValue("mod_info_tab_order", names); } -std::optional GeometrySettings::getListDialog() const -{ - return getOptional(m_Settings, "geometry/ListDialog"); -} - -void GeometrySettings::setListDialog(const QByteArray& v) -{ - m_Settings.setValue("geometry/ListDialog", v); -} - -std::optional GeometrySettings::getProblemsDialog() const -{ - return getOptional(m_Settings, "geometry/ProblemsDialog"); -} - -void GeometrySettings::setProblemsDialog(const QByteArray& v) -{ - m_Settings.setValue("geometry/ProblemsDialog", v); -} - -std::optional GeometrySettings::getCategoriesDialog() const -{ - return getOptional(m_Settings, "geometry/CategoriesDialog"); -} - -void GeometrySettings::setCategoriesDialog(const QByteArray& v) -{ - m_Settings.setValue("geometry/CategoriesDialog", v); -} - -std::optional GeometrySettings::getPreviewDialog() const -{ - return getOptional(m_Settings, "geometry/PreviewDialog"); -} - -void GeometrySettings::setPreviewDialog(const QByteArray& v) -{ - m_Settings.setValue("geometry/PreviewDialog", v); -} - -std::optional GeometrySettings::getPluginListHeader() const -{ - return getOptional(m_Settings, "geometry/espList"); -} - -void GeometrySettings::setPluginListHeader(const QByteArray& v) const -{ - m_Settings.setValue("geometry/espList", v); -} - -std::optional GeometrySettings::getDataTreeHeader() const -{ - return getOptional(m_Settings, "geometry/dataTree"); -} - -void GeometrySettings::setDataTreeHeader(const QByteArray& v) const -{ - m_Settings.setValue("geometry/dataTree", v); -} - -std::optional GeometrySettings::getDownloadViewHeader() const -{ - return getOptional(m_Settings, "geometry/downloadView"); -} - -void GeometrySettings::setDownloadViewHeader(const QByteArray& v) const -{ - m_Settings.setValue("geometry/downloadView", v); -} - -std::optional GeometrySettings::getModListHeader() const -{ - return getOptional(m_Settings, "geometry/modList"); -} - -void GeometrySettings::setModListHeader(const QByteArray& v) const -{ - m_Settings.setValue("geometry/modList", v); -} - std::optional GeometrySettings::getMainWindowMonitor() const { return getOptional(m_Settings, "window_monitor"); @@ -1109,3 +1081,15 @@ std::optional GeometrySettings::isCategoryListVisible() const { return getOptional(m_Settings, "categorylist_visible"); } + + +GeometrySaver::GeometrySaver(Settings& s, QDialog* dialog) + : m_settings(s), m_dialog(dialog) +{ + m_settings.restoreGeometry(m_dialog); +} + +GeometrySaver::~GeometrySaver() +{ + m_settings.saveGeometry(m_dialog); +} diff --git a/src/settings.h b/src/settings.h index 2c4c7ca6..1575b3cd 100644 --- a/src/settings.h +++ b/src/settings.h @@ -30,6 +30,18 @@ namespace MOBase { class PluginContainer; struct ServerInfo; +class Settings; + +class GeometrySaver +{ +public: + GeometrySaver(Settings& s, QDialog* dialog); + ~GeometrySaver(); + +private: + Settings& m_settings; + QDialog* m_dialog; +}; class GeometrySettings @@ -37,54 +49,17 @@ class GeometrySettings public: GeometrySettings(QSettings& s); - std::optional getMainWindow() const; - std::optional getMainWindowState() const; std::optional getToolbarSize() const; std::optional getToolbarButtonStyle() const; + std::optional getMenubarVisible() const; std::optional getStatusbarVisible() const; std::optional getMainSplitterState() const; std::optional getFiltersVisible() const; - std::optional getExecutablesDialog() const; - void setExecutablesDialog(const QByteArray& v); - - std::optional getProfilesDialog() const; - void setProfilesDialog(const QByteArray& v); - - std::optional getOverwriteDialog() const; - void setOverwriteDialog(const QByteArray& v); - - std::optional getModInfoDialog() const; - void setModInfoDialog(const QByteArray& v) const; - QStringList getModInfoTabOrder() const; void setModInfoTabOrder(const QString& names); - std::optional getListDialog() const; - void setListDialog(const QByteArray& v); - - std::optional getProblemsDialog() const; - void setProblemsDialog(const QByteArray& v); - - std::optional getCategoriesDialog() const; - void setCategoriesDialog(const QByteArray& v); - - std::optional getPreviewDialog() const; - void setPreviewDialog(const QByteArray& v); - - std::optional getPluginListHeader() const; - void setPluginListHeader(const QByteArray& v) const; - - std::optional getDataTreeHeader() const; - void setDataTreeHeader(const QByteArray& v) const; - - std::optional getDownloadViewHeader() const; - void setDownloadViewHeader(const QByteArray& v) const; - - std::optional getModListHeader() const; - void setModListHeader(const QByteArray& v) const; - std::optional getMainWindowMonitor() const; void setDockSize(const QString& name, int size); @@ -228,6 +203,19 @@ public: const GeometrySettings& geometry() const; + void saveGeometry(const QWidget* w); + bool restoreGeometry(QWidget* w) const; + + void saveState(const QMainWindow* window); + bool restoreState(QMainWindow* window) const; + + void saveState(const QHeaderView* header); + bool restoreState(QHeaderView* header) const; + + void saveState(const QToolBar* toolbar); + bool restoreState(QToolBar* toolbar) const; + + /** * retrieve the directory where profiles stored (with native separators) **/ -- cgit v1.3.1 From 3f487a5a6c9c23824298fdde3d76dc82edf3ca46 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Fri, 16 Aug 2019 07:03:52 -0400 Subject: merged toolbars into restoreToolbars() and saveToolbars() added centerOnMainWindowMonitor(), now also used by validation dialog added overloads for splitter, used by main splitter fixed saveState() for QMainWindow calling the wrong function --- src/main.cpp | 11 +------ src/mainwindow.cpp | 28 +++++----------- src/nxmaccessmanager.cpp | 13 ++++++-- src/nxmaccessmanager.h | 2 ++ src/pch.h | 1 + src/settings.cpp | 86 ++++++++++++++++++++++++++++++++++++++++++------ src/settings.h | 19 ++++++++--- 7 files changed, 114 insertions(+), 46 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/main.cpp b/src/main.cpp index 506c6270..8eee41e4 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -697,16 +697,7 @@ int runApplication(MOApplication &application, SingleInstance &instance, QPixmap pixmap(splashPath); QSplashScreen splash(pixmap); - const auto monitor = settings.geometry().getMainWindowMonitor(); - if (monitor && QGuiApplication::screens().size() > *monitor) { - QGuiApplication::screens().at(*monitor)->geometry().center(); - const QPoint center = QGuiApplication::screens().at(*monitor)->geometry().center(); - splash.move(center - splash.rect().center()); - } else { - const QPoint center = QGuiApplication::primaryScreen()->geometry().center(); - splash.move(center - splash.rect().center()); - } - + settings.geometry().centerOnMainWindowMonitor(&splash); splash.show(); splash.activateWindow(); diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 85be8563..6e6e3d22 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -2261,14 +2261,8 @@ void MainWindow::readSettings(const Settings& settings) { settings.restoreGeometry(this); settings.restoreState(this); - - if (auto v=settings.geometry().getToolbarSize()) { - setToolbarSize(*v); - } - - if (auto v=settings.geometry().getToolbarButtonStyle()) { - setToolbarButtonStyle(*v); - } + settings.geometry().restoreToolbars(this); + settings.restoreState(ui->splitter); if (auto v=settings.geometry().getMenubarVisible()) { showMenuBar(*v); @@ -2278,10 +2272,6 @@ void MainWindow::readSettings(const Settings& settings) showStatusBar(*v); } - if (auto v=settings.geometry().getMainSplitterState()) { - ui->splitter->restoreState(*v); - } - { auto v = settings.geometry().getFiltersVisible().value_or(false); setCategoryListVisible(v); @@ -2366,14 +2356,12 @@ void MainWindow::storeSettings(Settings& s) { s.saveState(this); s.saveGeometry(this); - settings.setValue("toolbar_size", ui->toolBar->iconSize()); - settings.setValue("toolbar_button_style", static_cast(ui->toolBar->toolButtonStyle())); - settings.setValue("menubar_visible", m_menuBarVisible); - settings.setValue("statusbar_visible", m_statusBarVisible); - settings.setValue("window_split", ui->splitter->saveState()); - QScreen *screen = this->window()->windowHandle()->screen(); - int screenId = QGuiApplication::screens().indexOf(screen); - settings.setValue("window_monitor", screenId); + s.geometry().setMenubarVisible(m_menuBarVisible); + s.geometry().saveToolbars(this); + s.geometry().setStatusbarVisible(m_statusBarVisible); + s.saveState(ui->splitter); + s.geometry().saveMainWindowMonitor(this); + settings.setValue("browser_geometry", m_IntegratedBrowser.saveGeometry()); settings.setValue("filters_visible", ui->displayCategoriesBtn->isChecked()); diff --git a/src/nxmaccessmanager.cpp b/src/nxmaccessmanager.cpp index fd1dc0c1..16190ca4 100644 --- a/src/nxmaccessmanager.cpp +++ b/src/nxmaccessmanager.cpp @@ -48,8 +48,9 @@ const QString NexusSSO("wss://sso.nexusmods.com"); const QString NexusSSOPage("https://www.nexusmods.com/sso?id=%1&application=modorganizer2"); -ValidationProgressDialog::ValidationProgressDialog(std::chrono::seconds t) - : m_timeout(t), m_bar(nullptr), m_buttons(nullptr), m_timer(nullptr) +ValidationProgressDialog::ValidationProgressDialog(std::chrono::seconds t) : + m_timeout(t), m_bar(nullptr), m_buttons(nullptr), m_timer(nullptr), + m_first(true) { m_bar = new QProgressBar; m_bar->setTextVisible(false); @@ -103,6 +104,14 @@ void ValidationProgressDialog::stop() hide(); } +void ValidationProgressDialog::showEvent(QShowEvent* e) +{ + if (m_first) { + Settings::instance().geometry().centerOnMainWindowMonitor(this); + m_first = false; + } +} + void ValidationProgressDialog::closeEvent(QCloseEvent* e) { hide(); diff --git a/src/nxmaccessmanager.h b/src/nxmaccessmanager.h index eed7c1c9..0c85153b 100644 --- a/src/nxmaccessmanager.h +++ b/src/nxmaccessmanager.h @@ -48,6 +48,7 @@ public: using QDialog::show; protected: + void showEvent(QShowEvent* e) override; void closeEvent(QCloseEvent* e) override; private: @@ -56,6 +57,7 @@ private: QDialogButtonBox* m_buttons; QTimer* m_timer; QElapsedTimer m_elapsed; + bool m_first; void onButton(QAbstractButton* b); void onTimer(); diff --git a/src/pch.h b/src/pch.h index 504ef8f1..dd65efbe 100644 --- a/src/pch.h +++ b/src/pch.h @@ -189,6 +189,7 @@ #include #include #include +#include #include #include #include diff --git a/src/settings.cpp b/src/settings.cpp index 91e667d5..a3d12070 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -958,7 +958,7 @@ bool Settings::restoreGeometry(QWidget* w) const void Settings::saveState(const QMainWindow* w) { - m_Settings.setValue(stateSettingName(w), w->saveGeometry()); + m_Settings.setValue(stateSettingName(w), w->saveState()); } bool Settings::restoreState(QMainWindow* w) const @@ -986,24 +986,61 @@ bool Settings::restoreState(QHeaderView* w) const return false; } +void Settings::saveState(const QSplitter* w) +{ + m_Settings.setValue(stateSettingName(w), w->saveState()); +} + +bool Settings::restoreState(QSplitter* w) const +{ + if (auto v=getOptional(m_Settings, stateSettingName(w))) { + w->restoreState(*v); + return true; + } + + return false; +} + GeometrySettings::GeometrySettings(QSettings& s) : m_Settings(s) { } -std::optional GeometrySettings::getToolbarSize() const +bool GeometrySettings::restoreToolbars(QMainWindow* w) const { - return getOptional(m_Settings, "toolbar_size"); + const auto size = getOptional(m_Settings, "toolbar_size"); + const auto style = getOptional(m_Settings, "toolbar_button_style"); + + if (!size && !style) { + return false; + } + + for (auto* tb : w->findChildren()) { + if (size) { + tb->setIconSize(*size); + } + + if (style) { + tb->setToolButtonStyle(static_cast(*style)); + } + } + + return true; } -std::optional GeometrySettings::getToolbarButtonStyle() const +void GeometrySettings::saveToolbars(const QMainWindow* w) { - if (auto v=getOptional(m_Settings, "toolbar_button_style")) { - return static_cast(*v); + // all toolbars are identical, just save the first one + const auto tbs = w->findChildren(); + if (tbs.isEmpty()) { + return; } - return {}; + const auto* tb = tbs[0]; + + m_Settings.setValue("toolbar_size", tb->iconSize()); + m_Settings.setValue("toolbar_button_style", static_cast(tb->toolButtonStyle())); } std::optional GeometrySettings::getMenubarVisible() const @@ -1011,14 +1048,19 @@ std::optional GeometrySettings::getMenubarVisible() const return getOptional(m_Settings, "menubar_visible"); } +void GeometrySettings::setMenubarVisible(bool b) +{ + m_Settings.setValue("menubar_visible", b); +} + std::optional GeometrySettings::getStatusbarVisible() const { return getOptional(m_Settings, "statusbar_visible"); } -std::optional GeometrySettings::getMainSplitterState() const +void GeometrySettings::setStatusbarVisible(bool b) { - return getOptional(m_Settings, "window_split"); + m_Settings.setValue("statusbar_visible", b); } std::optional GeometrySettings::getFiltersVisible() const @@ -1064,7 +1106,31 @@ void GeometrySettings::setModInfoTabOrder(const QString& names) std::optional GeometrySettings::getMainWindowMonitor() const { - return getOptional(m_Settings, "window_monitor"); + return getOptional(m_Settings, "geometry/window_monitor"); +} + +void GeometrySettings::centerOnMainWindowMonitor(QWidget* w) +{ + const auto monitor = getMainWindowMonitor(); + QPoint center; + + if (monitor && QGuiApplication::screens().size() > *monitor) { + center = QGuiApplication::screens().at(*monitor)->geometry().center(); + } else { + center = QGuiApplication::primaryScreen()->geometry().center(); + } + + w->move(center - w->rect().center()); +} + +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/window_monitor", screenId); + } + } } void GeometrySettings::setDockSize(const QString& name, int size) diff --git a/src/settings.h b/src/settings.h index 1575b3cd..bbf008f0 100644 --- a/src/settings.h +++ b/src/settings.h @@ -28,6 +28,8 @@ namespace MOBase { class IPluginGame; } +class QSplitter; + class PluginContainer; struct ServerInfo; class Settings; @@ -49,18 +51,24 @@ class GeometrySettings public: GeometrySettings(QSettings& s); - std::optional getToolbarSize() const; - std::optional getToolbarButtonStyle() const; - std::optional getMenubarVisible() const; + void setMenubarVisible(bool b); + + bool restoreToolbars(QMainWindow* w) const; + void saveToolbars(const QMainWindow* w); + std::optional getStatusbarVisible() const; - std::optional getMainSplitterState() const; + void setStatusbarVisible(bool b); + std::optional getFiltersVisible() const; QStringList getModInfoTabOrder() const; void setModInfoTabOrder(const QString& names); std::optional getMainWindowMonitor() const; + void centerOnMainWindowMonitor(QWidget* w); + void saveMainWindowMonitor(const QMainWindow* w); + void setDockSize(const QString& name, int size); std::optional getDockSize(const QString& name) const; @@ -215,6 +223,9 @@ public: void saveState(const QToolBar* toolbar); bool restoreState(QToolBar* toolbar) const; + void saveState(const QSplitter* splitter); + bool restoreState(QSplitter* splitter) const; + /** * retrieve the directory where profiles stored (with native separators) -- cgit v1.3.1 From a5cb39aaf44b1f84003fb2ec2d36f07bf28916e4 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Fri, 16 Aug 2019 08:02:14 -0400 Subject: moved all geometry save, restore and reset to GeometrySettings changed reset button in settings to restart immediately --- src/browserdialog.cpp | 3 +- src/main.cpp | 12 ++++-- src/mainwindow.cpp | 75 +++++++++++-------------------------- src/mainwindow.h | 1 - src/overwriteinfodialog.cpp | 4 +- src/settings.cpp | 79 ++++++++++++++++++++++++++------------- src/settings.h | 39 +++++++++---------- src/settingsdialog.cpp | 11 +----- src/settingsdialog.h | 2 - src/settingsdialog.ui | 3 -- src/settingsdialogworkarounds.cpp | 16 ++++++-- 11 files changed, 121 insertions(+), 124 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/browserdialog.cpp b/src/browserdialog.cpp index 73a6a2d0..70da0b9c 100644 --- a/src/browserdialog.cpp +++ b/src/browserdialog.cpp @@ -72,7 +72,7 @@ BrowserDialog::~BrowserDialog() void BrowserDialog::closeEvent(QCloseEvent *event) { -// m_AccessManager->showCookies(); + Settings::instance().geometry().saveGeometry(this); QDialog::closeEvent(event); } @@ -126,6 +126,7 @@ void BrowserDialog::urlChanged(const QUrl &url) void BrowserDialog::openUrl(const QUrl &url) { if (isHidden()) { + Settings::instance().geometry().restoreGeometry(this); show(); } openInNewTab(url); diff --git a/src/main.cpp b/src/main.cpp index 8eee41e4..6d4108fa 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -718,6 +718,7 @@ int runApplication(MOApplication &application, SingleInstance &instance, } int res = 1; + { // scope to control lifetime of mainwindow // set up main window and its data structures MainWindow mainWindow(settings, organizer, pluginContainer); @@ -743,17 +744,20 @@ int runApplication(MOApplication &application, SingleInstance &instance, splash.finish(&mainWindow); - const auto ret = application.exec(); + res = application.exec(); NexusInterface::instance(&pluginContainer) ->getAccessManager()->setTopLevelWidget(nullptr); - - return ret; } + + settings.geometry().resetIfNeeded(); + return res; + } catch (const std::exception &e) { reportError(e.what()); - return 1; } + + return 1; } int doCoreDump(env::CoreDumpTypes type) diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 6e6e3d22..28e1de2e 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -366,9 +366,11 @@ MainWindow::MainWindow(Settings &settings initDownloadView(); - const bool pluginListAdjusted = settings.restoreState(ui->espList->header()); - settings.restoreState(ui->dataTree->header()); - settings.restoreState(ui->downloadView->header()); + const bool pluginListAdjusted = + settings.geometry().restoreState(ui->espList->header()); + + settings.geometry().restoreState(ui->dataTree->header()); + settings.geometry().restoreState(ui->downloadView->header()); ui->splitter->setStretchFactor(0, 3); ui->splitter->setStretchFactor(1, 2); @@ -575,7 +577,7 @@ void MainWindow::setupModList() ui->modList->header()->installEventFilter(m_OrganizerCore.modList()); - if (m_OrganizerCore.settings().restoreState(ui->modList->header())) { + if (m_OrganizerCore.settings().geometry().restoreState(ui->modList->header())) { // hack: force the resize-signal to be triggered because restoreState doesn't seem to do that for (int column = 0; column <= ModList::COL_LASTCOLUMN; ++column) { int sectionSize = ui->modList->header()->sectionSize(column); @@ -1417,12 +1419,6 @@ void MainWindow::cleanup() m_MetaSave.waitForFinished(); } - -void MainWindow::setBrowserGeometry(const QByteArray &geometry) -{ - m_IntegratedBrowser.restoreGeometry(geometry); -} - void MainWindow::displaySaveGameInfo(QListWidgetItem *newItem) { // don't display the widget if the main window doesn't have focus @@ -2259,10 +2255,10 @@ void MainWindow::activateProxy(bool activate) void MainWindow::readSettings(const Settings& settings) { - settings.restoreGeometry(this); - settings.restoreState(this); + settings.geometry().restoreGeometry(this); + settings.geometry().restoreState(this); settings.geometry().restoreToolbars(this); - settings.restoreState(ui->splitter); + settings.geometry().restoreState(ui->splitter); if (auto v=settings.geometry().getMenubarVisible()) { showMenuBar(*v); @@ -2340,38 +2336,22 @@ void MainWindow::storeSettings(Settings& s) { settings.setValue("selected_executable", ui->executablesListBox->currentIndex()); - if (settings.value("reset_geometry", false).toBool()) { - settings.remove("window_geometry"); - settings.remove("window_state"); - settings.remove("toolbar_size"); - settings.remove("toolbar_button_style"); - settings.remove("menubar_visible"); - settings.remove("window_split"); - settings.remove("window_monitor"); - settings.remove("filters_visible"); - settings.remove("browser_geometry"); - settings.remove("geometry"); - settings.remove("reset_geometry"); - } else { - s.saveState(this); - s.saveGeometry(this); - - s.geometry().setMenubarVisible(m_menuBarVisible); - s.geometry().saveToolbars(this); - s.geometry().setStatusbarVisible(m_statusBarVisible); - s.saveState(ui->splitter); - s.geometry().saveMainWindowMonitor(this); + s.geometry().saveState(this); + s.geometry().saveGeometry(this); - settings.setValue("browser_geometry", m_IntegratedBrowser.saveGeometry()); - settings.setValue("filters_visible", ui->displayCategoriesBtn->isChecked()); + s.geometry().setMenubarVisible(m_menuBarVisible); + s.geometry().saveToolbars(this); + s.geometry().setStatusbarVisible(m_statusBarVisible); + s.geometry().saveState(ui->splitter); + s.geometry().saveMainWindowMonitor(this); + s.geometry().setFiltersVisible(ui->displayCategoriesBtn->isChecked()); - s.saveState(ui->espList->header()); - s.saveState(ui->dataTree->header()); - s.saveState(ui->downloadView->header()); - s.saveState(ui->modList->header()); + s.geometry().saveState(ui->espList->header()); + s.geometry().saveState(ui->dataTree->header()); + s.geometry().saveState(ui->downloadView->header()); + s.geometry().saveState(ui->modList->header()); - DockFixer::save(this, s); - } + DockFixer::save(this, s); } ILockedWaitingForProcess* MainWindow::lock() @@ -6489,7 +6469,6 @@ void MainWindow::processLOOTOut(const std::string &lootOut, std::string &errorMe void MainWindow::on_bossButton_clicked() { - std::string reportURL; std::string errorMessages; //m_OrganizerCore.currentProfile()->writeModlistNow(); @@ -6637,16 +6616,6 @@ void MainWindow::on_bossButton_clicked() if (success) { m_DidUpdateMasterList = true; - if (reportURL.length() > 0) { - m_IntegratedBrowser.setWindowTitle("LOOT Report"); - QString report(reportURL.c_str()); - QStringList temp = report.split("?"); - QUrl url = QUrl::fromLocalFile(temp.at(0)); - if (temp.size() > 1) { - url.setQuery(temp.at(1).toUtf8()); - } - m_IntegratedBrowser.openUrl(url); - } m_OrganizerCore.refreshESPList(false); m_OrganizerCore.savePluginList(); } diff --git a/src/mainwindow.h b/src/mainwindow.h index 946a341b..8542dc8a 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -293,7 +293,6 @@ private: static void setupNetworkProxy(bool activate); void activateProxy(bool activate); - void setBrowserGeometry(const QByteArray &geometry); bool createBackup(const QString &filePath, const QDateTime &time); QString queryRestore(const QString &filePath); diff --git a/src/overwriteinfodialog.cpp b/src/overwriteinfodialog.cpp index 47416311..fe1d8825 100644 --- a/src/overwriteinfodialog.cpp +++ b/src/overwriteinfodialog.cpp @@ -106,13 +106,13 @@ OverwriteInfoDialog::~OverwriteInfoDialog() void OverwriteInfoDialog::showEvent(QShowEvent* e) { - Settings::instance().restoreGeometry(this); + Settings::instance().geometry().restoreGeometry(this); QDialog::showEvent(e); } void OverwriteInfoDialog::done(int r) { - Settings::instance().saveGeometry(this); + Settings::instance().geometry().saveGeometry(this); QDialog::done(r); } diff --git a/src/settings.cpp b/src/settings.cpp index a3d12070..db6cecdf 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -884,6 +884,7 @@ void Settings::dump() const m_Settings.endGroup(); } + QString widgetNameWithTopLevel(const QWidget* widget) { QStringList components; @@ -941,12 +942,46 @@ QString stateSettingName(const Widget* widget) return "geometry/" + widgetName(widget) + "_state"; } -void Settings::saveGeometry(const QWidget* w) + +GeometrySettings::GeometrySettings(QSettings& s) + : m_Settings(s), m_Reset(false) +{ +} + +void GeometrySettings::requestReset() +{ + m_Reset = true; +} + +void GeometrySettings::resetIfNeeded() +{ + if (!m_Reset) { + return; + } + + m_Settings.beginGroup("geometry"); + m_Settings.remove(""); + m_Settings.endGroup(); + + /*settings.remove("window_geometry"); + settings.remove("window_state"); + settings.remove("toolbar_size"); + settings.remove("toolbar_button_style"); + settings.remove("menubar_visible"); + settings.remove("window_split"); + settings.remove("window_monitor"); + settings.remove("filters_visible"); + settings.remove("browser_geometry"); + settings.remove("geometry"); + settings.remove("reset_geometry");*/ +} + +void GeometrySettings::saveGeometry(const QWidget* w) { m_Settings.setValue(geoSettingName(w), w->saveGeometry()); } -bool Settings::restoreGeometry(QWidget* w) const +bool GeometrySettings::restoreGeometry(QWidget* w) const { if (auto v=getOptional(m_Settings, geoSettingName(w))) { w->restoreGeometry(*v); @@ -956,12 +991,12 @@ bool Settings::restoreGeometry(QWidget* w) const return false; } -void Settings::saveState(const QMainWindow* w) +void GeometrySettings::saveState(const QMainWindow* w) { m_Settings.setValue(stateSettingName(w), w->saveState()); } -bool Settings::restoreState(QMainWindow* w) const +bool GeometrySettings::restoreState(QMainWindow* w) const { if (auto v=getOptional(m_Settings, stateSettingName(w))) { w->restoreState(*v); @@ -971,12 +1006,12 @@ bool Settings::restoreState(QMainWindow* w) const return false; } -void Settings::saveState(const QHeaderView* w) +void GeometrySettings::saveState(const QHeaderView* w) { m_Settings.setValue(stateSettingName(w), w->saveState()); } -bool Settings::restoreState(QHeaderView* w) const +bool GeometrySettings::restoreState(QHeaderView* w) const { if (auto v=getOptional(m_Settings, stateSettingName(w))) { w->restoreState(*v); @@ -986,12 +1021,12 @@ bool Settings::restoreState(QHeaderView* w) const return false; } -void Settings::saveState(const QSplitter* w) +void GeometrySettings::saveState(const QSplitter* w) { m_Settings.setValue(stateSettingName(w), w->saveState()); } -bool Settings::restoreState(QSplitter* w) const +bool GeometrySettings::restoreState(QSplitter* w) const { if (auto v=getOptional(m_Settings, stateSettingName(w))) { w->restoreState(*v); @@ -1001,12 +1036,6 @@ bool Settings::restoreState(QSplitter* w) const return false; } - -GeometrySettings::GeometrySettings(QSettings& s) - : m_Settings(s) -{ -} - bool GeometrySettings::restoreToolbars(QMainWindow* w) const { const auto size = getOptional(m_Settings, "toolbar_size"); @@ -1068,6 +1097,11 @@ std::optional GeometrySettings::getFiltersVisible() const return getOptional(m_Settings, "filters_visible"); } +void GeometrySettings::setFiltersVisible(bool b) +{ + m_Settings.setValue("filters_visible", b); +} + QStringList GeometrySettings::getModInfoTabOrder() const { QStringList v; @@ -1106,7 +1140,7 @@ void GeometrySettings::setModInfoTabOrder(const QString& names) std::optional GeometrySettings::getMainWindowMonitor() const { - return getOptional(m_Settings, "geometry/window_monitor"); + return getOptional(m_Settings, "geometry/MainWindow_monitor"); } void GeometrySettings::centerOnMainWindowMonitor(QWidget* w) @@ -1128,34 +1162,29 @@ 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/window_monitor", screenId); + m_Settings.setValue("geometry/MainWindow_monitor", screenId); } } } void GeometrySettings::setDockSize(const QString& name, int size) { - m_Settings.setValue("geometry/" + name + "_size", size); + m_Settings.setValue("geometry/MainWindow_docks_" + name + "_size", size); } std::optional GeometrySettings::getDockSize(const QString& name) const { - return getOptional(m_Settings, "geometry/" + name + "_size"); -} - -std::optional GeometrySettings::isCategoryListVisible() const -{ - return getOptional(m_Settings, "categorylist_visible"); + return getOptional(m_Settings, "geometry/MainWindow_docks_" + name + "_size"); } GeometrySaver::GeometrySaver(Settings& s, QDialog* dialog) : m_settings(s), m_dialog(dialog) { - m_settings.restoreGeometry(m_dialog); + m_settings.geometry().restoreGeometry(m_dialog); } GeometrySaver::~GeometrySaver() { - m_settings.saveGeometry(m_dialog); + m_settings.geometry().saveGeometry(m_dialog); } diff --git a/src/settings.h b/src/settings.h index bbf008f0..9ae58803 100644 --- a/src/settings.h +++ b/src/settings.h @@ -51,6 +51,24 @@ class GeometrySettings public: GeometrySettings(QSettings& s); + void requestReset(); + void resetIfNeeded(); + + void saveGeometry(const QWidget* w); + bool restoreGeometry(QWidget* w) const; + + void saveState(const QMainWindow* window); + bool restoreState(QMainWindow* window) const; + + 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; + std::optional getMenubarVisible() const; void setMenubarVisible(bool b); @@ -61,6 +79,7 @@ public: void setStatusbarVisible(bool b); std::optional getFiltersVisible() const; + void setFiltersVisible(bool b); QStringList getModInfoTabOrder() const; void setModInfoTabOrder(const QString& names); @@ -73,10 +92,9 @@ public: std::optional getDockSize(const QString& name) const; - std::optional isCategoryListVisible() const; - private: QSettings& m_Settings; + bool m_Reset; }; @@ -210,23 +228,6 @@ public: GeometrySettings& geometry(); const GeometrySettings& geometry() const; - - void saveGeometry(const QWidget* w); - bool restoreGeometry(QWidget* w) const; - - void saveState(const QMainWindow* window); - bool restoreState(QMainWindow* window) const; - - 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; - - /** * retrieve the directory where profiles stored (with native separators) **/ diff --git a/src/settingsdialog.cpp b/src/settingsdialog.cpp index fbd9ecd1..d74507c9 100644 --- a/src/settingsdialog.cpp +++ b/src/settingsdialog.cpp @@ -34,7 +34,6 @@ SettingsDialog::SettingsDialog(PluginContainer *pluginContainer, Settings* setti , ui(new Ui::SettingsDialog) , m_settings(settings) , m_PluginContainer(pluginContainer) - , m_GeometriesReset(false) , m_keyChanged(false) { ui->setupUi(this); @@ -101,10 +100,7 @@ int SettingsDialog::exec() if (getApiKeyChanged()) { restartNeeded = true; } - if (getResetGeometries()) { - restartNeeded = true; - qsettings.setValue("reset_geometry", true); - } + if (restartNeeded) { if (QMessageBox::question(nullptr, tr("Restart Mod Organizer?"), @@ -156,11 +152,6 @@ void SettingsDialog::accept() TutorableDialog::accept(); } -bool SettingsDialog::getResetGeometries() -{ - return ui->resetGeometryBtn->isChecked(); -} - bool SettingsDialog::getApiKeyChanged() { return m_keyChanged; diff --git a/src/settingsdialog.h b/src/settingsdialog.h index 03bba7cf..efc4a095 100644 --- a/src/settingsdialog.h +++ b/src/settingsdialog.h @@ -71,7 +71,6 @@ public: // temp Ui::SettingsDialog *ui; bool m_keyChanged; - bool m_GeometriesReset; PluginContainer *m_PluginContainer; int exec() override; @@ -81,7 +80,6 @@ public slots: public: bool getApiKeyChanged(); - bool getResetGeometries(); private: Settings* m_settings; diff --git a/src/settingsdialog.ui b/src/settingsdialog.ui index e011542e..e7676387 100644 --- a/src/settingsdialog.ui +++ b/src/settingsdialog.ui @@ -1233,9 +1233,6 @@ programs you are intentionally running. Reset Window Geometries - - true - diff --git a/src/settingsdialogworkarounds.cpp b/src/settingsdialogworkarounds.cpp index 9ac46ac1..fc859289 100644 --- a/src/settingsdialogworkarounds.cpp +++ b/src/settingsdialogworkarounds.cpp @@ -26,8 +26,6 @@ WorkaroundsSettingsTab::WorkaroundsSettingsTab(Settings *m_parent, SettingsDialo 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(); }); @@ -89,6 +87,16 @@ void WorkaroundsSettingsTab::on_bsaDateBtn_clicked() void WorkaroundsSettingsTab::on_resetGeometryBtn_clicked() { - m_dialog.m_GeometriesReset = true; - ui->resetGeometryBtn->setChecked(true); + const auto caption = QObject::tr("Restart Mod Organizer?"); + const auto text = QObject::tr( + "In order to reset the geometry, Mod Organizer must be restarted.\n" + "Restart now?"); + + const auto res = QMessageBox::question( + nullptr, caption, text, QMessageBox::Yes | QMessageBox::Cancel); + + if (res == QMessageBox::Yes) { + m_parent->geometry().requestReset(); + qApp->exit(INT_MAX); + } } -- cgit v1.3.1 From 0374291a3451c464fb27e53077da42ad21c27cd6 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Fri, 16 Aug 2019 09:00:31 -0400 Subject: StatusBar now inherits from QStatusBar to handle hide/show events merged settings into saveVisibility() and restoreVisibility() call MainWindow::storeSettings() earlier so widget visibility is still valid --- src/iuserinterface.h | 5 - src/main.cpp | 2 - src/mainwindow.cpp | 78 +- src/mainwindow.h | 15 +- src/mainwindow.ui | 2129 +++++++++++++++++++++++++------------------------ src/organizercore.cpp | 4 - src/settings.cpp | 96 +-- src/settings.h | 13 +- src/statusbar.cpp | 65 +- src/statusbar.h | 14 +- 10 files changed, 1200 insertions(+), 1221 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/iuserinterface.h b/src/iuserinterface.h index 7205f982..a309ed9b 100644 --- a/src/iuserinterface.h +++ b/src/iuserinterface.h @@ -10,14 +10,9 @@ #include -class Settings; - class IUserInterface { public: - - virtual void storeSettings(Settings &settings) = 0; - virtual void registerPluginTool(MOBase::IPluginTool *tool, QString name = QString(), QMenu *menu = nullptr) = 0; virtual void registerPluginTools(std::vector toolPlugins) = 0; virtual void registerModPage(MOBase::IPluginModPage *modPage) = 0; diff --git a/src/main.cpp b/src/main.cpp index 6d4108fa..aa781c19 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -736,8 +736,6 @@ int runApplication(MOApplication &application, SingleInstance &instance, // this must be before readSettings(), see DockFixer in mainwindow.cpp splash.finish(&mainWindow); - mainWindow.readSettings(settings); - log::debug("displaying main window"); mainWindow.show(); mainWindow.activateWindow(); diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 28e1de2e..7e471d24 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -285,8 +285,6 @@ MainWindow::MainWindow(Settings &settings : QMainWindow(parent) , ui(new Ui::MainWindow) , m_WasVisible(false) - , m_menuBarVisible(true) - , m_statusBarVisible(true) , m_linksSeparator(nullptr) , m_Tutorial(this, "MainWindow") , m_OldProfileIndex(-1) @@ -312,7 +310,7 @@ MainWindow::MainWindow(Settings &settings QWebEngineProfile::defaultProfile()->setPersistentStoragePath(settings.getCacheDirectory()); ui->setupUi(this); - m_statusBar.reset(new StatusBar(statusBar(), ui)); + ui->statusBar->setup(ui); { auto* ni = NexusInterface::instance(&m_PluginContainer); @@ -336,7 +334,7 @@ MainWindow::MainWindow(Settings &settings // in the rare case where the user restarts MO through the settings, this // will correctly pick up the previous values updateWindowTitle(ni->getAPIUserAccount()); - m_statusBar->setAPI(ni->getAPIStats(), ni->getAPIUserAccount()); + ui->statusBar->setAPI(ni->getAPIStats(), ni->getAPIUserAccount()); } languageChange(settings.language()); @@ -708,7 +706,7 @@ void MainWindow::updateWindowTitle(const APIUserAccount& user) void MainWindow::onRequestsChanged(const APIStats& stats, const APIUserAccount& user) { - m_statusBar->setAPI(stats, user); + ui->statusBar->setAPI(stats, user); } @@ -902,7 +900,7 @@ QMenu* MainWindow::createPopupMenu() void MainWindow::on_actionMainMenuToggle_triggered() { - showMenuBar(!ui->menuBar->isVisible()); + ui->menuBar->setVisible(!ui->menuBar->isVisible()); } void MainWindow::on_actionToolBarMainToggle_triggered() @@ -912,7 +910,7 @@ void MainWindow::on_actionToolBarMainToggle_triggered() void MainWindow::on_actionStatusBarToggle_triggered() { - showStatusBar(!ui->statusBar->isVisible()); + ui->statusBar->setVisible(!ui->statusBar->isVisible()); } void MainWindow::on_actionToolBarSmallIcons_triggered() @@ -964,36 +962,6 @@ void MainWindow::setToolbarButtonStyle(Qt::ToolButtonStyle s) } } -void MainWindow::showMenuBar(bool b) -{ - ui->menuBar->setVisible(b); - m_menuBarVisible = b; -} - -void MainWindow::showStatusBar(bool b) -{ - ui->statusBar->setVisible(b); - m_statusBarVisible = b; - - // the central widget typically has no bottom padding because the status bar - // is more than enough, but when it's hidden, the bottom widget (currently - // the log) touches the bottom border of the window, which looks ugly - // - // when hiding the statusbar, the central widget is given the same border - // margin as it has on the top (which is typically 6, as it's the default from - // the qt designer) - - auto m = ui->centralWidget->layout()->contentsMargins(); - - if (b) { - m.setBottom(0); - } else { - m.setBottom(m.top()); - } - - ui->centralWidget->layout()->setContentsMargins(m); -} - void MainWindow::on_centralWidget_customContextMenuRequested(const QPoint &pos) { // this allows for getting the context menu even if both the menubar and all @@ -1075,8 +1043,8 @@ void MainWindow::updateProblemsButton() } // updating the status bar, may be null very early when MO is starting - if (m_statusBar) { - m_statusBar->setNotifications(numProblems > 0); + if (ui->statusBar) { + ui->statusBar->setNotifications(numProblems > 0); } } @@ -1319,6 +1287,8 @@ void MainWindow::hookUpWindowTutorials() void MainWindow::showEvent(QShowEvent *event) { + readSettings(m_OrganizerCore.settings()); + refreshFilters(); QMainWindow::showEvent(event); @@ -1378,7 +1348,10 @@ void MainWindow::closeEvent(QCloseEvent* event) { if (!confirmExit()) { event->ignore(); + return; } + + storeSettings(m_OrganizerCore.settings()); } bool MainWindow::confirmExit() @@ -2259,17 +2232,12 @@ void MainWindow::readSettings(const Settings& settings) settings.geometry().restoreState(this); settings.geometry().restoreToolbars(this); settings.geometry().restoreState(ui->splitter); - - if (auto v=settings.geometry().getMenubarVisible()) { - showMenuBar(*v); - } - - if (auto v=settings.geometry().getStatusbarVisible()) { - showStatusBar(*v); - } + settings.geometry().restoreVisibility(ui->menuBar); + settings.geometry().restoreVisibility(ui->statusBar); { - auto v = settings.geometry().getFiltersVisible().value_or(false); + settings.geometry().restoreVisibility(ui->categoriesGroup, false); + const auto v = ui->categoriesGroup->isVisible(); setCategoryListVisible(v); ui->displayCategoriesBtn->setChecked(v); } @@ -2339,12 +2307,12 @@ void MainWindow::storeSettings(Settings& s) { s.geometry().saveState(this); s.geometry().saveGeometry(this); - s.geometry().setMenubarVisible(m_menuBarVisible); + s.geometry().saveVisibility(ui->menuBar); + s.geometry().saveVisibility(ui->statusBar); s.geometry().saveToolbars(this); - s.geometry().setStatusbarVisible(m_statusBarVisible); s.geometry().saveState(ui->splitter); s.geometry().saveMainWindowMonitor(this); - s.geometry().setFiltersVisible(ui->displayCategoriesBtn->isChecked()); + s.geometry().saveVisibility(ui->categoriesGroup); s.geometry().saveState(ui->espList->header()); s.geometry().saveState(ui->dataTree->header()); @@ -2606,7 +2574,7 @@ void MainWindow::setESPListSorting(int index) void MainWindow::refresher_progress(int percent) { setEnabled(percent == 100); - m_statusBar->setProgress(percent); + ui->statusBar->setProgress(percent); } void MainWindow::directory_refreshed() @@ -5216,7 +5184,7 @@ void MainWindow::on_actionSettings_triggered() activateProxy(settings.useProxy()); } - m_statusBar->checkSettings(m_OrganizerCore.settings()); + ui->statusBar->checkSettings(m_OrganizerCore.settings()); updateDownloadView(); m_OrganizerCore.setLogLevel(settings.logLevel()); @@ -5525,7 +5493,7 @@ void MainWindow::updateAvailable() { ui->actionUpdate->setEnabled(true); ui->actionUpdate->setToolTip(tr("Update available")); - m_statusBar->setUpdateAvailable(true); + ui->statusBar->setUpdateAvailable(true); } @@ -6858,7 +6826,7 @@ void MainWindow::keyReleaseEvent(QKeyEvent *event) // if the menubar is hidden, pressing Alt will make it visible if (event->key() == Qt::Key_Alt) { if (!ui->menuBar->isVisible()) { - showMenuBar(true); + ui->menuBar->show(); } } diff --git a/src/mainwindow.h b/src/mainwindow.h index 8542dc8a..a905a163 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -40,7 +40,6 @@ class Executable; class CategoryFactory; class LockedDialogBase; class OrganizerCore; -class StatusBar; class PluginListSortProxy; namespace BSA { class Archive; } @@ -118,8 +117,6 @@ public: QWidget *parent = 0); ~MainWindow(); - void storeSettings(Settings& settings) override; - void readSettings(const Settings& settings); void processUpdates(Settings& settings); virtual ILockedWaitingForProcess* lock() override; @@ -331,12 +328,6 @@ private: bool m_WasVisible; - // this has to be remembered because by the time storeSettings() is called, - // the window is closed and the all bars are hidden - bool m_menuBarVisible, m_statusBarVisible; - - std::unique_ptr m_statusBar; - // last separator on the toolbar, used to add spacer for right-alignment and // as an insert point for executables QAction* m_linksSeparator; @@ -685,11 +676,9 @@ private slots: // ui slots void on_categoriesOrBtn_toggled(bool checked); void on_managedArchiveLabel_linkHovered(const QString &link); + void storeSettings(Settings& settings); + void readSettings(const Settings& settings); void setupModList(); - void showMenuBar(bool b); - void showStatusBar(bool b); }; - - #endif // MAINWINDOW_H diff --git a/src/mainwindow.ui b/src/mainwindow.ui index e9910b83..02c6dec0 100644 --- a/src/mainwindow.ui +++ b/src/mainwindow.ui @@ -48,1239 +48,1239 @@ - + + + - - - - - Categories - - - + + + Categories + + + + 0 + + + 3 + + + 7 + + + 3 + + + 1 + + + + + + 120 + 0 + + + + + 214 + 16777215 + + + + Qt::CustomContextMenu + + + QAbstractItemView::ExtendedSelection + + 0 - - 3 + + true - - 7 + + false + + + + 1 + + + + + + + + false - - 3 + + + 0 + 0 + - - 1 + + + 0 + 25 + - - - - - 120 - 0 - - - - - 214 - 16777215 - - - - Qt::CustomContextMenu - - - QAbstractItemView::ExtendedSelection - - - 0 - - - true - - - false - - - - 1 - - - - - - - - false - - - - 0 - 0 - - - - - 0 - 25 - - - - Clear - - - true - - - - - - - - 0 - 0 - - - - - - - If checked, only mods that match all selected categories are displayed. - - - And - - - true - - - - - - - If checked, all mods that match at least one of the selected categories are displayed. - - - Or - - - - - - - - - - - - - - - - 0 - 0 - - - - Qt::Horizontal - - - - - 2 - - - - - - - - 0 - 0 - - - - Profile - - - profileBox - - - - - - - Pick a module collection - - - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> -<html><head><meta name="qrichtext" content="1" /><style type="text/css"> -p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Create profiles here. Each profile contains its own list of active mods and esps. This way you can quickly switch between setups for different playthroughs.</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Please note that right now your esp load order is not kept separate for different profiles.</span></p></body></html> - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 16777215 - 16777215 - - - - Open list options... - - - Refresh list. This is usually not necessary unless you modified data outside the program. - - - - - - - :/MO/gui/settings:/MO/gui/settings - - - - 16 - 16 - - - - - - - - Show Open Folders menu... - - - - - - - :/MO/gui/open_folder:/MO/gui/open_folder - - - + + Clear + + + true + + + + + + + + 0 + 0 + + + - + - Restore Backup... + If checked, only mods that match all selected categories are displayed. - + And - - - :/MO/gui/restore:/MO/gui/restore + + true - + - Create Backup - - - - - - - :/MO/gui/backup:/MO/gui/backup + If checked, all mods that match at least one of the selected categories are displayed. - - - - - Active: - - - - - - - - 0 - 26 - - - - This provides statistics about the mod list. The total number of active mod is normally displayed. Other statistics may be accessed with the tooltip of this counter. - - - QFrame::Sunken - - - 5 - - - QLCDNumber::Flat + Or + + + + + + + + + + + + 0 + 0 + + + + Qt::Horizontal + + + + + 2 + + + + + + + + 0 + 0 + + + + Profile + + + profileBox + + - - + + + Pick a module collection + + + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Create profiles here. Each profile contains its own list of active mods and esps. This way you can quickly switch between setups for different playthroughs.</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Please note that right now your esp load order is not kept separate for different profiles.</span></p></body></html> + + + + + + + Qt::Horizontal + + - 330 - 400 + 40 + 20 - - Qt::CustomContextMenu + + + + + + + 16777215 + 16777215 + - List of available mods. + Open list options... - This is a list of installed mods. Use the checkboxes to activate/deactivate mods and drag & drop mods to change their "installation" orders. + Refresh list. This is usually not necessary unless you modified data outside the program. - + + + + + + :/MO/gui/settings:/MO/gui/settings + + + + 16 + 16 + + + + + + + + Show Open Folders menu... + + + + + + + :/MO/gui/open_folder:/MO/gui/open_folder + + + + + + + Restore Backup... + + - - QAbstractItemView::EditKeyPressed|QAbstractItemView::SelectedClicked + + + :/MO/gui/restore:/MO/gui/restore - - true + + + + + + Create Backup - - true + + - - QAbstractItemView::DragDrop + + + :/MO/gui/backup:/MO/gui/backup - - Qt::MoveAction + + + + + + Active: - - true + + + + + + + 0 + 26 + - - QAbstractItemView::ExtendedSelection + + This provides statistics about the mod list. The total number of active mod is normally displayed. Other statistics may be accessed with the tooltip of this counter. - - QAbstractItemView::SelectRows + + QFrame::Sunken - - 20 + + 5 - - true + + QLCDNumber::Flat - - true + + + + + + + + + 330 + 400 + + + + Qt::CustomContextMenu + + + List of available mods. + + + This is a list of installed mods. Use the checkboxes to activate/deactivate mods and drag & drop mods to change their "installation" orders. + + + + + + QAbstractItemView::EditKeyPressed|QAbstractItemView::SelectedClicked + + + true + + + true + + + QAbstractItemView::DragDrop + + + Qt::MoveAction + + + true + + + QAbstractItemView::ExtendedSelection + + + QAbstractItemView::SelectRows + + + 20 + + + true + + + true + + + true + + + false + + + 35 + + + true + + + false + + + + + + + + + + 20 + 16777215 + - - true + + x - - false + + + 20 + 20 + - - 35 - - + true - - + + + + + + + + 0 + 0 + + + + Filter + + + + + + + + 8 + true + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 0 + 0 + + + + + 0 + 22 + + + + + 95 + 0 + + + false - + + + Qt::RightToLeft + + + border:1px solid #ff0000; + + + Clear all Filters + + + + :/MO/gui/edit_clear:/MO/gui/edit_clear + + + + 12 + 12 + + - - - - - - 20 - 16777215 - - - - x - - - - 20 - 20 - - - - true - - - - - - - - 0 - 0 - - - - Filter - - - - - - - - 8 - true - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 0 - 0 - - - - - 0 - 22 - - - - - 95 - 0 - - - - false - - - Qt::RightToLeft - - - border:1px solid #ff0000; - - - Clear all Filters - - - - :/MO/gui/edit_clear:/MO/gui/edit_clear - - - - 12 - 12 - - - + + + + 220 + 0 + + + + Qt::ClickFocus + + + + No groups + - - - - 220 - 0 - - - - Qt::ClickFocus - - - - No groups - - - - - Categories - - - - - Nexus IDs - - - + + Categories + - - - - 220 - 0 - - - - Filter - - + + Nexus IDs + - + - - - - - - + + + + 220 + 0 + + + + Filter + + + + + + + + + + + + + + + + + 0 + 0 + + + + + 0 + 40 + + + + + 9 + 75 + true + + + + Pick a program to run. + + + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Choose the program to run. Once you start using ModOrganizer, you should always run your game and tools from here or through shortcuts created here, otherwise mods installed through MO will not be visible.</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">You can add new Tools to this list, but I can't promise tools I haven't tested will work.</span></p></body></html> + + + + 32 + 32 + + + + false + + + + + - + - + 0 0 - 0 - 40 + 120 + 0 + + + + + 16777215 + 16777215 - 9 + 10 75 true - Pick a program to run. + Run program <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Choose the program to run. Once you start using ModOrganizer, you should always run your game and tools from here or through shortcuts created here, otherwise mods installed through MO will not be visible.</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">You can add new Tools to this list, but I can't promise tools I haven't tested will work.</span></p></body></html> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Run the selected program with ModOrganizer enabled.</span></p></body></html> + + + + + + Run + + + + :/MO/gui/run:/MO/gui/run - 32 - 32 + 36 + 36 - - false - - - - - - - 0 - 0 - - - - - 120 - 0 - - - - - 16777215 - 16777215 - - - - - 10 - 75 - true - - - - Run program - - - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> -<html><head><meta name="qrichtext" content="1" /><style type="text/css"> -p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Run the selected program with ModOrganizer enabled.</span></p></body></html> - - - - - - Run - - - - :/MO/gui/run:/MO/gui/run - - - - 36 - 36 - - - - - - - - - 0 - 0 - - - - - 140 - 0 - - - - - 16777215 - 16777215 - - - - - 0 - 0 - - - - Create a shortcut in your start menu or on the desktop to the specified program - - - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> + + + + 0 + 0 + + + + + 140 + 0 + + + + + 16777215 + 16777215 + + + + + 0 + 0 + + + + Create a shortcut in your start menu or on the desktop to the specified program + + + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">This creates a start menu shortcut that directly starts the selected program with the MO active.</span></p></body></html> - - - Shortcut - - - - :/MO/gui/link:/MO/gui/link - - - - + + + Shortcut + + + + :/MO/gui/link:/MO/gui/link + + - - - - - - - 340 - 250 - - - - - 16777215 - 16777215 - + + + + + + + + + 340 + 250 + + + + + 16777215 + 16777215 + + + + Qt::NoContextMenu + + + QTabWidget::Rounded + + + 0 + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + Plugins + + + + 6 - - Qt::NoContextMenu + + 6 - - QTabWidget::Rounded + + 6 - + 0 - - - - 0 - 0 - - - - - 16777215 - 16777215 - - - - Plugins - - - - 6 + + + + + + true + + + Sort + + + + :/MO/gui/sort:/MO/gui/sort + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Restore Backup... + + + + + + + :/MO/gui/restore:/MO/gui/restore + + + + 16 + 16 + + + + + + + + Create Backup + + + + + + + :/MO/gui/backup:/MO/gui/backup + + + + + + + Active: + + + + + + + + 0 + 26 + + + + This provides statistics about the plugin list. The total number of active plugins is normally displayed. Other statistics may be accessed with the tooltip of this counter. + + + QFrame::Sunken + + + 4 + + + QLCDNumber::Flat + + + + + + + + + + 250 + 250 + + + + Qt::CustomContextMenu + + + List of available esp/esm files + + + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">This list contains the esps, esms, and esls contained in the active mods. These require their own load order. Use drag&amp;drop to modify this load order. Please note that MO will only save the load order for mods that are active/checked.<br />There is a great tool named &quot;BOSS&quot; to automatically sort these files.</span></p></body></html> + + + QAbstractItemView::EditKeyPressed|QAbstractItemView::SelectedClicked + + + true + + + false + + + QAbstractItemView::InternalMove + + + Qt::MoveAction + + + true + + + QAbstractItemView::ExtendedSelection + + + QAbstractItemView::SelectRows + + + 0 + + + true - - 6 + + false - - 6 + + true - - 0 + + false + + false + + + + + - - - - - true - - - Sort - - - - :/MO/gui/sort:/MO/gui/sort - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Restore Backup... - - - - - - - :/MO/gui/restore:/MO/gui/restore - - - - 16 - 16 - - - - - - - - Create Backup - - - - - - - :/MO/gui/backup:/MO/gui/backup - - - - - - - Active: - - - - - - - - 0 - 26 - - - - This provides statistics about the plugin list. The total number of active plugins is normally displayed. Other statistics may be accessed with the tooltip of this counter. - - - QFrame::Sunken - - - 4 - - - QLCDNumber::Flat - - - - - - - - - - 250 - 250 - + + + - - Qt::CustomContextMenu + + Filter + + + + + + + + + false + + + Archives + + + + 6 + + + 6 + + + 6 + + + 6 + + + + + - List of available esp/esm files - - - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> -<html><head><meta name="qrichtext" content="1" /><style type="text/css"> -p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">This list contains the esps, esms, and esls contained in the active mods. These require their own load order. Use drag&amp;drop to modify this load order. Please note that MO will only save the load order for mods that are active/checked.<br />There is a great tool named &quot;BOSS&quot; to automatically sort these files.</span></p></body></html> - - - QAbstractItemView::EditKeyPressed|QAbstractItemView::SelectedClicked - - - true - - - false - - - QAbstractItemView::InternalMove - - - Qt::MoveAction - - - true - - - QAbstractItemView::ExtendedSelection - - - QAbstractItemView::SelectRows - - - 0 - - - true + <html><head/><body><p>BSAs / BA2s are bundles of game assets (textures, scripts, etc.). By default, the engine loads these bundles in a separate step from loose files. <p>Their load order is specified by the priority of the corresponding plugin (right pane, plugins tab).</p><p>If there is a matching plugin, the game will load them no matter what.</p></body></html> - - false + + <html><head/><body><p>Currently detected archives. (<a href="#"><span style=" text-decoration: underline; color:#0000ff;">What is an archive?</span></a>)</p></body></html> - + true - - false - - - false - - - - - - - - - - Filter - - - - - - - - - false - - - Archives - - - - 6 + + + + + Qt::CustomContextMenu - - 6 + + List of available BS Archives. Archives not checked here are not managed by MO and ignore installation order. - - 6 + + BSA files are archives (comparable to .zip files) that contain data assets (meshes, textures, ...) to be used by the game. As such they "compete" with loose files in your data directory over which is loaded. + By default, BSAs that share their base name with an enabled ESP (i.e. plugin.esp and plugin.bsa) are automatically loaded and will have precedence over all loose files, the installation order you set up to the left is then ignored! + + BSAs checked here are loaded in such a way that your installation order is obeyed properly. - - 6 + + false + + false + + + false + + + 20 + + + true + + + 1 + + + + + + + + Data + + + + 6 + + + 6 + + + 6 + + + 6 + + + + + refresh data-directory overview + + + Refresh the overview. This may take a moment. + + + Refresh + + + + :/MO/gui/resources/view-refresh.png:/MO/gui/resources/view-refresh.png + + + + + - - - - - <html><head/><body><p>BSAs / BA2s are bundles of game assets (textures, scripts, etc.). By default, the engine loads these bundles in a separate step from loose files. <p>Their load order is specified by the priority of the corresponding plugin (right pane, plugins tab).</p><p>If there is a matching plugin, the game will load them no matter what.</p></body></html> - - - <html><head/><body><p>Currently detected archives. (<a href="#"><span style=" text-decoration: underline; color:#0000ff;">What is an archive?</span></a>)</p></body></html> - - - true - - - - - - - + Qt::CustomContextMenu - - List of available BS Archives. Archives not checked here are not managed by MO and ignore installation order. - - BSA files are archives (comparable to .zip files) that contain data assets (meshes, textures, ...) to be used by the game. As such they "compete" with loose files in your data directory over which is loaded. - By default, BSAs that share their base name with an enabled ESP (i.e. plugin.esp and plugin.bsa) are automatically loaded and will have precedence over all loose files, the installation order you set up to the left is then ignored! - - BSAs checked here are loaded in such a way that your installation order is obeyed properly. - - - false - - - false - - - false + This is an overview of your data directory as visible to the game (and tools). - - 20 - - + true - - 1 + + true + + 400 + + + + File + + + + + Mod + + - - - - Data - - - - 6 - - - 6 - - - 6 - - - 6 - + + + - + - refresh data-directory overview + Filters the above list so that only conflicts are displayed. - Refresh the overview. This may take a moment. + Filters the above list so that only conflicts are displayed. - Refresh - - - - :/MO/gui/resources/view-refresh.png:/MO/gui/resources/view-refresh.png + Show only conflicts - - - - - Qt::CustomContextMenu - - - This is an overview of your data directory as visible to the game (and tools). - - - true - - - true - - - 400 - - - - File - - - - - Mod - - - - - - - - - - - - Filters the above list so that only conflicts are displayed. - - - Filters the above list so that only conflicts are displayed. - - - Show only conflicts - - - - - - - Filters the above list so that files from archives are not shown - - - - - - Filters the above list so that files from archives are not shown - - - Show files from Archives - - - - + + + Filters the above list so that files from archives are not shown + + + + + + Filters the above list so that files from archives are not shown + + + Show files from Archives + + - - - - Saves - - - - 6 + + + + + + Saves + + + + 6 + + + 6 + + + 6 + + + 6 + + + + + Qt::CustomContextMenu + + + + + + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">This is a list of all save games for this game. Hover over a list entry to get detailed information about the save including a list of esps/esms that were used at the time this save was created but aren't active now.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:8pt;"></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">If you click &quot;Fix Mods...&quot; in the context menu, MO will try to activate all mods and esps to fix those missing esps. It will not disable anything!</span></p></body></html> + + + QAbstractItemView::ExtendedSelection + + + QAbstractItemView::SelectRows - - 6 + + + + + + + Downloads + + + + 2 + + + 2 + + + 2 + + + 2 + + + + + Refresh downloads view - - 6 + + Refresh - - 6 + + + :/MO/gui/resources/view-refresh.png:/MO/gui/resources/view-refresh.png + + + + - + + + + 320 + 0 + + Qt::CustomContextMenu + + true + - + - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> -<html><head><meta name="qrichtext" content="1" /><style type="text/css"> -p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">This is a list of all save games for this game. Hover over a list entry to get detailed information about the save including a list of esps/esms that were used at the time this save was created but aren't active now.</span></p> -<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:8pt;"></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">If you click &quot;Fix Mods...&quot; in the context menu, MO will try to activate all mods and esps to fix those missing esps. It will not disable anything!</span></p></body></html> + This is a list of mods you downloaded from Nexus. Double click one to install it. You can also drag an archive into here. + + + Qt::ScrollBarAlwaysOn + + + true + + + QAbstractItemView::DragDrop + + + Qt::MoveAction + + + true + + + QAbstractItemView::ScrollPerPixel + + + 0 - - QAbstractItemView::ExtendedSelection + + false - - QAbstractItemView::SelectRows + + true - - - - Downloads - - - - 2 - - - 2 - - - 2 - - - 2 - + + + - - - Refresh downloads view - + - Refresh - - - - :/MO/gui/resources/view-refresh.png:/MO/gui/resources/view-refresh.png + Show Hidden - - - - - - 320 - 0 - - - - Qt::CustomContextMenu - - - true - - - - - - This is a list of mods you downloaded from Nexus. Double click one to install it. You can also drag an archive into here. - - - Qt::ScrollBarAlwaysOn - - - true - - - QAbstractItemView::DragDrop - - - Qt::MoveAction - - - true - - - QAbstractItemView::ScrollPerPixel - - - 0 - - - false - - - true - - - - + + + Qt::Horizontal + + + + 40 + 20 + + + - - - - - Show Hidden - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Filter - - - - + + + Filter + + - - - - - - - - + + + + + + + + + + @@ -1320,7 +1320,7 @@ p, li { white-space: pre-wrap; } - + @@ -1790,6 +1790,11 @@ p, li { white-space: pre-wrap; } QTreeView
loglist.h
+ + StatusBar + QStatusBar +
statusbar.h
+
diff --git a/src/organizercore.cpp b/src/organizercore.cpp index 2d11dafd..a2b0fd69 100644 --- a/src/organizercore.cpp +++ b/src/organizercore.cpp @@ -335,10 +335,6 @@ OrganizerCore::~OrganizerCore() void OrganizerCore::storeSettings() { - if (m_UserInterface != nullptr) { - m_UserInterface->storeSettings(m_Settings); - } - if (m_CurrentProfile != nullptr) { m_Settings.setSelectedProfileName(m_CurrentProfile->name()); } diff --git a/src/settings.cpp b/src/settings.cpp index db6cecdf..06b4446a 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -942,6 +942,12 @@ QString stateSettingName(const Widget* widget) return "geometry/" + widgetName(widget) + "_state"; } +template +QString visibilitySettingName(const Widget* widget) +{ + return "geometry/" + widgetName(widget) + "_visibility"; +} + GeometrySettings::GeometrySettings(QSettings& s) : m_Settings(s), m_Reset(false) @@ -962,18 +968,6 @@ void GeometrySettings::resetIfNeeded() m_Settings.beginGroup("geometry"); m_Settings.remove(""); m_Settings.endGroup(); - - /*settings.remove("window_geometry"); - settings.remove("window_state"); - settings.remove("toolbar_size"); - settings.remove("toolbar_button_style"); - settings.remove("menubar_visible"); - settings.remove("window_split"); - settings.remove("window_monitor"); - settings.remove("filters_visible"); - settings.remove("browser_geometry"); - settings.remove("geometry"); - settings.remove("reset_geometry");*/ } void GeometrySettings::saveGeometry(const QWidget* w) @@ -1036,15 +1030,32 @@ bool GeometrySettings::restoreState(QSplitter* w) const return false; } -bool GeometrySettings::restoreToolbars(QMainWindow* w) const +void GeometrySettings::saveVisibility(const QWidget* w) { - const auto size = getOptional(m_Settings, "toolbar_size"); - const auto style = getOptional(m_Settings, "toolbar_button_style"); + m_Settings.setValue(visibilitySettingName(w), w->isVisible()); +} - if (!size && !style) { - return false; +bool GeometrySettings::restoreVisibility(QWidget* w, std::optional def) const +{ + auto v = getOptional(m_Settings, visibilitySettingName(w)); + if (!v) { + v = def; + } + + if (v) { + w->setVisible(*v); + return true; } + return false; +} + +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"); + for (auto* tb : w->findChildren()) { if (size) { tb->setIconSize(*size); @@ -1053,53 +1064,28 @@ bool GeometrySettings::restoreToolbars(QMainWindow* w) const if (style) { tb->setToolButtonStyle(static_cast(*style)); } - } - return true; + restoreVisibility(tb); + } } void GeometrySettings::saveToolbars(const QMainWindow* w) { - // all toolbars are identical, just save the first one const auto tbs = w->findChildren(); - if (tbs.isEmpty()) { - return; - } - - const auto* tb = tbs[0]; - - m_Settings.setValue("toolbar_size", tb->iconSize()); - m_Settings.setValue("toolbar_button_style", static_cast(tb->toolButtonStyle())); -} - -std::optional GeometrySettings::getMenubarVisible() const -{ - return getOptional(m_Settings, "menubar_visible"); -} - -void GeometrySettings::setMenubarVisible(bool b) -{ - m_Settings.setValue("menubar_visible", b); -} - -std::optional GeometrySettings::getStatusbarVisible() const -{ - return getOptional(m_Settings, "statusbar_visible"); -} -void GeometrySettings::setStatusbarVisible(bool b) -{ - m_Settings.setValue("statusbar_visible", b); -} + // save visibility for all + for (auto* tb : tbs) { + saveVisibility(tb); + } -std::optional GeometrySettings::getFiltersVisible() const -{ - return getOptional(m_Settings, "filters_visible"); -} + // all toolbars have the same size and button style settings, just save the + // first one + if (!tbs.isEmpty()) { + const auto* tb = tbs[0]; -void GeometrySettings::setFiltersVisible(bool b) -{ - m_Settings.setValue("filters_visible", b); + m_Settings.setValue("toolbar_size", tb->iconSize()); + m_Settings.setValue("toolbar_button_style", static_cast(tb->toolButtonStyle())); + } } QStringList GeometrySettings::getModInfoTabOrder() const diff --git a/src/settings.h b/src/settings.h index 9ae58803..072b4066 100644 --- a/src/settings.h +++ b/src/settings.h @@ -54,6 +54,7 @@ public: void requestReset(); void resetIfNeeded(); + void saveGeometry(const QWidget* w); bool restoreGeometry(QWidget* w) const; @@ -69,17 +70,13 @@ public: void saveState(const QSplitter* splitter); bool restoreState(QSplitter* splitter) const; - std::optional getMenubarVisible() const; - void setMenubarVisible(bool b); - bool restoreToolbars(QMainWindow* w) const; - void saveToolbars(const QMainWindow* w); + void saveVisibility(const QWidget* w); + bool restoreVisibility(QWidget* w, std::optional defaultValue={}) const; - std::optional getStatusbarVisible() const; - void setStatusbarVisible(bool b); - std::optional getFiltersVisible() const; - void setFiltersVisible(bool b); + void saveToolbars(const QMainWindow* w); + void restoreToolbars(QMainWindow* w) const; QStringList getModInfoTabOrder() const; void setModInfoTabOrder(const QString& names); diff --git a/src/statusbar.cpp b/src/statusbar.cpp index e9a6e658..d22010a5 100644 --- a/src/statusbar.cpp +++ b/src/statusbar.cpp @@ -3,26 +3,32 @@ #include "settings.h" #include "ui_mainwindow.h" -StatusBar::StatusBar(QStatusBar* bar, Ui::MainWindow* ui) : - m_bar(bar), m_progress(new QProgressBar), - m_notifications(new StatusBarAction(ui->actionNotifications)), - m_update(new StatusBarAction(ui->actionUpdate)), - m_api(new QLabel) +StatusBar::StatusBar(QWidget* parent) : + QStatusBar(parent), ui(nullptr), m_progress(new QProgressBar), + m_notifications(nullptr), m_update(nullptr), m_api(new QLabel) { +} + +void StatusBar::setup(Ui::MainWindow* mainWindowUI) +{ + ui = mainWindowUI; + m_notifications = new StatusBarAction(ui->actionNotifications); + m_update = new StatusBarAction(ui->actionUpdate); + QWidget* spacer1 = new QWidget; spacer1->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); spacer1->setHidden(true); spacer1->setVisible(true); - m_bar->addPermanentWidget(spacer1, 0); - m_bar->addPermanentWidget(m_progress); + addPermanentWidget(spacer1, 0); + addPermanentWidget(m_progress); QWidget* spacer2 = new QWidget; spacer2->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); spacer2->setHidden(true); spacer2->setVisible(true); - m_bar->addPermanentWidget(spacer2,0); - m_bar->addPermanentWidget(m_notifications); - m_bar->addPermanentWidget(m_update); - m_bar->addPermanentWidget(m_api); + addPermanentWidget(spacer2,0); + addPermanentWidget(m_notifications); + addPermanentWidget(m_update); + addPermanentWidget(m_api); m_progress->setTextVisible(true); @@ -42,7 +48,7 @@ StatusBar::StatusBar(QStatusBar* bar, Ui::MainWindow* ui) : "be unable to queue downloads, check updates, parse mod info, or even log " "in. Both pools must be consumed before this happens.")); - m_bar->clearMessage(); + clearMessage(); setProgress(-1); setAPI({}, {}); } @@ -50,10 +56,10 @@ StatusBar::StatusBar(QStatusBar* bar, Ui::MainWindow* ui) : void StatusBar::setProgress(int percent) { if (percent < 0 || percent >= 100) { - m_bar->clearMessage(); + clearMessage(); m_progress->setVisible(false); } else { - m_bar->showMessage(QObject::tr("Loading...")); + showMessage(QObject::tr("Loading...")); m_progress->setVisible(true); m_progress->setValue(percent); } @@ -126,6 +132,37 @@ void StatusBar::checkSettings(const Settings& settings) m_api->setVisible(!settings.hideAPICounter()); } +void StatusBar::showEvent(QShowEvent*) +{ + visibilityChanged(true); +} + +void StatusBar::hideEvent(QHideEvent*) +{ + visibilityChanged(false); +} + +void StatusBar::visibilityChanged(bool visible) +{ + // the central widget typically has no bottom padding because the status bar + // is more than enough, but when it's hidden, the bottom widget (currently + // the log) touches the bottom border of the window, which looks ugly + // + // when hiding the statusbar, the central widget is given the same border + // margin as it has on the top (which is typically 6, as it's the default from + // the qt designer) + + auto m = ui->centralWidget->layout()->contentsMargins(); + + if (visible) { + m.setBottom(0); + } else { + m.setBottom(m.top()); + } + + ui->centralWidget->layout()->setContentsMargins(m); +} + StatusBarAction::StatusBarAction(QAction* action) : m_action(action), m_icon(new QLabel), m_text(new QLabel) diff --git a/src/statusbar.h b/src/statusbar.h index 2baf12ee..442b9acf 100644 --- a/src/statusbar.h +++ b/src/statusbar.h @@ -29,10 +29,12 @@ private: }; -class StatusBar +class StatusBar : public QStatusBar { public: - StatusBar(QStatusBar* bar, Ui::MainWindow* ui); + StatusBar(QWidget* parent=nullptr); + + void setup(Ui::MainWindow* ui); void setProgress(int percent); void setNotifications(bool hasNotifications); @@ -40,12 +42,18 @@ public: void setUpdateAvailable(bool b); void checkSettings(const Settings& settings); +protected: + void showEvent(QShowEvent* e); + void hideEvent(QHideEvent* e); + private: - QStatusBar* m_bar; + Ui::MainWindow* ui; QProgressBar* m_progress; StatusBarAction* m_notifications; StatusBarAction* m_update; QLabel* m_api; + + void visibilityChanged(bool visible); }; #endif // MO_STATUSBAR_H -- cgit v1.3.1 From 965eccb328a0a2b0cb4d1945a0382df9f0f91147 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Fri, 16 Aug 2019 10:29:42 -0400 Subject: merged DockFixer into GeometrySettings added combobox index to settings --- src/mainwindow.cpp | 156 ++++++-------------------------- src/mainwindow.h | 2 - src/pch.h | 1 + src/settings.cpp | 258 +++++++++++++++++++++++++++++++++++------------------ src/settings.h | 18 ++-- 5 files changed, 210 insertions(+), 225 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 7e471d24..bce92e48 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -194,90 +194,6 @@ const QSize MediumToolbarSize(32, 32); const QSize LargeToolbarSize(42, 36); -// this attempts to fix https://bugreports.qt.io/browse/QTBUG-46620 where dock -// sizes are not restored when the main window is maximized; it is used in -// MainWindow::readSettings() and MainWindow::storeSettings() -// -// there's also https://stackoverflow.com/questions/44005852, which has what -// seems to be a popular fix, but it breaks the restored size of the window -// by setting it to the desktop's resolution, so that doesn't work -// -// the only fix I could find is to remember the sizes of the docks and manually -// setting them back; saving is straightforward, but restoring is messy -// -// this also depends on the window being visible before the timer in restore() -// is fired and the timer must be processed by application.exec(); therefore, -// the splash screen _must_ be closed before readSettings() is called, because -// it has its own event loop, which seems to interfere with this -// -// all of this should become unnecessary when QTBUG-46620 is fixed -// -class DockFixer -{ -public: - static void save(MainWindow* mw, Settings& settings) - { - // saves the size of each dock - for (const auto* dock : mw->findChildren()) { - int size = 0; - - // save the width for horizontal docks, or the height for vertical - if (orientation(mw, dock) == Qt::Horizontal) { - size = dock->size().width(); - } else { - size = dock->size().height(); - } - - settings.geometry().setDockSize(dock->objectName(), size); - } - } - - static void restore(MainWindow* mw, const Settings& settings) - { - struct DockInfo - { - QDockWidget* d; - int size = 0; - Qt::Orientation ori; - }; - - std::vector dockInfos; - - // for each dock - for (auto* dock : mw->findChildren()) { - if (auto size=settings.geometry().getDockSize(dock->objectName())) { - // remember this dock, its size and orientation - dockInfos.push_back({dock, *size, orientation(mw, dock)}); - } - } - - // the main window must have had time to process the settings from - // readSettings() or it seems to override whatever is set here - // - // some people said a single processEvents() call is enough, but it doesn't - // look like it - QTimer::singleShot(5, [=] { - for (const auto& info : dockInfos) { - mw->resizeDocks({info.d}, {info.size}, info.ori); - } - }); - } - - static Qt::Orientation orientation(QMainWindow* mw, const QDockWidget* d) - { - // docks in these areas are horizontal - const auto horizontalAreas = - Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea; - - if (mw->dockWidgetArea(const_cast(d)) & horizontalAreas) { - return Qt::Horizontal; - } else { - return Qt::Vertical; - } - } -}; - - MainWindow::MainWindow(Settings &settings , OrganizerCore &organizerCore , PluginContainer &pluginContainer @@ -1328,12 +1244,10 @@ void MainWindow::showEvent(QShowEvent *event) QObject::tr("Please use \"Help\" from the toolbar to get usage instructions to all elements")); } - m_OrganizerCore.settings().directInterface().setValue("first_start", false); + m_OrganizerCore.settings().directInterface().setValue("first_start", false); } - // this has no visible impact when called before the ui is visible - int grouping = m_OrganizerCore.settings().directInterface().value("group_state").toInt(); - ui->groupCombo->setCurrentIndex(grouping); + m_OrganizerCore.settings().restoreIndex(ui->groupCombo); allowListResize(); @@ -1621,18 +1535,6 @@ void MainWindow::startExeAction() } - -void MainWindow::setExecutableIndex(int index) -{ - QComboBox *executableBox = findChild("executablesListBox"); - - if ((index != 0) && (executableBox->count() > index)) { - executableBox->setCurrentIndex(index); - } else { - executableBox->setCurrentIndex(1); - } -} - void MainWindow::activateSelectedProfile() { m_OrganizerCore.setCurrentProfile(ui->profileBox->currentText()); @@ -1895,7 +1797,7 @@ void MainWindow::refreshExecutablesList() ++i; } - setExecutableIndex(1); + ui->executablesListBox->setCurrentIndex(1); executablesList->setEnabled(true); } @@ -2230,11 +2132,24 @@ void MainWindow::readSettings(const Settings& settings) { settings.geometry().restoreGeometry(this); settings.geometry().restoreState(this); + settings.geometry().restoreDocks(this); settings.geometry().restoreToolbars(this); settings.geometry().restoreState(ui->splitter); settings.geometry().restoreVisibility(ui->menuBar); settings.geometry().restoreVisibility(ui->statusBar); + { + // special case in case someone puts 0 in the INI + auto v = settings.getIndex(ui->executablesListBox); + if (!v || v == 0) { + v = 1; + } + + ui->executablesListBox->setCurrentIndex(*v); + } + + settings.restoreIndex(ui->groupCombo); + { settings.geometry().restoreVisibility(ui->categoriesGroup, false); const auto v = ui->categoriesGroup->isVisible(); @@ -2242,17 +2157,11 @@ void MainWindow::readSettings(const Settings& settings) ui->displayCategoriesBtn->setChecked(v); } - if (auto v=settings.getSelectedExecutable()) { - setExecutableIndex(*v); - } - if (auto v=settings.getUseProxy()) { if (*v) { activateProxy(true); } } - - DockFixer::restore(this, settings); } void MainWindow::processUpdates(Settings& settings) { @@ -2297,15 +2206,11 @@ void MainWindow::processUpdates(Settings& settings) { } } -void MainWindow::storeSettings(Settings& s) { - auto& settings = s.directInterface(); - - settings.setValue("group_state", ui->groupCombo->currentIndex()); - settings.setValue("selected_executable", - ui->executablesListBox->currentIndex()); - +void MainWindow::storeSettings(Settings& s) +{ s.geometry().saveState(this); s.geometry().saveGeometry(this); + s.geometry().saveDocks(this); s.geometry().saveVisibility(ui->menuBar); s.geometry().saveVisibility(ui->statusBar); @@ -2319,7 +2224,8 @@ void MainWindow::storeSettings(Settings& s) { s.geometry().saveState(ui->downloadView->header()); s.geometry().saveState(ui->modList->header()); - DockFixer::save(this, s); + s.saveIndex(ui->groupCombo); + s.saveIndex(ui->executablesListBox); } ILockedWaitingForProcess* MainWindow::lock() @@ -2451,20 +2357,16 @@ bool MainWindow::modifyExecutablesDialog() void MainWindow::on_executablesListBox_currentIndexChanged(int index) { - QComboBox* executablesList = findChild("executablesListBox"); + if (!ui->executablesListBox->isEnabled()) { + return; + } - int previousIndex = m_OldExecutableIndex; + const int previousIndex = m_OldExecutableIndex; m_OldExecutableIndex = index; - if (executablesList->isEnabled()) { - //I think the 2nd test is impossible - if ((index == 0) || (index > static_cast(m_OrganizerCore.executablesList()->size()))) { - if (modifyExecutablesDialog()) { - setExecutableIndex(previousIndex); - } - } else { - setExecutableIndex(index); - } + if (index == 0) { + modifyExecutablesDialog(); + ui->executablesListBox->setCurrentIndex(previousIndex); } } @@ -2540,7 +2442,7 @@ void MainWindow::on_actionAdd_Profile_triggered() void MainWindow::on_actionModify_Executables_triggered() { if (modifyExecutablesDialog()) { - setExecutableIndex(m_OldExecutableIndex); + ui->executablesListBox->setCurrentIndex(m_OldExecutableIndex); } } diff --git a/src/mainwindow.h b/src/mainwindow.h index a905a163..6f06b9d5 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -226,8 +226,6 @@ private: QMenu* createPopupMenu() override; void activateSelectedProfile(); - void setExecutableIndex(int index); - void startSteam(); void updateTo(QTreeWidgetItem *subTree, const std::wstring &directorySoFar, const MOShared::DirectoryEntry &directoryEntry, bool conflictsOnly, QIcon *fileIcon, QIcon *folderIcon); diff --git a/src/pch.h b/src/pch.h index dd65efbe..af1a4ade 100644 --- a/src/pch.h +++ b/src/pch.h @@ -95,6 +95,7 @@ #include #include #include +#include #include #include #include diff --git a/src/settings.cpp b/src/settings.cpp index 06b4446a..40f4dd95 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -28,13 +28,88 @@ along with Mod Organizer. If not, see . using namespace MOBase; template -std::optional getOptional(const QSettings& s, const QString& name) +std::optional getOptional( + const QSettings& s, const QString& name, std::optional def={}) { if (s.contains(name)) { return s.value(name).value(); } - return {}; + return def; +} + + +QString widgetNameWithTopLevel(const QWidget* widget) +{ + QStringList components; + + auto* tl = widget->window(); + + if (tl == widget) { + // this is a top level widget, such as a dialog + components.push_back(widget->objectName()); + } else { + // this is a widget + const auto toplevelName = tl->objectName(); + if (!toplevelName.isEmpty()) { + components.push_back(toplevelName); + } + + const auto widgetName = widget->objectName(); + if (!widgetName.isEmpty()) { + components.push_back(widgetName); + } + } + + if (components.isEmpty()) { + // can't do much + return "unknown_widget"; + } + + return components.join("_"); +} + +QString widgetName(const QMainWindow* w) +{ + return w->objectName(); +} + +QString widgetName(const QHeaderView* w) +{ + return widgetNameWithTopLevel(w->parentWidget()); +} + +QString widgetName(const QWidget* w) +{ + return widgetNameWithTopLevel(w); +} + +template +QString geoSettingName(const Widget* widget) +{ + return "geometry/" + widgetName(widget) + "_geometry"; +} + +template +QString stateSettingName(const Widget* widget) +{ + return "geometry/" + widgetName(widget) + "_state"; +} + +template +QString visibilitySettingName(const Widget* widget) +{ + return "geometry/" + widgetName(widget) + "_visibility"; +} + +QString dockSettingName(const QDockWidget* dock) +{ + return "geometry/MainWindow_docks_" + dock->objectName() + "_size"; +} + +QString indexSettingName(const QWidget* widget) +{ + return widgetNameWithTopLevel(widget) + "_index"; } @@ -395,11 +470,6 @@ void Settings::setStyleName(const QString& name) m_Settings.setValue("Settings/style", name); } -std::optional Settings::getSelectedExecutable() const -{ - return getOptional(m_Settings, "selected_executable"); -} - std::optional Settings::getUseProxy() const { return getOptional(m_Settings, "Settings/use_proxy"); @@ -847,6 +917,23 @@ void Settings::setExecutables(const std::vector>& v) m_Settings.endArray(); } +std::optional Settings::getIndex(QComboBox* cb) const +{ + return getOptional(m_Settings, indexSettingName(cb)); +} + +void Settings::saveIndex(const QComboBox* cb) +{ + m_Settings.setValue(indexSettingName(cb), cb->currentIndex()); +} + +void Settings::restoreIndex(QComboBox* cb, std::optional def) const +{ + if (auto v=getOptional(m_Settings, indexSettingName(cb), def)) { + cb->setCurrentIndex(*v); + } +} + GeometrySettings& Settings::geometry() { return m_Geometry; @@ -885,70 +972,6 @@ void Settings::dump() const } -QString widgetNameWithTopLevel(const QWidget* widget) -{ - QStringList components; - - auto* tl = widget->window(); - - if (tl == widget) { - // this is a top level widget, such as a dialog - components.push_back(widget->objectName()); - } else { - // this is a widget - const auto toplevelName = tl->objectName(); - if (!toplevelName.isEmpty()) { - components.push_back(toplevelName); - } - - const auto widgetName = widget->objectName(); - if (!widgetName.isEmpty()) { - components.push_back(widgetName); - } - } - - if (components.isEmpty()) { - // can't do much - return "unknown_widget"; - } - - return components.join("_"); -} - -QString widgetName(const QMainWindow* w) -{ - return w->objectName(); -} - -QString widgetName(const QHeaderView* w) -{ - return widgetNameWithTopLevel(w->parentWidget()); -} - -QString widgetName(const QWidget* w) -{ - return widgetNameWithTopLevel(w); -} - -template -QString geoSettingName(const Widget* widget) -{ - return "geometry/" + widgetName(widget) + "_geometry"; -} - -template -QString stateSettingName(const Widget* widget) -{ - return "geometry/" + widgetName(widget) + "_state"; -} - -template -QString visibilitySettingName(const Widget* widget) -{ - return "geometry/" + widgetName(widget) + "_visibility"; -} - - GeometrySettings::GeometrySettings(QSettings& s) : m_Settings(s), m_Reset(false) { @@ -1037,12 +1060,7 @@ void GeometrySettings::saveVisibility(const QWidget* w) bool GeometrySettings::restoreVisibility(QWidget* w, std::optional def) const { - auto v = getOptional(m_Settings, visibilitySettingName(w)); - if (!v) { - v = def; - } - - if (v) { + if (auto v=getOptional(m_Settings, visibilitySettingName(w), def)) { w->setVisible(*v); return true; } @@ -1124,14 +1142,10 @@ void GeometrySettings::setModInfoTabOrder(const QString& names) m_Settings.setValue("mod_info_tab_order", names); } -std::optional GeometrySettings::getMainWindowMonitor() const -{ - return getOptional(m_Settings, "geometry/MainWindow_monitor"); -} - void GeometrySettings::centerOnMainWindowMonitor(QWidget* w) { - const auto monitor = getMainWindowMonitor(); + const auto monitor = getOptional(m_Settings, "geometry/MainWindow_monitor"); + QPoint center; if (monitor && QGuiApplication::screens().size() > *monitor) { @@ -1153,14 +1167,84 @@ void GeometrySettings::saveMainWindowMonitor(const QMainWindow* w) } } -void GeometrySettings::setDockSize(const QString& name, int size) +Qt::Orientation dockOrientation(const QMainWindow* mw, const QDockWidget* d) { - m_Settings.setValue("geometry/MainWindow_docks_" + name + "_size", size); + // docks in these areas are horizontal + const auto horizontalAreas = + Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea; + + if (mw->dockWidgetArea(const_cast(d)) & horizontalAreas) { + return Qt::Horizontal; + } else { + return Qt::Vertical; + } } -std::optional GeometrySettings::getDockSize(const QString& name) const +void GeometrySettings::saveDocks(const QMainWindow* mw) +{ + // this attempts to fix https://bugreports.qt.io/browse/QTBUG-46620 where dock + // sizes are not restored when the main window is maximized; it is used in + // MainWindow::readSettings() and MainWindow::storeSettings() + // + // there's also https://stackoverflow.com/questions/44005852, which has what + // seems to be a popular fix, but it breaks the restored size of the window + // by setting it to the desktop's resolution, so that doesn't work + // + // the only fix I could find is to remember the sizes of the docks and manually + // setting them back; saving is straightforward, but restoring is messy + // + // this also depends on the window being visible before the timer in restore() + // is fired and the timer must be processed by application.exec(); therefore, + // the splash screen _must_ be closed before readSettings() is called, because + // it has its own event loop, which seems to interfere with this + // + // all of this should become unnecessary when QTBUG-46620 is fixed + // + + // saves the size of each dock + for (const auto* dock : mw->findChildren()) { + int size = 0; + + // save the width for horizontal docks, or the height for vertical + if (dockOrientation(mw, dock) == Qt::Horizontal) { + size = dock->size().width(); + } else { + size = dock->size().height(); + } + + m_Settings.setValue(dockSettingName(dock), size); + } +} + +void GeometrySettings::restoreDocks(QMainWindow* mw) const { - return getOptional(m_Settings, "geometry/MainWindow_docks_" + name + "_size"); + struct DockInfo + { + QDockWidget* d; + int size = 0; + Qt::Orientation ori; + }; + + std::vector dockInfos; + + // for each dock + for (auto* dock : mw->findChildren()) { + if (auto size=getOptional(m_Settings, dockSettingName(dock))) { + // remember this dock, its size and orientation + dockInfos.push_back({dock, *size, dockOrientation(mw, dock)}); + } + } + + // the main window must have had time to process the settings from + // readSettings() or it seems to override whatever is set here + // + // some people said a single processEvents() call is enough, but it doesn't + // look like it + QTimer::singleShot(5, [=] { + for (const auto& info : dockInfos) { + mw->resizeDocks({info.d}, {info.size}, info.ori); + } + }); } diff --git a/src/settings.h b/src/settings.h index 072b4066..1b6616a0 100644 --- a/src/settings.h +++ b/src/settings.h @@ -70,25 +70,21 @@ public: void saveState(const QSplitter* splitter); bool restoreState(QSplitter* splitter) const; - void saveVisibility(const QWidget* w); - bool restoreVisibility(QWidget* w, std::optional defaultValue={}) const; - + bool restoreVisibility(QWidget* w, std::optional def={}) const; void saveToolbars(const QMainWindow* w); void restoreToolbars(QMainWindow* w) const; + void saveDocks(const QMainWindow* w); + void restoreDocks(QMainWindow* w) const; + QStringList getModInfoTabOrder() const; void setModInfoTabOrder(const QString& names); - std::optional getMainWindowMonitor() const; void centerOnMainWindowMonitor(QWidget* w); void saveMainWindowMonitor(const QMainWindow* w); - void setDockSize(const QString& name, int size); - - std::optional getDockSize(const QString& name) const; - private: QSettings& m_Settings; bool m_Reset; @@ -206,7 +202,6 @@ public: std::optional getStyleName() const; void setStyleName(const QString& name); - std::optional getSelectedExecutable() const; std::optional getUseProxy() const; std::optional getVersion() const; @@ -222,6 +217,11 @@ public: std::vector> getExecutables() const; void setExecutables(const std::vector>& v); + + std::optional getIndex(QComboBox* cb) const; + void saveIndex(const QComboBox* cb); + void restoreIndex(QComboBox* cb, std::optional def={}) const; + GeometrySettings& geometry(); const GeometrySettings& geometry() const; -- cgit v1.3.1 From d9cb15f1d117b91f0d75c1b7702696f7da93d3d2 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sat, 17 Aug 2019 07:42:37 -0400 Subject: put endorsement state and first start in settings --- src/mainwindow.cpp | 54 +++++++++++++++++++++++++++++++++++++----------------- src/settings.cpp | 18 ++++++++++++++++++ src/settings.h | 11 +++++++++++ 3 files changed, 66 insertions(+), 17 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index bce92e48..f0e2fe56 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -1225,7 +1225,7 @@ void MainWindow::showEvent(QShowEvent *event) hookUpWindowTutorials(); - if (m_OrganizerCore.settings().directInterface().value("first_start", true).toBool()) { + if (m_OrganizerCore.settings().getFirstStart()) { QString firstStepsTutorial = ToQString(AppConfig::firstStepsTutorial()); if (TutorialManager::instance().hasTutorial(firstStepsTutorial)) { if (QMessageBox::question(this, tr("Show tutorial?"), @@ -1244,7 +1244,7 @@ void MainWindow::showEvent(QShowEvent *event) QObject::tr("Please use \"Help\" from the toolbar to get usage instructions to all elements")); } - m_OrganizerCore.settings().directInterface().setValue("first_start", false); + m_OrganizerCore.settings().setFirstStart(false); } m_OrganizerCore.settings().restoreIndex(ui->groupCombo); @@ -5567,22 +5567,42 @@ void MainWindow::modUpdateCheck(std::multimap IDs) void MainWindow::toggleMO2EndorseState() { - if (Settings::instance().endorsementIntegration()) { - ui->actionEndorseMO->setVisible(true); - if (Settings::instance().directInterface().contains("endorse_state")) { - ui->actionEndorseMO->menu()->setEnabled(false); - if (Settings::instance().directInterface().value("endorse_state").toString() == "Endorsed") { - ui->actionEndorseMO->setToolTip(tr("Thank you for endorsing MO2! :)")); - ui->actionEndorseMO->setStatusTip(tr("Thank you for endorsing MO2! :)")); - } else if (Settings::instance().directInterface().value("endorse_state").toString() == "Abstained") { - ui->actionEndorseMO->setToolTip(tr("Please reconsider endorsing MO2 on Nexus!")); - ui->actionEndorseMO->setStatusTip(tr("Please reconsider endorsing MO2 on Nexus!")); - } - } else { - ui->actionEndorseMO->menu()->setEnabled(true); - } - } else + const auto& s = m_OrganizerCore.settings(); + + if (!s.endorsementIntegration()) { ui->actionEndorseMO->setVisible(false); + return; + } + + ui->actionEndorseMO->setVisible(true); + + bool enabled = false; + QString text; + + switch (s.endorsementState()) + { + case EndorsementState::Accepted: + { + text = tr("Thank you for endorsing MO2! :)"); + break; + } + + case EndorsementState::Refused: + { + text = tr("Please reconsider endorsing MO2 on Nexus!"); + break; + } + + case EndorsementState::NoDecision: + { + enabled = true; + break; + } + } + + ui->actionEndorseMO->menu()->setEnabled(enabled); + ui->actionEndorseMO->setToolTip(text); + ui->actionEndorseMO->setStatusTip(text); } void MainWindow::nxmEndorsementsAvailable(QVariant userData, QVariant resultData, int) diff --git a/src/settings.cpp b/src/settings.cpp index 40f4dd95..882984f3 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -489,6 +489,11 @@ bool Settings::getFirstStart() const return getOptional(m_Settings, "first_start").value_or(true); } +void Settings::setFirstStart(bool b) +{ + m_Settings.setValue("first_start", b); +} + std::optional Settings::getPreviousSeparatorColor() const { const auto c = getOptional(m_Settings, "previousSeparatorColor"); @@ -689,6 +694,19 @@ bool Settings::endorsementIntegration() const return m_Settings.value("Settings/endorsement_integration", true).toBool(); } +EndorsementState Settings::endorsementState() const +{ + const auto v = getOptional(m_Settings, "endorse_state"); + + if (!v) { + return EndorsementState::NoDecision; + } else if (*v == "Abstained") { + return EndorsementState::Refused; + } else { + return EndorsementState::Accepted; + } +} + bool Settings::hideAPICounter() const { return m_Settings.value("Settings/hide_api_counter", false).toBool(); diff --git a/src/settings.h b/src/settings.h index 1b6616a0..167c74fc 100644 --- a/src/settings.h +++ b/src/settings.h @@ -91,6 +91,13 @@ private: }; +enum class EndorsementState +{ + Accepted = 1, + Refused, + NoDecision +}; + /** * manages the settings for Mod Organizer. The settings are not cached * inside the class but read/written directly from/to disc @@ -205,7 +212,9 @@ public: std::optional getUseProxy() const; std::optional getVersion() const; + bool getFirstStart() const; + void setFirstStart(bool b); std::optional getPreviousSeparatorColor() const; void setPreviousSeparatorColor(const QColor& c) const; @@ -354,6 +363,8 @@ public: */ bool endorsementIntegration() const; + EndorsementState endorsementState() const; + /** * @return true if the API counter should be hidden */ -- cgit v1.3.1 From 7cc5f220520ab19940462fb6d2f660d8b7e2d600 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sat, 17 Aug 2019 08:27:13 -0400 Subject: put tutorials in the settings finished moving endorsement to settings --- src/mainwindow.cpp | 52 ++++++++++++++++++++++++++++++++++++++++----------- src/settings.cpp | 55 +++++++++++++++++++++++++++++++++++++++++++++++++----- src/settings.h | 8 ++++++++ 3 files changed, 99 insertions(+), 16 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index f0e2fe56..6e77f507 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -1194,7 +1194,7 @@ void MainWindow::hookUpWindowTutorials() QString firstLine = QString::fromUtf8(file.readLine()); if (firstLine.startsWith("//WIN")) { QString windowName = firstLine.mid(6).trimmed(); - if (!m_OrganizerCore.settings().directInterface().value("CompletedWindowTutorials/" + windowName, false).toBool()) { + if (!m_OrganizerCore.settings().isTutorialCompleted(windowName)) { TutorialManager::instance().activateTutorial(windowName, fileName); } } @@ -3017,7 +3017,7 @@ void MainWindow::untrack_clicked() void MainWindow::windowTutorialFinished(const QString &windowName) { - m_OrganizerCore.settings().directInterface().setValue(QString("CompletedWindowTutorials/") + windowName, true); + m_OrganizerCore.settings().setTutorialCompleted(windowName); } void MainWindow::overwriteClosed(int) @@ -5636,7 +5636,9 @@ void MainWindow::nxmEndorsementsAvailable(QVariant userData, QVariant resultData if (Settings::instance().endorsementIntegration()) { if (result->first == "skyrimspecialedition" && result->second.first == gamePlugin->nexusModOrganizerID()) { - Settings::instance().directInterface().setValue("endorse_state", result->second.second); + m_OrganizerCore.settings().setEndorsementState( + endorsementStateFromString(result->second.second)); + toggleMO2EndorseState(); } } @@ -5649,7 +5651,9 @@ void MainWindow::nxmEndorsementsAvailable(QVariant userData, QVariant resultData auto iter = sorted.equal_range(gamePlugin->gameNexusName()); for (auto result = iter.first; result != iter.second; ++result) { if (result->second.first == gamePlugin->nexusModOrganizerID()) { - Settings::instance().directInterface().setValue("endorse_state", result->second.second); + m_OrganizerCore.settings().setEndorsementState( + endorsementStateFromString(result->second.second)); + toggleMO2EndorseState(); break; } @@ -5829,15 +5833,41 @@ void MainWindow::nxmModInfoAvailable(QString gameName, int modID, QVariant userD void MainWindow::nxmEndorsementToggled(QString, int, QVariant, QVariant resultData, int) { - QMap results = resultData.toMap(); - if (results["status"].toString().compare("Endorsed") == 0) { - QMessageBox::information(this, tr("Thank you!"), tr("Thank you for your endorsement!")); - Settings::instance().directInterface().setValue("endorse_state", "Endorsed"); - } else if (results["status"].toString().compare("Abstained") == 0) { - QMessageBox::information(this, tr("Okay."), tr("This mod will not be endorsed and will no longer ask you to endorse.")); - Settings::instance().directInterface().setValue("endorse_state", "Abstained"); + const QMap results = resultData.toMap(); + + auto itor = results.find("status"); + if (itor == results.end()) { + log::error("endorsement response has no status"); + return; + } + + const auto s = endorsementStateFromString(itor->toString()); + + switch (s) + { + case EndorsementState::Accepted: + { + QMessageBox::information(this, tr("Thank you!"), tr("Thank you for your endorsement!")); + break; + } + + case EndorsementState::Refused: + { + // don't spam message boxes if the user doesn't want to endorse + log::info("Mod Organizer will not be endorsed and will no longer ask you to endorse."); + break; + } + + case EndorsementState::NoDecision: + { + log::error("bad status '{}' in endorsement response", itor->toString()); + return; + } } + + m_OrganizerCore.settings().setEndorsementState(s); toggleMO2EndorseState(); + if (!disconnect(sender(), SIGNAL(nxmEndorsementToggled(QString, int, QVariant, QVariant, int)), this, SLOT(nxmEndorsementToggled(QString, int, QVariant, QVariant, int)))) { log::error("failed to disconnect endorsement slot"); diff --git a/src/settings.cpp b/src/settings.cpp index 882984f3..af32a082 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -39,6 +39,34 @@ std::optional getOptional( } +EndorsementState endorsementStateFromString(const QString& s) +{ + if (s == "Endorsed") { + return EndorsementState::Accepted; + } else if (s == "Abstained") { + return EndorsementState::Refused; + } else { + return EndorsementState::NoDecision; + } +} + +QString toString(EndorsementState s) +{ + switch (s) + { + case EndorsementState::Accepted: + return "Endorsed"; + + case EndorsementState::Refused: + return "Abstained"; + + case EndorsementState::NoDecision: // fall-through + default: + return {}; + } +} + + QString widgetNameWithTopLevel(const QWidget* widget) { QStringList components; @@ -697,13 +725,17 @@ bool Settings::endorsementIntegration() const EndorsementState Settings::endorsementState() const { const auto v = getOptional(m_Settings, "endorse_state"); + return endorsementStateFromString(v.value_or("")); +} - if (!v) { - return EndorsementState::NoDecision; - } else if (*v == "Abstained") { - return EndorsementState::Refused; +void Settings::setEndorsementState(EndorsementState s) +{ + const auto v = toString(s); + + if (v.isEmpty()) { + m_Settings.remove("endorse_state"); } else { - return EndorsementState::Accepted; + m_Settings.setValue("endorse_state", v); } } @@ -935,6 +967,19 @@ void Settings::setExecutables(const std::vector>& v) m_Settings.endArray(); } +bool Settings::isTutorialCompleted(const QString& windowName) const +{ + const auto v = getOptional( + m_Settings, "CompletedWindowTutorials/" + windowName); + + return v.value_or(false); +} + +void Settings::setTutorialCompleted(const QString& windowName, bool b) +{ + m_Settings.setValue("CompletedWindowTutorials/" + windowName, true); +} + std::optional Settings::getIndex(QComboBox* cb) const { return getOptional(m_Settings, indexSettingName(cb)); diff --git a/src/settings.h b/src/settings.h index 167c74fc..5044af98 100644 --- a/src/settings.h +++ b/src/settings.h @@ -98,6 +98,10 @@ enum class EndorsementState NoDecision }; +EndorsementState endorsementStateFromString(const QString& s); +QString toString(EndorsementState s); + + /** * manages the settings for Mod Organizer. The settings are not cached * inside the class but read/written directly from/to disc @@ -226,6 +230,8 @@ public: std::vector> getExecutables() const; void setExecutables(const std::vector>& v); + bool isTutorialCompleted(const QString& windowName) const; + void setTutorialCompleted(const QString& windowName, bool b=true); std::optional getIndex(QComboBox* cb) const; void saveIndex(const QComboBox* cb); @@ -364,6 +370,8 @@ public: bool endorsementIntegration() const; EndorsementState endorsementState() const; + void setEndorsementState(EndorsementState s); + void setEndorsementState(const QString& s); /** * @return true if the API counter should be hidden -- cgit v1.3.1 From dfa15218f33ad06a6e868e8e5f1022026b6530a9 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sat, 17 Aug 2019 12:42:27 -0400 Subject: passes callbacks to QuestionBoxMemory so it doesn't access the ini directly fixed selected executable being empty after closing the edit dialog put backup_install inside Settings --- src/installationmanager.cpp | 13 ++++++--- src/mainwindow.cpp | 6 ++-- src/organizercore.cpp | 2 -- src/settings.cpp | 68 +++++++++++++++++++++++++++++++++++++++++++ src/settings.h | 16 ++++++++++ src/settingsdialoggeneral.cpp | 2 +- 6 files changed, 97 insertions(+), 10 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/installationmanager.cpp b/src/installationmanager.cpp index 89d0079f..522489e4 100644 --- a/src/installationmanager.cpp +++ b/src/installationmanager.cpp @@ -476,13 +476,18 @@ QString InstallationManager::generateBackupName(const QString &directoryName) co bool InstallationManager::testOverwrite(GuessedValue &modName, bool *merge) const { QString targetDirectory = QDir::fromNativeSeparators(m_ModsDirectory + "\\" + modName); + while (QDir(targetDirectory).exists()) { Settings &settings(Settings::instance()); - bool backup = settings.directInterface().value("backup_install", false).toBool(); - QueryOverwriteDialog overwriteDialog(m_ParentWidget, - backup ? QueryOverwriteDialog::BACKUP_YES : QueryOverwriteDialog::BACKUP_NO); + + const bool backup = settings.keepBackupOnInstall(); + QueryOverwriteDialog overwriteDialog( + m_ParentWidget, + backup ? QueryOverwriteDialog::BACKUP_YES : QueryOverwriteDialog::BACKUP_NO); + if (overwriteDialog.exec()) { - settings.directInterface().setValue("backup_install", overwriteDialog.backup()); + settings.setKeepBackupOnInstall(overwriteDialog.backup()); + if (overwriteDialog.backup()) { QString backupDirectory = generateBackupName(targetDirectory); if (!copyDir(targetDirectory, backupDirectory, false)) { diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 6e77f507..2ce6f9d9 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -2340,8 +2340,6 @@ bool MainWindow::modifyExecutablesDialog() bool result = false; try { - const auto oldExecutables = *m_OrganizerCore.executablesList(); - EditExecutablesDialog dialog(m_OrganizerCore, this); result = (dialog.exec() == QDialog::Accepted); @@ -2361,7 +2359,9 @@ void MainWindow::on_executablesListBox_currentIndexChanged(int index) return; } - const int previousIndex = m_OldExecutableIndex; + const int previousIndex = + (m_OldExecutableIndex > 0 ? m_OldExecutableIndex : 1); + m_OldExecutableIndex = index; if (index == 0) { diff --git a/src/organizercore.cpp b/src/organizercore.cpp index a2b0fd69..233a631e 100644 --- a/src/organizercore.cpp +++ b/src/organizercore.cpp @@ -280,8 +280,6 @@ OrganizerCore::OrganizerCore(Settings &settings) NexusInterface::instance(m_PluginContainer)->setCacheDirectory(m_Settings.getCacheDirectory()); - MOBase::QuestionBoxMemory::init(m_Settings.directInterface().fileName()); - m_InstallationManager.setModsDirectory(m_Settings.getModDirectory()); m_InstallationManager.setDownloadDirectory(m_Settings.getDownloadDirectory()); diff --git a/src/settings.cpp b/src/settings.cpp index af32a082..9001ac65 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -151,10 +151,16 @@ Settings::Settings(const QString& path) } else { s_Instance = this; } + + MOBase::QuestionBoxMemory::setCallbacks( + [this](auto&& w, auto&& f){ return getQuestionButton(w, f); }, + [this](auto&& w, auto&& b){ setQuestionWindowButton(w, b); }, + [this](auto&& w, auto&& f, auto&& b){ setQuestionFileButton(w, f, b); }); } Settings::~Settings() { + MOBase::QuestionBoxMemory::setCallbacks({}, {}, {}); s_Instance = nullptr; } @@ -980,6 +986,68 @@ void Settings::setTutorialCompleted(const QString& windowName, bool b) m_Settings.setValue("CompletedWindowTutorials/" + windowName, true); } +bool Settings::keepBackupOnInstall() const +{ + return getOptional(m_Settings, "backup_install").value_or(false); +} + +void Settings::setKeepBackupOnInstall(bool b) +{ + m_Settings.setValue("backup_install", b); +} + +QuestionBoxMemory::Button Settings::getQuestionButton( + const QString& windowName, const QString& filename) const +{ + const QString windowSetting("DialogChoices/" + windowName); + + if (!filename.isEmpty()) { + const auto fileSetting = windowSetting + "/" + filename; + + if (auto v=getOptional(m_Settings, fileSetting)) { + return static_cast(*v); + } + } + + if (auto v=getOptional(m_Settings, windowSetting)) { + return static_cast(*v); + } + + return QuestionBoxMemory::NoButton; +} + +void Settings::setQuestionWindowButton( + const QString& windowName, QuestionBoxMemory::Button button) +{ + const QString settingName("DialogChoices/" + windowName); + + if (button == QuestionBoxMemory::NoButton) { + m_Settings.remove(settingName); + } else { + m_Settings.setValue(settingName, static_cast(button)); + } +} + +void Settings::setQuestionFileButton( + const QString& windowName, const QString& filename, + QuestionBoxMemory::Button button) +{ + const QString settingName("DialogChoices/" + windowName + "/" + filename); + + if (button == QuestionBoxMemory::NoButton) { + m_Settings.remove(settingName); + } else { + m_Settings.setValue(settingName, static_cast(button)); + } +} + +void Settings::resetQuestionButtons() +{ + m_Settings.beginGroup("DialogChoices"); + m_Settings.remove(""); + m_Settings.endGroup(); +} + std::optional Settings::getIndex(QComboBox* cb) const { return getOptional(m_Settings, indexSettingName(cb)); diff --git a/src/settings.h b/src/settings.h index 5044af98..d46c358c 100644 --- a/src/settings.h +++ b/src/settings.h @@ -21,6 +21,7 @@ along with Mod Organizer. If not, see . #define SETTINGS_H #include "loadmechanism.h" +#include #include namespace MOBase { @@ -233,6 +234,21 @@ public: bool isTutorialCompleted(const QString& windowName) const; void setTutorialCompleted(const QString& windowName, bool b=true); + bool keepBackupOnInstall() const; + void setKeepBackupOnInstall(bool b); + + MOBase::QuestionBoxMemory::Button getQuestionButton( + const QString& windowName, const QString& filename) const; + + void setQuestionWindowButton( + const QString& windowName, MOBase::QuestionBoxMemory::Button button); + + void setQuestionFileButton( + const QString& windowName, const QString& filename, + MOBase::QuestionBoxMemory::Button choice); + + void resetQuestionButtons(); + std::optional getIndex(QComboBox* cb) const; void saveIndex(const QComboBox* cb); void restoreIndex(QComboBox* cb, std::optional def={}) const; diff --git a/src/settingsdialoggeneral.cpp b/src/settingsdialoggeneral.cpp index 324dc4f4..fda50220 100644 --- a/src/settingsdialoggeneral.cpp +++ b/src/settingsdialoggeneral.cpp @@ -141,7 +141,7 @@ void GeneralSettingsTab::addStyles() void GeneralSettingsTab::resetDialogs() { - QuestionBoxMemory::resetDialogs(); + m_parent->resetQuestionButtons(); } void GeneralSettingsTab::setButtonColor(QPushButton *button, const QColor &color) -- cgit v1.3.1 From 0f712305c840bc509fa8f00eebf2a2a4bbf28bfd Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sat, 24 Aug 2019 13:04:10 -0400 Subject: added settings for QTabWidget, checkable QAbstractButton and ExpanderWidget removed directInterface() from mod info conflicts --- src/expanderwidget.cpp | 27 +++++++++++ src/expanderwidget.h | 5 ++ src/modinfodialogconflicts.cpp | 102 +++++++++-------------------------------- src/settings.cpp | 74 +++++++++++++++++++++++++++++- src/settings.h | 14 +++++- 5 files changed, 140 insertions(+), 82 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/expanderwidget.cpp b/src/expanderwidget.cpp index 2f47da5b..a9d045a5 100644 --- a/src/expanderwidget.cpp +++ b/src/expanderwidget.cpp @@ -52,3 +52,30 @@ bool ExpanderWidget::opened() const { return opened_; } + +QByteArray ExpanderWidget::saveState() const +{ + QByteArray result; + QDataStream stream(&result, QIODevice::WriteOnly); + + stream << opened(); + + return result; +} + +void ExpanderWidget::restoreState(const QByteArray& a) +{ + QDataStream stream(a); + + bool opened = false; + stream >> opened; + + if (stream.status() == QDataStream::Ok) { + toggle(opened); + } +} + +QToolButton* ExpanderWidget::button() const +{ + return m_button; +} diff --git a/src/expanderwidget.h b/src/expanderwidget.h index da3eb9d6..99b2d303 100644 --- a/src/expanderwidget.h +++ b/src/expanderwidget.h @@ -37,6 +37,11 @@ public: **/ bool opened() const; + QByteArray saveState() const; + void restoreState(const QByteArray& a); + + QToolButton* button() const; + private: QToolButton* m_button; QWidget* m_content; diff --git a/src/modinfodialogconflicts.cpp b/src/modinfodialogconflicts.cpp index 03b490a2..7840269d 100644 --- a/src/modinfodialogconflicts.cpp +++ b/src/modinfodialogconflicts.cpp @@ -409,8 +409,7 @@ void ConflictsTab::clear() void ConflictsTab::saveState(Settings& s) { - s.directInterface().setValue( - "mod_info_conflicts_tab", ui->tabConflictsTabs->currentIndex()); + s.saveIndex(ui->tabConflictsTabs); m_general.saveState(s); m_advanced.saveState(s); @@ -418,8 +417,7 @@ void ConflictsTab::saveState(Settings& s) void ConflictsTab::restoreState(const Settings& s) { - ui->tabConflictsTabs->setCurrentIndex( - s.directInterface().value("mod_info_conflicts_tab", 0).toInt()); + s.restoreIndex(ui->tabConflictsTabs, 0); m_general.restoreState(s); m_advanced.restoreState(s); @@ -817,55 +815,22 @@ void GeneralConflictsTab::clear() void GeneralConflictsTab::saveState(Settings& s) { - QByteArray result; - QDataStream stream(&result, QIODevice::WriteOnly); - - stream - << m_expanders.overwrite.opened() - << m_expanders.overwritten.opened() - << m_expanders.nonconflict.opened(); - - s.directInterface().setValue( - "mod_info_conflicts_general_expanders", result); - - s.directInterface().setValue( - "mod_info_conflicts_general_overwrite", - ui->overwriteTree->header()->saveState()); - - s.directInterface().setValue( - "mod_info_conflicts_general_noconflict", - ui->noConflictTree->header()->saveState()); - - s.directInterface().setValue( - "mod_info_conflicts_general_overwritten", - ui->overwrittenTree->header()->saveState()); + s.geometry().saveState(&m_expanders.overwrite); + s.geometry().saveState(&m_expanders.overwritten); + s.geometry().saveState(&m_expanders.nonconflict); + s.geometry().saveState(ui->overwriteTree->header()); + s.geometry().saveState(ui->noConflictTree->header()); + s.geometry().saveState(ui->overwrittenTree->header()); } void GeneralConflictsTab::restoreState(const Settings& s) { - QDataStream stream(s.directInterface() - .value("mod_info_conflicts_general_expanders").toByteArray()); - - bool overwriteExpanded = false; - bool overwrittenExpanded = false; - bool noConflictExpanded = false; - - stream >> overwriteExpanded >> overwrittenExpanded >> noConflictExpanded; - - if (stream.status() == QDataStream::Ok) { - m_expanders.overwrite.toggle(overwriteExpanded); - m_expanders.overwritten.toggle(overwrittenExpanded); - m_expanders.nonconflict.toggle(noConflictExpanded); - } - - ui->overwriteTree->header()->restoreState(s.directInterface() - .value("mod_info_conflicts_general_overwrite").toByteArray()); - - ui->noConflictTree->header()->restoreState(s.directInterface() - .value("mod_info_conflicts_general_noconflict").toByteArray()); - - ui->overwrittenTree->header()->restoreState(s.directInterface() - .value("mod_info_conflicts_general_overwritten").toByteArray()); + s.geometry().restoreState(&m_expanders.overwrite); + s.geometry().restoreState(&m_expanders.overwritten); + s.geometry().restoreState(&m_expanders.nonconflict); + s.geometry().restoreState(ui->overwriteTree->header()); + s.geometry().restoreState(ui->noConflictTree->header()); + s.geometry().restoreState(ui->overwrittenTree->header()); } bool GeneralConflictsTab::update() @@ -1048,41 +1013,18 @@ void AdvancedConflictsTab::clear() void AdvancedConflictsTab::saveState(Settings& s) { - s.directInterface().setValue( - "mod_info_conflicts_advanced_list", - ui->conflictsAdvancedList->header()->saveState()); - - QByteArray result; - QDataStream stream(&result, QIODevice::WriteOnly); - - stream - << ui->conflictsAdvancedShowNoConflict->isChecked() - << ui->conflictsAdvancedShowAll->isChecked() - << ui->conflictsAdvancedShowNearest->isChecked(); - - s.directInterface().setValue( - "mod_info_conflicts_advanced_options", result); + s.geometry().saveState(ui->conflictsAdvancedList->header()); + s.saveChecked(ui->conflictsAdvancedShowNoConflict); + s.saveChecked(ui->conflictsAdvancedShowAll); + s.saveChecked(ui->conflictsAdvancedShowNearest); } void AdvancedConflictsTab::restoreState(const Settings& s) { - ui->conflictsAdvancedList->header()->restoreState( - s.directInterface().value("mod_info_conflicts_advanced_list").toByteArray()); - - QDataStream stream(s.directInterface() - .value("mod_info_conflicts_advanced_options").toByteArray()); - - bool noConflictChecked = false; - bool showAllChecked = false; - bool showNearestChecked = false; - - stream >> noConflictChecked >> showAllChecked >> showNearestChecked; - - if (stream.status() == QDataStream::Ok) { - ui->conflictsAdvancedShowNoConflict->setChecked(noConflictChecked); - ui->conflictsAdvancedShowAll->setChecked(showAllChecked); - ui->conflictsAdvancedShowNearest->setChecked(showNearestChecked); - } + s.geometry().restoreState(ui->conflictsAdvancedList->header()); + s.restoreChecked(ui->conflictsAdvancedShowNoConflict); + s.restoreChecked(ui->conflictsAdvancedShowAll); + s.restoreChecked(ui->conflictsAdvancedShowNearest); } void AdvancedConflictsTab::update() diff --git a/src/settings.cpp b/src/settings.cpp index 9001ac65..844ee81e 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -21,6 +21,7 @@ along with Mod Organizer. If not, see . #include "serverinfo.h" #include "executableslist.h" #include "appconfig.h" +#include "expanderwidget.h" #include #include #include @@ -107,6 +108,11 @@ QString widgetName(const QHeaderView* w) return widgetNameWithTopLevel(w->parentWidget()); } +QString widgetName(const ExpanderWidget* w) +{ + return widgetNameWithTopLevel(w->button()); +} + QString widgetName(const QWidget* w) { return widgetNameWithTopLevel(w); @@ -140,6 +146,19 @@ QString indexSettingName(const QWidget* widget) return widgetNameWithTopLevel(widget) + "_index"; } +QString checkedSettingName(const QAbstractButton* b) +{ + return widgetNameWithTopLevel(b) + "_checked"; +} + +void warnIfNotCheckable(const QAbstractButton* b) +{ + if (!b->isCheckable()) { + log::warn( + "button '{}' used in the settings as a checkbox or radio button " + "but is not checkable", b->objectName()); + } +} Settings *Settings::s_Instance = nullptr; @@ -1048,7 +1067,7 @@ void Settings::resetQuestionButtons() m_Settings.endGroup(); } -std::optional Settings::getIndex(QComboBox* cb) const +std::optional Settings::getIndex(const QComboBox* cb) const { return getOptional(m_Settings, indexSettingName(cb)); } @@ -1065,6 +1084,44 @@ void Settings::restoreIndex(QComboBox* cb, std::optional def) const } } +std::optional Settings::getIndex(const QTabWidget* w) const +{ + return getOptional(m_Settings, indexSettingName(w)); +} + +void Settings::saveIndex(const QTabWidget* w) +{ + m_Settings.setValue(indexSettingName(w), w->currentIndex()); +} + +void Settings::restoreIndex(QTabWidget* w, std::optional def) const +{ + if (auto v=getOptional(m_Settings, indexSettingName(w), def)) { + w->setCurrentIndex(*v); + } +} + +std::optional Settings::getChecked(const QAbstractButton* w) const +{ + warnIfNotCheckable(w); + return getOptional(m_Settings, checkedSettingName(w)); +} + +void Settings::saveChecked(const QAbstractButton* w) +{ + warnIfNotCheckable(w); + m_Settings.setValue(checkedSettingName(w), w->isChecked()); +} + +void Settings::restoreChecked(QAbstractButton* w, std::optional def) const +{ + warnIfNotCheckable(w); + + if (auto v=getOptional(m_Settings, checkedSettingName(w), def)) { + w->setChecked(*v); + } +} + GeometrySettings& Settings::geometry() { return m_Geometry; @@ -1184,6 +1241,21 @@ bool GeometrySettings::restoreState(QSplitter* w) const return false; } +void GeometrySettings::saveState(const ExpanderWidget* expander) +{ + m_Settings.setValue(stateSettingName(expander), expander->saveState()); +} + +bool GeometrySettings::restoreState(ExpanderWidget* expander) const +{ + if (auto v=getOptional(m_Settings, stateSettingName(expander))) { + expander->restoreState(*v); + return true; + } + + return false; +} + void GeometrySettings::saveVisibility(const QWidget* w) { m_Settings.setValue(visibilitySettingName(w), w->isVisible()); diff --git a/src/settings.h b/src/settings.h index d46c358c..b25af15f 100644 --- a/src/settings.h +++ b/src/settings.h @@ -34,6 +34,7 @@ class QSplitter; class PluginContainer; struct ServerInfo; class Settings; +class ExpanderWidget; class GeometrySaver { @@ -71,6 +72,9 @@ public: void saveState(const QSplitter* splitter); bool restoreState(QSplitter* splitter) const; + void saveState(const ExpanderWidget* expander); + bool restoreState(ExpanderWidget* expander) const; + void saveVisibility(const QWidget* w); bool restoreVisibility(QWidget* w, std::optional def={}) const; @@ -249,10 +253,18 @@ public: void resetQuestionButtons(); - std::optional getIndex(QComboBox* cb) const; + std::optional getIndex(const QComboBox* cb) const; void saveIndex(const QComboBox* cb); void restoreIndex(QComboBox* cb, std::optional def={}) const; + std::optional getIndex(const QTabWidget* w) const; + void saveIndex(const QTabWidget* w); + void restoreIndex(QTabWidget* w, std::optional def={}) const; + + std::optional getChecked(const QAbstractButton* w) const; + void saveChecked(const QAbstractButton* w); + void restoreChecked(QAbstractButton* w, std::optional def={}) const; + GeometrySettings& geometry(); const GeometrySettings& geometry() const; -- cgit v1.3.1 From 4f1b15f0a1b2e6cbca4b420608d81570af489067 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sat, 24 Aug 2019 16:07:07 -0400 Subject: changed crash dump type to use enum instead of int added ColorSettings settings dialog general and diag tabs don't use qsettings anymore removed logging of setting changes, will be added back to Settings class --- src/modinfo.cpp | 1 - src/modlist.cpp | 10 +-- src/organizercore.cpp | 6 +- src/organizercore.h | 4 +- src/pluginlist.cpp | 2 +- src/settings.cpp | 160 ++++++++++++++++++++++++++++++-------- src/settings.h | 70 ++++++++++------- src/settingsdialog.cpp | 26 +------ src/settingsdialog.ui | 20 ----- src/settingsdialogdiagnostics.cpp | 38 ++++++++- src/settingsdialogdiagnostics.h | 1 + src/settingsdialoggeneral.cpp | 66 ++++++++-------- src/usvfsconnector.cpp | 7 +- src/usvfsconnector.h | 2 +- 14 files changed, 259 insertions(+), 154 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/modinfo.cpp b/src/modinfo.cpp index 5a05e7ca..e3daa4fd 100644 --- a/src/modinfo.cpp +++ b/src/modinfo.cpp @@ -42,7 +42,6 @@ along with Mod Organizer. If not, see . #include #include #include -#include using namespace MOBase; using namespace MOShared; diff --git a/src/modlist.cpp b/src/modlist.cpp index c591c49b..94b4a387 100644 --- a/src/modlist.cpp +++ b/src/modlist.cpp @@ -416,15 +416,15 @@ QVariant ModList::data(const QModelIndex &modelIndex, int role) const bool archiveOverwritten = m_ArchiveOverwritten.find(modIndex) != m_ArchiveOverwritten.end(); bool archiveLooseOverwritten = m_ArchiveLooseOverwritten.find(modIndex) != m_ArchiveLooseOverwritten.end(); if (modInfo->getHighlight() & ModInfo::HIGHLIGHT_PLUGIN) { - return Settings::instance().modlistContainsPluginColor(); + return Settings::instance().colors().modlistContainsPlugin(); } else if (overwritten || archiveLooseOverwritten) { - return Settings::instance().modlistOverwritingLooseColor(); + return Settings::instance().colors().modlistOverwritingLoose(); } else if (overwrite || archiveLooseOverwrite) { - return Settings::instance().modlistOverwrittenLooseColor(); + return Settings::instance().colors().modlistOverwrittenLoose(); } else if (archiveOverwritten) { - return Settings::instance().modlistOverwritingArchiveColor(); + return Settings::instance().colors().modlistOverwritingArchive(); } else if (archiveOverwrite) { - return Settings::instance().modlistOverwrittenArchiveColor(); + return Settings::instance().colors().modlistOverwrittenArchive(); } else if (modInfo->hasFlag(ModInfo::FLAG_SEPARATOR) && modInfo->getColor().isValid() && ((role != ViewMarkingScrollBar::DEFAULT_ROLE) diff --git a/src/organizercore.cpp b/src/organizercore.cpp index 73d0abac..5a8ee4c2 100644 --- a/src/organizercore.cpp +++ b/src/organizercore.cpp @@ -667,7 +667,7 @@ void OrganizerCore::prepareVFS() } void OrganizerCore::updateVFSParams( - log::Levels logLevel, int crashDumpsType, QString executableBlacklist) + log::Levels logLevel, CrashDumpsType crashDumpsType, QString executableBlacklist) { setGlobalCrashDumpsType(crashDumpsType); m_USVFS.updateParams(logLevel, crashDumpsType, executableBlacklist); @@ -692,8 +692,8 @@ bool OrganizerCore::cycleDiagnostics() { } //static -void OrganizerCore::setGlobalCrashDumpsType(int crashDumpsType) { - m_globalCrashDumpsType = ::crashDumpsType(crashDumpsType); +void OrganizerCore::setGlobalCrashDumpsType(CrashDumpsType type) { + m_globalCrashDumpsType = type; } //static diff --git a/src/organizercore.h b/src/organizercore.h index 4bcfe745..a14d79a9 100644 --- a/src/organizercore.h +++ b/src/organizercore.h @@ -193,7 +193,7 @@ public: void prepareVFS(); void updateVFSParams( - MOBase::log::Levels logLevel, int crashDumpsType, + MOBase::log::Levels logLevel, CrashDumpsType crashDumpsType, QString executableBlacklist); void setLogLevel(MOBase::log::Levels level); @@ -201,7 +201,7 @@ public: bool cycleDiagnostics(); static CrashDumpsType getGlobalCrashDumpsType() { return m_globalCrashDumpsType; } - static void setGlobalCrashDumpsType(int crashDumpsType); + static void setGlobalCrashDumpsType(CrashDumpsType crashDumpsType); static std::wstring crashDumpsPath(); public: diff --git a/src/pluginlist.cpp b/src/pluginlist.cpp index 8637f546..ddfe492e 100644 --- a/src/pluginlist.cpp +++ b/src/pluginlist.cpp @@ -931,7 +931,7 @@ QVariant PluginList::data(const QModelIndex &modelIndex, int role) const } else if (role == Qt::BackgroundRole || (role == ViewMarkingScrollBar::DEFAULT_ROLE)) { if (m_ESPs[index].m_ModSelected) { - return Settings::instance().pluginListContainedColor(); + return Settings::instance().colors().pluginListContained(); } else { return QVariant(); } diff --git a/src/settings.cpp b/src/settings.cpp index 844ee81e..2236fc9d 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -24,7 +24,6 @@ along with Mod Organizer. If not, see . #include "expanderwidget.h" #include #include -#include using namespace MOBase; @@ -33,7 +32,13 @@ std::optional getOptional( const QSettings& s, const QString& name, std::optional def={}) { if (s.contains(name)) { - return s.value(name).value(); + const auto v = s.value(name); + + if constexpr (std::is_enum_v) { + return static_cast(v.value>()); + } else { + return v.value(); + } } return def; @@ -160,10 +165,12 @@ void warnIfNotCheckable(const QAbstractButton* b) } } + Settings *Settings::s_Instance = nullptr; -Settings::Settings(const QString& path) - : m_Settings(path, QSettings::IniFormat), m_Geometry(m_Settings) +Settings::Settings(const QString& path) : + m_Settings(path, QSettings::IniFormat), + m_Geometry(m_Settings), m_Colors(m_Settings) { if (s_Instance != nullptr) { throw std::runtime_error("second instance of \"Settings\" created"); @@ -280,6 +287,11 @@ bool Settings::colorSeparatorScrollbar() const return m_Settings.value("Settings/colorSeparatorScrollbars", true).toBool(); } +void Settings::setColorSeparatorScrollbar(bool b) +{ + m_Settings.setValue("Settings/colorSeparatorScrollbars", b); +} + void Settings::managedGameChanged(IPluginGame const *gamePlugin) { m_GamePlugin = gamePlugin; @@ -397,6 +409,11 @@ bool Settings::usePrereleases() const return m_Settings.value("Settings/use_prereleases", false).toBool(); } +void Settings::setUsePrereleases(bool b) +{ + m_Settings.setValue("Settings/use_prereleases", b); +} + void Settings::setDownloadSpeed(const QString &serverName, int bytesPerSecond) { m_Settings.beginGroup("Servers"); @@ -615,16 +632,27 @@ bool Settings::getSteamLogin(QString &username, QString &password) const return !username.isEmpty() && !password.isEmpty(); } + bool Settings::compactDownloads() const { return m_Settings.value("Settings/compact_downloads", false).toBool(); } +void Settings::setCompactDownloads(bool b) +{ + m_Settings.setValue("Settings/compact_downloads", b); +} + bool Settings::metaDownloads() const { return m_Settings.value("Settings/meta_downloads", false).toBool(); } +void Settings::setMetaDownloads(bool b) +{ + m_Settings.setValue("Settings/meta_downloads", b); +} + bool Settings::offlineMode() const { return m_Settings.value("Settings/offline_mode", false).toBool(); @@ -640,44 +668,25 @@ void Settings::setLogLevel(log::Levels level) m_Settings.setValue("Settings/log_level", static_cast(level)); } -int Settings::crashDumpsType() const +CrashDumpsType Settings::crashDumpsType() const { - return m_Settings.value("Settings/crash_dumps_type", static_cast(CrashDumpsType::Mini)).toInt(); + const auto v = getOptional(m_Settings, "Settings/crash_dumps_type"); + return v.value_or(CrashDumpsType::Mini); } -int Settings::crashDumpsMax() const +void Settings::setCrashDumpsType(CrashDumpsType type) { - return m_Settings.value("Settings/crash_dumps_max", 5).toInt(); + m_Settings.setValue("Settings/crash_dumps_type", static_cast(type)); } -QColor Settings::modlistOverwrittenLooseColor() const -{ - return m_Settings.value("Settings/overwrittenLooseFilesColor", QColor(0, 255, 0, 64)).value(); -} - -QColor Settings::modlistOverwritingLooseColor() const -{ - return m_Settings.value("Settings/overwritingLooseFilesColor", QColor(255, 0, 0, 64)).value(); -} - -QColor Settings::modlistOverwrittenArchiveColor() const -{ - return m_Settings.value("Settings/overwrittenArchiveFilesColor", QColor(0, 255, 255, 64)).value(); -} - -QColor Settings::modlistOverwritingArchiveColor() const -{ - return m_Settings.value("Settings/overwritingArchiveFilesColor", QColor(255, 0, 255, 64)).value(); -} - -QColor Settings::modlistContainsPluginColor() const +int Settings::crashDumpsMax() const { - return m_Settings.value("Settings/containsPluginColor", QColor(0, 0, 255, 64)).value(); + return m_Settings.value("Settings/crash_dumps_max", 5).toInt(); } -QColor Settings::pluginListContainedColor() const +void Settings::setCrashDumpsMax(int n) { - return m_Settings.value("Settings/containedColor", QColor(0, 0, 255, 64)).value(); + return m_Settings.setValue("Settings/crash_dumps_max", n); } QString Settings::executablesBlacklist() const @@ -850,6 +859,11 @@ QString Settings::language() return result; } +void Settings::setLanguage(const QString& name) +{ + m_Settings.setValue("Settings/language", name); +} + void Settings::updateServers(const QList &servers) { m_Settings.beginGroup("Servers"); @@ -1132,6 +1146,16 @@ const GeometrySettings& Settings::geometry() const return m_Geometry; } +ColorSettings& Settings::colors() +{ + return m_Colors; +} + +const ColorSettings& Settings::colors() const +{ + return m_Colors; +} + QSettings::Status Settings::sync() const { m_Settings.sync(); @@ -1451,6 +1475,78 @@ void GeometrySettings::restoreDocks(QMainWindow* mw) const } +ColorSettings::ColorSettings(QSettings& s) + : m_Settings(s) +{ +} + +QColor ColorSettings::modlistOverwrittenLoose() const +{ + return getOptional(m_Settings, "Settings/overwrittenLooseFilesColor") + .value_or(QColor(0, 255, 0, 64)); +} + +void ColorSettings::setModlistOverwrittenLoose(const QColor& c) +{ + m_Settings.setValue("Settings/overwrittenLooseFilesColor", c); +} + +QColor ColorSettings::modlistOverwritingLoose() const +{ + return getOptional(m_Settings, "Settings/overwritingLooseFilesColor") + .value_or(QColor(255, 0, 0, 64)); +} + +void ColorSettings::setModlistOverwritingLoose(const QColor& c) +{ + m_Settings.setValue("Settings/overwritingLooseFilesColor", c); +} + +QColor ColorSettings::modlistOverwrittenArchive() const +{ + return getOptional(m_Settings, "Settings/overwrittenArchiveFilesColor") + .value_or(QColor(0, 255, 255, 64)); +} + +void ColorSettings::setModlistOverwrittenArchive(const QColor& c) +{ + m_Settings.setValue("Settings/overwrittenArchiveFilesColor", c); +} + +QColor ColorSettings::modlistOverwritingArchive() const +{ + return getOptional(m_Settings, "Settings/overwritingArchiveFilesColor") + .value_or(QColor(255, 0, 255, 64)); +} + +void ColorSettings::setModlistOverwritingArchive(const QColor& c) +{ + m_Settings.setValue("Settings/overwritingArchiveFilesColor", c); +} + +QColor ColorSettings::modlistContainsPlugin() const +{ + return getOptional(m_Settings, "Settings/containsPluginColor") + .value_or(QColor(0, 0, 255, 64)); +} + +void ColorSettings::setModlistContainsPlugin(const QColor& c) +{ + m_Settings.setValue("Settings/containsPluginColor", c); +} + +QColor ColorSettings::pluginListContained() const +{ + return getOptional(m_Settings, "Settings/containedColor") + .value_or(QColor(0, 0, 255, 64)); +} + +void ColorSettings::setPluginListContained(const QColor& c) +{ + m_Settings.setValue("Settings/containedColor", c); +} + + GeometrySaver::GeometrySaver(Settings& s, QDialog* dialog) : m_settings(s), m_dialog(dialog) { diff --git a/src/settings.h b/src/settings.h index b25af15f..5b1d7bfc 100644 --- a/src/settings.h +++ b/src/settings.h @@ -23,6 +23,7 @@ along with Mod Organizer. If not, see . #include "loadmechanism.h" #include #include +#include namespace MOBase { class IPlugin; @@ -96,6 +97,36 @@ private: }; +class ColorSettings +{ +public: + ColorSettings(QSettings& s); + + void setCrashDumpsMax(int i) const; + + QColor modlistOverwrittenLoose() const; + void setModlistOverwrittenLoose(const QColor& c); + + QColor modlistOverwritingLoose() const; + void setModlistOverwritingLoose(const QColor& c); + + QColor modlistOverwrittenArchive() const; + void setModlistOverwrittenArchive(const QColor& c); + + QColor modlistOverwritingArchive() const; + void setModlistOverwritingArchive(const QColor& c); + + QColor modlistContainsPlugin() const; + void setModlistContainsPlugin(const QColor& c); + + QColor pluginListContained() const; + void setPluginListContained(const QColor& c) ; + +private: + QSettings& m_Settings; +}; + + enum class EndorsementState { Accepted = 1, @@ -268,6 +299,10 @@ public: GeometrySettings& geometry(); const GeometrySettings& geometry() const; + ColorSettings& colors(); + const ColorSettings& colors() const; + + /** * retrieve the directory where profiles stored (with native separators) **/ @@ -329,43 +364,22 @@ public: * @return true if the user chose compact downloads */ bool compactDownloads() const; + void setCompactDownloads(bool b); /** * @return true if the user chose meta downloads */ bool metaDownloads() const; + void setMetaDownloads(bool b); - /** - * @return the configured log level - */ MOBase::log::Levels logLevel() const; - - /** - * sets the log level setting - */ void setLogLevel(MOBase::log::Levels level); - /** - * @return the configured crash dumps type - */ - int crashDumpsType() const; + CrashDumpsType crashDumpsType() const; + void setCrashDumpsType(CrashDumpsType type); - /** - * @return the configured crash dumps max - */ int crashDumpsMax() const; - - QColor modlistOverwrittenLooseColor() const; - - QColor modlistOverwritingLooseColor() const; - - QColor modlistOverwrittenArchiveColor() const; - - QColor modlistOverwritingArchiveColor() const; - - QColor modlistContainsPluginColor() const; - - QColor pluginListContainedColor() const; + void setCrashDumpsMax(int n); QString executablesBlacklist() const; @@ -473,6 +487,7 @@ public: * @return short code of the configured language (corresponding to the translation files) */ QString language(); + void setLanguage(const QString& name); /** * @brief updates the list of known servers @@ -499,6 +514,7 @@ public: std::vector plugins() const { return m_Plugins; } bool usePrereleases() const; + void setUsePrereleases(bool b); /** * @brief register MO as the handler for nxm links @@ -512,6 +528,7 @@ public: * @return the state of the setting */ bool colorSeparatorScrollbar() const; + void setColorSeparatorScrollbar(bool b); static QColor getIdealTextColor(const QColor& rBackgroundColor); @@ -540,6 +557,7 @@ private: MOBase::IPluginGame const *m_GamePlugin; mutable QSettings m_Settings; GeometrySettings m_Geometry; + ColorSettings m_Colors; LoadMechanism m_LoadMechanism; std::vector m_Plugins; diff --git a/src/settingsdialog.cpp b/src/settingsdialog.cpp index 097dafc8..9d031785 100644 --- a/src/settingsdialog.cpp +++ b/src/settingsdialog.cpp @@ -51,43 +51,19 @@ int SettingsDialog::exec() { GeometrySaver gs(m_settings, this); - auto& qsettings = m_settings.directInterface(); auto ret = TutorableDialog::exec(); if (ret == QDialog::Accepted) { - for (auto&& tab : m_tabs) { tab->closing(); } - // remember settings before change - QMap before; - qsettings.beginGroup("Settings"); - for (auto k : qsettings.allKeys()) - before[k] = qsettings.value(k).toString(); - qsettings.endGroup(); - - // transfer modified settings to configuration file + // update settings for each tab for (std::unique_ptr const &tab: m_tabs) { tab->update(); } - - // print "changed" settings - qsettings.beginGroup("Settings"); - bool first_update = true; - for (auto k : qsettings.allKeys()) - if (qsettings.value(k).toString() != before[k] && !k.contains("username") && !k.contains("password")) - { - if (first_update) { - log::debug("Changed settings:"); - first_update = false; - } - log::debug(" {}={}", k, qsettings.value(k).toString()); - } - qsettings.endGroup(); } - // These changes happen regardless of accepted or rejected bool restartNeeded = false; if (getApiKeyChanged()) { restartNeeded = true; diff --git a/src/settingsdialog.ui b/src/settingsdialog.ui index e7676387..af230bc0 100644 --- a/src/settingsdialog.ui +++ b/src/settingsdialog.ui @@ -1346,26 +1346,6 @@ programs you are intentionally running. "Full" Even larger dumps with a full memory dump of the process.
- - - None - - - - - Mini (recommended) - - - - - Data - - - - - Full - -
diff --git a/src/settingsdialogdiagnostics.cpp b/src/settingsdialogdiagnostics.cpp index 227d1dfa..278da0bf 100644 --- a/src/settingsdialogdiagnostics.cpp +++ b/src/settingsdialogdiagnostics.cpp @@ -10,10 +10,13 @@ DiagnosticsSettingsTab::DiagnosticsSettingsTab(Settings& s, SettingsDialog& d) : SettingsTab(s, d) { setLevelsBox(); - ui->dumpsTypeBox->setCurrentIndex(settings().crashDumpsType()); + setCrashDumpTypesBox(); + ui->dumpsMaxEdit->setValue(settings().crashDumpsMax()); + QString logsPath = qApp->property("dataPath").toString() + "/" + QString::fromStdWString(AppConfig::logPath()); + ui->diagnosticsExplainedLabel->setText( ui->diagnosticsExplainedLabel->text() .replace("LOGS_FULL_PATH", logsPath) @@ -40,9 +43,36 @@ void DiagnosticsSettingsTab::setLevelsBox() } } +void DiagnosticsSettingsTab::setCrashDumpTypesBox() +{ + ui->dumpsTypeBox->clear(); + + auto add = [&](auto&& text, auto&& type) { + ui->dumpsTypeBox->addItem(text, static_cast(type)); + }; + + add(QObject::tr("None"), CrashDumpsType::None); + add(QObject::tr("Mini (recommended)"), CrashDumpsType::Mini); + add(QObject::tr("Data"), CrashDumpsType::Data); + add(QObject::tr("Full"), CrashDumpsType::Full); + + const auto current = static_cast(settings().crashDumpsType()); + + for (int i=0; idumpsTypeBox->count(); ++i) { + if (ui->dumpsTypeBox->itemData(i) == current) { + ui->dumpsTypeBox->setCurrentIndex(i); + break; + } + } +} + void DiagnosticsSettingsTab::update() { - qsettings().setValue("Settings/log_level", ui->logLevelBox->currentData().toInt()); - qsettings().setValue("Settings/crash_dumps_type", ui->dumpsTypeBox->currentIndex()); - qsettings().setValue("Settings/crash_dumps_max", ui->dumpsMaxEdit->value()); + settings().setLogLevel( + static_cast(ui->logLevelBox->currentData().toInt())); + + settings().setCrashDumpsType( + static_cast(ui->dumpsTypeBox->currentData().toInt())); + + settings().setCrashDumpsMax(ui->dumpsMaxEdit->value()); } diff --git a/src/settingsdialogdiagnostics.h b/src/settingsdialogdiagnostics.h index f20413f8..f0fbf770 100644 --- a/src/settingsdialogdiagnostics.h +++ b/src/settingsdialogdiagnostics.h @@ -13,6 +13,7 @@ public: private: void setLevelsBox(); + void setCrashDumpTypesBox(); }; #endif // SETTINGSDIALOGDIAGNOSTICS_H diff --git a/src/settingsdialoggeneral.cpp b/src/settingsdialoggeneral.cpp index 35012db7..e3d73037 100644 --- a/src/settingsdialoggeneral.cpp +++ b/src/settingsdialoggeneral.cpp @@ -26,28 +26,30 @@ GeneralSettingsTab::GeneralSettingsTab(Settings& s, SettingsDialog& d) } addStyles(); + { - int currentID = ui->styleBox->findData( - qsettings().value("Settings/style", "").toString()); + const int currentID = ui->styleBox->findData( + settings().getStyleName().value_or("")); + if (currentID != -1) { ui->styleBox->setCurrentIndex(currentID); } } //version with stylesheet - setButtonColor(ui->overwritingBtn, settings().modlistOverwritingLooseColor()); - setButtonColor(ui->overwrittenBtn, settings().modlistOverwrittenLooseColor()); - setButtonColor(ui->overwritingArchiveBtn, settings().modlistOverwritingArchiveColor()); - setButtonColor(ui->overwrittenArchiveBtn, settings().modlistOverwrittenArchiveColor()); - setButtonColor(ui->containsBtn, settings().modlistContainsPluginColor()); - setButtonColor(ui->containedBtn, settings().pluginListContainedColor()); - - setOverwritingColor(settings().modlistOverwritingLooseColor()); - setOverwrittenColor(settings().modlistOverwrittenLooseColor()); - setOverwritingArchiveColor(settings().modlistOverwritingArchiveColor()); - setOverwrittenArchiveColor(settings().modlistOverwrittenArchiveColor()); - setContainsColor(settings().modlistContainsPluginColor()); - setContainedColor(settings().pluginListContainedColor()); + setButtonColor(ui->overwritingBtn, settings().colors().modlistOverwritingLoose()); + setButtonColor(ui->overwrittenBtn, settings().colors().modlistOverwrittenLoose()); + setButtonColor(ui->overwritingArchiveBtn, settings().colors().modlistOverwritingArchive()); + setButtonColor(ui->overwrittenArchiveBtn, settings().colors().modlistOverwrittenArchive()); + setButtonColor(ui->containsBtn, settings().colors().modlistContainsPlugin()); + setButtonColor(ui->containedBtn, settings().colors().pluginListContained()); + + setOverwritingColor(settings().colors().modlistOverwritingLoose()); + setOverwrittenColor(settings().colors().modlistOverwrittenLoose()); + setOverwritingArchiveColor(settings().colors().modlistOverwritingArchive()); + setOverwrittenArchiveColor(settings().colors().modlistOverwrittenArchive()); + setContainsColor(settings().colors().modlistContainsPlugin()); + setContainedColor(settings().colors().pluginListContained()); ui->compactBox->setChecked(settings().compactDownloads()); ui->showMetaBox->setChecked(settings().metaDownloads()); @@ -67,30 +69,32 @@ GeneralSettingsTab::GeneralSettingsTab(Settings& s, SettingsDialog& d) void GeneralSettingsTab::update() { - QString oldLanguage = settings().language(); - QString newLanguage = ui->languageBox->itemData(ui->languageBox->currentIndex()).toString(); + const QString oldLanguage = settings().language(); + const QString newLanguage = ui->languageBox->itemData(ui->languageBox->currentIndex()).toString(); + if (newLanguage != oldLanguage) { - qsettings().setValue("Settings/language", newLanguage); + settings().setLanguage(newLanguage); emit settings().languageChanged(newLanguage); } - QString oldStyle = qsettings().value("Settings/style", "").toString(); - QString newStyle = ui->styleBox->itemData(ui->styleBox->currentIndex()).toString(); + const QString oldStyle = settings().getStyleName().value_or(""); + const QString newStyle = ui->styleBox->itemData(ui->styleBox->currentIndex()).toString(); if (oldStyle != newStyle) { - qsettings().setValue("Settings/style", newStyle); + settings().setStyleName(newStyle); emit settings().styleChanged(newStyle); } - qsettings().setValue("Settings/overwritingLooseFilesColor", getOverwritingColor()); - qsettings().setValue("Settings/overwrittenLooseFilesColor", getOverwrittenColor()); - qsettings().setValue("Settings/overwritingArchiveFilesColor", getOverwritingArchiveColor()); - qsettings().setValue("Settings/overwrittenArchiveFilesColor", getOverwrittenArchiveColor()); - qsettings().setValue("Settings/containsPluginColor", getContainsColor()); - qsettings().setValue("Settings/containedColor", getContainedColor()); - qsettings().setValue("Settings/compact_downloads", ui->compactBox->isChecked()); - qsettings().setValue("Settings/meta_downloads", ui->showMetaBox->isChecked()); - qsettings().setValue("Settings/use_prereleases", ui->usePrereleaseBox->isChecked()); - qsettings().setValue("Settings/colorSeparatorScrollbars", ui->colorSeparatorsBox->isChecked()); + settings().colors().setModlistOverwritingLoose(getOverwritingColor()); + settings().colors().setModlistOverwrittenLoose(getOverwrittenColor()); + settings().colors().setModlistOverwritingArchive(getOverwritingArchiveColor()); + settings().colors().setModlistOverwrittenArchive(getOverwrittenArchiveColor()); + settings().colors().setModlistContainsPlugin(getContainsColor()); + settings().colors().setPluginListContained(getContainedColor()); + + settings().setCompactDownloads(ui->compactBox->isChecked()); + settings().setMetaDownloads(ui->showMetaBox->isChecked()); + settings().setUsePrereleases(ui->usePrereleaseBox->isChecked()); + settings().setColorSeparatorScrollbar(ui->colorSeparatorsBox->isChecked()); } void GeneralSettingsTab::addLanguages() diff --git a/src/usvfsconnector.cpp b/src/usvfsconnector.cpp index b5e6edb1..41f58308 100644 --- a/src/usvfsconnector.cpp +++ b/src/usvfsconnector.cpp @@ -164,7 +164,7 @@ UsvfsConnector::UsvfsConnector() { USVFSParameters params; LogLevel level = toUsvfsLogLevel(Settings::instance().logLevel()); - CrashDumpsType dumpType = crashDumpsType(Settings::instance().crashDumpsType()); + CrashDumpsType dumpType = Settings::instance().crashDumpsType(); std::string dumpPath = MOShared::ToString(OrganizerCore::crashDumpsPath(), true); USVFSInitParameters(¶ms, SHMID, false, level, dumpType, dumpPath.c_str()); @@ -249,9 +249,10 @@ void UsvfsConnector::updateMapping(const MappingType &mapping) } void UsvfsConnector::updateParams( - MOBase::log::Levels logLevel, int crashDumpsType, QString executableBlacklist) + MOBase::log::Levels logLevel, CrashDumpsType crashDumpsType, + QString executableBlacklist) { - USVFSUpdateParams(toUsvfsLogLevel(logLevel), ::crashDumpsType(crashDumpsType)); + USVFSUpdateParams(toUsvfsLogLevel(logLevel), crashDumpsType); ClearExecutableBlacklist(); for (auto exec : executableBlacklist.split(";")) { std::wstring buf = exec.toStdWString(); diff --git a/src/usvfsconnector.h b/src/usvfsconnector.h index b0bd320c..cd5d56b2 100644 --- a/src/usvfsconnector.h +++ b/src/usvfsconnector.h @@ -87,7 +87,7 @@ public: void updateMapping(const MappingType &mapping); void updateParams( - MOBase::log::Levels logLevel, int crashDumpsType, + MOBase::log::Levels logLevel, CrashDumpsType crashDumpsType, QString executableBlacklist); void updateForcedLibraries(const QList &forcedLibraries); -- cgit v1.3.1 From b1687380c5c10342699f95361e30f18a32bad585 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Mon, 26 Aug 2019 00:01:07 -0400 Subject: moved more nexus stuff to settings settings tab remembered --- src/settings.cpp | 24 ++++++++++++++++++++++-- src/settings.h | 4 ++++ src/settingsdialog.cpp | 4 ++++ src/settingsdialognexus.cpp | 12 ++++++------ 4 files changed, 36 insertions(+), 8 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/settings.cpp b/src/settings.cpp index 2236fc9d..9c9e4c4d 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -545,6 +545,11 @@ std::optional Settings::getUseProxy() const return getOptional(m_Settings, "Settings/use_proxy"); } +void Settings::setUseProxy(bool b) +{ + m_Settings.setValue("Settings/use_proxy", b); +} + std::optional Settings::getVersion() const { if (auto v=getOptional(m_Settings, "version")) { @@ -658,6 +663,11 @@ bool Settings::offlineMode() const return m_Settings.value("Settings/offline_mode", false).toBool(); } +void Settings::setOfflineMode(bool b) +{ + m_Settings.setValue("Settings/offline_mode", b); +} + log::Levels Settings::logLevel() const { return static_cast(m_Settings.value("Settings/log_level").toInt()); @@ -756,6 +766,11 @@ bool Settings::endorsementIntegration() const return m_Settings.value("Settings/endorsement_integration", true).toBool(); } +void Settings::setEndorsementIntegration(bool b) const +{ + m_Settings.setValue("Settings/endorsement_integration", b); +} + EndorsementState Settings::endorsementState() const { const auto v = getOptional(m_Settings, "endorse_state"); @@ -778,6 +793,11 @@ bool Settings::hideAPICounter() const return m_Settings.value("Settings/hide_api_counter", false).toBool(); } +void Settings::setHideAPICounter(bool b) +{ + m_Settings.setValue("Settings/hide_api_counter", b); +} + bool Settings::displayForeign() const { return m_Settings.value("Settings/display_foreign", true).toBool(); @@ -886,8 +906,8 @@ void Settings::updateServers(const QList &servers) data["premium"] = server.premium; m_Settings.setValue(server.name, data); + } } - } // clean up unavailable servers QDate now = QDate::currentDate(); @@ -1166,7 +1186,7 @@ void Settings::dump() const { static const QStringList ignore({ "username", "password", "nexus_api_key" - }); + }); log::debug("settings:"); diff --git a/src/settings.h b/src/settings.h index 5b1d7bfc..21776169 100644 --- a/src/settings.h +++ b/src/settings.h @@ -359,6 +359,7 @@ public: * @return true if the user disabled internet features */ bool offlineMode() const; + void setOfflineMode(bool b); /** * @return true if the user chose compact downloads @@ -405,11 +406,13 @@ public: * @return true if the user configured the use of a network proxy */ bool useProxy() const; + void setUseProxy(bool b); /** * @return true if endorsement integration is enabled */ bool endorsementIntegration() const; + void setEndorsementIntegration(bool b) const; EndorsementState endorsementState() const; void setEndorsementState(EndorsementState s); @@ -419,6 +422,7 @@ public: * @return true if the API counter should be hidden */ bool hideAPICounter() const; + void setHideAPICounter(bool b); /** * @return true if the user wants to see non-official plugins installed outside MO in his mod list diff --git a/src/settingsdialog.cpp b/src/settingsdialog.cpp index 9d031785..a24416e9 100644 --- a/src/settingsdialog.cpp +++ b/src/settingsdialog.cpp @@ -51,8 +51,12 @@ int SettingsDialog::exec() { GeometrySaver gs(m_settings, this); + m_settings.restoreIndex(ui->tabWidget); + auto ret = TutorableDialog::exec(); + m_settings.saveIndex(ui->tabWidget); + if (ret == QDialog::Accepted) { for (auto&& tab : m_tabs) { tab->closing(); diff --git a/src/settingsdialognexus.cpp b/src/settingsdialognexus.cpp index b1964069..4d9a18a2 100644 --- a/src/settingsdialognexus.cpp +++ b/src/settingsdialognexus.cpp @@ -114,10 +114,10 @@ NexusSettingsTab::NexusSettingsTab(Settings& s, SettingsDialog& d) void NexusSettingsTab::update() { - qsettings().setValue("Settings/offline_mode", ui->offlineBox->isChecked()); - qsettings().setValue("Settings/use_proxy", ui->proxyBox->isChecked()); - qsettings().setValue("Settings/endorsement_integration", ui->endorsementBox->isChecked()); - qsettings().setValue("Settings/hide_api_counter", ui->hideAPICounterBox->isChecked()); + settings().setOfflineMode(ui->offlineBox->isChecked()); + settings().setUseProxy(ui->proxyBox->isChecked()); + settings().setEndorsementIntegration(ui->endorsementBox->isChecked()); + settings().setHideAPICounter(ui->hideAPICounterBox->isChecked()); // store server preference qsettings().beginGroup("Servers"); @@ -126,14 +126,14 @@ void NexusSettingsTab::update() QVariantMap val = qsettings().value(key).toMap(); val["preferred"] = 0; qsettings().setValue(key, val); - } + } int count = ui->preferredServersList->count(); for (int i = 0; i < count; ++i) { QString key = ui->preferredServersList->item(i)->data(Qt::UserRole).toString(); QVariantMap val = qsettings().value(key).toMap(); val["preferred"] = count - i; qsettings().setValue(key, val); - } + } qsettings().endGroup(); } -- cgit v1.3.1 From 7395fbb7544740a136884e103cb0829bd10b5655 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Mon, 26 Aug 2019 00:21:41 -0400 Subject: made ServerInfo a class moved server functions together in Settings --- src/mainwindow.cpp | 10 +++---- src/serverinfo.cpp | 31 ++++++++++++++++++++ src/serverinfo.h | 20 +++++++++---- src/settings.cpp | 86 +++++++++++++++++++++++++++--------------------------- src/settings.h | 26 ++++++++--------- 5 files changed, 107 insertions(+), 66 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index f1a2047f..b6ae59a1 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -5909,11 +5909,11 @@ void MainWindow::nxmDownloadURLs(QString, int, int, QVariant, QVariant resultDat QList servers; for (const QVariant &server : serverList) { QVariantMap serverInfo = server.toMap(); - ServerInfo info; - info.name = serverInfo["short_name"].toString(); - info.premium = serverInfo["name"].toString().contains("Premium", Qt::CaseInsensitive); - info.lastSeen = QDate::currentDate(); - info.preferred = serverInfo["short_name"].toString().contains("CDN", Qt::CaseInsensitive); + ServerInfo info( + serverInfo["short_name"].toString(), + serverInfo["name"].toString().contains("Premium", Qt::CaseInsensitive), + QDate::currentDate(), + serverInfo["short_name"].toString().contains("CDN", Qt::CaseInsensitive)); servers.append(info); } m_OrganizerCore.settings().updateServers(servers); diff --git a/src/serverinfo.cpp b/src/serverinfo.cpp index e96b69d2..5912c226 100644 --- a/src/serverinfo.cpp +++ b/src/serverinfo.cpp @@ -1 +1,32 @@ #include "serverinfo.h" + +ServerInfo::ServerInfo() + : ServerInfo({}, false, {}, false) +{ +} + +ServerInfo::ServerInfo(QString n, bool premium, QDate last, bool preferred) : + m_name(std::move(n)), m_premium(premium), m_lastSeen(std::move(last)), + m_preferred(preferred) +{ +} + +const QString& ServerInfo::name() const +{ + return m_name; +} + +bool ServerInfo::isPremium() const +{ + return m_premium; +} + +const QDate& ServerInfo::lastSeen() const +{ + return m_lastSeen; +} + +bool ServerInfo::isPreferred() const +{ + return m_preferred; +} diff --git a/src/serverinfo.h b/src/serverinfo.h index 8e5e935a..79b90e77 100644 --- a/src/serverinfo.h +++ b/src/serverinfo.h @@ -5,12 +5,22 @@ #include #include -struct ServerInfo +class ServerInfo { - QString name; - bool premium; - QDate lastSeen; - bool preferred; +public: + ServerInfo(); + ServerInfo(QString name, bool premium, QDate lastSeen, bool preferred); + + const QString& name() const; + bool isPremium() const; + const QDate& lastSeen() const; + bool isPreferred() const; + +private: + QString m_name; + bool m_premium; + QDate m_lastSeen; + bool m_preferred; }; Q_DECLARE_METATYPE(ServerInfo) diff --git a/src/settings.cpp b/src/settings.cpp index 9c9e4c4d..9975642b 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -414,40 +414,6 @@ void Settings::setUsePrereleases(bool b) m_Settings.setValue("Settings/use_prereleases", b); } -void Settings::setDownloadSpeed(const QString &serverName, int bytesPerSecond) -{ - m_Settings.beginGroup("Servers"); - - for (const QString &serverKey : m_Settings.childKeys()) { - QVariantMap data = m_Settings.value(serverKey).toMap(); - if (serverKey == serverName) { - data["downloadCount"] = data["downloadCount"].toInt() + 1; - data["downloadSpeed"] = data["downloadSpeed"].toDouble() + static_cast(bytesPerSecond); - m_Settings.setValue(serverKey, data); - } - } - - m_Settings.endGroup(); - m_Settings.sync(); -} - -std::map Settings::getPreferredServers() -{ - std::map result; - m_Settings.beginGroup("Servers"); - - for (const QString &serverKey : m_Settings.childKeys()) { - QVariantMap data = m_Settings.value(serverKey).toMap(); - int preference = data["preferred"].toInt(); - if (preference > 0) { - result[serverKey] = preference; - } - } - m_Settings.endGroup(); - - return result; -} - QString Settings::getConfigurablePath(const QString &key, const QString &def, bool resolve) const @@ -884,28 +850,62 @@ void Settings::setLanguage(const QString& name) m_Settings.setValue("Settings/language", name); } +void Settings::setDownloadSpeed(const QString &serverName, int bytesPerSecond) +{ + m_Settings.beginGroup("Servers"); + + for (const QString &serverKey : m_Settings.childKeys()) { + QVariantMap data = m_Settings.value(serverKey).toMap(); + if (serverKey == serverName) { + data["downloadCount"] = data["downloadCount"].toInt() + 1; + data["downloadSpeed"] = data["downloadSpeed"].toDouble() + static_cast(bytesPerSecond); + m_Settings.setValue(serverKey, data); + } + } + + m_Settings.endGroup(); + m_Settings.sync(); +} + +std::map Settings::getPreferredServers() +{ + std::map result; + m_Settings.beginGroup("Servers"); + + for (const QString &serverKey : m_Settings.childKeys()) { + QVariantMap data = m_Settings.value(serverKey).toMap(); + int preference = data["preferred"].toInt(); + if (preference > 0) { + result[serverKey] = preference; + } + } + m_Settings.endGroup(); + + return result; +} + void Settings::updateServers(const QList &servers) { m_Settings.beginGroup("Servers"); QStringList oldServerKeys = m_Settings.childKeys(); for (const ServerInfo &server : servers) { - if (!oldServerKeys.contains(server.name)) { + if (!oldServerKeys.contains(server.name())) { // not yet known server QVariantMap newVal; - newVal["premium"] = server.premium; - newVal["preferred"] = server.preferred ? 1 : 0; - newVal["lastSeen"] = server.lastSeen; + newVal["premium"] = server.isPremium(); + newVal["preferred"] = server.isPreferred() ? 1 : 0; + newVal["lastSeen"] = server.lastSeen(); newVal["downloadCount"] = 0; newVal["downloadSpeed"] = 0.0; - m_Settings.setValue(server.name, newVal); + m_Settings.setValue(server.name(), newVal); } else { - QVariantMap data = m_Settings.value(server.name).toMap(); - data["lastSeen"] = server.lastSeen; - data["premium"] = server.premium; + QVariantMap data = m_Settings.value(server.name()).toMap(); + data["lastSeen"] = server.lastSeen(); + data["premium"] = server.isPremium(); - m_Settings.setValue(server.name, data); + m_Settings.setValue(server.name(), data); } } diff --git a/src/settings.h b/src/settings.h index 21776169..4662ed19 100644 --- a/src/settings.h +++ b/src/settings.h @@ -33,7 +33,7 @@ namespace MOBase { class QSplitter; class PluginContainer; -struct ServerInfo; +class ServerInfo; class Settings; class ExpanderWidget; @@ -190,13 +190,6 @@ public: */ bool lockGUI() const; - /** - * @brief register download speed - * @param url complete download url - * @param bytesPerSecond download size in bytes per second - */ - void setDownloadSpeed(const QString &serverName, int bytesPerSecond); - /** * the steam appid is assigned by the steam platform to each product sold there. * The appid may differ between different versions of a game so it may be impossible @@ -216,11 +209,6 @@ public: **/ QString getDownloadDirectory(bool resolve = true) const; - /** - * retrieve a sorted list of preferred servers - */ - std::map getPreferredServers(); - /** * retrieve the directory where mods are stored (with native separators) **/ @@ -493,6 +481,18 @@ public: QString language(); void setLanguage(const QString& name); + /** + * @brief register download speed + * @param url complete download url + * @param bytesPerSecond download size in bytes per second + */ + void setDownloadSpeed(const QString &serverName, int bytesPerSecond); + + /** + * retrieve a sorted list of preferred servers + */ + std::map getPreferredServers(); + /** * @brief updates the list of known servers * @param list of servers from a recent query -- cgit v1.3.1 From 36dbb4bad74b097d44b843a2e934aa4a58ef6492 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Mon, 26 Aug 2019 00:48:25 -0400 Subject: ServerList instead of a QList of ServerInfo changed preferred to an int moved all server settings to Settings --- src/mainwindow.cpp | 24 ++++++++------ src/serverinfo.cpp | 63 ++++++++++++++++++++++++++++++++++--- src/serverinfo.h | 35 +++++++++++++++++++-- src/settings.cpp | 36 ++++++++++++++++++--- src/settings.h | 5 ++- src/settingsdialognexus.cpp | 77 ++++++++++++++++++++++++++++++++------------- 6 files changed, 194 insertions(+), 46 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index b6ae59a1..9921ad82 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -5904,18 +5904,22 @@ void MainWindow::nxmTrackedModsAvailable(QVariant userData, QVariant resultData, void MainWindow::nxmDownloadURLs(QString, int, int, QVariant, QVariant resultData, int) { - QVariantList serverList = resultData.toList(); - - QList servers; - for (const QVariant &server : serverList) { - QVariantMap serverInfo = server.toMap(); - ServerInfo info( - serverInfo["short_name"].toString(), - serverInfo["name"].toString().contains("Premium", Qt::CaseInsensitive), + ServerList servers; + + for (const QVariant &var : resultData.toList()) { + const QVariantMap map = var.toMap(); + + ServerInfo server( + map["short_name"].toString(), + map["name"].toString().contains("Premium", Qt::CaseInsensitive), QDate::currentDate(), - serverInfo["short_name"].toString().contains("CDN", Qt::CaseInsensitive)); - servers.append(info); + map["short_name"].toString().contains("CDN", Qt::CaseInsensitive) ? 1 : 0, + map["downloadCount"].toInt(), + map["downloadSpeed"].toDouble()); + + servers.add(std::move(server)); } + m_OrganizerCore.settings().updateServers(servers); } diff --git a/src/serverinfo.cpp b/src/serverinfo.cpp index 5912c226..67a80b9e 100644 --- a/src/serverinfo.cpp +++ b/src/serverinfo.cpp @@ -1,13 +1,15 @@ #include "serverinfo.h" ServerInfo::ServerInfo() - : ServerInfo({}, false, {}, false) + : ServerInfo({}, false, {}, 0, 0, 0.0) { } -ServerInfo::ServerInfo(QString n, bool premium, QDate last, bool preferred) : - m_name(std::move(n)), m_premium(premium), m_lastSeen(std::move(last)), - m_preferred(preferred) +ServerInfo::ServerInfo( + QString name, bool premium, QDate last, int preferred, + int count, double speed) : + m_name(std::move(name)), m_premium(premium), m_lastSeen(std::move(last)), + m_preferred(preferred), m_downloadCount(count), m_downloadSpeed(speed) { } @@ -26,7 +28,58 @@ const QDate& ServerInfo::lastSeen() const return m_lastSeen; } -bool ServerInfo::isPreferred() const +int ServerInfo::preferred() const { return m_preferred; } + +int ServerInfo::downloadCount() const +{ + return m_downloadCount; +} + +double ServerInfo::downloadSpeed() const +{ + return m_downloadSpeed; +} + +void ServerInfo::setPreferred(int i) +{ + m_preferred = i; +} + + +void ServerList::add(ServerInfo s) +{ + m_servers.push_back(std::move(s)); +} + +ServerList::iterator ServerList::begin() +{ + return m_servers.begin(); +} + +ServerList::const_iterator ServerList::begin() const +{ + return m_servers.begin(); +} + +ServerList::iterator ServerList::end() +{ + return m_servers.end(); +} + +ServerList::const_iterator ServerList::end() const +{ + return m_servers.end(); +} + +std::size_t ServerList::size() const +{ + return m_servers.size(); +} + +bool ServerList::empty() const +{ + return m_servers.empty(); +} diff --git a/src/serverinfo.h b/src/serverinfo.h index 79b90e77..0a8a5028 100644 --- a/src/serverinfo.h +++ b/src/serverinfo.h @@ -9,20 +9,49 @@ class ServerInfo { public: ServerInfo(); - ServerInfo(QString name, bool premium, QDate lastSeen, bool preferred); + ServerInfo( + QString name, bool premium, QDate lastSeen, int preferred, + int downloadCount, double downloadSpeed); const QString& name() const; bool isPremium() const; const QDate& lastSeen() const; - bool isPreferred() const; + int preferred() const; + int downloadCount() const; + double downloadSpeed() const; + + void setPreferred(int i); private: QString m_name; bool m_premium; QDate m_lastSeen; - bool m_preferred; + int m_preferred; + int m_downloadCount; + double m_downloadSpeed; }; Q_DECLARE_METATYPE(ServerInfo) + +class ServerList +{ +public: + using container = QList; + using iterator = container::iterator; + using const_iterator = container::const_iterator; + + void add(ServerInfo s); + + iterator begin(); + const_iterator begin() const; + iterator end(); + const_iterator end() const; + std::size_t size() const; + bool empty() const; + +private: + container m_servers; +}; + #endif // SERVERINFO_H diff --git a/src/settings.cpp b/src/settings.cpp index 9975642b..5ddffd8f 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -884,17 +884,42 @@ std::map Settings::getPreferredServers() return result; } -void Settings::updateServers(const QList &servers) +ServerList Settings::getServers() const +{ + ServerList list; + + m_Settings.beginGroup("Servers"); + + for (const QString &serverKey : m_Settings.childKeys()) { + QVariantMap data = m_Settings.value(serverKey).toMap(); + + ServerInfo server( + serverKey, + data["premium"].toBool(), + data["lastSeen"].toDate(), + data["preferred"].toInt(), + data["downloadCount"].toInt(), + data["downloadSpeed"].toDouble()); + + list.add(std::move(server)); + } + + m_Settings.endGroup(); + + return list; +} + +void Settings::updateServers(const ServerList& servers) { m_Settings.beginGroup("Servers"); QStringList oldServerKeys = m_Settings.childKeys(); - for (const ServerInfo &server : servers) { + for (const auto& server : servers) { if (!oldServerKeys.contains(server.name())) { // not yet known server QVariantMap newVal; newVal["premium"] = server.isPremium(); - newVal["preferred"] = server.isPreferred() ? 1 : 0; + newVal["preferred"] = server.preferred(); newVal["lastSeen"] = server.lastSeen(); newVal["downloadCount"] = 0; newVal["downloadSpeed"] = 0.0; @@ -902,12 +927,13 @@ void Settings::updateServers(const QList &servers) m_Settings.setValue(server.name(), newVal); } else { QVariantMap data = m_Settings.value(server.name()).toMap(); - data["lastSeen"] = server.lastSeen(); data["premium"] = server.isPremium(); + data["lastSeen"] = server.lastSeen(); + data["preferred"] = server.preferred(); m_Settings.setValue(server.name(), data); - } } + } // clean up unavailable servers QDate now = QDate::currentDate(); diff --git a/src/settings.h b/src/settings.h index 4662ed19..31dbf85c 100644 --- a/src/settings.h +++ b/src/settings.h @@ -34,6 +34,7 @@ class QSplitter; class PluginContainer; class ServerInfo; +class ServerList; class Settings; class ExpanderWidget; @@ -493,11 +494,13 @@ public: */ std::map getPreferredServers(); + ServerList getServers() const; + /** * @brief updates the list of known servers * @param list of servers from a recent query */ - void updateServers(const QList &servers); + void updateServers(const ServerList& servers); /** * @brief add a plugin that is to be blacklisted diff --git a/src/settingsdialognexus.cpp b/src/settingsdialognexus.cpp index 4d9a18a2..926ea9a6 100644 --- a/src/settingsdialognexus.cpp +++ b/src/settingsdialognexus.cpp @@ -2,9 +2,11 @@ #include "ui_settingsdialog.h" #include "ui_nexusmanualkey.h" #include "nexusinterface.h" +#include "serverinfo.h" +#include "log.h" #include -namespace shell = MOBase::shell; +using namespace MOBase; template class ServerItem : public QListWidgetItem { @@ -78,30 +80,31 @@ NexusSettingsTab::NexusSettingsTab(Settings& s, SettingsDialog& d) ui->hideAPICounterBox->setChecked(settings().hideAPICounter()); // display server preferences - qsettings().beginGroup("Servers"); - for (const QString &key : qsettings().childKeys()) { - QVariantMap val = qsettings().value(key).toMap(); - QString descriptor = key; + for (const auto& server : s.getServers()) { + QString descriptor = server.name(); + if (!descriptor.compare("CDN", Qt::CaseInsensitive)) { descriptor += QStringLiteral(" (automatic)"); } - if (val.contains("downloadSpeed") && val.contains("downloadCount") && (val["downloadCount"].toInt() > 0)) { - int bps = static_cast(val["downloadSpeed"].toDouble() / val["downloadCount"].toInt()); + + if (server.downloadSpeed() > 0 && server.downloadCount() > 0) { + const int bps = static_cast(server.downloadSpeed() / server.downloadCount()); descriptor += QString(" (%1 kbps)").arg(bps / 1024); } QListWidgetItem *newItem = new ServerItem(descriptor, Qt::UserRole + 1); - newItem->setData(Qt::UserRole, key); - newItem->setData(Qt::UserRole + 1, val["preferred"].toInt()); - if (val["preferred"].toInt() > 0) { + newItem->setData(Qt::UserRole, server.name()); + newItem->setData(Qt::UserRole + 1, server.preferred()); + + if (server.preferred() > 0) { ui->preferredServersList->addItem(newItem); } else { ui->knownServersList->addItem(newItem); } + ui->preferredServersList->sortItems(Qt::DescendingOrder); } - qsettings().endGroup(); QObject::connect(ui->nexusConnect, &QPushButton::clicked, [&]{ on_nexusConnect_clicked(); }); QObject::connect(ui->nexusManualKey, &QPushButton::clicked, [&]{ on_nexusManualKey_clicked(); }); @@ -119,22 +122,52 @@ void NexusSettingsTab::update() settings().setEndorsementIntegration(ui->endorsementBox->isChecked()); settings().setHideAPICounter(ui->hideAPICounterBox->isChecked()); + auto servers = settings().getServers(); + // store server preference - qsettings().beginGroup("Servers"); for (int i = 0; i < ui->knownServersList->count(); ++i) { - QString key = ui->knownServersList->item(i)->data(Qt::UserRole).toString(); - QVariantMap val = qsettings().value(key).toMap(); - val["preferred"] = 0; - qsettings().setValue(key, val); + const QString key = ui->knownServersList->item(i)->data(Qt::UserRole).toString(); + + bool found = false; + + for (auto& server : servers) { + if (server.name() == key) { + server.setPreferred(0); + found = true; + break; + } } - int count = ui->preferredServersList->count(); + + if (!found) { + log::error("while setting preferred to 0, server '{}' not found", key); + } + } + + const int count = ui->preferredServersList->count(); + for (int i = 0; i < count; ++i) { - QString key = ui->preferredServersList->item(i)->data(Qt::UserRole).toString(); - QVariantMap val = qsettings().value(key).toMap(); - val["preferred"] = count - i; - qsettings().setValue(key, val); + const QString key = ui->preferredServersList->item(i)->data(Qt::UserRole).toString(); + const int newPreferred = count - i; + + bool found = false; + + for (auto& server : servers) { + + if (server.name() == key) { + server.setPreferred(newPreferred); + found = true; + break; } - qsettings().endGroup(); + } + + if (!found) { + log::error( + "while setting preference to {}, server '{}' not found", + newPreferred, key); + } + } + + settings().updateServers(servers); } void NexusSettingsTab::on_nexusConnect_clicked() -- cgit v1.3.1 From aff3ee8fcf427c9ff8c554a179222eabec3a95e2 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Mon, 26 Aug 2019 01:07:03 -0400 Subject: moved preferred servers into ServerList --- src/downloadmanager.cpp | 40 +++++++++++++++++++++++++++++----------- src/downloadmanager.h | 11 +++++++---- src/mainwindow.cpp | 2 +- src/organizercore.cpp | 2 +- src/serverinfo.cpp | 17 +++++++++++++++++ src/serverinfo.h | 2 ++ src/settings.cpp | 17 ----------------- src/settings.h | 16 ---------------- 8 files changed, 57 insertions(+), 50 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/downloadmanager.cpp b/src/downloadmanager.cpp index 3b084b83..45cfdeed 100644 --- a/src/downloadmanager.cpp +++ b/src/downloadmanager.cpp @@ -288,9 +288,9 @@ void DownloadManager::setOutputDirectory(const QString &outputDirectory) } -void DownloadManager::setPreferredServers(const std::map &preferredServers) +void DownloadManager::setServers(const ServerList& servers) { - m_PreferredServers = preferredServers; + m_Servers = servers; } @@ -1667,23 +1667,38 @@ void DownloadManager::nxmFileInfoAvailable(QString gameName, int modID, int file m_RequestIDs.insert(m_NexusInterface->requestDownloadURL(info->gameName, info->modID, info->fileID, this, qVariantFromValue(test), QString())); } -static int evaluateFileInfoMap(const QVariantMap &map, const std::map &preferredServers) +static int evaluateFileInfoMap( + const QVariantMap &map, + const QList& preferredServers) { - int result = 0; + int preference = 0; + bool found = false; + const auto name = map["short_name"].toString(); - auto preference = preferredServers.find(map["short_name"].toString()); + for (const auto& server : preferredServers) { + if (server.name() == name) { + preference = server.preferred(); + found = true; + break; + } + } - if (preference != preferredServers.end()) { - result += 100 + preference->second * 20; + if (!found) { + log::error("server '{}' not found while sorting by preference", name); + return 0; } - return result; + return 100 + preference * 20; } // sort function to sort by best download server -bool DownloadManager::ServerByPreference(const std::map &preferredServers, const QVariant &LHS, const QVariant &RHS) +bool DownloadManager::ServerByPreference( + const QList& preferredServers, + const QVariant &LHS, const QVariant &RHS) { - return evaluateFileInfoMap(LHS.toMap(), preferredServers) > evaluateFileInfoMap(RHS.toMap(), preferredServers); + const auto a = evaluateFileInfoMap(LHS.toMap(), preferredServers); + const auto b = evaluateFileInfoMap(RHS.toMap(), preferredServers); + return (a > b); } int DownloadManager::startDownloadURLs(const QStringList &urls) @@ -1732,7 +1747,10 @@ void DownloadManager::nxmDownloadURLsAvailable(QString gameName, int modID, int return; } - std::sort(resultList.begin(), resultList.end(), boost::bind(&DownloadManager::ServerByPreference, m_PreferredServers, _1, _2)); + std::sort( + resultList.begin(), + resultList.end(), + boost::bind(&DownloadManager::ServerByPreference, m_Servers.getPreferred(), _1, _2)); info->userData["downloadMap"] = resultList; diff --git a/src/downloadmanager.h b/src/downloadmanager.h index feef0eaa..f739f4f0 100644 --- a/src/downloadmanager.h +++ b/src/downloadmanager.h @@ -20,6 +20,7 @@ along with Mod Organizer. If not, see . #ifndef DOWNLOADMANAGER_H #define DOWNLOADMANAGER_H +#include "serverinfo.h" #include #include #include @@ -174,9 +175,9 @@ public: QString getOutputDirectory() const { return m_OutputDirectory; } /** - * @brief setPreferredServers set the list of preferred servers + * @brief sets the list of servers */ - void setPreferredServers(const std::map &preferredServers); + void setServers(const ServerList& servers); /** * @brief set the list of supported extensions @@ -366,7 +367,9 @@ public: * @param RHS * @return */ - static bool ServerByPreference(const std::map &preferredServers, const QVariant &LHS, const QVariant &RHS); + static bool ServerByPreference( + const QList& preferredServers, + const QVariant &LHS, const QVariant &RHS); virtual int startDownloadURLs(const QStringList &urls); @@ -548,7 +551,7 @@ private: QVector m_ActiveDownloads; QString m_OutputDirectory; - std::map m_PreferredServers; + ServerList m_Servers; QStringList m_SupportedExtensions; std::set m_RequestIDs; QVector m_AlphabeticalTranslation; diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 9921ad82..79203d29 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -5050,7 +5050,7 @@ void MainWindow::on_actionSettings_triggered() dlManager->setOutputDirectory(settings.getDownloadDirectory()); } } - dlManager->setPreferredServers(settings.getPreferredServers()); + dlManager->setServers(settings.getServers()); if ((settings.getModDirectory() != oldModDirectory) || (settings.displayForeign() != oldDisplayForeign)) { diff --git a/src/organizercore.cpp b/src/organizercore.cpp index 5a8ee4c2..522d28be 100644 --- a/src/organizercore.cpp +++ b/src/organizercore.cpp @@ -276,7 +276,7 @@ OrganizerCore::OrganizerCore(Settings &settings) , m_PluginListsWriter(std::bind(&OrganizerCore::savePluginList, this)) { m_DownloadManager.setOutputDirectory(m_Settings.getDownloadDirectory()); - m_DownloadManager.setPreferredServers(m_Settings.getPreferredServers()); + m_DownloadManager.setServers(m_Settings.getServers()); NexusInterface::instance(m_PluginContainer)->setCacheDirectory(m_Settings.getCacheDirectory()); diff --git a/src/serverinfo.cpp b/src/serverinfo.cpp index 67a80b9e..70cdec6d 100644 --- a/src/serverinfo.cpp +++ b/src/serverinfo.cpp @@ -52,6 +52,10 @@ void ServerInfo::setPreferred(int i) void ServerList::add(ServerInfo s) { m_servers.push_back(std::move(s)); + + std::sort(m_servers.begin(), m_servers.end(), [](auto&& a, auto&& b){ + return (a.preferred() < b.preferred()); + }); } ServerList::iterator ServerList::begin() @@ -83,3 +87,16 @@ bool ServerList::empty() const { return m_servers.empty(); } + +ServerList::container ServerList::getPreferred() const +{ + container v; + + for (const auto& server : m_servers) { + if (server.preferred() > 0) { + v.push_back(server); + } + } + + return v; +} diff --git a/src/serverinfo.h b/src/serverinfo.h index 0a8a5028..2e5682fc 100644 --- a/src/serverinfo.h +++ b/src/serverinfo.h @@ -50,6 +50,8 @@ public: std::size_t size() const; bool empty() const; + container getPreferred() const; + private: container m_servers; }; diff --git a/src/settings.cpp b/src/settings.cpp index 5ddffd8f..c57530e4 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -867,23 +867,6 @@ void Settings::setDownloadSpeed(const QString &serverName, int bytesPerSecond) m_Settings.sync(); } -std::map Settings::getPreferredServers() -{ - std::map result; - m_Settings.beginGroup("Servers"); - - for (const QString &serverKey : m_Settings.childKeys()) { - QVariantMap data = m_Settings.value(serverKey).toMap(); - int preference = data["preferred"].toInt(); - if (preference > 0) { - result[serverKey] = preference; - } - } - m_Settings.endGroup(); - - return result; -} - ServerList Settings::getServers() const { ServerList list; diff --git a/src/settings.h b/src/settings.h index 31dbf85c..e7337301 100644 --- a/src/settings.h +++ b/src/settings.h @@ -482,24 +482,8 @@ public: QString language(); void setLanguage(const QString& name); - /** - * @brief register download speed - * @param url complete download url - * @param bytesPerSecond download size in bytes per second - */ void setDownloadSpeed(const QString &serverName, int bytesPerSecond); - - /** - * retrieve a sorted list of preferred servers - */ - std::map getPreferredServers(); - ServerList getServers() const; - - /** - * @brief updates the list of known servers - * @param list of servers from a recent query - */ void updateServers(const ServerList& servers); /** -- cgit v1.3.1 From 896d80d02ccef746ba6598534ce444da2755ae04 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Mon, 26 Aug 2019 01:31:56 -0400 Subject: server settings converted to array instead of byte array map moved cleanup to ServerList --- src/serverinfo.cpp | 22 +++++++++++++ src/serverinfo.h | 4 +++ src/settings.cpp | 94 +++++++++++++++++++++++++++++++++++------------------- src/settings.h | 3 +- 4 files changed, 90 insertions(+), 33 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/serverinfo.cpp b/src/serverinfo.cpp index 70cdec6d..16e65f52 100644 --- a/src/serverinfo.cpp +++ b/src/serverinfo.cpp @@ -1,4 +1,7 @@ #include "serverinfo.h" +#include "log.h" + +using namespace MOBase; ServerInfo::ServerInfo() : ServerInfo({}, false, {}, 0, 0, 0.0) @@ -100,3 +103,22 @@ ServerList::container ServerList::getPreferred() const return v; } + +void ServerList::cleanup() +{ + QDate now = QDate::currentDate(); + + for (auto itor=m_servers.begin(); itor!=m_servers.end(); ) { + const QDate lastSeen = itor->lastSeen(); + + if (lastSeen.daysTo(now) > 30) { + log::debug( + "removing server {} since it hasn't been available for downloads " + "in over a month", itor->name()); + + itor = m_servers.erase(itor); + } else { + ++itor; + } + } +} diff --git a/src/serverinfo.h b/src/serverinfo.h index 2e5682fc..c6e3b640 100644 --- a/src/serverinfo.h +++ b/src/serverinfo.h @@ -52,6 +52,10 @@ public: container getPreferred() const; + // removes servers that haven't been seen in a while + // + void cleanup(); + private: container m_servers; }; diff --git a/src/settings.cpp b/src/settings.cpp index c57530e4..3a7bda75 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -869,6 +869,50 @@ void Settings::setDownloadSpeed(const QString &serverName, int bytesPerSecond) ServerList Settings::getServers() const { + // servers used to be a map of byte arrays until 2.2.1, it's now an array of + // individual values instead + // + // 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 + m_Settings.beginGroup("Servers"); + const auto keys = m_Settings.childKeys(); + m_Settings.endGroup(); + + if (!keys.empty() && keys[0] != "size") { + // old format + return getServersFromOldMap(); + } + + + ServerList list; + + const int size = m_Settings.beginReadArray("Servers"); + + for (int i=0; i 30) { - log::debug("removing server {} since it hasn't been available for downloads in over a month", key); - m_Settings.remove(key); - } + ++i; } - m_Settings.endGroup(); - - m_Settings.sync(); + m_Settings.endArray(); } void Settings::addBlacklistPlugin(const QString &fileName) diff --git a/src/settings.h b/src/settings.h index e7337301..810daac2 100644 --- a/src/settings.h +++ b/src/settings.h @@ -484,7 +484,8 @@ public: void setDownloadSpeed(const QString &serverName, int bytesPerSecond); ServerList getServers() const; - void updateServers(const ServerList& servers); + ServerList getServersFromOldMap() const; + void updateServers(ServerList servers); /** * @brief add a plugin that is to be blacklisted -- cgit v1.3.1 From c42e5fb2fec9b20fe6956d8798b85874b2eff73e Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Mon, 26 Aug 2019 03:01:55 -0400 Subject: changed total speed and count to a list of the last 5 downloads existing servers now merged when retrieving the download links download manager doesn't store the servers any more, queries the settings every time --- src/downloadmanager.cpp | 17 +++++------ src/downloadmanager.h | 17 ----------- src/mainwindow.cpp | 31 ++++++++++++------- src/organizercore.cpp | 1 - src/serverinfo.cpp | 72 +++++++++++++++++++++++++++++++++++++++------ src/serverinfo.h | 21 ++++++++----- src/settings.cpp | 51 ++++++++++++++++++++++---------- src/settingsdialognexus.cpp | 6 ++-- 8 files changed, 143 insertions(+), 73 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/downloadmanager.cpp b/src/downloadmanager.cpp index 45cfdeed..93ca1608 100644 --- a/src/downloadmanager.cpp +++ b/src/downloadmanager.cpp @@ -288,12 +288,6 @@ void DownloadManager::setOutputDirectory(const QString &outputDirectory) } -void DownloadManager::setServers(const ServerList& servers) -{ - m_Servers = servers; -} - - void DownloadManager::setSupportedExtensions(const QStringList &extensions) { m_SupportedExtensions = extensions; @@ -1669,7 +1663,7 @@ void DownloadManager::nxmFileInfoAvailable(QString gameName, int modID, int file static int evaluateFileInfoMap( const QVariantMap &map, - const QList& preferredServers) + const ServerList::container& preferredServers) { int preference = 0; bool found = false; @@ -1692,8 +1686,9 @@ static int evaluateFileInfoMap( } // sort function to sort by best download server -bool DownloadManager::ServerByPreference( - const QList& preferredServers, +// +bool ServerByPreference( + const ServerList::container& preferredServers, const QVariant &LHS, const QVariant &RHS) { const auto a = evaluateFileInfoMap(LHS.toMap(), preferredServers); @@ -1747,10 +1742,12 @@ void DownloadManager::nxmDownloadURLsAvailable(QString gameName, int modID, int return; } + const auto servers = m_OrganizerCore->settings().getServers(); + std::sort( resultList.begin(), resultList.end(), - boost::bind(&DownloadManager::ServerByPreference, m_Servers.getPreferred(), _1, _2)); + boost::bind(&ServerByPreference, servers.getPreferred(), _1, _2)); info->userData["downloadMap"] = resultList; diff --git a/src/downloadmanager.h b/src/downloadmanager.h index f739f4f0..bed1b3cc 100644 --- a/src/downloadmanager.h +++ b/src/downloadmanager.h @@ -174,11 +174,6 @@ public: **/ QString getOutputDirectory() const { return m_OutputDirectory; } - /** - * @brief sets the list of servers - */ - void setServers(const ServerList& servers); - /** * @brief set the list of supported extensions * @param extensions list of supported extensions @@ -361,17 +356,6 @@ public: */ void refreshList(); - /** - * @brief Sort function for download servers - * @param LHS - * @param RHS - * @return - */ - static bool ServerByPreference( - const QList& preferredServers, - const QVariant &LHS, const QVariant &RHS); - - virtual int startDownloadURLs(const QStringList &urls); virtual int startDownloadNexusFile(int modID, int fileID); @@ -551,7 +535,6 @@ private: QVector m_ActiveDownloads; QString m_OutputDirectory; - ServerList m_Servers; QStringList m_SupportedExtensions; std::set m_RequestIDs; QVector m_AlphabeticalTranslation; diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 79203d29..4c2594b8 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -5050,7 +5050,6 @@ void MainWindow::on_actionSettings_triggered() dlManager->setOutputDirectory(settings.getDownloadDirectory()); } } - dlManager->setServers(settings.getServers()); if ((settings.getModDirectory() != oldModDirectory) || (settings.displayForeign() != oldDisplayForeign)) { @@ -5904,20 +5903,32 @@ void MainWindow::nxmTrackedModsAvailable(QVariant userData, QVariant resultData, void MainWindow::nxmDownloadURLs(QString, int, int, QVariant, QVariant resultData, int) { - ServerList servers; + auto servers = m_OrganizerCore.settings().getServers(); for (const QVariant &var : resultData.toList()) { const QVariantMap map = var.toMap(); - ServerInfo server( - map["short_name"].toString(), - map["name"].toString().contains("Premium", Qt::CaseInsensitive), - QDate::currentDate(), - map["short_name"].toString().contains("CDN", Qt::CaseInsensitive) ? 1 : 0, - map["downloadCount"].toInt(), - map["downloadSpeed"].toDouble()); + const auto name = map["short_name"].toString(); + const auto isPremium = map["name"].toString().contains("Premium", Qt::CaseInsensitive); + const auto isCDN = map["short_name"].toString().contains("CDN", Qt::CaseInsensitive); - servers.add(std::move(server)); + bool found = false; + + for (auto& server : servers) { + if (server.name() == name) { + // already exists, update + server.setPremium(isPremium); + server.updateLastSeen(); + found = true; + break; + } + } + + if (!found) { + // new server + ServerInfo server(name, isPremium, QDate::currentDate(), isCDN ? 1 : 0, {}); + servers.add(std::move(server)); + } } m_OrganizerCore.settings().updateServers(servers); diff --git a/src/organizercore.cpp b/src/organizercore.cpp index 522d28be..ec13ca9c 100644 --- a/src/organizercore.cpp +++ b/src/organizercore.cpp @@ -276,7 +276,6 @@ OrganizerCore::OrganizerCore(Settings &settings) , m_PluginListsWriter(std::bind(&OrganizerCore::savePluginList, this)) { m_DownloadManager.setOutputDirectory(m_Settings.getDownloadDirectory()); - m_DownloadManager.setServers(m_Settings.getServers()); NexusInterface::instance(m_PluginContainer)->setCacheDirectory(m_Settings.getCacheDirectory()); diff --git a/src/serverinfo.cpp b/src/serverinfo.cpp index 16e65f52..aece61da 100644 --- a/src/serverinfo.cpp +++ b/src/serverinfo.cpp @@ -3,17 +3,23 @@ using namespace MOBase; +const std::size_t MaxDownloadCount = 5; + + ServerInfo::ServerInfo() - : ServerInfo({}, false, {}, 0, 0, 0.0) + : ServerInfo({}, false, {}, 0, {}) { } ServerInfo::ServerInfo( QString name, bool premium, QDate last, int preferred, - int count, double speed) : + SpeedList lastDownloads) : m_name(std::move(name)), m_premium(premium), m_lastSeen(std::move(last)), - m_preferred(preferred), m_downloadCount(count), m_downloadSpeed(speed) + m_preferred(preferred), m_lastDownloads(std::move(lastDownloads)) { + if (m_lastDownloads.size() > MaxDownloadCount) { + m_lastDownloads.resize(MaxDownloadCount); + } } const QString& ServerInfo::name() const @@ -26,29 +32,77 @@ bool ServerInfo::isPremium() const return m_premium; } +void ServerInfo::setPremium(bool b) +{ + m_premium = b; +} + const QDate& ServerInfo::lastSeen() const { return m_lastSeen; } +void ServerInfo::updateLastSeen() +{ + m_lastSeen = QDate::currentDate(); +} + int ServerInfo::preferred() const { return m_preferred; } -int ServerInfo::downloadCount() const +void ServerInfo::setPreferred(int i) { - return m_downloadCount; + m_preferred = i; } -double ServerInfo::downloadSpeed() const +const ServerInfo::SpeedList& ServerInfo::lastDownloads() const { - return m_downloadSpeed; + return m_lastDownloads; } -void ServerInfo::setPreferred(int i) +int ServerInfo::averageSpeed() const { - m_preferred = i; + int count = 0; + int total = 0; + + for (const auto& s : m_lastDownloads) { + if (s > 0) { + ++count; + total += s; + } + } + + if (count > 0) { + return static_cast(total) / count; + } + + return 0; +} + +void ServerInfo::addDownload(int bytesPerSecond) +{ + if (bytesPerSecond <= 0) { + log::error( + "trying to add download with {} B/s to server '{}'; ignoring", + bytesPerSecond, m_name); + + return; + } + + if (m_lastDownloads.size() == MaxDownloadCount) { + std::rotate( + m_lastDownloads.begin(), + m_lastDownloads.begin() + 1, + m_lastDownloads.end()); + + m_lastDownloads.back() = bytesPerSecond; + } else { + m_lastDownloads.push_back(bytesPerSecond); + } + + log::debug("added download at {} B/s to server '{}'", bytesPerSecond, m_name); } diff --git a/src/serverinfo.h b/src/serverinfo.h index c6e3b640..af8f77c8 100644 --- a/src/serverinfo.h +++ b/src/serverinfo.h @@ -8,27 +8,34 @@ class ServerInfo { public: + using SpeedList = std::vector; + ServerInfo(); ServerInfo( QString name, bool premium, QDate lastSeen, int preferred, - int downloadCount, double downloadSpeed); + SpeedList lastDownloads); const QString& name() const; + bool isPremium() const; + void setPremium(bool b); + const QDate& lastSeen() const; - int preferred() const; - int downloadCount() const; - double downloadSpeed() const; + void updateLastSeen(); + int preferred() const; void setPreferred(int i); + const SpeedList& lastDownloads() const; + int averageSpeed() const; + void addDownload(int bytesPerSecond); + private: QString m_name; bool m_premium; QDate m_lastSeen; int m_preferred; - int m_downloadCount; - double m_downloadSpeed; + SpeedList m_lastDownloads; }; Q_DECLARE_METATYPE(ServerInfo) @@ -37,7 +44,7 @@ Q_DECLARE_METATYPE(ServerInfo) class ServerList { public: - using container = QList; + using container = std::vector; using iterator = container::iterator; using const_iterator = container::const_iterator; diff --git a/src/settings.cpp b/src/settings.cpp index 3a7bda75..b11bc61c 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -850,21 +850,21 @@ void Settings::setLanguage(const QString& name) m_Settings.setValue("Settings/language", name); } -void Settings::setDownloadSpeed(const QString &serverName, int bytesPerSecond) +void Settings::setDownloadSpeed(const QString& name, int bytesPerSecond) { - m_Settings.beginGroup("Servers"); + auto servers = getServers(); - for (const QString &serverKey : m_Settings.childKeys()) { - QVariantMap data = m_Settings.value(serverKey).toMap(); - if (serverKey == serverName) { - data["downloadCount"] = data["downloadCount"].toInt() + 1; - data["downloadSpeed"] = data["downloadSpeed"].toDouble() + static_cast(bytesPerSecond); - m_Settings.setValue(serverKey, data); + for (auto& server : servers) { + if (server.name() == name) { + server.addDownload(bytesPerSecond); + updateServers(servers); + return; } } - m_Settings.endGroup(); - m_Settings.sync(); + log::error( + "server '{}' not found while trying to add a download with bps {}", + name, bytesPerSecond); } ServerList Settings::getServers() const @@ -885,6 +885,7 @@ ServerList Settings::getServers() const return getServersFromOldMap(); } + // post 2.2.1 format, array of values ServerList list; @@ -893,13 +894,22 @@ ServerList Settings::getServers() const for (int i=0; i 0) { + lastDownloads.push_back(bytesPerSecond); + } + } + 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(), - m_Settings.value("downloadCount").toInt(), - m_Settings.value("downloadSpeed").toDouble()); + lastDownloads); list.add(std::move(server)); } @@ -925,8 +935,10 @@ ServerList Settings::getServersFromOldMap() const data["premium"].toBool(), data["lastSeen"].toDate(), data["preferred"].toInt(), - data["downloadCount"].toInt(), - data["downloadSpeed"].toDouble()); + {}); + + // ignoring download count and speed, it's now a list of values instead of + // a total list.add(std::move(server)); } @@ -955,8 +967,15 @@ void Settings::updateServers(ServerList servers) m_Settings.setValue("premium", server.isPremium()); m_Settings.setValue("lastSeen", server.lastSeen().toString(Qt::ISODate)); m_Settings.setValue("preferred", server.preferred()); - m_Settings.setValue("downloadCount", server.downloadCount()); - m_Settings.setValue("downloadSpeed", server.downloadSpeed()); + + QString lastDownloads; + for (const auto& speed : server.lastDownloads()) { + if (speed > 0) { + lastDownloads += QString("%1 ").arg(speed); + } + } + + m_Settings.setValue("lastDownloads", lastDownloads.trimmed()); ++i; } diff --git a/src/settingsdialognexus.cpp b/src/settingsdialognexus.cpp index 926ea9a6..f2bd3ab5 100644 --- a/src/settingsdialognexus.cpp +++ b/src/settingsdialognexus.cpp @@ -87,9 +87,9 @@ NexusSettingsTab::NexusSettingsTab(Settings& s, SettingsDialog& d) descriptor += QStringLiteral(" (automatic)"); } - if (server.downloadSpeed() > 0 && server.downloadCount() > 0) { - const int bps = static_cast(server.downloadSpeed() / server.downloadCount()); - descriptor += QString(" (%1 kbps)").arg(bps / 1024); + const auto averageSpeed = server.averageSpeed(); + if (averageSpeed > 0) { + descriptor += QString(" (%1 kbps)").arg(averageSpeed / 1024); } QListWidgetItem *newItem = new ServerItem(descriptor, Qt::UserRole + 1); -- cgit v1.3.1 From 2eee72da6815f9d5c643b58c95f633e69da5150a Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Mon, 26 Aug 2019 04:21:06 -0400 Subject: moved code for byte sizes and speed to uibase added scoped classes for QSettings groups and arrays servers logged on startup --- src/downloadlist.cpp | 21 +--- src/downloadlist.h | 2 - src/downloadmanager.cpp | 19 +--- src/settings.cpp | 270 +++++++++++++++++++++++++++++--------------- src/settingsdialognexus.cpp | 2 +- 5 files changed, 184 insertions(+), 130 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/downloadlist.cpp b/src/downloadlist.cpp index 36bc2b7f..6957f270 100644 --- a/src/downloadlist.cpp +++ b/src/downloadlist.cpp @@ -19,6 +19,7 @@ along with Mod Organizer. If not, see . #include "downloadlist.h" #include "downloadmanager.h" +#include #include #include #include @@ -121,7 +122,7 @@ QVariant DownloadList::data(const QModelIndex &index, int role) const return QString("%1").arg(m_Manager->getModID(index.row())); } } - case COL_SIZE: return sizeFormat(m_Manager->getFileSize(index.row())); + case COL_SIZE: return MOBase::localizedByteSize(m_Manager->getFileSize(index.row())); case COL_FILETIME: return m_Manager->getFileTime(index.row()); case COL_STATUS: switch (m_Manager->getState(index.row())) { @@ -195,21 +196,3 @@ void DownloadList::update(int row) else log::error("invalid row {} in download list, update failed", row); } - -QString DownloadList::sizeFormat(quint64 size) const -{ - qreal calc = size; - QStringList list; - list << "MB" << "GB" << "TB"; - - QStringListIterator i(list); - QString unit("KB"); - - calc /= 1024.0; - while (calc >= 1024.0 && i.hasNext()) { - unit = i.next(); - calc /= 1024.0; - } - - return QString().setNum(calc, 'f', 2) + " " + unit; -} diff --git a/src/downloadlist.h b/src/downloadlist.h index 6f63f0c8..51ab4541 100644 --- a/src/downloadlist.h +++ b/src/downloadlist.h @@ -99,8 +99,6 @@ private: DownloadManager *m_Manager; bool m_MetaDisplay; - - QString sizeFormat(quint64 size) const; }; #endif // DOWNLOADLIST_H diff --git a/src/downloadmanager.cpp b/src/downloadmanager.cpp index 93ca1608..a5dc164c 100644 --- a/src/downloadmanager.cpp +++ b/src/downloadmanager.cpp @@ -1441,22 +1441,11 @@ void DownloadManager::downloadProgress(qint64 bytesReceived, qint64 bytesTotal) std::get<4>(info->m_SpeedDiff) = ((calc*0.5) + (std::get<4>(info->m_SpeedDiff)*1.5)) / 2; // calculate the download speed - double speed = (std::get<4>(info->m_SpeedDiff) * 1000.0) / (5 * 1000); + const double speed = (std::get<4>(info->m_SpeedDiff) * 1000.0) / (5 * 1000); - QString unit; - if (speed < 1000) { - unit = "B/s"; - } - else if (speed < 1000*1024) { - speed /= 1024; - unit = "KB/s"; - } - else { - speed /= 1024 * 1024; - unit = "MB/s"; - } - - info->m_Progress.second = QString::fromLatin1("%1% - %2 %3").arg(info->m_Progress.first).arg(QString::number(speed, 'f', 1)).arg(unit); + info->m_Progress.second = QString::fromLatin1("%1% - %2") + .arg(info->m_Progress.first) + .arg(MOBase::localizedByteSpeed(speed)); TaskProgressManager::instance().updateProgress(info->m_TaskProgressId, bytesReceived, bytesTotal); emit update(index); diff --git a/src/settings.cpp b/src/settings.cpp index b11bc61c..406544f7 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -27,6 +27,78 @@ along with Mod Organizer. If not, see . using namespace MOBase; +class ScopedGroup +{ +public: + ScopedGroup(QSettings& s, const QString& name) + : m_settings(s) + { + m_settings.beginGroup(name); + } + + ~ScopedGroup() + { + m_settings.endGroup(); + } + + ScopedGroup(const ScopedGroup&) = delete; + ScopedGroup& operator=(const ScopedGroup&) = delete; + +private: + QSettings& m_settings; +}; + + +class ScopedReadArray +{ +public: + ScopedReadArray(QSettings& s, const QString& name) + : m_settings(s), m_count(0) + { + m_count = m_settings.beginReadArray(name); + } + + ~ScopedReadArray() + { + m_settings.endArray(); + } + + ScopedReadArray(const ScopedReadArray&) = delete; + ScopedReadArray& operator=(const ScopedReadArray&) = delete; + + int count() const + { + return m_count; + } + +private: + QSettings& m_settings; + int m_count; +}; + + +class ScopedWriteArray +{ +public: + ScopedWriteArray(QSettings& s, const QString& name) + : m_settings(s) + { + m_settings.beginWriteArray(name); + } + + ~ScopedWriteArray() + { + m_settings.endArray(); + } + + ScopedWriteArray(const ScopedWriteArray&) = delete; + ScopedWriteArray& operator=(const ScopedWriteArray&) = delete; + +private: + QSettings& m_settings; +}; + + template std::optional getOptional( const QSettings& s, const QString& name, std::optional def={}) @@ -206,19 +278,21 @@ void Settings::processUpdates( } if (lastVersion < QVersionNumber(2, 2, 0)) { - m_Settings.beginGroup("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"); - m_Settings.endGroup(); - - m_Settings.beginGroup("Servers"); - m_Settings.remove(""); - m_Settings.endGroup(); + { + 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"); + } + + { + ScopedGroup sg(m_Settings, "Servers"); + m_Settings.remove(""); + } } if (lastVersion < QVersionNumber(2, 2, 1)) { @@ -251,12 +325,12 @@ void Settings::clearPlugins() m_PluginSettings.clear(); m_PluginBlacklist.clear(); - int count = m_Settings.beginReadArray("pluginBlacklist"); - for (int i = 0; i < count; ++i) { + + 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()); } - m_Settings.endArray(); } bool Settings::pluginBlacklisted(const QString &fileName) const @@ -876,46 +950,50 @@ ServerList Settings::getServers() const // in 2.2.1, one key per server is returned // getting the keys - m_Settings.beginGroup("Servers"); - const auto keys = m_Settings.childKeys(); - m_Settings.endGroup(); + QStringList keys; + + { + ScopedGroup sg(m_Settings, "Servers"); + keys = m_Settings.childKeys(); + } if (!keys.empty() && keys[0] != "size") { // old format return getServersFromOldMap(); } + // post 2.2.1 format, array of values ServerList list; - const int size = m_Settings.beginReadArray("Servers"); + { + ScopedReadArray sra(m_Settings, "Servers"); - for (int i=0; i 0) { - lastDownloads.push_back(bytesPerSecond); + const auto lastDownloadsString = m_Settings.value("lastDownloads").toString(); + for (const auto& s : lastDownloadsString.split(" ")) { + const auto bytesPerSecond = s.toInt(); + if (bytesPerSecond > 0) { + lastDownloads.push_back(bytesPerSecond); + } } - } - 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(), - lastDownloads); + 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(), + lastDownloads); - list.add(std::move(server)); + list.add(std::move(server)); + } } - m_Settings.endArray(); - return list; } @@ -924,8 +1002,7 @@ ServerList Settings::getServersFromOldMap() const // for 2.2.1 and before ServerList list; - - m_Settings.beginGroup("Servers"); + ScopedGroup sg(m_Settings, "Servers"); for (const QString &serverKey : m_Settings.childKeys()) { QVariantMap data = m_Settings.value(serverKey).toMap(); @@ -943,8 +1020,6 @@ ServerList Settings::getServersFromOldMap() const list.add(std::move(server)); } - m_Settings.endGroup(); - return list; } @@ -953,34 +1028,35 @@ void Settings::updateServers(ServerList servers) // clean up unavailable servers servers.cleanup(); - m_Settings.beginGroup("Servers"); - m_Settings.remove(""); - m_Settings.endGroup(); - - m_Settings.beginWriteArray("Servers"); - - int i=0; - for (const auto& server : servers) { - m_Settings.setArrayIndex(i); - - 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()); + { + ScopedGroup sg(m_Settings, "Servers"); + m_Settings.remove(""); + } - QString lastDownloads; - for (const auto& speed : server.lastDownloads()) { - if (speed > 0) { - lastDownloads += QString("%1 ").arg(speed); + { + ScopedWriteArray swa(m_Settings, "Servers"); + + int i=0; + for (const auto& server : servers) { + m_Settings.setArrayIndex(i); + + 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()); + + QString lastDownloads; + for (const auto& speed : server.lastDownloads()) { + if (speed > 0) { + lastDownloads += QString("%1 ").arg(speed); + } } - } - m_Settings.setValue("lastDownloads", lastDownloads.trimmed()); + m_Settings.setValue("lastDownloads", lastDownloads.trimmed()); - ++i; + ++i; + } } - - m_Settings.endArray(); } void Settings::addBlacklistPlugin(const QString &fileName) @@ -992,23 +1068,22 @@ void Settings::addBlacklistPlugin(const QString &fileName) void Settings::writePluginBlacklist() { m_Settings.remove("pluginBlacklist"); - m_Settings.beginWriteArray("pluginBlacklist"); + + ScopedWriteArray swa(m_Settings, "pluginBlacklist"); int idx = 0; for (const QString &plugin : m_PluginBlacklist) { m_Settings.setArrayIndex(idx++); m_Settings.setValue("name", plugin); } - - m_Settings.endArray(); } std::map Settings::getRecentDirectories() const { std::map map; - const int size = m_Settings.beginReadArray("recentDirectories"); + ScopedReadArray sra(m_Settings, "recentDirectories"); - for (int i=0; i Settings::getRecentDirectories() const } } - m_Settings.endArray(); - return map; } void Settings::setRecentDirectories(const std::map& map) { m_Settings.remove("recentDirectories"); - m_Settings.beginWriteArray("recentDirectories"); + + ScopedWriteArray swa(m_Settings, "recentDirectories"); int index = 0; for (auto&& p : map) { @@ -1037,16 +1111,14 @@ void Settings::setRecentDirectories(const std::map& map) ++index; } - - m_Settings.endArray(); } std::vector> Settings::getExecutables() const { - const int count = m_Settings.beginReadArray("customExecutables"); + ScopedReadArray sra(m_Settings, "customExecutables"); std::vector> v; - for (int i=0; i map; @@ -1059,15 +1131,14 @@ std::vector> Settings::getExecutables() const v.push_back(map); } - m_Settings.endArray(); - return v; } void Settings::setExecutables(const std::vector>& v) { m_Settings.remove("customExecutables"); - m_Settings.beginWriteArray("customExecutables"); + + ScopedWriteArray swa(m_Settings, "customExecutables"); int i = 0; @@ -1080,8 +1151,6 @@ void Settings::setExecutables(const std::vector>& v) ++i; } - - m_Settings.endArray(); } bool Settings::isTutorialCompleted(const QString& windowName) const @@ -1154,9 +1223,8 @@ void Settings::setQuestionFileButton( void Settings::resetQuestionButtons() { - m_Settings.beginGroup("DialogChoices"); + ScopedGroup sg(m_Settings, "DialogChoices"); m_Settings.remove(""); - m_Settings.endGroup(); } std::optional Settings::getIndex(const QComboBox* cb) const @@ -1248,17 +1316,34 @@ void Settings::dump() const log::debug("settings:"); - m_Settings.beginGroup("Settings"); + { + ScopedGroup sg(m_Settings, "Settings"); - for (auto k : m_Settings.allKeys()) { - if (ignore.contains(k, Qt::CaseInsensitive)) { - continue; - } + for (auto k : m_Settings.allKeys()) { + if (ignore.contains(k, Qt::CaseInsensitive)) { + continue; + } - log::debug(" . {}={}", k, m_Settings.value(k).toString()); + log::debug(" . {}={}", k, m_Settings.value(k).toString()); + } } - m_Settings.endGroup(); + log::debug("servers:"); + + for (const auto& server : getServers()) { + QString lastDownloads; + for (auto speed : server.lastDownloads()) { + lastDownloads += QString("%1 ").arg(speed); + } + + log::debug( + " . {} premium={} lastSeen={} preferred={} lastDownloads={}", + server.name(), + server.isPremium() ? "yes" : "no", + server.lastSeen().toString(Qt::ISODate), + server.preferred(), + lastDownloads.trimmed()); + } } @@ -1278,9 +1363,8 @@ void GeometrySettings::resetIfNeeded() return; } - m_Settings.beginGroup("geometry"); + ScopedGroup sg(m_Settings, "geometry"); m_Settings.remove(""); - m_Settings.endGroup(); } void GeometrySettings::saveGeometry(const QWidget* w) diff --git a/src/settingsdialognexus.cpp b/src/settingsdialognexus.cpp index f2bd3ab5..3de1a6ba 100644 --- a/src/settingsdialognexus.cpp +++ b/src/settingsdialognexus.cpp @@ -89,7 +89,7 @@ NexusSettingsTab::NexusSettingsTab(Settings& s, SettingsDialog& d) const auto averageSpeed = server.averageSpeed(); if (averageSpeed > 0) { - descriptor += QString(" (%1 kbps)").arg(averageSpeed / 1024); + descriptor += QString(" (%1)").arg(MOBase::localizedByteSpeed(averageSpeed)); } QListWidgetItem *newItem = new ServerItem(descriptor, Qt::UserRole + 1); -- cgit v1.3.1 From 8708265f69491b807b1dc56d0804230b80ffbdb8 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Mon, 26 Aug 2019 04:52:15 -0400 Subject: moved setting paths to Settings --- src/settings.cpp | 97 +++++++++++++++++++++++++++++++++++++-------- src/settings.h | 37 +++++------------ src/settingsdialogpaths.cpp | 36 ++++++++--------- 3 files changed, 107 insertions(+), 63 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/settings.cpp b/src/settings.cpp index 406544f7..34b1b4ac 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -492,34 +492,108 @@ QString Settings::getConfigurablePath(const QString &key, const QString &def, bool resolve) const { + const QString settingName = "Settings/" + key; + QString result = QDir::fromNativeSeparators( - m_Settings.value(QString("settings/") + key, QString("%BASE_DIR%/") + def) - .toString()); + m_Settings.value(settingName, QString("%BASE_DIR%/") + def).toString()); + if (resolve) { result.replace("%BASE_DIR%", getBaseDirectory()); } + return result; } +void Settings::setConfigurablePath(const QString &key, const QString& path) +{ + const QString settingName = "Settings/" + key; + + if (path.isEmpty()) { + m_Settings.remove(settingName); + } else { + m_Settings.setValue(settingName, path); + } +} + QString Settings::getBaseDirectory() const { return QDir::fromNativeSeparators(m_Settings.value( - "settings/base_directory", qApp->property("dataPath").toString()).toString()); + "settings/base_directory", + qApp->property("dataPath").toString()).toString()); } QString Settings::getDownloadDirectory(bool resolve) const { - return getConfigurablePath("download_directory", ToQString(AppConfig::downloadPath()), resolve); + return getConfigurablePath( + "download_directory", + ToQString(AppConfig::downloadPath()), + resolve); } QString Settings::getCacheDirectory(bool resolve) const { - return getConfigurablePath("cache_directory", ToQString(AppConfig::cachePath()), resolve); + return getConfigurablePath( + "cache_directory", + ToQString(AppConfig::cachePath()), + resolve); } QString Settings::getModDirectory(bool resolve) const { - return getConfigurablePath("mod_directory", ToQString(AppConfig::modsPath()), resolve); + return getConfigurablePath( + "mod_directory", + ToQString(AppConfig::modsPath()), + resolve); +} + +QString Settings::getProfileDirectory(bool resolve) const +{ + return getConfigurablePath( + "profiles_directory", + ToQString(AppConfig::profilesPath()), + resolve); +} + +QString Settings::getOverwriteDirectory(bool resolve) const +{ + return getConfigurablePath( + "overwrite_directory", + ToQString(AppConfig::overwritePath()), + resolve); +} + +void Settings::setBaseDirectory(const QString& path) +{ + if (path.isEmpty()) { + m_Settings.remove("Settings/base_directory"); + } else { + m_Settings.setValue("Settings/base_directory", path); + } +} + +void Settings::setDownloadDirectory(const QString& path) +{ + setConfigurablePath("download_directory", path); +} + +void Settings::setModDirectory(const QString& path) +{ + setConfigurablePath("mod_directory", path); +} + +void Settings::setCacheDirectory(const QString& path) +{ + setConfigurablePath("cache_directory", path); +} + +void Settings::setProfileDirectory(const QString& path) +{ + setConfigurablePath("profiles_directory", path); +} + +void Settings::setOverwriteDirectory(const QString& path) +{ + setConfigurablePath("overwrite_directory", path); } std::optional Settings::getManagedGameDirectory() const @@ -629,17 +703,6 @@ void Settings::removePreviousSeparatorColor() m_Settings.remove("previousSeparatorColor"); } -QString Settings::getProfileDirectory(bool resolve) const -{ - return getConfigurablePath("profiles_directory", ToQString(AppConfig::profilesPath()), resolve); -} - -QString Settings::getOverwriteDirectory(bool resolve) const -{ - return getConfigurablePath("overwrite_directory", - ToQString(AppConfig::overwritePath()), resolve); -} - bool Settings::getNexusApiKey(QString &apiKey) const { QString tempKey = deObfuscate("APIKEY"); diff --git a/src/settings.h b/src/settings.h index 810daac2..698cfe21 100644 --- a/src/settings.h +++ b/src/settings.h @@ -199,26 +199,19 @@ public: **/ QString getSteamAppID() const; - /** - * retrieves the base directory under which the other directories usually - * reside - */ QString getBaseDirectory() const; - - /** - * retrieve the directory where downloads are stored (with native separators) - **/ QString getDownloadDirectory(bool resolve = true) const; - - /** - * retrieve the directory where mods are stored (with native separators) - **/ QString getModDirectory(bool resolve = true) const; - - /** - * retrieve the directory where the web cache is stored (with native separators) - **/ QString getCacheDirectory(bool resolve = true) const; + QString getProfileDirectory(bool resolve = true) const; + QString getOverwriteDirectory(bool resolve = true) const; + + void setBaseDirectory(const QString& path); + void setDownloadDirectory(const QString& path); + void setModDirectory(const QString& path); + void setCacheDirectory(const QString& path); + void setProfileDirectory(const QString& path); + void setOverwriteDirectory(const QString& path); /** * retrieve the directory where the managed game is stored (with native separators) @@ -292,17 +285,6 @@ public: const ColorSettings& colors() const; - /** - * retrieve the directory where profiles stored (with native separators) - **/ - QString getProfileDirectory(bool resolve = true) const; - - /** - * retrieve the directory were new files are stored that can't be assigned - * to a mod (with native separators) - */ - QString getOverwriteDirectory(bool resolve = true) const; - /** * @return true if the user has set up automatic login to nexus **/ @@ -558,6 +540,7 @@ private: void readPluginBlacklist(); QString getConfigurablePath(const QString &key, const QString &def, bool resolve) const; + void setConfigurablePath(const QString &key, const QString& path); }; #endif // SETTINGS_H diff --git a/src/settingsdialogpaths.cpp b/src/settingsdialogpaths.cpp index 290ceeb3..32aaf4bf 100644 --- a/src/settingsdialogpaths.cpp +++ b/src/settingsdialogpaths.cpp @@ -40,22 +40,22 @@ PathsSettingsTab::PathsSettingsTab(Settings& s, SettingsDialog& d) void PathsSettingsTab::update() { - typedef std::tuple Directory; + using Setter = void (Settings::*)(const QString&); + using Directory = std::tuple; QString basePath = settings().getBaseDirectory(); for (const Directory &dir :{ - Directory{ui->downloadDirEdit->text(), "download_directory", AppConfig::downloadPath()}, - Directory{ui->cacheDirEdit->text(), "cache_directory", AppConfig::cachePath()}, - Directory{ui->modDirEdit->text(), "mod_directory", AppConfig::modsPath()}, - Directory{ui->overwriteDirEdit->text(), "overwrite_directory", AppConfig::overwritePath()}, - Directory{ui->profilesDirEdit->text(), "profiles_directory", AppConfig::profilesPath()} + Directory{ui->downloadDirEdit->text(), &Settings::setDownloadDirectory, AppConfig::downloadPath()}, + Directory{ui->cacheDirEdit->text(), &Settings::setCacheDirectory, AppConfig::cachePath()}, + Directory{ui->modDirEdit->text(), &Settings::setModDirectory, AppConfig::modsPath()}, + Directory{ui->overwriteDirEdit->text(), &Settings::setOverwriteDirectory, AppConfig::overwritePath()}, + Directory{ui->profilesDirEdit->text(), &Settings::setProfileDirectory, AppConfig::profilesPath()} }) { - QString path, settingsKey; + QString path; + Setter setter; std::wstring defaultName; - std::tie(path, settingsKey, defaultName) = dir; - - settingsKey = QString("Settings/%1").arg(settingsKey); + std::tie(path, setter, defaultName) = dir; QString realPath = path; realPath.replace("%BASE_DIR%", ui->baseDirEdit->text()); @@ -69,25 +69,23 @@ void PathsSettingsTab::update() } } - if (QFileInfo(realPath) - != QFileInfo(basePath + "/" + QString::fromStdWString(defaultName))) { - qsettings().setValue(settingsKey, path); + if (QFileInfo(realPath) != QFileInfo(basePath + "/" + QString::fromStdWString(defaultName))) { + (settings().*setter)(path); } else { - qsettings().remove(settingsKey); + (settings().*setter)(""); } } - if (QFileInfo(ui->baseDirEdit->text()) != - QFileInfo(qApp->property("dataPath").toString())) { - qsettings().setValue("Settings/base_directory", ui->baseDirEdit->text()); + if (QFileInfo(ui->baseDirEdit->text()) != QFileInfo(qApp->property("dataPath").toString())) { + settings().setBaseDirectory(ui->baseDirEdit->text()); } else { - qsettings().remove("Settings/base_directory"); + settings().setBaseDirectory(""); } QFileInfo oldGameExe(settings().gamePlugin()->gameDirectory().absoluteFilePath(settings().gamePlugin()->binaryName())); QFileInfo newGameExe(ui->managedGameDirEdit->text()); if (oldGameExe != newGameExe) { - qsettings().setValue("gamePath", newGameExe.absolutePath()); + settings().setManagedGameDirectory(newGameExe.absolutePath()); } } -- cgit v1.3.1 From a174d4a2aa3d07c6a3c4bedfdf77471f71ec1dba Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Mon, 2 Sep 2019 09:22:45 -0400 Subject: moved plugins to settings --- src/organizercore.cpp | 10 +- src/plugincontainer.cpp | 6 +- src/settings.cpp | 264 ++++++++++++++++++++++++++---------------- src/settings.h | 123 +++++++------------- src/settingsdialogplugins.cpp | 28 +++-- 5 files changed, 228 insertions(+), 203 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/organizercore.cpp b/src/organizercore.cpp index ec13ca9c..af0cf969 100644 --- a/src/organizercore.cpp +++ b/src/organizercore.cpp @@ -512,7 +512,7 @@ void OrganizerCore::disconnectPlugins() m_DownloadManager.setPluginContainer(nullptr); m_ModList.setPluginContainer(nullptr); - m_Settings.clearPlugins(); + m_Settings.plugins().clearPlugins(); m_GamePlugin = nullptr; m_PluginContainer = nullptr; } @@ -864,26 +864,26 @@ void OrganizerCore::modDataChanged(MOBase::IModInterface *) QVariant OrganizerCore::pluginSetting(const QString &pluginName, const QString &key) const { - return m_Settings.pluginSetting(pluginName, key); + return m_Settings.plugins().pluginSetting(pluginName, key); } void OrganizerCore::setPluginSetting(const QString &pluginName, const QString &key, const QVariant &value) { - m_Settings.setPluginSetting(pluginName, key, value); + m_Settings.plugins().setPluginSetting(pluginName, key, value); } QVariant OrganizerCore::persistent(const QString &pluginName, const QString &key, const QVariant &def) const { - return m_Settings.pluginPersistent(pluginName, key, def); + return m_Settings.plugins().pluginPersistent(pluginName, key, def); } void OrganizerCore::setPersistent(const QString &pluginName, const QString &key, const QVariant &value, bool sync) { - m_Settings.setPluginPersistent(pluginName, key, value, sync); + m_Settings.plugins().setPluginPersistent(pluginName, key, value, sync); } QString OrganizerCore::pluginDataPath() const diff --git a/src/plugincontainer.cpp b/src/plugincontainer.cpp index 62cdff1e..16a77387 100644 --- a/src/plugincontainer.cpp +++ b/src/plugincontainer.cpp @@ -95,7 +95,7 @@ bool PluginContainer::registerPlugin(QObject *plugin, const QString &fileName) return false; } plugin->setProperty("filename", fileName); - m_Organizer->settings().registerPlugin(pluginObj); + m_Organizer->settings().plugins().registerPlugin(pluginObj); } { // diagnosis plugin @@ -266,7 +266,7 @@ void PluginContainer::loadPlugins() "(Please note: If this is the first time you see this message for this plugin you may want to give it another try. " "The plugin may be able to recover from the problem)").arg(fileName), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) == QMessageBox::Yes) { - m_Organizer->settings().addBlacklistPlugin(fileName); + m_Organizer->settings().plugins().addBlacklistPlugin(fileName); } loadCheck.close(); } @@ -279,7 +279,7 @@ void PluginContainer::loadPlugins() while (iter.hasNext()) { iter.next(); - if (m_Organizer->settings().pluginBlacklisted(iter.fileName())) { + if (m_Organizer->settings().plugins().pluginBlacklisted(iter.fileName())) { log::debug("plugin \"{}\" blacklisted", iter.fileName()); continue; } diff --git a/src/settings.cpp b/src/settings.cpp index 34b1b4ac..072318a2 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -242,7 +242,7 @@ Settings *Settings::s_Instance = nullptr; Settings::Settings(const QString& path) : m_Settings(path, QSettings::IniFormat), - m_Geometry(m_Settings), m_Colors(m_Settings) + m_Geometry(m_Settings), m_Colors(m_Settings), m_Plugins(m_Settings) { if (s_Instance != nullptr) { throw std::runtime_error("second instance of \"Settings\" created"); @@ -319,25 +319,6 @@ QString Settings::getFilename() const return m_Settings.fileName(); } -void Settings::clearPlugins() -{ - m_Plugins.clear(); - m_PluginSettings.clear(); - - 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()); - } -} - -bool Settings::pluginBlacklisted(const QString &fileName) const -{ - return m_PluginBlacklist.contains(fileName); -} - void Settings::registerAsNXMHandler(bool force) { const auto nxmPath = QCoreApplication::applicationDirPath() + "/nxmhandler.exe"; @@ -371,24 +352,6 @@ void Settings::managedGameChanged(IPluginGame const *gamePlugin) m_GamePlugin = gamePlugin; } -void Settings::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); - 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()); - } -} - bool Settings::obfuscate(const QString key, const QString data) { QString finalKey("ModOrganizer2_" + key); @@ -921,51 +884,6 @@ bool Settings::archiveParsing() const return m_Settings.value("Settings/archive_parsing_experimental", false).toBool(); } -QVariant Settings::pluginSetting(const QString &pluginName, const QString &key) const -{ - auto iterPlugin = m_PluginSettings.find(pluginName); - if (iterPlugin == m_PluginSettings.end()) { - return QVariant(); - } - auto iterSetting = iterPlugin->find(key); - if (iterSetting == iterPlugin->end()) { - return QVariant(); - } - - return *iterSetting; -} - -void Settings::setPluginSetting(const QString &pluginName, const QString &key, const QVariant &value) -{ - auto iterPlugin = m_PluginSettings.find(pluginName); - if (iterPlugin == m_PluginSettings.end()) { - throw MyException(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); -} - -QVariant Settings::pluginPersistent(const QString &pluginName, const QString &key, const QVariant &def) const -{ - if (!m_PluginSettings.contains(pluginName)) { - return def; - } - return m_Settings.value("PluginPersistance/" + pluginName + "/" + key, def); -} - -void Settings::setPluginPersistent(const QString &pluginName, const QString &key, const QVariant &value, bool sync) -{ - if (!m_PluginSettings.contains(pluginName)) { - throw MyException(tr("attempt to store setting for unknown plugin \"%1\"").arg(pluginName)); - } - m_Settings.setValue("PluginPersistance/" + pluginName + "/" + key, value); - if (sync) { - m_Settings.sync(); - } -} - QString Settings::language() { QString result = m_Settings.value("Settings/language", "").toString(); @@ -1122,24 +1040,6 @@ void Settings::updateServers(ServerList servers) } } -void Settings::addBlacklistPlugin(const QString &fileName) -{ - m_PluginBlacklist.insert(fileName); - writePluginBlacklist(); -} - -void Settings::writePluginBlacklist() -{ - m_Settings.remove("pluginBlacklist"); - - ScopedWriteArray swa(m_Settings, "pluginBlacklist"); - int idx = 0; - for (const QString &plugin : m_PluginBlacklist) { - m_Settings.setArrayIndex(idx++); - m_Settings.setValue("name", plugin); - } -} - std::map Settings::getRecentDirectories() const { std::map map; @@ -1365,6 +1265,16 @@ const ColorSettings& Settings::colors() const return m_Colors; } +PluginSettings& Settings::plugins() +{ + return m_Plugins; +} + +const PluginSettings& Settings::plugins() const +{ + return m_Plugins; +} + QSettings::Status Settings::sync() const { m_Settings.sync(); @@ -1772,6 +1682,158 @@ void ColorSettings::setPluginListContained(const QColor& c) } +PluginSettings::PluginSettings(QSettings& settings) + : m_Settings(settings) +{ +} + +void PluginSettings::clearPlugins() +{ + m_Plugins.clear(); + m_PluginSettings.clear(); + + 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()); + } +} + +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); + 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()); + } +} + +bool PluginSettings::pluginBlacklisted(const QString &fileName) const +{ + return m_PluginBlacklist.contains(fileName); +} + +QVariant PluginSettings::pluginSetting(const QString &pluginName, const QString &key) const +{ + auto iterPlugin = m_PluginSettings.find(pluginName); + if (iterPlugin == m_PluginSettings.end()) { + return QVariant(); + } + auto iterSetting = iterPlugin->find(key); + if (iterSetting == iterPlugin->end()) { + return QVariant(); + } + + return *iterSetting; +} + +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)); + } + + // store the new setting both in memory and in the ini + m_PluginSettings[pluginName][key] = value; + m_Settings.setValue("Plugins/" + pluginName + "/" + key, value); +} + +QVariant PluginSettings::pluginPersistent(const QString &pluginName, const QString &key, const QVariant &def) const +{ + if (!m_PluginSettings.contains(pluginName)) { + return def; + } + return m_Settings.value("PluginPersistance/" + pluginName + "/" + key, def); +} + +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)); + } + m_Settings.setValue("PluginPersistance/" + pluginName + "/" + key, value); + if (sync) { + m_Settings.sync(); + } +} + +void PluginSettings::addBlacklistPlugin(const QString &fileName) +{ + m_PluginBlacklist.insert(fileName); + writePluginBlacklist(); +} + +void PluginSettings::writePluginBlacklist() +{ + m_Settings.remove("pluginBlacklist"); + + ScopedWriteArray swa(m_Settings, "pluginBlacklist"); + int idx = 0; + for (const QString &plugin : m_PluginBlacklist) { + m_Settings.setArrayIndex(idx++); + m_Settings.setValue("name", plugin); + } +} + +QVariantMap PluginSettings::pluginSettings(const QString &pluginName) const +{ + return m_PluginSettings[pluginName]; +} + +void PluginSettings::setPluginSettings(const QString &pluginName, const QVariantMap& map) +{ + m_PluginSettings[pluginName] = map; +} + +QVariantMap PluginSettings::pluginDescriptions(const QString &pluginName) const +{ + return m_PluginDescriptions[pluginName]; +} + +void PluginSettings::pluginDescriptions(const QString &pluginName, const QVariantMap& map) +{ + m_PluginDescriptions[pluginName] = map; +} + +const QSet& PluginSettings::pluginBlacklist() const +{ + return m_PluginBlacklist; +} + +void PluginSettings::setPluginBlacklist(const QStringList& pluginNames) +{ + m_PluginBlacklist.clear(); + + for (const auto& name : pluginNames) { + m_PluginBlacklist.insert(name); + } +} + +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()); + } + } + + writePluginBlacklist(); +} + + GeometrySaver::GeometrySaver(Settings& s, QDialog* dialog) : m_settings(s), m_dialog(dialog) { diff --git a/src/settings.h b/src/settings.h index 698cfe21..fc33e0de 100644 --- a/src/settings.h +++ b/src/settings.h @@ -128,6 +128,46 @@ private: }; +class PluginSettings +{ +public: + PluginSettings(QSettings& settings); + + void clearPlugins(); + void registerPlugin(MOBase::IPlugin *plugin); + void addPluginSettings(const std::vector &plugins); + + QVariant pluginSetting(const QString &pluginName, const QString &key) const; + void setPluginSetting(const QString &pluginName, const QString &key, const QVariant &value); + QVariant pluginPersistent(const QString &pluginName, const QString &key, const QVariant &def) const; + void setPluginPersistent(const QString &pluginName, const QString &key, const QVariant &value, bool sync); + void addBlacklistPlugin(const QString &fileName); + bool pluginBlacklisted(const QString &fileName) const; + void setPluginBlacklist(const QStringList& pluginNames); + std::vector plugins() const { return m_Plugins; } + + QVariantMap pluginSettings(const QString &pluginName) const; + void setPluginSettings(const QString &pluginName, const QVariantMap& map); + + QVariantMap pluginDescriptions(const QString &pluginName) const; + void pluginDescriptions(const QString &pluginName, const QVariantMap& map); + + const QSet& pluginBlacklist() const; + + void save(); + +private: + QSettings& m_Settings; + std::vector m_Plugins; + QMap m_PluginSettings; + QMap m_PluginDescriptions; + QSet m_PluginBlacklist; + + void readPluginBlacklist(); + void writePluginBlacklist(); +}; + + enum class EndorsementState { Accepted = 1, @@ -158,23 +198,6 @@ public: QString getFilename() const; - /** - * unregister all plugins from settings - */ - void clearPlugins(); - - /** - * @brief register plugin to be configurable - * @param plugin the plugin to register - * @return true if the plugin may be registered, false if it is blacklisted - */ - void registerPlugin(MOBase::IPlugin *plugin); - - /** - * set up the settings for the specified plugins - **/ - void addPluginSettings(const std::vector &plugins); - /** * @return true if the user wants unchecked plugins (esp, esm) should be hidden from * the virtual dat adirectory @@ -284,6 +307,9 @@ public: ColorSettings& colors(); const ColorSettings& colors() const; + PluginSettings& plugins(); + const PluginSettings& plugins() const; + /** * @return true if the user has set up automatic login to nexus @@ -422,42 +448,6 @@ public: QSettings &directInterface() { return m_Settings; } const QSettings &directInterface() const { return m_Settings; } - /** - * @brief retrieve a setting for one of the installed plugins - * @param pluginName name of the plugin - * @param key name of the setting to retrieve - * @return the requested value as a QVariant - * @note an invalid QVariant is returned if the the plugin/setting is not declared - */ - QVariant pluginSetting(const QString &pluginName, const QString &key) const; - - /** - * @brief set a setting for one of the installed mods - * @param pluginName name of the plugin - * @param key name of the setting to change - * @param value the new value to set - * @throw an exception is thrown if pluginName is invalid - */ - void setPluginSetting(const QString &pluginName, const QString &key, const QVariant &value); - - /** - * @brief retrieve a persistent value for a plugin - * @param pluginName name of the plugin to store data for - * @param key id of the value to retrieve - * @param def default value to return if the value is not set - * @return the requested value - */ - QVariant pluginPersistent(const QString &pluginName, const QString &key, const QVariant &def) const; - - /** - * @brief set a persistent value for a plugin - * @param pluginName name of the plugin to store data for - * @param key id of the value to retrieve - * @param value value to set - * @throw an exception is thrown if pluginName is invalid - */ - void setPluginPersistent(const QString &pluginName, const QString &key, const QVariant &value, bool sync); - /** * @return short code of the configured language (corresponding to the translation files) */ @@ -469,24 +459,6 @@ public: ServerList getServersFromOldMap() const; void updateServers(ServerList servers); - /** - * @brief add a plugin that is to be blacklisted - * @param fileName name of the plugin to blacklist - */ - void addBlacklistPlugin(const QString &fileName); - - /** - * @brief test if a plugin is blacklisted and shouldn't be loaded - * @param fileName name of the plugin - * @return true if the file is blacklisted - */ - bool pluginBlacklisted(const QString &fileName) const; - - /** - * @return all loaded MO plugins - */ - std::vector plugins() const { return m_Plugins; } - bool usePrereleases() const; void setUsePrereleases(bool b); @@ -513,12 +485,6 @@ public: void dump() const; - // temp - QMap m_PluginSettings; - QMap m_PluginDescriptions; - QSet m_PluginBlacklist; - void writePluginBlacklist(); - public slots: void managedGameChanged(MOBase::IPluginGame const *gamePlugin); @@ -532,13 +498,12 @@ private: mutable QSettings m_Settings; GeometrySettings m_Geometry; ColorSettings m_Colors; + PluginSettings m_Plugins; LoadMechanism m_LoadMechanism; - std::vector m_Plugins; static bool obfuscate(const QString key, const QString data); static QString deObfuscate(const QString key); - void readPluginBlacklist(); QString getConfigurablePath(const QString &key, const QString &def, bool resolve) const; void setConfigurablePath(const QString &key, const QString& path); }; diff --git a/src/settingsdialogplugins.cpp b/src/settingsdialogplugins.cpp index 329ba301..956971fe 100644 --- a/src/settingsdialogplugins.cpp +++ b/src/settingsdialogplugins.cpp @@ -12,19 +12,19 @@ PluginsSettingsTab::PluginsSettingsTab(Settings& s, SettingsDialog& d) // display plugin settings QSet handledNames; - for (IPlugin *plugin : settings().plugins()) { + for (IPlugin *plugin : settings().plugins().plugins()) { if (handledNames.contains(plugin->name())) continue; QListWidgetItem *listItem = new QListWidgetItem(plugin->name(), ui->pluginsList); listItem->setData(Qt::UserRole, QVariant::fromValue((void*)plugin)); - listItem->setData(Qt::UserRole + 1, settings().m_PluginSettings[plugin->name()]); - listItem->setData(Qt::UserRole + 2, settings().m_PluginDescriptions[plugin->name()]); + listItem->setData(Qt::UserRole + 1, settings().plugins().pluginSettings(plugin->name())); + listItem->setData(Qt::UserRole + 2, settings().plugins().pluginDescriptions(plugin->name())); ui->pluginsList->addItem(listItem); handledNames.insert(plugin->name()); } // display plugin blacklist - for (const QString &pluginName : settings().m_PluginBlacklist) { + for (const QString &pluginName : settings().plugins().pluginBlacklist()) { ui->pluginBlacklist->addItem(pluginName); } @@ -42,21 +42,19 @@ void PluginsSettingsTab::update() // transfer plugin settings to in-memory structure for (int i = 0; i < ui->pluginsList->count(); ++i) { QListWidgetItem *item = ui->pluginsList->item(i); - settings().m_PluginSettings[item->text()] = item->data(Qt::UserRole + 1).toMap(); - } - // store plugin settings on disc - for (auto iterPlugins = settings().m_PluginSettings.begin(); iterPlugins != settings().m_PluginSettings.end(); ++iterPlugins) { - for (auto iterSettings = iterPlugins->begin(); iterSettings != iterPlugins->end(); ++iterSettings) { - qsettings().setValue("Plugins/" + iterPlugins.key() + "/" + iterSettings.key(), iterSettings.value()); - } + settings().plugins().setPluginSettings( + item->text(), item->data(Qt::UserRole + 1).toMap()); } - // store plugin blacklist - settings().m_PluginBlacklist.clear(); + // set plugin blacklist + QStringList names; for (QListWidgetItem *item : ui->pluginBlacklist->findItems("*", Qt::MatchWildcard)) { - settings().m_PluginBlacklist.insert(item->text()); + names.push_back(item->text()); } - settings().writePluginBlacklist(); + + settings().plugins().setPluginBlacklist(names); + + settings().plugins().save(); } void PluginsSettingsTab::closing() -- cgit v1.3.1 From ca2a7da3f6534515160d5fbf92f72d6ff2bce3e8 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Mon, 2 Sep 2019 09:35:11 -0400 Subject: moved workarounds to settings --- src/settings.cpp | 43 +++++++++++++++++++++++++++++++++++++++ src/settings.h | 8 ++++++++ src/settingsdialogworkarounds.cpp | 22 +++++++++++--------- 3 files changed, 63 insertions(+), 10 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/settings.cpp b/src/settings.cpp index 072318a2..f6be8ba0 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -421,16 +421,31 @@ bool Settings::hideUncheckedPlugins() const return m_Settings.value("Settings/hide_unchecked_plugins", false).toBool(); } +void Settings::setHideUncheckedPlugins(bool b) +{ + m_Settings.setValue("Settings/hide_unchecked_plugins", b); +} + bool Settings::forceEnableCoreFiles() const { return m_Settings.value("Settings/force_enable_core_files", true).toBool(); } +void Settings::setForceEnableCoreFiles(bool b) +{ + m_Settings.setValue("Settings/force_enable_core_files", b); +} + bool Settings::lockGUI() const { return m_Settings.value("Settings/lock_gui", true).toBool(); } +void Settings::setLockGUI(bool b) +{ + m_Settings.setValue("Settings/lock_gui", b); +} + bool Settings::automaticLoginEnabled() const { return m_Settings.value("Settings/nexus_login", false).toBool(); @@ -441,6 +456,15 @@ QString Settings::getSteamAppID() const return m_Settings.value("Settings/app_id", m_GamePlugin->steamAPPId()).toString(); } +void Settings::setSteamAppID(const QString& id) +{ + if (id.isEmpty()) { + m_Settings.remove("Settings/app_id"); + } else { + m_Settings.setValue("Settings/app_id", id); + } +} + bool Settings::usePrereleases() const { return m_Settings.value("Settings/use_prereleases", false).toBool(); @@ -782,6 +806,11 @@ QString Settings::executablesBlacklist() const ).toString(); } +void Settings::setExecutablesBlacklist(const QString& s) +{ + m_Settings.setValue("Settings/executable_blacklist", s); +} + void Settings::setSteamLogin(QString username, QString password) { if (username == "") { @@ -815,6 +844,10 @@ LoadMechanism::EMechanism Settings::getLoadMechanism() const } } +void Settings::setLoadMechanism(LoadMechanism::EMechanism m) +{ + m_Settings.setValue("Settings/load_mechanism", static_cast(m)); +} void Settings::setupLoadMechanism() { @@ -869,6 +902,11 @@ bool Settings::displayForeign() const return m_Settings.value("Settings/display_foreign", true).toBool(); } +void Settings::setDisplayForeign(bool b) +{ + m_Settings.setValue("Settings/display_foreign", b); +} + void Settings::setMotDHash(uint hash) { m_Settings.setValue("motd_hash", hash); @@ -884,6 +922,11 @@ bool Settings::archiveParsing() const return m_Settings.value("Settings/archive_parsing_experimental", false).toBool(); } +void Settings::setArchiveParsing(bool b) +{ + m_Settings.setValue("Settings/archive_parsing_experimental", b); +} + QString Settings::language() { QString result = m_Settings.value("Settings/language", "").toString(); diff --git a/src/settings.h b/src/settings.h index fc33e0de..09141274 100644 --- a/src/settings.h +++ b/src/settings.h @@ -203,16 +203,19 @@ public: * the virtual dat adirectory **/ bool hideUncheckedPlugins() const; + void setHideUncheckedPlugins(bool b); /** * @return true if files of the core game are forced-enabled so the user can't accidentally disable them */ bool forceEnableCoreFiles() const; + void setForceEnableCoreFiles(bool b); /** * @return true if the GUI should be locked when running executables */ bool lockGUI() const; + void setLockGUI(bool b); /** * the steam appid is assigned by the steam platform to each product sold there. @@ -221,6 +224,7 @@ public: * @return the steam appid for the game **/ QString getSteamAppID() const; + void setSteamAppID(const QString& id); QString getBaseDirectory() const; QString getDownloadDirectory(bool resolve = true) const; @@ -380,6 +384,7 @@ public: void setCrashDumpsMax(int n); QString executablesBlacklist() const; + void setExecutablesBlacklist(const QString& s); /** * @brief set the steam login information @@ -393,6 +398,7 @@ public: * @return the load mechanism to be used **/ LoadMechanism::EMechanism getLoadMechanism() const; + void setLoadMechanism(LoadMechanism::EMechanism m); /** * @brief activate the load mechanism selected by the user @@ -425,6 +431,7 @@ public: * @return true if the user wants to see non-official plugins installed outside MO in his mod list */ bool displayForeign() const; + void setDisplayForeign(bool b); /** * @brief sets the new motd hash @@ -435,6 +442,7 @@ public: * @return true if the user wants to have archives being parsed to show conflicts and contents */ bool archiveParsing() const; + void setArchiveParsing(bool b); /** * @return hash of the last displayed message of the day diff --git a/src/settingsdialogworkarounds.cpp b/src/settingsdialogworkarounds.cpp index 443ba54e..b06bd77c 100644 --- a/src/settingsdialogworkarounds.cpp +++ b/src/settingsdialogworkarounds.cpp @@ -36,18 +36,20 @@ WorkaroundsSettingsTab::WorkaroundsSettingsTab(Settings& s, SettingsDialog& d) void WorkaroundsSettingsTab::update() { if (ui->appIDEdit->text() != settings().gamePlugin()->steamAPPId()) { - qsettings().setValue("Settings/app_id", ui->appIDEdit->text()); + settings().setSteamAppID(ui->appIDEdit->text()); } else { - qsettings().remove("Settings/app_id"); + settings().setSteamAppID(""); } - qsettings().setValue("Settings/load_mechanism", ui->mechanismBox->itemData(ui->mechanismBox->currentIndex()).toInt()); - qsettings().setValue("Settings/hide_unchecked_plugins", ui->hideUncheckedBox->isChecked()); - qsettings().setValue("Settings/force_enable_core_files", ui->forceEnableBox->isChecked()); - qsettings().setValue("Settings/display_foreign", ui->displayForeignBox->isChecked()); - qsettings().setValue("Settings/lock_gui", ui->lockGUIBox->isChecked()); - qsettings().setValue("Settings/archive_parsing_experimental", ui->enableArchiveParsingBox->isChecked()); - - qsettings().setValue("Settings/executable_blacklist", getExecutableBlacklist()); + + settings().setLoadMechanism(static_cast( + ui->mechanismBox->itemData(ui->mechanismBox->currentIndex()).toInt())); + + settings().setHideUncheckedPlugins(ui->hideUncheckedBox->isChecked()); + settings().setForceEnableCoreFiles(ui->forceEnableBox->isChecked()); + settings().setDisplayForeign(ui->displayForeignBox->isChecked()); + settings().setLockGUI(ui->lockGUIBox->isChecked()); + settings().setArchiveParsing(ui->enableArchiveParsingBox->isChecked()); + settings().setExecutablesBlacklist(getExecutableBlacklist()); } void WorkaroundsSettingsTab::on_execBlacklistBtn_clicked() -- 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/settings.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 From e9dba260cb9548dd5863ac66da18c295f6499b92 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Mon, 2 Sep 2019 14:52:02 -0400 Subject: split settings into a bunch of classes removed "get" from the getters that had it --- src/browserdialog.cpp | 2 +- src/downloadlistsortproxy.cpp | 2 +- src/downloadmanager.cpp | 2 +- src/executableslist.cpp | 2 +- src/filedialogmemory.cpp | 4 +- src/main.cpp | 26 +- src/mainwindow.cpp | 121 +-- src/modinfodialog.cpp | 2 +- src/modinfodialogconflicts.cpp | 16 +- src/modinfodialogimages.cpp | 4 +- src/modinfodialognexus.cpp | 2 +- src/modinfooverwrite.cpp | 2 +- src/modinforegular.cpp | 2 +- src/modlist.cpp | 8 +- src/nxmaccessmanager.cpp | 2 +- src/organizercore.cpp | 112 +- src/pluginlist.cpp | 2 +- src/profile.cpp | 8 +- src/profilesdialog.cpp | 4 +- src/settings.cpp | 2075 ++++++++++++++++++++----------------- src/settings.h | 569 ++++++---- src/settingsdialog.cpp | 6 +- src/settingsdialogdiagnostics.cpp | 13 +- src/settingsdialoggeneral.cpp | 28 +- src/settingsdialognexus.cpp | 32 +- src/settingsdialogpaths.cpp | 52 +- src/settingsdialogsteam.cpp | 4 +- src/settingsdialogworkarounds.cpp | 30 +- src/statusbar.cpp | 2 +- src/usvfsconnector.cpp | 4 +- 30 files changed, 1712 insertions(+), 1426 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/browserdialog.cpp b/src/browserdialog.cpp index 70da0b9c..72cb8862 100644 --- a/src/browserdialog.cpp +++ b/src/browserdialog.cpp @@ -49,7 +49,7 @@ BrowserDialog::BrowserDialog(QWidget *parent) ui->setupUi(this); m_AccessManager->setCookieJar(new PersistentCookieJar( - QDir::fromNativeSeparators(Settings::instance().getCacheDirectory() + "/cookies.dat"))); + QDir::fromNativeSeparators(Settings::instance().paths().cache() + "/cookies.dat"))); Qt::WindowFlags flags = windowFlags() | Qt::WindowMaximizeButtonHint | Qt::WindowMinimizeButtonHint; Qt::WindowFlags helpFlag = Qt::WindowContextHelpButtonHint; diff --git a/src/downloadlistsortproxy.cpp b/src/downloadlistsortproxy.cpp index 7bda139b..a69993c0 100644 --- a/src/downloadlistsortproxy.cpp +++ b/src/downloadlistsortproxy.cpp @@ -110,7 +110,7 @@ bool DownloadListSortProxy::filterAcceptsRow(int sourceRow, const QModelIndex&) if (m_CurrentFilter.length() == 0) { return true; } else if (sourceRow < m_Manager->numTotalDownloads()) { - QString displayedName = Settings::instance().metaDownloads() + QString displayedName = Settings::instance().interface().metaDownloads() ? m_Manager->getDisplayName(sourceRow) : m_Manager->getFileName(sourceRow); return displayedName.contains(m_CurrentFilter, Qt::CaseInsensitive); diff --git a/src/downloadmanager.cpp b/src/downloadmanager.cpp index a5dc164c..56238ef3 100644 --- a/src/downloadmanager.cpp +++ b/src/downloadmanager.cpp @@ -1731,7 +1731,7 @@ void DownloadManager::nxmDownloadURLsAvailable(QString gameName, int modID, int return; } - const auto servers = m_OrganizerCore->settings().getServers(); + const auto servers = m_OrganizerCore->settings().network().servers(); std::sort( resultList.begin(), diff --git a/src/executableslist.cpp b/src/executableslist.cpp index f2df2d6d..dce9181b 100644 --- a/src/executableslist.cpp +++ b/src/executableslist.cpp @@ -75,7 +75,7 @@ void ExecutablesList::load(const MOBase::IPluginGame* game, const Settings& s) // executables from 2.2.0, see upgradeFromCustom() bool needsUpgrade = false; - for (auto& map : s.getExecutables()) { + for (auto& map : s.executables()) { Executable::Flags flags; if (map["toolbar"].toBool()) diff --git a/src/filedialogmemory.cpp b/src/filedialogmemory.cpp index 96587ac7..8cfeb6b5 100644 --- a/src/filedialogmemory.cpp +++ b/src/filedialogmemory.cpp @@ -25,12 +25,12 @@ static std::map g_Cache; void FileDialogMemory::save(Settings& s) { - s.setRecentDirectories(g_Cache); + s.paths().setRecent(g_Cache); } void FileDialogMemory::restore(const Settings& s) { - g_Cache = s.getRecentDirectories(); + g_Cache = s.paths().recent(); } QString FileDialogMemory::getOpenFileName( diff --git a/src/main.cpp b/src/main.cpp index aa781c19..b5568fec 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -246,7 +246,7 @@ static bool HaveWriteAccess(const std::wstring &path) QString determineProfile(QStringList &arguments, const Settings &settings) { - auto selectedProfileName = settings.getSelectedProfileName(); + auto selectedProfileName = settings.game().selectedProfileName(); { // see if there is a profile on the command line int profileIndex = arguments.indexOf("-p", 1); @@ -271,12 +271,12 @@ QString determineProfile(QStringList &arguments, const Settings &settings) MOBase::IPluginGame *selectGame( Settings &settings, QDir const &gamePath, MOBase::IPluginGame *game) { - settings.setManagedGameName(game->gameName()); + settings.game().setName(game->gameName()); QString gameDir = gamePath.absolutePath(); game->setGamePath(gameDir); - settings.setManagedGameDirectory(gameDir); + settings.game().setDirectory(gameDir); return game; } @@ -289,7 +289,7 @@ MOBase::IPluginGame *determineCurrentGame( //user has done something odd. //If the game name has been set up, try to use that. - const auto gameName = settings.getManagedGameName(); + const auto gameName = settings.game().name(); const bool gameConfigured = (gameName.has_value() && *gameName != ""); if (gameConfigured) { @@ -299,7 +299,7 @@ MOBase::IPluginGame *determineCurrentGame( return nullptr; } - auto gamePath = settings.getManagedGameDirectory(); + auto gamePath = settings.game().directory(); if (!gamePath || *gamePath == "") { gamePath = game->gameDirectory().absolutePath(); } @@ -320,7 +320,7 @@ MOBase::IPluginGame *determineCurrentGame( //If we've made it this far and the instance is already configured for a game, something has gone wrong. //Tell the user about it. if (gameConfigured) { - const auto gamePath = settings.getManagedGameDirectory(); + const auto gamePath = settings.game().directory(); reportError( QObject::tr("Could not use configuration settings for game \"%1\", path \"%2\".") @@ -570,11 +570,11 @@ int runApplication(MOApplication &application, SingleInstance &instance, log::info("working directory: {}", QDir::currentPath()); Settings settings(dataPath + "/" + QString::fromStdWString(AppConfig::iniFileName())); - log::getDefault().setLevel(settings.logLevel()); + log::getDefault().setLevel(settings.diagnostics().logLevel()); // global crashDumpType sits in OrganizerCore to make a bit less ugly to // update it when the settings are changed during runtime - OrganizerCore::setGlobalCrashDumpsType(settings.crashDumpsType()); + OrganizerCore::setGlobalCrashDumpsType(settings.diagnostics().crashDumpsType()); env::Environment env; @@ -621,7 +621,7 @@ int runApplication(MOApplication &application, SingleInstance &instance, QString edition; - if (auto v=settings.getManagedGameEdition()) { + if (auto v=settings.game().edition()) { edition = *v; } else { QStringList editions = game->gameVariants(); @@ -640,7 +640,7 @@ int runApplication(MOApplication &application, SingleInstance &instance, return 1; } else { edition = selection.getChoiceString(); - settings.setManagedGameEdition(edition); + settings.game().setEdition(edition); } } } @@ -702,7 +702,7 @@ int runApplication(MOApplication &application, SingleInstance &instance, splash.activateWindow(); QString apiKey; - if (settings.getNexusApiKey(apiKey)) { + if (settings.nexus().apiKey(apiKey)) { NexusInterface::instance(&pluginContainer)->getAccessManager()->apiCheck(apiKey); } @@ -712,9 +712,9 @@ int runApplication(MOApplication &application, SingleInstance &instance, + QString::fromStdWString(AppConfig::tutorialsPath()) + "/", &organizer); - if (!application.setStyleFile(settings.getStyleName().value_or(""))) { + if (!application.setStyleFile(settings.interface().styleName().value_or(""))) { // disable invalid stylesheet - settings.setStyleName(""); + settings.interface().setStyleName(""); } int res = 1; diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 42b19cb7..657c1a27 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -222,8 +222,8 @@ MainWindow::MainWindow(Settings &settings { QWebEngineProfile::defaultProfile()->setPersistentCookiesPolicy(QWebEngineProfile::NoPersistentCookies); QWebEngineProfile::defaultProfile()->setHttpCacheMaximumSize(52428800); - QWebEngineProfile::defaultProfile()->setCachePath(settings.getCacheDirectory()); - QWebEngineProfile::defaultProfile()->setPersistentStoragePath(settings.getCacheDirectory()); + QWebEngineProfile::defaultProfile()->setCachePath(settings.paths().cache()); + QWebEngineProfile::defaultProfile()->setPersistentStoragePath(settings.paths().cache()); ui->setupUi(this); ui->statusBar->setup(ui); @@ -253,7 +253,7 @@ MainWindow::MainWindow(Settings &settings ui->statusBar->setAPI(ni->getAPIStats(), ni->getAPIUserAccount()); } - languageChange(settings.language()); + languageChange(settings.interface().language()); m_CategoryFactory.loadCategories(); @@ -1194,7 +1194,7 @@ void MainWindow::hookUpWindowTutorials() QString firstLine = QString::fromUtf8(file.readLine()); if (firstLine.startsWith("//WIN")) { QString windowName = firstLine.mid(6).trimmed(); - if (!m_OrganizerCore.settings().isTutorialCompleted(windowName)) { + if (!m_OrganizerCore.settings().interface().isTutorialCompleted(windowName)) { TutorialManager::instance().activateTutorial(windowName, fileName); } } @@ -1225,7 +1225,7 @@ void MainWindow::showEvent(QShowEvent *event) hookUpWindowTutorials(); - if (m_OrganizerCore.settings().getFirstStart()) { + if (m_OrganizerCore.settings().firstStart()) { QString firstStepsTutorial = ToQString(AppConfig::firstStepsTutorial()); if (TutorialManager::instance().hasTutorial(firstStepsTutorial)) { if (QMessageBox::question(this, tr("Show tutorial?"), @@ -1247,11 +1247,11 @@ void MainWindow::showEvent(QShowEvent *event) m_OrganizerCore.settings().setFirstStart(false); } - m_OrganizerCore.settings().restoreIndex(ui->groupCombo); + m_OrganizerCore.settings().widgets().restoreIndex(ui->groupCombo); allowListResize(); - m_OrganizerCore.settings().registerAsNXMHandler(false); + m_OrganizerCore.settings().nexus().registerAsNXMHandler(false); m_WasVisible = true; updateProblemsButton(); } @@ -1751,7 +1751,7 @@ bool MainWindow::refreshProfiles(bool selectProfile) profileBox->clear(); profileBox->addItem(QObject::tr("")); - QDir profilesDir(Settings::instance().getProfileDirectory()); + QDir profilesDir(Settings::instance().paths().profiles()); profilesDir.setFilter(QDir::AllDirs | QDir::NoDotAndDotDot); QDirIterator profileIter(profilesDir); @@ -1990,7 +1990,7 @@ void MainWindow::updateBSAList(const QStringList &defaultArchives, const QString newItem->setFlags(newItem->flags() & ~(Qt::ItemIsDropEnabled | Qt::ItemIsUserCheckable)); newItem->setCheckState(0, (index != -1) ? Qt::Checked : Qt::Unchecked); newItem->setData(0, Qt::UserRole, false); - if (m_OrganizerCore.settings().forceEnableCoreFiles() + if (m_OrganizerCore.settings().game().forceEnableCoreFiles() && defaultArchives.contains(fileInfo.fileName())) { newItem->setCheckState(0, Qt::Checked); newItem->setDisabled(true); @@ -2140,7 +2140,7 @@ void MainWindow::readSettings(const Settings& settings) { // special case in case someone puts 0 in the INI - auto v = settings.getIndex(ui->executablesListBox); + auto v = settings.widgets().index(ui->executablesListBox); if (!v || v == 0) { v = 1; } @@ -2148,7 +2148,7 @@ void MainWindow::readSettings(const Settings& settings) ui->executablesListBox->setCurrentIndex(*v); } - settings.restoreIndex(ui->groupCombo); + settings.widgets().restoreIndex(ui->groupCombo); { settings.geometry().restoreVisibility(ui->categoriesGroup, false); @@ -2157,7 +2157,7 @@ void MainWindow::readSettings(const Settings& settings) ui->displayCategoriesBtn->setChecked(v); } - if (settings.getUseProxy()) { + if (settings.network().useProxy()) { activateProxy(true); } } @@ -2165,12 +2165,12 @@ void MainWindow::readSettings(const Settings& settings) void MainWindow::processUpdates(Settings& settings) { const auto earliest = QVersionNumber::fromString("2.1.2").normalized(); - const auto lastVersion = settings.getVersion().value_or(earliest); + const auto lastVersion = settings.version().value_or(earliest); const auto currentVersion = m_OrganizerCore.getVersion().asQVersionNumber(); settings.processUpdates(currentVersion, lastVersion); - if (!settings.getFirstStart()) { + if (!settings.firstStart()) { if (lastVersion < QVersionNumber(2, 1, 3)) { bool lastHidden = true; for (int i = ModList::COL_GAME; i < ui->modList->model()->columnCount(); ++i) { @@ -2222,8 +2222,8 @@ void MainWindow::storeSettings(Settings& s) s.geometry().saveState(ui->downloadView->header()); s.geometry().saveState(ui->modList->header()); - s.saveIndex(ui->groupCombo); - s.saveIndex(ui->executablesListBox); + s.widgets().saveIndex(ui->groupCombo); + s.widgets().saveIndex(ui->executablesListBox); } ILockedWaitingForProcess* MainWindow::lock() @@ -2751,7 +2751,7 @@ void MainWindow::restoreBackup_clicked() ModInfo::Ptr modInfo = ModInfo::getByIndex(m_ContextRow); if (backupRegEx.indexIn(modInfo->name()) != -1) { QString regName = backupRegEx.cap(1); - QDir modDir(QDir::fromNativeSeparators(m_OrganizerCore.settings().getModDirectory())); + QDir modDir(QDir::fromNativeSeparators(m_OrganizerCore.settings().paths().mods())); if (!modDir.exists(regName) || (QMessageBox::question(this, tr("Overwrite?"), tr("This will replace the existing mod \"%1\". Continue?").arg(regName), @@ -2759,7 +2759,7 @@ void MainWindow::restoreBackup_clicked() if (modDir.exists(regName) && !shellDelete(QStringList(modDir.absoluteFilePath(regName)))) { reportError(tr("failed to remove mod \"%1\"").arg(regName)); } else { - QString destinationPath = QDir::fromNativeSeparators(m_OrganizerCore.settings().getModDirectory()) + "/" + regName; + QString destinationPath = QDir::fromNativeSeparators(m_OrganizerCore.settings().paths().mods()) + "/" + regName; if (!modDir.rename(modInfo->absolutePath(), destinationPath)) { reportError(tr("failed to rename \"%1\" to \"%2\"").arg(modInfo->absolutePath()).arg(destinationPath)); } @@ -3015,7 +3015,7 @@ void MainWindow::untrack_clicked() void MainWindow::windowTutorialFinished(const QString &windowName) { - m_OrganizerCore.settings().setTutorialCompleted(windowName); + m_OrganizerCore.settings().interface().setTutorialCompleted(windowName); } void MainWindow::overwriteClosed(int) @@ -3645,7 +3645,7 @@ void MainWindow::createSeparator_clicked() m_OrganizerCore.modList()->changeModPriority(ModInfo::getIndex(name), newPriority); } - if (auto c=m_OrganizerCore.settings().getPreviousSeparatorColor()) { + if (auto c=m_OrganizerCore.settings().colors().previousSeparatorColor()) { ModInfo::getByIndex(ModInfo::getIndex(name))->setColor(*c); } } @@ -3662,7 +3662,7 @@ void MainWindow::setColor_clicked() if (currentColor.isValid()) { dialog.setCurrentColor(currentColor); } - else if (auto c=settings.getPreviousSeparatorColor()) { + else if (auto c=settings.colors().previousSeparatorColor()) { dialog.setCurrentColor(*c); } @@ -3673,7 +3673,7 @@ void MainWindow::setColor_clicked() if (!currentColor.isValid()) return; - settings.setPreviousSeparatorColor(currentColor); + settings.colors().setPreviousSeparatorColor(currentColor); QItemSelectionModel *selection = ui->modList->selectionModel(); if (selection->hasSelection() && selection->selectedRows().count() > 1) { @@ -3710,7 +3710,7 @@ void MainWindow::resetColor_clicked() modInfo->setColor(color); } - m_OrganizerCore.settings().removePreviousSeparatorColor(); + m_OrganizerCore.settings().colors().removePreviousSeparatorColor(); } void MainWindow::createModFromOverwrite() @@ -4184,7 +4184,7 @@ void MainWindow::checkModsForUpdates() NexusInterface::instance(&m_PluginContainer)->requestTrackingInfo(this, QVariant(), QString()); } else { QString apiKey; - if (m_OrganizerCore.settings().getNexusApiKey(apiKey)) { + if (m_OrganizerCore.settings().nexus().apiKey(apiKey)) { m_OrganizerCore.doAfterLogin([this] () { this->checkModsForUpdates(); }); NexusInterface::instance(&m_PluginContainer)->getAccessManager()->apiCheck(apiKey); } else { @@ -4387,12 +4387,12 @@ void MainWindow::openIniFolder() void MainWindow::openDownloadsFolder() { - shell::ExploreFile(m_OrganizerCore.settings().getDownloadDirectory()); + shell::ExploreFile(m_OrganizerCore.settings().paths().downloads()); } void MainWindow::openModsFolder() { - shell::ExploreFile(m_OrganizerCore.settings().getModDirectory()); + shell::ExploreFile(m_OrganizerCore.settings().paths().mods()); } void MainWindow::openGameFolder() @@ -4758,7 +4758,7 @@ void MainWindow::on_modList_customContextMenuRequested(const QPoint &pos) menu.addSeparator(); - if (info->getNexusID() > 0 && Settings::instance().endorsementIntegration()) { + if (info->getNexusID() > 0 && Settings::instance().nexus().endorsementIntegration()) { switch (info->endorsedState()) { case ModInfo::ENDORSED_TRUE: { menu.addAction(tr("Un-Endorse"), this, SLOT(unendorse_clicked())); @@ -5007,19 +5007,19 @@ void MainWindow::on_actionSettings_triggered() { Settings &settings = m_OrganizerCore.settings(); - QString oldModDirectory(settings.getModDirectory()); - QString oldCacheDirectory(settings.getCacheDirectory()); - QString oldProfilesDirectory(settings.getProfileDirectory()); - QString oldManagedGameDirectory(settings.getManagedGameDirectory().value_or("")); - bool oldDisplayForeign(settings.displayForeign()); - bool proxy = settings.getUseProxy(); + QString oldModDirectory(settings.paths().mods()); + QString oldCacheDirectory(settings.paths().cache()); + QString oldProfilesDirectory(settings.paths().profiles()); + QString oldManagedGameDirectory(settings.game().directory().value_or("")); + bool oldDisplayForeign(settings.interface().displayForeign()); + bool proxy = settings.network().useProxy(); DownloadManager *dlManager = m_OrganizerCore.downloadManager(); SettingsDialog dialog(&m_PluginContainer, settings, this); dialog.exec(); - if (oldManagedGameDirectory != settings.getManagedGameDirectory()) { + if (oldManagedGameDirectory != settings.game().directory()) { QMessageBox::about(this, tr("Restarting MO"), tr("Changing the managed game directory requires restarting MO.\n" "Any pending downloads will be paused.\n\n" @@ -5029,28 +5029,28 @@ void MainWindow::on_actionSettings_triggered() } InstallationManager *instManager = m_OrganizerCore.installationManager(); - instManager->setModsDirectory(settings.getModDirectory()); - instManager->setDownloadDirectory(settings.getDownloadDirectory()); + instManager->setModsDirectory(settings.paths().mods()); + instManager->setDownloadDirectory(settings.paths().downloads()); fixCategories(); refreshFilters(); - if (settings.getProfileDirectory() != oldProfilesDirectory) { + if (settings.paths().profiles() != oldProfilesDirectory) { refreshProfiles(); } - if (dlManager->getOutputDirectory() != settings.getDownloadDirectory()) { + if (dlManager->getOutputDirectory() != settings.paths().downloads()) { if (dlManager->downloadsInProgress()) { MessageDialog::showMessage(tr("Can't change download directory while " "downloads are in progress!"), this); } else { - dlManager->setOutputDirectory(settings.getDownloadDirectory()); + dlManager->setOutputDirectory(settings.paths().downloads()); } } - if ((settings.getModDirectory() != oldModDirectory) - || (settings.displayForeign() != oldDisplayForeign)) { + if ((settings.paths().mods() != oldModDirectory) + || (settings.interface().displayForeign() != oldDisplayForeign)) { m_OrganizerCore.profileRefresh(); } @@ -5075,18 +5075,19 @@ void MainWindow::on_actionSettings_triggered() m_OrganizerCore.refreshLists(); } - if (settings.getCacheDirectory() != oldCacheDirectory) { - NexusInterface::instance(&m_PluginContainer)->setCacheDirectory(settings.getCacheDirectory()); + if (settings.paths().cache() != oldCacheDirectory) { + NexusInterface::instance(&m_PluginContainer)->setCacheDirectory( + settings.paths().cache()); } - if (proxy != settings.getUseProxy()) { - activateProxy(settings.getUseProxy()); + if (proxy != settings.network().useProxy()) { + activateProxy(settings.network().useProxy()); } ui->statusBar->checkSettings(m_OrganizerCore.settings()); updateDownloadView(); - m_OrganizerCore.setLogLevel(settings.logLevel()); + m_OrganizerCore.setLogLevel(settings.diagnostics().logLevel()); m_OrganizerCore.cycleDiagnostics(); toggleMO2EndorseState(); @@ -5402,10 +5403,10 @@ void MainWindow::motdReceived(const QString &motd) // internet connection is faster next time if (m_StartTime.secsTo(QTime::currentTime()) < 5) { uint hash = qHash(motd); - if (hash != m_OrganizerCore.settings().getMotDHash()) { + if (hash != m_OrganizerCore.settings().motdHash()) { MotDDialog dialog(motd); dialog.exec(); - m_OrganizerCore.settings().setMotDHash(hash); + m_OrganizerCore.settings().setMotdHash(hash); } } } @@ -5528,7 +5529,7 @@ void MainWindow::initDownloadView() void MainWindow::updateDownloadView() { // set the view attribute and default row sizes - if (m_OrganizerCore.settings().compactDownloads()) { + if (m_OrganizerCore.settings().interface().compactDownloads()) { ui->downloadView->setProperty("downloadView", "compact"); setStyleSheet("DownloadListWidget::item { padding: 4px 2px; }"); } else { @@ -5541,7 +5542,7 @@ void MainWindow::updateDownloadView() // reapply global stylesheet on the widget level (!) to override the defaults //ui->downloadView->setStyleSheet(styleSheet()); - ui->downloadView->setMetaDisplay(m_OrganizerCore.settings().metaDownloads()); + ui->downloadView->setMetaDisplay(m_OrganizerCore.settings().interface().metaDownloads()); ui->downloadView->style()->unpolish(ui->downloadView); ui->downloadView->style()->polish(ui->downloadView); qobject_cast(ui->downloadView->header())->customResizeSections(); @@ -5554,7 +5555,7 @@ void MainWindow::modUpdateCheck(std::multimap IDs) ModInfo::manualUpdateCheck(&m_PluginContainer, this, IDs); } else { QString apiKey; - if (m_OrganizerCore.settings().getNexusApiKey(apiKey)) { + if (m_OrganizerCore.settings().nexus().apiKey(apiKey)) { m_OrganizerCore.doAfterLogin([=]() { this->modUpdateCheck(IDs); }); NexusInterface::instance(&m_PluginContainer)->getAccessManager()->apiCheck(apiKey); } else @@ -5566,7 +5567,7 @@ void MainWindow::toggleMO2EndorseState() { const auto& s = m_OrganizerCore.settings(); - if (!s.endorsementIntegration()) { + if (!s.nexus().endorsementIntegration()) { ui->actionEndorseMO->setVisible(false); return; } @@ -5576,7 +5577,7 @@ void MainWindow::toggleMO2EndorseState() bool enabled = false; QString text; - switch (s.endorsementState()) + switch (s.nexus().endorsementState()) { case EndorsementState::Accepted: { @@ -5631,9 +5632,9 @@ void MainWindow::nxmEndorsementsAvailable(QVariant userData, QVariant resultData mod->setIsEndorsed(false); } - if (Settings::instance().endorsementIntegration()) { + if (Settings::instance().nexus().endorsementIntegration()) { if (result->first == "skyrimspecialedition" && result->second.first == gamePlugin->nexusModOrganizerID()) { - m_OrganizerCore.settings().setEndorsementState( + m_OrganizerCore.settings().nexus().setEndorsementState( endorsementStateFromString(result->second.second)); toggleMO2EndorseState(); @@ -5642,13 +5643,13 @@ void MainWindow::nxmEndorsementsAvailable(QVariant userData, QVariant resultData } } - if (!searchedMO2NexusGame && Settings::instance().endorsementIntegration()) { + if (!searchedMO2NexusGame && Settings::instance().nexus().endorsementIntegration()) { auto gamePlugin = m_OrganizerCore.getGame("SkyrimSE"); if (gamePlugin) { auto iter = sorted.equal_range(gamePlugin->gameNexusName()); for (auto result = iter.first; result != iter.second; ++result) { if (result->second.first == gamePlugin->nexusModOrganizerID()) { - m_OrganizerCore.settings().setEndorsementState( + m_OrganizerCore.settings().nexus().setEndorsementState( endorsementStateFromString(result->second.second)); toggleMO2EndorseState(); @@ -5862,7 +5863,7 @@ void MainWindow::nxmEndorsementToggled(QString, int, QVariant, QVariant resultDa } } - m_OrganizerCore.settings().setEndorsementState(s); + m_OrganizerCore.settings().nexus().setEndorsementState(s); toggleMO2EndorseState(); if (!disconnect(sender(), SIGNAL(nxmEndorsementToggled(QString, int, QVariant, QVariant, int)), @@ -5901,7 +5902,7 @@ void MainWindow::nxmTrackedModsAvailable(QVariant userData, QVariant resultData, void MainWindow::nxmDownloadURLs(QString, int, int, QVariant, QVariant resultData, int) { - auto servers = m_OrganizerCore.settings().getServers(); + auto servers = m_OrganizerCore.settings().network().servers(); for (const QVariant &var : resultData.toList()) { const QVariantMap map = var.toMap(); @@ -5929,7 +5930,7 @@ void MainWindow::nxmDownloadURLs(QString, int, int, QVariant, QVariant resultDat } } - m_OrganizerCore.settings().updateServers(servers); + m_OrganizerCore.settings().network().updateServers(servers); } diff --git a/src/modinfodialog.cpp b/src/modinfodialog.cpp index f3840230..2178ef34 100644 --- a/src/modinfodialog.cpp +++ b/src/modinfodialog.cpp @@ -381,7 +381,7 @@ void ModInfoDialog::reAddTabs( Q_ASSERT(visibility.size() == m_tabs.size()); // ordered tab names from settings - const auto orderedNames = m_core->settings().geometry().getModInfoTabOrder(); + const auto orderedNames = m_core->settings().geometry().modInfoTabOrder(); // whether the tabs can be sorted; if the object name of a tab widget is not // found in orderedNames, the list cannot be sorted safely diff --git a/src/modinfodialogconflicts.cpp b/src/modinfodialogconflicts.cpp index 7840269d..3a71b405 100644 --- a/src/modinfodialogconflicts.cpp +++ b/src/modinfodialogconflicts.cpp @@ -409,7 +409,7 @@ void ConflictsTab::clear() void ConflictsTab::saveState(Settings& s) { - s.saveIndex(ui->tabConflictsTabs); + s.widgets().saveIndex(ui->tabConflictsTabs); m_general.saveState(s); m_advanced.saveState(s); @@ -417,7 +417,7 @@ void ConflictsTab::saveState(Settings& s) void ConflictsTab::restoreState(const Settings& s) { - s.restoreIndex(ui->tabConflictsTabs, 0); + s.widgets().restoreIndex(ui->tabConflictsTabs, 0); m_general.restoreState(s); m_advanced.restoreState(s); @@ -1014,17 +1014,17 @@ void AdvancedConflictsTab::clear() void AdvancedConflictsTab::saveState(Settings& s) { s.geometry().saveState(ui->conflictsAdvancedList->header()); - s.saveChecked(ui->conflictsAdvancedShowNoConflict); - s.saveChecked(ui->conflictsAdvancedShowAll); - s.saveChecked(ui->conflictsAdvancedShowNearest); + s.widgets().saveChecked(ui->conflictsAdvancedShowNoConflict); + s.widgets().saveChecked(ui->conflictsAdvancedShowAll); + s.widgets().saveChecked(ui->conflictsAdvancedShowNearest); } void AdvancedConflictsTab::restoreState(const Settings& s) { s.geometry().restoreState(ui->conflictsAdvancedList->header()); - s.restoreChecked(ui->conflictsAdvancedShowNoConflict); - s.restoreChecked(ui->conflictsAdvancedShowAll); - s.restoreChecked(ui->conflictsAdvancedShowNearest); + s.widgets().restoreChecked(ui->conflictsAdvancedShowNoConflict); + s.widgets().restoreChecked(ui->conflictsAdvancedShowAll); + s.widgets().restoreChecked(ui->conflictsAdvancedShowNearest); } void AdvancedConflictsTab::update() diff --git a/src/modinfodialogimages.cpp b/src/modinfodialogimages.cpp index 38c12d8a..9d347f57 100644 --- a/src/modinfodialogimages.cpp +++ b/src/modinfodialogimages.cpp @@ -130,13 +130,13 @@ void ImagesTab::update() void ImagesTab::saveState(Settings& s) { - s.saveChecked(ui->imagesShowDDS); + s.widgets().saveChecked(ui->imagesShowDDS); s.geometry().saveState(ui->tabImagesSplitter); } void ImagesTab::restoreState(const Settings& s) { - s.restoreChecked(ui->imagesShowDDS); + s.widgets().restoreChecked(ui->imagesShowDDS); s.geometry().restoreState(ui->tabImagesSplitter); } diff --git a/src/modinfodialognexus.cpp b/src/modinfodialognexus.cpp index 6d28cbe3..95e62328 100644 --- a/src/modinfodialognexus.cpp +++ b/src/modinfodialognexus.cpp @@ -19,7 +19,7 @@ NexusTab::NexusTab(ModInfoDialogTabContext cx) : ModInfoDialogTab(std::move(cx)), m_requestStarted(false), m_loading(false) { ui->modID->setValidator(new QIntValidator(ui->modID)); - ui->endorse->setVisible(core().settings().endorsementIntegration()); + ui->endorse->setVisible(core().settings().nexus().endorsementIntegration()); connect(ui->modID, &QLineEdit::editingFinished, [&]{ onModIDChanged(); }); connect( diff --git a/src/modinfooverwrite.cpp b/src/modinfooverwrite.cpp index 37c8c650..fb110abb 100644 --- a/src/modinfooverwrite.cpp +++ b/src/modinfooverwrite.cpp @@ -23,7 +23,7 @@ bool ModInfoOverwrite::isEmpty() const QString ModInfoOverwrite::absolutePath() const { - return Settings::instance().getOverwriteDirectory(); + return Settings::instance().paths().overwrite(); } std::vector ModInfoOverwrite::getFlags() const diff --git a/src/modinforegular.cpp b/src/modinforegular.cpp index ce29e11e..3cff914a 100644 --- a/src/modinforegular.cpp +++ b/src/modinforegular.cpp @@ -631,7 +631,7 @@ std::vector ModInfoRegular::getFlags() const std::vector result = ModInfoWithConflictInfo::getFlags(); if ((m_NexusID > 0) && (endorsedState() == ENDORSED_FALSE) && - Settings::instance().endorsementIntegration()) { + Settings::instance().nexus().endorsementIntegration()) { result.push_back(ModInfo::FLAG_NOTENDORSED); } if ((m_NexusID > 0) && diff --git a/src/modlist.cpp b/src/modlist.cpp index 94b4a387..6018d3d4 100644 --- a/src/modlist.cpp +++ b/src/modlist.cpp @@ -390,7 +390,7 @@ QVariant ModList::data(const QModelIndex &modelIndex, int role) const return QVariant(); } else if (role == Qt::ForegroundRole) { if (modInfo->hasFlag(ModInfo::FLAG_SEPARATOR) && modInfo->getColor().isValid()) { - return Settings::getIdealTextColor(modInfo->getColor()); + return ColorSettings::idealTextColor(modInfo->getColor()); } else if (column == COL_NAME) { int highlight = modInfo->getHighlight(); if (highlight & ModInfo::HIGHLIGHT_IMPORTANT) @@ -428,7 +428,7 @@ QVariant ModList::data(const QModelIndex &modelIndex, int role) const } else if (modInfo->hasFlag(ModInfo::FLAG_SEPARATOR) && modInfo->getColor().isValid() && ((role != ViewMarkingScrollBar::DEFAULT_ROLE) - || Settings::instance().colorSeparatorScrollbar())) { + || Settings::instance().colors().colorSeparatorScrollbar())) { return modInfo->getColor(); } else { return QVariant(); @@ -999,8 +999,8 @@ bool ModList::dropURLs(const QMimeData *mimeData, int row, const QModelIndex &pa ModInfo::Ptr modInfo = ModInfo::getByIndex(row); QDir modDir = QDir(modInfo->absolutePath()); - QDir allModsDir(Settings::instance().getModDirectory()); - QDir overwriteDir(Settings::instance().getOverwriteDirectory()); + QDir allModsDir(Settings::instance().paths().mods()); + QDir overwriteDir(Settings::instance().paths().overwrite()); QStringList sourceList; QStringList targetList; diff --git a/src/nxmaccessmanager.cpp b/src/nxmaccessmanager.cpp index 16190ca4..c6ef7bc7 100644 --- a/src/nxmaccessmanager.cpp +++ b/src/nxmaccessmanager.cpp @@ -572,7 +572,7 @@ NXMAccessManager::NXMAccessManager(QObject *parent, const QString &moVersion) m_validator.finished = [&](auto&& user){ onValidatorFinished(user); }; setCookieJar(new PersistentCookieJar(QDir::fromNativeSeparators( - Settings::instance().getCacheDirectory() + "/nexus_cookies.dat"))); + Settings::instance().paths().cache() + "/nexus_cookies.dat"))); if (networkAccessible() == QNetworkAccessManager::UnknownAccessibility) { // why is this necessary all of a sudden? diff --git a/src/organizercore.cpp b/src/organizercore.cpp index af0cf969..1a89641d 100644 --- a/src/organizercore.cpp +++ b/src/organizercore.cpp @@ -146,7 +146,7 @@ static void startSteam(QWidget *widget) QStringList args; QString username; QString password; - if (Settings::instance().getSteamLogin(username, password)) { + if (Settings::instance().steam().login(username, password)) { args << "-login"; args << username; if (password != "") { @@ -275,12 +275,13 @@ OrganizerCore::OrganizerCore(Settings &settings) , m_ArchivesInit(false) , m_PluginListsWriter(std::bind(&OrganizerCore::savePluginList, this)) { - m_DownloadManager.setOutputDirectory(m_Settings.getDownloadDirectory()); + m_DownloadManager.setOutputDirectory(m_Settings.paths().downloads()); - NexusInterface::instance(m_PluginContainer)->setCacheDirectory(m_Settings.getCacheDirectory()); + NexusInterface::instance(m_PluginContainer)->setCacheDirectory( + m_Settings.paths().cache()); - m_InstallationManager.setModsDirectory(m_Settings.getModDirectory()); - m_InstallationManager.setDownloadDirectory(m_Settings.getDownloadDirectory()); + m_InstallationManager.setModsDirectory(m_Settings.paths().mods()); + m_InstallationManager.setDownloadDirectory(m_Settings.paths().downloads()); connect(&m_DownloadManager, SIGNAL(downloadSpeed(QString, int)), this, SLOT(downloadSpeed(QString, int))); @@ -333,7 +334,7 @@ OrganizerCore::~OrganizerCore() void OrganizerCore::storeSettings() { if (m_CurrentProfile != nullptr) { - m_Settings.setSelectedProfileName(m_CurrentProfile->name()); + m_Settings.game().setSelectedProfileName(m_CurrentProfile->name()); } m_ExecutablesList.store(m_Settings); @@ -356,7 +357,7 @@ void OrganizerCore::storeSettings() QMessageBox::critical( qApp->activeWindow(), tr("Failed to write settings"), tr("An error occurred trying to write back MO settings to %1: %2") - .arg(m_Settings.getFilename(), reason)); + .arg(m_Settings.filename(), reason)); } } @@ -432,8 +433,9 @@ void OrganizerCore::updateExecutablesList() // TODO this has nothing to do with executables list move to an appropriate // function! - ModInfo::updateFromDisc(m_Settings.getModDirectory(), &m_DirectoryStructure, - m_PluginContainer, m_Settings.displayForeign(), managedGame()); + ModInfo::updateFromDisc( + m_Settings.paths().mods(), &m_DirectoryStructure, + m_PluginContainer, m_Settings.interface().displayForeign(), managedGame()); } void OrganizerCore::setUserInterface(IUserInterface *userInterface, @@ -478,7 +480,7 @@ void OrganizerCore::setUserInterface(IUserInterface *userInterface, if (userInterface != nullptr) { // this currently wouldn't work reliably if the ui isn't initialized yet to // display the result - if (isOnline() && !m_Settings.offlineMode()) { + if (isOnline() && !m_Settings.network().offlineMode()) { m_Updater.testForUpdate(); } else { log::debug("user doesn't seem to be connected to the internet"); @@ -541,7 +543,7 @@ bool OrganizerCore::nexusApi(bool retry) return false; } else { QString apiKey; - if (m_Settings.getNexusApiKey(apiKey)) { + if (m_Settings.nexus().apiKey(apiKey)) { // credentials stored or user entered them manually log::debug("attempt to verify nexus api key"); accessManager->apiCheck(apiKey); @@ -608,7 +610,7 @@ void OrganizerCore::removeOrigin(const QString &name) void OrganizerCore::downloadSpeed(const QString &serverName, int bytesPerSecond) { - m_Settings.setDownloadSpeed(serverName, bytesPerSecond); + m_Settings.network().setDownloadSpeed(serverName, bytesPerSecond); } InstallationManager *OrganizerCore::installationManager() @@ -629,9 +631,9 @@ bool OrganizerCore::createDirectory(const QString &path) { } bool OrganizerCore::checkPathSymlinks() { - bool hasSymlink = (QFileInfo(m_Settings.getProfileDirectory()).isSymLink() || - QFileInfo(m_Settings.getModDirectory()).isSymLink() || - QFileInfo(m_Settings.getOverwriteDirectory()).isSymLink()); + bool hasSymlink = (QFileInfo(m_Settings.paths().profiles()).isSymLink() || + QFileInfo(m_Settings.paths().mods()).isSymLink() || + QFileInfo(m_Settings.paths().overwrite()).isSymLink()); if (hasSymlink) { QMessageBox::critical(nullptr, QObject::tr("Error"), QObject::tr("One of the configured MO2 directories (profiles, mods, or overwrite) " @@ -643,17 +645,17 @@ bool OrganizerCore::checkPathSymlinks() { } bool OrganizerCore::bootstrap() { - return createDirectory(m_Settings.getProfileDirectory()) && - createDirectory(m_Settings.getModDirectory()) && - createDirectory(m_Settings.getDownloadDirectory()) && - createDirectory(m_Settings.getOverwriteDirectory()) && + return createDirectory(m_Settings.paths().profiles()) && + createDirectory(m_Settings.paths().mods()) && + createDirectory(m_Settings.paths().downloads()) && + createDirectory(m_Settings.paths().overwrite()) && createDirectory(QString::fromStdWString(crashDumpsPath())) && checkPathSymlinks() && cycleDiagnostics(); } void OrganizerCore::createDefaultProfile() { - QString profilesPath = settings().getProfileDirectory(); + QString profilesPath = settings().paths().profiles(); if (QDir(profilesPath).entryList(QDir::AllDirs | QDir::NoDotAndDotDot).size() == 0) { Profile newProf("Default", managedGame(), false); @@ -674,18 +676,18 @@ void OrganizerCore::updateVFSParams( void OrganizerCore::setLogLevel(log::Levels level) { - m_Settings.setLogLevel(level); + m_Settings.diagnostics().setLogLevel(level); updateVFSParams( - m_Settings.logLevel(), - m_Settings.crashDumpsType(), + m_Settings.diagnostics().logLevel(), + m_Settings.diagnostics().crashDumpsType(), m_Settings.executablesBlacklist()); - log::getDefault().setLevel(m_Settings.logLevel()); + log::getDefault().setLevel(m_Settings.diagnostics().logLevel()); } bool OrganizerCore::cycleDiagnostics() { - if (int maxDumps = settings().crashDumpsMax()) + if (int maxDumps = settings().diagnostics().crashDumpsMax()) removeOldFiles(QString::fromStdWString(crashDumpsPath()), "*.dmp", maxDumps, QDir::Time|QDir::Reversed); return true; } @@ -720,7 +722,7 @@ void OrganizerCore::setCurrentProfile(const QString &profileName) return; } - QDir profileBaseDir(settings().getProfileDirectory()); + QDir profileBaseDir(settings().paths().profiles()); QString profileDir = profileBaseDir.absoluteFilePath(profileName); if (!QDir(profileDir).exists()) { @@ -744,7 +746,7 @@ void OrganizerCore::setCurrentProfile(const QString &profileName) m_CurrentProfile->deactivateInvalidation(); } - m_Settings.setSelectedProfileName(m_CurrentProfile->name()); + m_Settings.game().setSelectedProfileName(m_CurrentProfile->name()); connect(m_CurrentProfile, SIGNAL(modStatusChanged(uint)), this, SLOT(modStatusChanged(uint))); connect(m_CurrentProfile, SIGNAL(modStatusChanged(QList)), this, SLOT(modStatusChanged(QList))); @@ -776,22 +778,22 @@ QString OrganizerCore::profilePath() const QString OrganizerCore::downloadsPath() const { - return QDir::fromNativeSeparators(m_Settings.getDownloadDirectory()); + return QDir::fromNativeSeparators(m_Settings.paths().downloads()); } QString OrganizerCore::overwritePath() const { - return QDir::fromNativeSeparators(m_Settings.getOverwriteDirectory()); + return QDir::fromNativeSeparators(m_Settings.paths().overwrite()); } QString OrganizerCore::basePath() const { - return QDir::fromNativeSeparators(m_Settings.getBaseDirectory()); + return QDir::fromNativeSeparators(m_Settings.paths().base()); } QString OrganizerCore::modsPath() const { - return QDir::fromNativeSeparators(m_Settings.getModDirectory()); + return QDir::fromNativeSeparators(m_Settings.paths().mods()); } MOBase::VersionInfo OrganizerCore::appVersion() const @@ -821,10 +823,10 @@ MOBase::IModInterface *OrganizerCore::createMod(GuessedValue &name) return nullptr; } - m_InstallationManager.setModsDirectory(m_Settings.getModDirectory()); + m_InstallationManager.setModsDirectory(m_Settings.paths().mods()); QString targetDirectory - = QDir::fromNativeSeparators(m_Settings.getModDirectory()) + = QDir::fromNativeSeparators(m_Settings.paths().mods()) .append("/") .append(name); @@ -912,7 +914,7 @@ MOBase::IModInterface *OrganizerCore::installMod(const QString &fileName, modName.update(initModName, GUESS_USER); } m_CurrentProfile->writeModlistNow(); - m_InstallationManager.setModsDirectory(m_Settings.getModDirectory()); + m_InstallationManager.setModsDirectory(m_Settings.paths().mods()); if (m_InstallationManager.install(fileName, modName, hasIniTweaks)) { MessageDialog::showMessage(tr("Installation successful"), qApp->activeWindow()); @@ -977,7 +979,7 @@ void OrganizerCore::installDownload(int index) m_CurrentProfile->writeModlistNow(); bool hasIniTweaks = false; - m_InstallationManager.setModsDirectory(m_Settings.getModDirectory()); + m_InstallationManager.setModsDirectory(m_Settings.paths().mods()); if (m_InstallationManager.install(fileName, modName, hasIniTweaks)) { MessageDialog::showMessage(tr("Installation successful"), qApp->activeWindow()); @@ -1270,7 +1272,7 @@ bool OrganizerCore::previewFileWithAlternatives( else { // crude: we search for the next slash after the base mod directory to skip // everything up to the data-relative directory - int offset = settings().getModDirectory().size() + 1; + int offset = settings().paths().mods().size() + 1; offset = fileName.indexOf("/", offset); fileName = fileName.mid(offset + 1); } @@ -1412,7 +1414,7 @@ HANDLE OrganizerCore::spawnBinaryDirect(const QFileInfo &binary, LPDWORD exitCode) { HANDLE processHandle = spawnBinaryProcess(binary, arguments, profileName, currentDirectory, steamAppID, customOverwrite, forcedLibraries); - if (Settings::instance().lockGUI() && processHandle != INVALID_HANDLE_VALUE) { + if (Settings::instance().interface().lockGUI() && processHandle != INVALID_HANDLE_VALUE) { std::unique_ptr dlg; ILockedWaitingForProcess* uilock = nullptr; @@ -1461,7 +1463,7 @@ HANDLE OrganizerCore::spawnBinaryProcess(const QFileInfo &binary, ::SetEnvironmentVariableW(L"SteamAPPId", ToWString(steamAppID).c_str()); } else { ::SetEnvironmentVariableW(L"SteamAPPId", - ToWString(m_Settings.getSteamAppID()).c_str()); + ToWString(m_Settings.steam().appID()).c_str()); } QWidget *window = qApp->activeWindow(); @@ -1477,7 +1479,7 @@ HANDLE OrganizerCore::spawnBinaryProcess(const QFileInfo &binary, || QFileInfo(managedGame()->gameDirectory().absoluteFilePath( "steam_api64.dll")) .exists()) - && (m_Settings.getLoadMechanism() == LoadMechanism::LOAD_MODORGANIZER)) { + && (m_Settings.game().loadMechanismType() == LoadMechanism::LOAD_MODORGANIZER)) { bool steamFound = true; bool steamAccess = true; @@ -1592,7 +1594,7 @@ HANDLE OrganizerCore::spawnBinaryProcess(const QFileInfo &binary, } } - QString modsPath = settings().getModDirectory(); + QString modsPath = settings().paths().mods(); // Check if this a request with either an executable or a working directory under our mods folder // then will start the process in a virtualized "environment" with the appropriate paths fixed: @@ -1749,7 +1751,7 @@ HANDLE OrganizerCore::startApplication(const QString &executable, bool OrganizerCore::waitForApplication(HANDLE handle, LPDWORD exitCode) { - if (!Settings::instance().lockGUI()) + if (!Settings::instance().interface().lockGUI()) return true; ILockedWaitingForProcess* uilock = nullptr; @@ -1960,8 +1962,10 @@ void OrganizerCore::refreshModList(bool saveChanges) if (saveChanges) { m_CurrentProfile->writeModlistNow(true); } - ModInfo::updateFromDisc(m_Settings.getModDirectory(), &m_DirectoryStructure, - m_PluginContainer, m_Settings.displayForeign(), managedGame()); + + ModInfo::updateFromDisc( + m_Settings.paths().mods(), &m_DirectoryStructure, + m_PluginContainer, m_Settings.interface().displayForeign(), managedGame()); m_CurrentProfile->refreshModStatus(); @@ -2130,7 +2134,7 @@ void OrganizerCore::updateModsInDirectoryStructure(QMaparchivesWriter().writeImmediately(false); @@ -2156,7 +2160,7 @@ void OrganizerCore::loggedInAction(QWidget* parent, std::function f) f(); } else { QString apiKey; - if (settings().getNexusApiKey(apiKey)) { + if (settings().nexus().apiKey(apiKey)) { doAfterLogin([f]{ f(); }); NexusInterface::instance(m_PluginContainer)->getAccessManager()->apiCheck(apiKey); } else { @@ -2295,8 +2299,10 @@ void OrganizerCore::profileRefresh() { // have to refresh mods twice (again in refreshModList), otherwise the refresh // isn't complete. Not sure why - ModInfo::updateFromDisc(m_Settings.getModDirectory(), &m_DirectoryStructure, - m_PluginContainer, m_Settings.displayForeign(), managedGame()); + ModInfo::updateFromDisc( + m_Settings.paths().mods(), &m_DirectoryStructure, + m_PluginContainer, m_Settings.interface().displayForeign(), managedGame()); + m_CurrentProfile->refreshModStatus(); refreshModList(); @@ -2463,7 +2469,7 @@ void OrganizerCore::syncOverwrite() SyncOverwriteDialog syncDialog(modInfo->absolutePath(), m_DirectoryStructure, qApp->activeWindow()); if (syncDialog.exec() == QDialog::Accepted) { - syncDialog.apply(QDir::fromNativeSeparators(m_Settings.getModDirectory())); + syncDialog.apply(QDir::fromNativeSeparators(m_Settings.paths().mods())); modInfo->testValid(); refreshDirectoryStructure(); } @@ -2486,7 +2492,7 @@ std::vector OrganizerCore::activeProblems() const const auto& hookdll = oldMO1HookDll(); if (!hookdll.isEmpty()) { // This warning will now be shown every time the problems are checked, which is a bit - // of a "log spam". But since this is a sevre error which will most likely make the + // of a "log spam". But since this is a sever error which will most likely make the // game crash/freeze/etc. and is very hard to diagnose, this "log spam" will make it // easier for the user to notice the warning. log::warn("hook.dll found in game folder: {}", hookdll); @@ -2562,7 +2568,7 @@ void OrganizerCore::savePluginList() } m_PluginList.saveTo(m_CurrentProfile->getLockedOrderFileName(), m_CurrentProfile->getDeleterFileName(), - m_Settings.hideUncheckedPlugins()); + m_Settings.game().hideUncheckedPlugins()); m_PluginList.saveLoadOrder(*m_DirectoryStructure); } @@ -2574,7 +2580,7 @@ void OrganizerCore::prepareStart() m_CurrentProfile->writeModlist(); m_CurrentProfile->createTweakedIniFile(); saveCurrentLists(); - m_Settings.setupLoadMechanism(); + m_Settings.game().setupLoadMechanism(); storeSettings(); } @@ -2588,7 +2594,7 @@ std::vector OrganizerCore::fileMapping(const QString &profileName, } IPluginGame *game = qApp->property("managed_game").value(); - Profile profile(QDir(m_Settings.getProfileDirectory() + "/" + profileName), + Profile profile(QDir(m_Settings.paths().profiles() + "/" + profileName), game); MappingType result; @@ -2634,7 +2640,7 @@ std::vector OrganizerCore::fileMapping(const QString &profileName, } result.insert(result.end(), { - QDir::toNativeSeparators(m_Settings.getOverwriteDirectory()), + QDir::toNativeSeparators(m_Settings.paths().overwrite()), dataPath, true, customOverwrite.isEmpty() diff --git a/src/pluginlist.cpp b/src/pluginlist.cpp index ddfe492e..33423225 100644 --- a/src/pluginlist.cpp +++ b/src/pluginlist.cpp @@ -191,7 +191,7 @@ void PluginList::refresh(const QString &profileName continue; } - bool forceEnabled = Settings::instance().forceEnableCoreFiles() && + bool forceEnabled = Settings::instance().game().forceEnableCoreFiles() && primaryPlugins.contains(filename, Qt::CaseInsensitive); //(std::find(primaryPlugins.begin(), primaryPlugins.end(), filename.toLower()) != primaryPlugins.end()); diff --git a/src/profile.cpp b/src/profile.cpp index 7f4ebcaa..e76060b9 100644 --- a/src/profile.cpp +++ b/src/profile.cpp @@ -73,7 +73,7 @@ Profile::Profile(const QString &name, IPluginGame const *gamePlugin, bool useDef : m_ModListWriter(std::bind(&Profile::doWriteModlist, this)) , m_GamePlugin(gamePlugin) { - QString profilesDir = Settings::instance().getProfileDirectory(); + QString profilesDir = Settings::instance().paths().profiles(); QDir profileBase(profilesDir); QString fixedName = name; if (!fixDirectoryName(fixedName)) { @@ -299,7 +299,7 @@ void Profile::createTweakedIniFile() // static void Profile::renameModInAllProfiles(const QString& oldName, const QString& newName) { - QDir profilesDir(Settings::instance().getProfileDirectory()); + QDir profilesDir(Settings::instance().paths().profiles()); profilesDir.setFilter(QDir::AllDirs | QDir::NoDotAndDotDot); QDirIterator profileIter(profilesDir); while (profileIter.hasNext()) { @@ -655,7 +655,7 @@ void Profile::setModPriority(unsigned int index, int &newPriority) Profile *Profile::createPtrFrom(const QString &name, const Profile &reference, MOBase::IPluginGame const *gamePlugin) { - QString profileDirectory = Settings::instance().getProfileDirectory() + "/" + name; + QString profileDirectory = Settings::instance().paths().profiles() + "/" + name; reference.copyFilesTo(profileDirectory); return new Profile(QDir(profileDirectory), gamePlugin); } @@ -906,7 +906,7 @@ QString Profile::savePath() const void Profile::rename(const QString &newName) { - QDir profileDir(Settings::instance().getProfileDirectory()); + QDir profileDir(Settings::instance().paths().profiles()); profileDir.rename(name(), newName); m_Directory.setPath(profileDir.absoluteFilePath(newName)); } diff --git a/src/profilesdialog.cpp b/src/profilesdialog.cpp index 2f1bd059..c91f48f4 100644 --- a/src/profilesdialog.cpp +++ b/src/profilesdialog.cpp @@ -57,7 +57,7 @@ ProfilesDialog::ProfilesDialog(const QString &profileName, MOBase::IPluginGame c { ui->setupUi(this); - QDir profilesDir(Settings::instance().getProfileDirectory()); + QDir profilesDir(Settings::instance().paths().profiles()); profilesDir.setFilter(QDir::AllDirs | QDir::NoDotAndDotDot); QDirIterator profileIter(profilesDir); @@ -203,7 +203,7 @@ void ProfilesDialog::on_removeProfileButton_clicked() if (confirmBox.exec() == QMessageBox::Yes) { QString profilePath; if (profileToDelete.get() == nullptr) { - profilePath = Settings::instance().getProfileDirectory() + profilePath = Settings::instance().paths().profiles() + "/" + ui->profilesList->currentItem()->text(); if (QMessageBox::question(this, tr("Profile broken"), tr("This profile you're about to delete seems to be broken or the path is invalid. " diff --git a/src/settings.cpp b/src/settings.cpp index 71288950..8b063efb 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -150,7 +150,7 @@ std::optional getOptional( template T get( const QSettings& settings, - const QString& section, const QString& key, T def={}) + const QString& section, const QString& key, T def) { if (auto v=getOptional(settings, section, key)) { return *v; @@ -453,22 +453,74 @@ void warnIfNotCheckable(const QAbstractButton* b) } +bool setWindowsCredential(const QString key, const QString data) +{ + QString finalKey("ModOrganizer2_" + key); + wchar_t* keyData = new wchar_t[finalKey.size()+1]; + finalKey.toWCharArray(keyData); + keyData[finalKey.size()] = L'\0'; + bool result = false; + if (data.isEmpty()) { + result = CredDeleteW(keyData, CRED_TYPE_GENERIC, 0); + if (!result) + if (GetLastError() == ERROR_NOT_FOUND) + result = true; + } else { + wchar_t* charData = new wchar_t[data.size()]; + data.toWCharArray(charData); + + CREDENTIALW cred = {}; + cred.Flags = 0; + cred.Type = CRED_TYPE_GENERIC; + cred.TargetName = keyData; + cred.CredentialBlob = (LPBYTE)charData; + cred.CredentialBlobSize = sizeof(wchar_t) * data.size(); + cred.Persist = CRED_PERSIST_LOCAL_MACHINE; + + result = CredWriteW(&cred, 0); + delete[] charData; + } + delete[] keyData; + return result; +} + +QString getWindowsCredential(const QString key) +{ + QString result; + QString finalKey("ModOrganizer2_" + key); + wchar_t* keyData = new wchar_t[finalKey.size()+1]; + finalKey.toWCharArray(keyData); + keyData[finalKey.size()] = L'\0'; + PCREDENTIALW creds; + if (CredReadW(keyData, 1, 0, &creds)) { + wchar_t *charData = (wchar_t *)creds->CredentialBlob; + result = QString::fromWCharArray(charData, creds->CredentialBlobSize / sizeof(wchar_t)); + CredFree(creds); + } else { + const auto e = GetLastError(); + if (e != ERROR_NOT_FOUND) { + log::error("Retrieving encrypted data failed: {}", formatSystemMessage(e)); + } + } + delete[] keyData; + return result; +} + + Settings *Settings::s_Instance = nullptr; Settings::Settings(const QString& path) : m_Settings(path, QSettings::IniFormat), - m_Geometry(m_Settings), m_Colors(m_Settings), m_Plugins(m_Settings) + m_Game(m_Settings), m_Geometry(m_Settings), m_Widgets(m_Settings), + m_Colors(m_Settings), m_Plugins(m_Settings), m_Paths(m_Settings), + m_Network(m_Settings), m_Nexus(*this, m_Settings), m_Steam(*this, m_Settings), + m_Interface(m_Settings), m_Diagnostics(m_Settings) { if (s_Instance != nullptr) { throw std::runtime_error("second instance of \"Settings\" created"); } else { s_Instance = this; } - - MOBase::QuestionBoxMemory::setCallbacks( - [this](auto&& w, auto&& f){ return getQuestionButton(w, f); }, - [this](auto&& w, auto&& b){ setQuestionWindowButton(w, b); }, - [this](auto&& w, auto&& f, auto&& b){ setQuestionFileButton(w, f, b); }); } Settings::~Settings() @@ -488,7 +540,7 @@ Settings &Settings::instance() void Settings::processUpdates( const QVersionNumber& currentVersion, const QVersionNumber& lastVersion) { - if (getFirstStart()) { + if (firstStart()) { return; } @@ -523,1569 +575,1670 @@ void Settings::processUpdates( set(m_Settings, "General", "version", currentVersion.toString()); } -QString Settings::getFilename() const +QString Settings::filename() const { return m_Settings.fileName(); } -void Settings::registerAsNXMHandler(bool force) +bool Settings::usePrereleases() const { - const auto nxmPath = QCoreApplication::applicationDirPath() + "/nxmhandler.exe"; - const auto executable = QCoreApplication::applicationFilePath(); - - QString mode = force ? "forcereg" : "reg"; - QString parameters = mode + " " + m_GamePlugin->gameShortName(); - for (const QString& altGame : m_GamePlugin->validShortNames()) { - parameters += "," + altGame; - } - parameters += " \"" + executable + "\""; - - if (!shell::Execute(nxmPath, parameters)) { - QMessageBox::critical( - nullptr, tr("Failed"), tr("Failed to start the helper application")); - } + return get(m_Settings, "Settings", "use_prereleases", false); } -bool Settings::colorSeparatorScrollbar() const +void Settings::setUsePrereleases(bool b) { - return get(m_Settings, "Settings", "colorSeparatorScrollbars", true); + set(m_Settings, "Settings", "use_prereleases", b); } -void Settings::setColorSeparatorScrollbar(bool b) +std::optional Settings::version() const { - set(m_Settings, "Settings", "colorSeparatorScrollbars", b); + if (auto v=getOptional(m_Settings, "General", "version")) { + return QVersionNumber::fromString(*v).normalized(); + } + + return {}; } -void Settings::managedGameChanged(IPluginGame const *gamePlugin) +bool Settings::firstStart() const { - m_GamePlugin = gamePlugin; + return get(m_Settings, "General", "first_start", true); } -bool Settings::obfuscate(const QString key, const QString data) +void Settings::setFirstStart(bool b) { - QString finalKey("ModOrganizer2_" + key); - wchar_t* keyData = new wchar_t[finalKey.size()+1]; - finalKey.toWCharArray(keyData); - keyData[finalKey.size()] = L'\0'; - bool result = false; - if (data.isEmpty()) { - result = CredDeleteW(keyData, CRED_TYPE_GENERIC, 0); - if (!result) - if (GetLastError() == ERROR_NOT_FOUND) - result = true; - } else { - wchar_t* charData = new wchar_t[data.size()]; - data.toWCharArray(charData); + set(m_Settings, "General", "first_start", b); +} - CREDENTIALW cred = {}; - cred.Flags = 0; - cred.Type = CRED_TYPE_GENERIC; - cred.TargetName = keyData; - cred.CredentialBlob = (LPBYTE)charData; - cred.CredentialBlobSize = sizeof(wchar_t) * data.size(); - cred.Persist = CRED_PERSIST_LOCAL_MACHINE; +QString Settings::executablesBlacklist() const +{ + static const QString def = (QStringList() + << "Chrome.exe" + << "Firefox.exe" + << "TSVNCache.exe" + << "TGitCache.exe" + << "Steam.exe" + << "GameOverlayUI.exe" + << "Discord.exe" + << "GalaxyClient.exe" + << "Spotify.exe" + ).join(";"); - result = CredWriteW(&cred, 0); - delete[] charData; - } - delete[] keyData; - return result; + return get(m_Settings, "Settings", "executable_blacklist", def); } -QString Settings::deObfuscate(const QString key) +void Settings::setExecutablesBlacklist(const QString& s) { - QString result; - QString finalKey("ModOrganizer2_" + key); - wchar_t* keyData = new wchar_t[finalKey.size()+1]; - finalKey.toWCharArray(keyData); - keyData[finalKey.size()] = L'\0'; - PCREDENTIALW creds; - if (CredReadW(keyData, 1, 0, &creds)) { - wchar_t *charData = (wchar_t *)creds->CredentialBlob; - result = QString::fromWCharArray(charData, creds->CredentialBlobSize / sizeof(wchar_t)); - CredFree(creds); - } else { - const auto e = GetLastError(); - if (e != ERROR_NOT_FOUND) { - log::error("Retrieving encrypted data failed: {}", formatSystemMessage(e)); - } - } - delete[] keyData; - return result; + set(m_Settings, "Settings", "executable_blacklist", s); } -QColor Settings::getIdealTextColor(const QColor& rBackgroundColor) +void Settings::setMotdHash(uint hash) { - if (rBackgroundColor.alpha() == 0) - return QColor(Qt::black); - - const int THRESHOLD = 106 * 255.0f / rBackgroundColor.alpha(); - int BackgroundDelta = (rBackgroundColor.red() * 0.299) + (rBackgroundColor.green() * 0.587) + (rBackgroundColor.blue() * 0.114); - return QColor((255 - BackgroundDelta <= THRESHOLD) ? Qt::black : Qt::white); + set(m_Settings, "General", "motd_hash", hash); } - -bool Settings::hideUncheckedPlugins() const +unsigned int Settings::motdHash() const { - return get(m_Settings, "Settings", "hide_unchecked_plugins", false); + return get(m_Settings, "General", "motd_hash", 0); } -void Settings::setHideUncheckedPlugins(bool b) +bool Settings::archiveParsing() const { - set(m_Settings, "Settings", "hide_unchecked_plugins", b); + return get(m_Settings, "Settings", "archive_parsing_experimental", false); } -bool Settings::forceEnableCoreFiles() const +void Settings::setArchiveParsing(bool b) { - return get(m_Settings, "Settings", "force_enable_core_files", true); + set(m_Settings, "Settings", "archive_parsing_experimental", b); } -void Settings::setForceEnableCoreFiles(bool b) +std::vector> Settings::executables() const { - set(m_Settings, "Settings", "force_enable_core_files", b); + ScopedReadArray sra(m_Settings, "customExecutables"); + std::vector> v; + + sra.for_each([&]{ + std::map map; + + for (auto&& key : sra.keys()) { + map[key] = m_Settings.value(key); + } + + v.push_back(map); + }); + + return v; } -bool Settings::lockGUI() const +void Settings::setExecutables(const std::vector>& v) { - return get(m_Settings, "Settings", "lock_gui", true); + removeSection(m_Settings, "customExecutables"); + + ScopedWriteArray swa(m_Settings, "customExecutables"); + + for (const auto& map : v) { + swa.next(); + + for (auto&& p : map) { + swa.set(p.first, p.second); + } + } } -void Settings::setLockGUI(bool b) +bool Settings::keepBackupOnInstall() const { - set(m_Settings, "Settings", "lock_gui", b); + return get(m_Settings, "General", "backup_install", false); } -bool Settings::automaticLoginEnabled() const +void Settings::setKeepBackupOnInstall(bool b) { - return get(m_Settings, "Settings", "nexus_login", false); + set(m_Settings, "General", "backup_install", b); } -QString Settings::getSteamAppID() const +GameSettings& Settings::game() { - return get(m_Settings, "Settings", "app_id", m_GamePlugin->steamAPPId()); + return m_Game; } -void Settings::setSteamAppID(const QString& id) +const GameSettings& Settings::game() const { - if (id.isEmpty()) { - remove(m_Settings, "Settings", "app_id"); - } else { - set(m_Settings, "Settings", "app_id", id); - } + return m_Game; } -bool Settings::usePrereleases() const +GeometrySettings& Settings::geometry() { - return get(m_Settings, "Settings", "use_prereleases", false); + return m_Geometry; } -void Settings::setUsePrereleases(bool b) +const GeometrySettings& Settings::geometry() const { - set(m_Settings, "Settings", "use_prereleases", b); + return m_Geometry; } -QString Settings::getConfigurablePath(const QString &key, - const QString &def, - bool resolve) const +WidgetSettings& Settings::widgets() { - QString result = QDir::fromNativeSeparators( - get(m_Settings, "Settings", key, QString("%BASE_DIR%/") + def)); - - if (resolve) { - result.replace("%BASE_DIR%", getBaseDirectory()); - } - - return result; + return m_Widgets; } -void Settings::setConfigurablePath(const QString &key, const QString& path) +const WidgetSettings& Settings::widgets() const { - if (path.isEmpty()) { - remove(m_Settings, "Settings", key); - } else { - set(m_Settings, "Settings", key, path); - } + return m_Widgets; } -QString Settings::getBaseDirectory() const +ColorSettings& Settings::colors() { - return QDir::fromNativeSeparators(get(m_Settings, - "Settings", "base_directory", qApp->property("dataPath").toString())); + return m_Colors; } -QString Settings::getDownloadDirectory(bool resolve) const +const ColorSettings& Settings::colors() const { - return getConfigurablePath( - "download_directory", - ToQString(AppConfig::downloadPath()), - resolve); + return m_Colors; } -QString Settings::getCacheDirectory(bool resolve) const +PluginSettings& Settings::plugins() { - return getConfigurablePath( - "cache_directory", - ToQString(AppConfig::cachePath()), - resolve); + return m_Plugins; } -QString Settings::getModDirectory(bool resolve) const +const PluginSettings& Settings::plugins() const { - return getConfigurablePath( - "mod_directory", - ToQString(AppConfig::modsPath()), - resolve); + return m_Plugins; } -QString Settings::getProfileDirectory(bool resolve) const +PathSettings& Settings::paths() { - return getConfigurablePath( - "profiles_directory", - ToQString(AppConfig::profilesPath()), - resolve); + return m_Paths; } -QString Settings::getOverwriteDirectory(bool resolve) const +const PathSettings& Settings::paths() const { - return getConfigurablePath( - "overwrite_directory", - ToQString(AppConfig::overwritePath()), - resolve); + return m_Paths; } -void Settings::setBaseDirectory(const QString& path) +NetworkSettings& Settings::network() { - if (path.isEmpty()) { - remove(m_Settings, "Settings", "base_directory"); - } else { - set(m_Settings, "Settings", "base_directory", path); - } + return m_Network; } -void Settings::setDownloadDirectory(const QString& path) +const NetworkSettings& Settings::network() const { - setConfigurablePath("download_directory", path); + return m_Network; } -void Settings::setModDirectory(const QString& path) +NexusSettings& Settings::nexus() { - setConfigurablePath("mod_directory", path); + return m_Nexus; } -void Settings::setCacheDirectory(const QString& path) +const NexusSettings& Settings::nexus() const { - setConfigurablePath("cache_directory", path); + return m_Nexus; } -void Settings::setProfileDirectory(const QString& path) +SteamSettings& Settings::steam() { - setConfigurablePath("profiles_directory", path); + return m_Steam; } -void Settings::setOverwriteDirectory(const QString& path) +const SteamSettings& Settings::steam() const { - setConfigurablePath("overwrite_directory", path); + return m_Steam; } -std::optional Settings::getManagedGameDirectory() const +InterfaceSettings& Settings::interface() { - if (auto v=getOptional(m_Settings, "General", "gamePath")) { - return QString::fromUtf8(*v); - } - - return {}; + return m_Interface; } -void Settings::setManagedGameDirectory(const QString& path) +const InterfaceSettings& Settings::interface() const { - set(m_Settings, "General", "gamePath", QDir::toNativeSeparators(path).toUtf8()); + return m_Interface; } -std::optional Settings::getManagedGameName() const +DiagnosticsSettings& Settings::diagnostics() { - return getOptional(m_Settings, "General", "gameName"); + return m_Diagnostics; } -void Settings::setManagedGameName(const QString& name) +const DiagnosticsSettings& Settings::diagnostics() const { - set(m_Settings, "General", "gameName", name); + return m_Diagnostics; } -std::optional Settings::getManagedGameEdition() const +QSettings::Status Settings::sync() const { - return getOptional(m_Settings, "General", "game_edition"); + m_Settings.sync(); + return m_Settings.status(); } -void Settings::setManagedGameEdition(const QString& name) +void Settings::dump() const { - set(m_Settings, "General", "game_edition", name); -} + static const QStringList ignore({ + "username", "password", "nexus_api_key" + }); -std::optional Settings::getSelectedProfileName() const -{ - if (auto v=getOptional(m_Settings, "General", "selected_profile")) { - return QString::fromUtf8(*v); + log::debug("settings:"); + + { + ScopedGroup sg(m_Settings, "Settings"); + + for (auto k : m_Settings.allKeys()) { + if (ignore.contains(k, Qt::CaseInsensitive)) { + continue; + } + + log::debug(" . {}={}", k, m_Settings.value(k).toString()); + } } - return {}; + m_Network.dump(); } -void Settings::setSelectedProfileName(const QString& name) +void Settings::managedGameChanged(IPluginGame const *gamePlugin) { - set(m_Settings, "General", "selected_profile", name.toUtf8()); + m_Game.setPlugin(gamePlugin); } -std::optional Settings::getStyleName() const + +GameSettings::GameSettings(QSettings& settings) + : m_Settings(settings), m_GamePlugin(nullptr) { - return getOptional(m_Settings, "Settings", "style"); } -void Settings::setStyleName(const QString& name) +const MOBase::IPluginGame* GameSettings::plugin() { - set(m_Settings, "Settings", "style", name); + return m_GamePlugin; } -bool Settings::getUseProxy() const +void GameSettings::setPlugin(const MOBase::IPluginGame* gamePlugin) { - return get(m_Settings, "Settings", "use_proxy", false); + m_GamePlugin = gamePlugin; } -void Settings::setUseProxy(bool b) +bool GameSettings::forceEnableCoreFiles() const { - set(m_Settings, "Settings", "use_proxy", b); + return get(m_Settings, "Settings", "force_enable_core_files", true); } -std::optional Settings::getVersion() const +void GameSettings::setForceEnableCoreFiles(bool b) { - if (auto v=getOptional(m_Settings, "General", "version")) { - return QVersionNumber::fromString(*v).normalized(); - } - - return {}; + set(m_Settings, "Settings", "force_enable_core_files", b); } -bool Settings::getFirstStart() const +std::optional GameSettings::directory() const { - return get(m_Settings, "General", "first_start", true); + if (auto v=getOptional(m_Settings, "General", "gamePath")) { + return QString::fromUtf8(*v); + } + + return {}; } -void Settings::setFirstStart(bool b) +void GameSettings::setDirectory(const QString& path) { - set(m_Settings, "General", "first_start", b); + set(m_Settings, "General", "gamePath", QDir::toNativeSeparators(path).toUtf8()); } -std::optional Settings::getPreviousSeparatorColor() const +std::optional GameSettings::name() const { - const auto c = getOptional(m_Settings, "General", "previousSeparatorColor"); - if (c && c->isValid()) { - return c; - } - - return {}; + return getOptional(m_Settings, "General", "gameName"); } -void Settings::setPreviousSeparatorColor(const QColor& c) const +void GameSettings::setName(const QString& name) { - set(m_Settings, "General", "previousSeparatorColor", c); + set(m_Settings, "General", "gameName", name); } -void Settings::removePreviousSeparatorColor() +std::optional GameSettings::edition() const { - remove(m_Settings, "General", "previousSeparatorColor"); + return getOptional(m_Settings, "General", "game_edition"); } -bool Settings::getNexusApiKey(QString &apiKey) const +void GameSettings::setEdition(const QString& name) { - QString tempKey = deObfuscate("APIKEY"); - if (tempKey.isEmpty()) - return false; - - apiKey = tempKey; - return true; + set(m_Settings, "General", "game_edition", name); } -bool Settings::setNexusApiKey(const QString& apiKey) +std::optional GameSettings::selectedProfileName() const { - if (!obfuscate("APIKEY", apiKey)) { - const auto e = GetLastError(); - log::error("Storing API key failed: {}", formatSystemMessage(e)); - return false; + if (auto v=getOptional(m_Settings, "General", "selected_profile")) { + return QString::fromUtf8(*v); } - return true; + return {}; } -bool Settings::clearNexusApiKey() +void GameSettings::setSelectedProfileName(const QString& name) { - return setNexusApiKey(""); + set(m_Settings, "General", "selected_profile", name.toUtf8()); } -bool Settings::hasNexusApiKey() const +LoadMechanism::EMechanism GameSettings::loadMechanismType() const { - return !deObfuscate("APIKEY").isEmpty(); -} + const auto def = LoadMechanism::LOAD_MODORGANIZER; -bool Settings::getSteamLogin(QString &username, QString &password) const -{ - username = get(m_Settings, "Settings", "steam_username", ""); - password = deObfuscate("steam_password"); + const auto i = get(m_Settings, + "Settings", "load_mechanism", def); - return !username.isEmpty() && !password.isEmpty(); -} + switch (i) + { + // ok + case LoadMechanism::LOAD_MODORGANIZER: // fall-through + { + break; + } -bool Settings::compactDownloads() const -{ - return get(m_Settings, "Settings", "compact_downloads", false); -} + default: + { + log::error( + "invalid load mechanism {}, reverting to {}", + static_cast(i), toString(def)); -void Settings::setCompactDownloads(bool b) -{ - set(m_Settings, "Settings", "compact_downloads", b); -} + set(m_Settings, "Settings", "load_mechanism", def); -bool Settings::metaDownloads() const -{ - return get(m_Settings, "Settings", "meta_downloads", false); -} + return def; + } + } -void Settings::setMetaDownloads(bool b) -{ - set(m_Settings, "Settings", "meta_downloads", b); + return i; } -bool Settings::offlineMode() const +void GameSettings::setLoadMechanism(LoadMechanism::EMechanism m) { - return get(m_Settings, "Settings/offline_mode", false); + set(m_Settings, "Settings", "load_mechanism", m); } -void Settings::setOfflineMode(bool b) +const LoadMechanism& GameSettings::loadMechanism() const { - set(m_Settings, "Settings", "offline_mode", b); + return m_LoadMechanism; } -log::Levels Settings::logLevel() const +void GameSettings::setupLoadMechanism() { - return get(m_Settings, "Settings", "log_level", log::Levels::Info); + m_LoadMechanism.activate(loadMechanismType()); } -void Settings::setLogLevel(log::Levels level) +bool GameSettings::hideUncheckedPlugins() const { - set(m_Settings, "Settings", "log_level", level); + return get(m_Settings, "Settings", "hide_unchecked_plugins", false); } -CrashDumpsType Settings::crashDumpsType() const +void GameSettings::setHideUncheckedPlugins(bool b) { - return get(m_Settings, - "Settings", "crash_dumps_type", CrashDumpsType::Mini); + set(m_Settings, "Settings", "hide_unchecked_plugins", b); } -void Settings::setCrashDumpsType(CrashDumpsType type) -{ - set(m_Settings, "Settings", "crash_dumps_type", type); -} -int Settings::crashDumpsMax() const +GeometrySettings::GeometrySettings(QSettings& s) + : m_Settings(s), m_Reset(false) { - return get(m_Settings, "Settings", "crash_dumps_max", 5); } -void Settings::setCrashDumpsMax(int n) +void GeometrySettings::requestReset() { - set(m_Settings, "Settings", "crash_dumps_max", n); + m_Reset = true; } -QString Settings::executablesBlacklist() const +void GeometrySettings::resetIfNeeded() { - static const QString def = (QStringList() - << "Chrome.exe" - << "Firefox.exe" - << "TSVNCache.exe" - << "TGitCache.exe" - << "Steam.exe" - << "GameOverlayUI.exe" - << "Discord.exe" - << "GalaxyClient.exe" - << "Spotify.exe" - ).join(";"); + if (!m_Reset) { + return; + } - return get(m_Settings, "Settings", "executable_blacklist", def); + removeSection(m_Settings, "Geometry"); } -void Settings::setExecutablesBlacklist(const QString& s) +void GeometrySettings::saveGeometry(const QWidget* w) { - set(m_Settings, "Settings", "executable_blacklist", s); + set(m_Settings, "Geometry", geoSettingName(w), w->saveGeometry()); } -void Settings::setSteamLogin(QString username, QString password) +bool GeometrySettings::restoreGeometry(QWidget* w) const { - if (username == "") { - remove(m_Settings, "Settings", "steam_username"); - password = ""; - } else { - set(m_Settings, "Settings", "steam_username", username); + if (auto v=getOptional(m_Settings, "Geometry", geoSettingName(w))) { + w->restoreGeometry(*v); + return true; } - if (!obfuscate("steam_password", password)) { - const auto e = GetLastError(); - log::error("Storing or deleting password failed: {}", formatSystemMessage(e)); - } + return false; } -LoadMechanism::EMechanism Settings::getLoadMechanism() const +void GeometrySettings::saveState(const QMainWindow* w) { - const auto def = LoadMechanism::LOAD_MODORGANIZER; - - const auto i = get(m_Settings, - "Settings", "load_mechanism", def); - - switch (i) - { - // ok - case LoadMechanism::LOAD_MODORGANIZER: // fall-through - { - break; - } - - default: - { - log::error( - "invalid load mechanism {}, reverting to {}", - static_cast(i), toString(def)); - - set(m_Settings, "Settings", "load_mechanism", def); - - return def; - } - } - - return i; + set(m_Settings, "Geometry", stateSettingName(w), w->saveState()); } -void Settings::setLoadMechanism(LoadMechanism::EMechanism m) +bool GeometrySettings::restoreState(QMainWindow* w) const { - set(m_Settings, "Settings", "load_mechanism", m); -} + if (auto v=getOptional(m_Settings, "Geometry", stateSettingName(w))) { + w->restoreState(*v); + return true; + } -void Settings::setupLoadMechanism() -{ - m_LoadMechanism.activate(getLoadMechanism()); + return false; } -bool Settings::endorsementIntegration() const +void GeometrySettings::saveState(const QHeaderView* w) { - return get(m_Settings, "Settings", "endorsement_integration", true); + set(m_Settings, "Geometry", stateSettingName(w), w->saveState()); } -void Settings::setEndorsementIntegration(bool b) const +bool GeometrySettings::restoreState(QHeaderView* w) const { - set(m_Settings, "Settings", "endorsement_integration", b); + if (auto v=getOptional(m_Settings, "Geometry", stateSettingName(w))) { + w->restoreState(*v); + return true; + } + + return false; } -EndorsementState Settings::endorsementState() const +void GeometrySettings::saveState(const QSplitter* w) { - return endorsementStateFromString( - get(m_Settings, "General", "endorse_state", "")); + set(m_Settings, "Geometry", stateSettingName(w), w->saveState()); } -void Settings::setEndorsementState(EndorsementState s) +bool GeometrySettings::restoreState(QSplitter* w) const { - const auto v = toString(s); - - if (v.isEmpty()) { - remove(m_Settings, "General", "endorse_state"); - } else { - set(m_Settings, "General", "endorse_state", v); + if (auto v=getOptional(m_Settings, "Geometry", stateSettingName(w))) { + w->restoreState(*v); + return true; } -} -bool Settings::hideAPICounter() const -{ - return get(m_Settings, "Settings", "hide_api_counter", false); + return false; } -void Settings::setHideAPICounter(bool b) +void GeometrySettings::saveState(const ExpanderWidget* expander) { - set(m_Settings, "Settings", "hide_api_counter", b); + set(m_Settings, "Geometry", stateSettingName(expander), expander->saveState()); } -bool Settings::displayForeign() const +bool GeometrySettings::restoreState(ExpanderWidget* expander) const { - return get(m_Settings, "Settings", "display_foreign", true); -} + if (auto v=getOptional(m_Settings, "Geometry", stateSettingName(expander))) { + expander->restoreState(*v); + return true; + } -void Settings::setDisplayForeign(bool b) -{ - set(m_Settings, "Settings", "display_foreign", b); + return false; } -void Settings::setMotDHash(uint hash) +void GeometrySettings::saveVisibility(const QWidget* w) { - set(m_Settings, "General", "motd_hash", hash); + set(m_Settings, "Geometry", visibilitySettingName(w), w->isVisible()); } -unsigned int Settings::getMotDHash() const +bool GeometrySettings::restoreVisibility(QWidget* w, std::optional def) const { - return get(m_Settings, "motd_hash", 0); -} + if (auto v=getOptional(m_Settings, "Geometry", visibilitySettingName(w), def)) { + w->setVisible(*v); + return true; + } -bool Settings::archiveParsing() const -{ - return get(m_Settings, "Settings", "archive_parsing_experimental", false); + return false; } -void Settings::setArchiveParsing(bool b) +void GeometrySettings::restoreToolbars(QMainWindow* w) const { - set(m_Settings, "Settings", "archive_parsing_experimental", b); -} + // all toolbars have the same size and button style settings + const auto size = getOptional(m_Settings, "Geometry", "toolbar_size"); + const auto style = getOptional(m_Settings, "Geometry", "toolbar_button_style"); -QString Settings::language() + for (auto* tb : w->findChildren()) { + if (size) { + tb->setIconSize(*size); + } + + if (style) { + tb->setToolButtonStyle(static_cast(*style)); + } + + restoreVisibility(tb); + } +} + +void GeometrySettings::saveToolbars(const QMainWindow* w) { - QString result = get(m_Settings, "Settings", "language", ""); + const auto tbs = w->findChildren(); - if (result.isEmpty()) { - QStringList languagePreferences = QLocale::system().uiLanguages(); + // save visibility for all + for (auto* tb : tbs) { + saveVisibility(tb); + } - if (languagePreferences.length() > 0) { - // the users most favoritest language - result = languagePreferences.at(0); - } else { - // fallback system locale - result = QLocale::system().name(); + // all toolbars have the same size and button style settings, just save the + // first one + if (!tbs.isEmpty()) { + const auto* tb = tbs[0]; + + set(m_Settings, "Geometry", "toolbar_size", tb->iconSize()); + set(m_Settings, "Geometry", "toolbar_button_style", static_cast(tb->toolButtonStyle())); + } +} + +QStringList GeometrySettings::modInfoTabOrder() const +{ + QStringList v; + + if (m_Settings.contains("mod_info_tabs")) { + // old byte array from 2.2.0 + QDataStream stream(m_Settings.value("mod_info_tabs").toByteArray()); + + int count = 0; + stream >> count; + + for (int i=0; i> s; + v.push_back(s); + } + } else { + // string list since 2.2.1 + QString string = m_Settings.value("mod_info_tab_order").toString(); + QTextStream stream(&string); + + while (!stream.atEnd()) { + QString s; + stream >> s; + v.push_back(s); } } - return result; + return v; } -void Settings::setLanguage(const QString& name) +void GeometrySettings::setModInfoTabOrder(const QString& names) { - set(m_Settings, "Settings", "language", name); + set(m_Settings, "Geometry", "mod_info_tab_order", names); } -void Settings::setDownloadSpeed(const QString& name, int bytesPerSecond) +void GeometrySettings::centerOnMainWindowMonitor(QWidget* w) { - auto servers = getServers(); + const auto monitor = getOptional( + m_Settings, "Geometry", "MainWindow_monitor"); - for (auto& server : servers) { - if (server.name() == name) { - server.addDownload(bytesPerSecond); - updateServers(servers); - return; + QPoint center; + + if (monitor && QGuiApplication::screens().size() > *monitor) { + center = QGuiApplication::screens().at(*monitor)->geometry().center(); + } else { + center = QGuiApplication::primaryScreen()->geometry().center(); + } + + w->move(center - w->rect().center()); +} + +void GeometrySettings::saveMainWindowMonitor(const QMainWindow* w) +{ + if (auto* handle=w->windowHandle()) { + if (auto* screen = handle->screen()) { + const int screenId = QGuiApplication::screens().indexOf(screen); + set(m_Settings, "Geometry", "MainWindow_monitor", screenId); } } +} - log::error( - "server '{}' not found while trying to add a download with bps {}", - name, bytesPerSecond); +Qt::Orientation dockOrientation(const QMainWindow* mw, const QDockWidget* d) +{ + // docks in these areas are horizontal + const auto horizontalAreas = + Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea; + + if (mw->dockWidgetArea(const_cast(d)) & horizontalAreas) { + return Qt::Horizontal; + } else { + return Qt::Vertical; + } } -ServerList Settings::getServers() const +void GeometrySettings::saveDocks(const QMainWindow* mw) { - // servers used to be a map of byte arrays until 2.2.1, it's now an array of - // individual values instead + // this attempts to fix https://bugreports.qt.io/browse/QTBUG-46620 where dock + // sizes are not restored when the main window is maximized; it is used in + // MainWindow::readSettings() and MainWindow::storeSettings() + // + // there's also https://stackoverflow.com/questions/44005852, which has what + // seems to be a popular fix, but it breaks the restored size of the window + // by setting it to the desktop's resolution, so that doesn't work + // + // the only fix I could find is to remember the sizes of the docks and manually + // setting them back; saving is straightforward, but restoring is messy + // + // this also depends on the window being visible before the timer in restore() + // is fired and the timer must be processed by application.exec(); therefore, + // the splash screen _must_ be closed before readSettings() is called, because + // it has its own event loop, which seems to interfere with this + // + // all of this should become unnecessary when QTBUG-46620 is fixed // - // 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 - { - const QStringList keys = ScopedGroup(m_Settings, "Servers").keys(); - if (!keys.empty() && keys[0] != "size") { - // old format - return getServersFromOldMap(); + // saves the size of each dock + for (const auto* dock : mw->findChildren()) { + int size = 0; + + // save the width for horizontal docks, or the height for vertical + if (dockOrientation(mw, dock) == Qt::Horizontal) { + size = dock->size().width(); + } else { + size = dock->size().height(); } + + set(m_Settings, "Geometry", dockSettingName(dock), size); } +} +void GeometrySettings::restoreDocks(QMainWindow* mw) const +{ + struct DockInfo + { + QDockWidget* d; + int size = 0; + Qt::Orientation ori; + }; - // post 2.2.1 format, array of values + std::vector dockInfos; - ServerList list; + // for each dock + for (auto* dock : mw->findChildren()) { + if (auto size=getOptional(m_Settings, "Geometry", dockSettingName(dock))) { + // remember this dock, its size and orientation + dockInfos.push_back({dock, *size, dockOrientation(mw, dock)}); + } + } - { - ScopedReadArray sra(m_Settings, "Servers"); + // the main window must have had time to process the settings from + // readSettings() or it seems to override whatever is set here + // + // some people said a single processEvents() call is enough, but it doesn't + // look like it + QTimer::singleShot(5, [=] { + for (const auto& info : dockInfos) { + mw->resizeDocks({info.d}, {info.size}, info.ori); + } + }); +} - sra.for_each([&] { - ServerInfo::SpeedList lastDownloads; - const auto lastDownloadsString = sra.get("lastDownloads", ""); +WidgetSettings::WidgetSettings(QSettings& s) + : m_Settings(s) +{ + MOBase::QuestionBoxMemory::setCallbacks( + [this](auto&& w, auto&& f){ return questionButton(w, f); }, + [this](auto&& w, auto&& b){ setQuestionWindowButton(w, b); }, + [this](auto&& w, auto&& f, auto&& b){ setQuestionFileButton(w, f, b); }); +} - for (const auto& s : lastDownloadsString.split(" ")) { - const auto bytesPerSecond = s.toInt(); - if (bytesPerSecond > 0) { - lastDownloads.push_back(bytesPerSecond); - } - } +std::optional WidgetSettings::index(const QComboBox* cb) const +{ + return getOptional(m_Settings, "Widgets", indexSettingName(cb)); +} - ServerInfo server( - sra.get("name", ""), - sra.get("premium", false), - QDate::fromString(sra.get("lastSeen", ""), Qt::ISODate), - sra.get("preferred", 0), - lastDownloads); +void WidgetSettings::saveIndex(const QComboBox* cb) +{ + set(m_Settings, "Widgets", indexSettingName(cb), cb->currentIndex()); +} - list.add(std::move(server)); - }); +void WidgetSettings::restoreIndex(QComboBox* cb, std::optional def) const +{ + if (auto v=getOptional(m_Settings, "Widgets", indexSettingName(cb), def)) { + cb->setCurrentIndex(*v); } - - return list; } -ServerList Settings::getServersFromOldMap() const +std::optional WidgetSettings::index(const QTabWidget* w) const { - // for 2.2.1 and before + return getOptional(m_Settings, "Widgets", indexSettingName(w)); +} - ServerList list; - const ScopedGroup sg(m_Settings, "Servers"); +void WidgetSettings::saveIndex(const QTabWidget* w) +{ + set(m_Settings, "Widgets", indexSettingName(w), w->currentIndex()); +} - sg.for_each([&](auto&& serverKey) { - QVariantMap data = sg.get(serverKey); +void WidgetSettings::restoreIndex(QTabWidget* w, std::optional def) const +{ + if (auto v=getOptional(m_Settings, "Widgets", indexSettingName(w), def)) { + w->setCurrentIndex(*v); + } +} - ServerInfo server( - serverKey, - data["premium"].toBool(), - data["lastSeen"].toDate(), - data["preferred"].toInt(), - {}); +std::optional WidgetSettings::checked(const QAbstractButton* w) const +{ + warnIfNotCheckable(w); + return getOptional(m_Settings, "Widgets", checkedSettingName(w)); +} - // ignoring download count and speed, it's now a list of values instead of - // a total +void WidgetSettings::saveChecked(const QAbstractButton* w) +{ + warnIfNotCheckable(w); + set(m_Settings, "Widgets", checkedSettingName(w), w->isChecked()); +} - list.add(std::move(server)); - }); +void WidgetSettings::restoreChecked(QAbstractButton* w, std::optional def) const +{ + warnIfNotCheckable(w); - return list; + if (auto v=getOptional(m_Settings, "Widgets", checkedSettingName(w), def)) { + w->setChecked(*v); + } } -void Settings::updateServers(ServerList servers) +QuestionBoxMemory::Button WidgetSettings::questionButton( + const QString& windowName, const QString& filename) const { - // clean up unavailable servers - servers.cleanup(); - - removeSection(m_Settings, "Servers"); + const QString sectionName("DialogChoices"); - { - ScopedWriteArray swa(m_Settings, "Servers"); + if (!filename.isEmpty()) { + const auto fileSetting = windowName + "/" + filename; + if (auto v=getOptional(m_Settings, sectionName, filename)) { + return static_cast(*v); + } + } - for (const auto& server : servers) { - swa.next(); + if (auto v=getOptional(m_Settings, sectionName, windowName)) { + return static_cast(*v); + } - swa.set("name", server.name()); - swa.set("premium", server.isPremium()); - swa.set("lastSeen", server.lastSeen().toString(Qt::ISODate)); - swa.set("preferred", server.preferred()); + return QuestionBoxMemory::NoButton; +} - QString lastDownloads; - for (const auto& speed : server.lastDownloads()) { - if (speed > 0) { - lastDownloads += QString("%1 ").arg(speed); - } - } +void WidgetSettings::setQuestionWindowButton( + const QString& windowName, QuestionBoxMemory::Button button) +{ + const QString sectionName("DialogChoices"); - swa.set("lastDownloads", lastDownloads.trimmed()); - } + if (button == QuestionBoxMemory::NoButton) { + remove(m_Settings, sectionName, windowName); + } else { + set(m_Settings, sectionName, windowName, button); } } -std::map Settings::getRecentDirectories() const +void WidgetSettings::setQuestionFileButton( + const QString& windowName, const QString& filename, + QuestionBoxMemory::Button button) { - std::map map; + const QString sectionName("DialogChoices"); + const QString settingName(windowName + "/" + filename); - ScopedReadArray sra(m_Settings, "RecentDirectories"); + if (button == QuestionBoxMemory::NoButton) { + remove(m_Settings, sectionName, settingName); + } else { + set(m_Settings, sectionName, settingName, button); + } +} - sra.for_each([&] { - const QVariant name = sra.get("name"); - const QVariant dir = sra.get("directory"); +void WidgetSettings::resetQuestionButtons() +{ + removeSection(m_Settings, "DialogChoices"); +} - if (name.isValid() && dir.isValid()) { - map.emplace(name.toString(), dir.toString()); - } - }); - return map; +ColorSettings::ColorSettings(QSettings& s) + : m_Settings(s) +{ } -void Settings::setRecentDirectories(const std::map& map) +QColor ColorSettings::modlistOverwrittenLoose() const { - removeSection(m_Settings, "RecentDirectories"); + return get( + m_Settings, "Settings", "overwrittenLooseFilesColor", + QColor(0, 255, 0, 64)); +} - ScopedWriteArray swa(m_Settings, "recentDirectories"); +void ColorSettings::setModlistOverwrittenLoose(const QColor& c) +{ + set(m_Settings, "Settings", "overwrittenLooseFilesColor", c); +} - for (auto&& p : map) { - swa.next(); +QColor ColorSettings::modlistOverwritingLoose() const +{ + return get( + m_Settings, "Settings", "overwritingLooseFilesColor", + QColor(255, 0, 0, 64)); +} - swa.set("name", p.first); - swa.set("directory", p.second); - } +void ColorSettings::setModlistOverwritingLoose(const QColor& c) +{ + set(m_Settings, "Settings", "overwritingLooseFilesColor", c); } -std::vector> Settings::getExecutables() const +QColor ColorSettings::modlistOverwrittenArchive() const { - ScopedReadArray sra(m_Settings, "customExecutables"); - std::vector> v; + return get( + m_Settings, "Settings", "overwrittenArchiveFilesColor", + QColor(0, 255, 255, 64)); +} - sra.for_each([&]{ - std::map map; +void ColorSettings::setModlistOverwrittenArchive(const QColor& c) +{ + set(m_Settings, "Settings", "overwrittenArchiveFilesColor", c); +} - for (auto&& key : sra.keys()) { - map[key] = m_Settings.value(key); - } +QColor ColorSettings::modlistOverwritingArchive() const +{ + return get( + m_Settings, "Settings", "overwritingArchiveFilesColor", + QColor(255, 0, 255, 64)); +} - v.push_back(map); - }); +void ColorSettings::setModlistOverwritingArchive(const QColor& c) +{ + set(m_Settings, "Settings", "overwritingArchiveFilesColor", c); +} - return v; +QColor ColorSettings::modlistContainsPlugin() const +{ + return get( + m_Settings, "Settings", "containsPluginColor", + QColor(0, 0, 255, 64)); } -void Settings::setExecutables(const std::vector>& v) +void ColorSettings::setModlistContainsPlugin(const QColor& c) { - removeSection(m_Settings, "customExecutables"); + set(m_Settings, "Settings", "containsPluginColor", c); +} - ScopedWriteArray swa(m_Settings, "customExecutables"); +QColor ColorSettings::pluginListContained() const +{ + return get( + m_Settings, "Settings", "containedColor", + QColor(0, 0, 255, 64)); +} - for (const auto& map : v) { - swa.next(); +void ColorSettings::setPluginListContained(const QColor& c) +{ + set(m_Settings, "Settings", "containedColor", c); +} - for (auto&& p : map) { - swa.set(p.first, p.second); - } +std::optional ColorSettings::previousSeparatorColor() const +{ + const auto c = getOptional(m_Settings, "General", "previousSeparatorColor"); + if (c && c->isValid()) { + return c; } + + return {}; } -bool Settings::isTutorialCompleted(const QString& windowName) const +void ColorSettings::setPreviousSeparatorColor(const QColor& c) const { - return get(m_Settings, "CompletedWindowTutorials", windowName, false); + set(m_Settings, "General", "previousSeparatorColor", c); } -void Settings::setTutorialCompleted(const QString& windowName, bool b) +void ColorSettings::removePreviousSeparatorColor() { - set(m_Settings, "CompletedWindowTutorials", windowName, b); + remove(m_Settings, "General", "previousSeparatorColor"); } -bool Settings::keepBackupOnInstall() const +bool ColorSettings::colorSeparatorScrollbar() const { - return get(m_Settings, "backup_install", false); + return get(m_Settings, "Settings", "colorSeparatorScrollbars", true); } -void Settings::setKeepBackupOnInstall(bool b) +void ColorSettings::setColorSeparatorScrollbar(bool b) { - set(m_Settings, "General", "backup_install", b); + set(m_Settings, "Settings", "colorSeparatorScrollbars", b); } -QuestionBoxMemory::Button Settings::getQuestionButton( - const QString& windowName, const QString& filename) const +QColor ColorSettings::idealTextColor(const QColor& rBackgroundColor) { - const QString sectionName("DialogChoices"); + if (rBackgroundColor.alpha() == 0) + return QColor(Qt::black); - if (!filename.isEmpty()) { - const auto fileSetting = windowName + "/" + filename; - if (auto v=getOptional(m_Settings, sectionName, filename)) { - return static_cast(*v); + const int THRESHOLD = 106 * 255.0f / rBackgroundColor.alpha(); + int BackgroundDelta = (rBackgroundColor.red() * 0.299) + (rBackgroundColor.green() * 0.587) + (rBackgroundColor.blue() * 0.114); + return QColor((255 - BackgroundDelta <= THRESHOLD) ? Qt::black : Qt::white); +} + + + +PluginSettings::PluginSettings(QSettings& settings) + : m_Settings(settings) +{ +} + +void PluginSettings::clearPlugins() +{ + m_Plugins.clear(); + m_PluginSettings.clear(); + + m_PluginBlacklist.clear(); + + ScopedReadArray sra(m_Settings, "pluginBlacklist"); + sra.for_each([&]{ + m_PluginBlacklist.insert(sra.get("name")); + }); +} + +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()) { + 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; } - } - if (auto v=getOptional(m_Settings, sectionName, windowName)) { - return static_cast(*v); + m_PluginSettings[plugin->name()][setting.key] = temp; + + m_PluginDescriptions[plugin->name()][setting.key] = QString("%1 (default: %2)") + .arg(setting.description) + .arg(setting.defaultValue.toString()); } +} - return QuestionBoxMemory::NoButton; +bool PluginSettings::pluginBlacklisted(const QString &fileName) const +{ + return m_PluginBlacklist.contains(fileName); } -void Settings::setQuestionWindowButton( - const QString& windowName, QuestionBoxMemory::Button button) +QVariant PluginSettings::pluginSetting(const QString &pluginName, const QString &key) const { - const QString sectionName("DialogChoices/"); + auto iterPlugin = m_PluginSettings.find(pluginName); + if (iterPlugin == m_PluginSettings.end()) { + return QVariant(); + } - if (button == QuestionBoxMemory::NoButton) { - remove(m_Settings, sectionName, windowName); - } else { - set(m_Settings, sectionName, windowName, button); + auto iterSetting = iterPlugin->find(key); + if (iterSetting == iterPlugin->end()) { + return QVariant(); } + + return *iterSetting; } -void Settings::setQuestionFileButton( - const QString& windowName, const QString& filename, - QuestionBoxMemory::Button button) +void PluginSettings::setPluginSetting(const QString &pluginName, const QString &key, const QVariant &value) { - const QString sectionName("DialogChoices"); - const QString settingName(windowName + "/" + filename); + auto iterPlugin = m_PluginSettings.find(pluginName); - if (button == QuestionBoxMemory::NoButton) { - remove(m_Settings, sectionName, settingName); - } else { - set(m_Settings, sectionName, settingName, button); + if (iterPlugin == m_PluginSettings.end()) { + 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; + set(m_Settings, "Plugins", pluginName + "/" + key, value); } -void Settings::resetQuestionButtons() +QVariant PluginSettings::pluginPersistent(const QString &pluginName, const QString &key, const QVariant &def) const { - removeSection(m_Settings, "DialogChoices"); + if (!m_PluginSettings.contains(pluginName)) { + return def; + } + + return get(m_Settings, "PluginPersistance", pluginName + "/" + key, def); } -std::optional Settings::getIndex(const QComboBox* cb) const +void PluginSettings::setPluginPersistent( + const QString &pluginName, const QString &key, const QVariant &value, bool sync) { - return getOptional(m_Settings, "Widgets", indexSettingName(cb)); + if (!m_PluginSettings.contains(pluginName)) { + throw MyException( + QObject::tr("attempt to store setting for unknown plugin \"%1\"") + .arg(pluginName)); + } + + set(m_Settings, "PluginPersistance", pluginName + "/" + key, value); + + if (sync) { + m_Settings.sync(); + } } -void Settings::saveIndex(const QComboBox* cb) +void PluginSettings::addBlacklistPlugin(const QString &fileName) { - set(m_Settings, "Widgets", indexSettingName(cb), cb->currentIndex()); + m_PluginBlacklist.insert(fileName); + writePluginBlacklist(); } -void Settings::restoreIndex(QComboBox* cb, std::optional def) const +void PluginSettings::writePluginBlacklist() { - if (auto v=getOptional(m_Settings, "Widgets", indexSettingName(cb), def)) { - cb->setCurrentIndex(*v); + removeSection(m_Settings, "PluginBlacklist"); + + ScopedWriteArray swa(m_Settings, "PluginBlacklist"); + + for (const QString &plugin : m_PluginBlacklist) { + swa.next(); + swa.set("name", plugin); } } -std::optional Settings::getIndex(const QTabWidget* w) const +QVariantMap PluginSettings::pluginSettings(const QString &pluginName) const { - return getOptional(m_Settings, "Widgets", indexSettingName(w)); + return m_PluginSettings[pluginName]; } -void Settings::saveIndex(const QTabWidget* w) +void PluginSettings::setPluginSettings(const QString &pluginName, const QVariantMap& map) { - set(m_Settings, "Widgets", indexSettingName(w), w->currentIndex()); + m_PluginSettings[pluginName] = map; } -void Settings::restoreIndex(QTabWidget* w, std::optional def) const +QVariantMap PluginSettings::pluginDescriptions(const QString &pluginName) const { - if (auto v=getOptional(m_Settings, "Widgets", indexSettingName(w), def)) { - w->setCurrentIndex(*v); - } + return m_PluginDescriptions[pluginName]; } -std::optional Settings::getChecked(const QAbstractButton* w) const +void PluginSettings::pluginDescriptions(const QString &pluginName, const QVariantMap& map) { - warnIfNotCheckable(w); - return getOptional(m_Settings, "Widgets", checkedSettingName(w)); + m_PluginDescriptions[pluginName] = map; } -void Settings::saveChecked(const QAbstractButton* w) +const QSet& PluginSettings::pluginBlacklist() const { - warnIfNotCheckable(w); - set(m_Settings, "Widgets", checkedSettingName(w), w->isChecked()); + return m_PluginBlacklist; } -void Settings::restoreChecked(QAbstractButton* w, std::optional def) const +void PluginSettings::setPluginBlacklist(const QStringList& pluginNames) { - warnIfNotCheckable(w); + m_PluginBlacklist.clear(); - if (auto v=getOptional(m_Settings, "Widgets", checkedSettingName(w), def)) { - w->setChecked(*v); + for (const auto& name : pluginNames) { + m_PluginBlacklist.insert(name); } } -GeometrySettings& Settings::geometry() +void PluginSettings::save() { - return m_Geometry; -} + for (auto iterPlugins=m_PluginSettings.begin(); iterPlugins!=m_PluginSettings.end(); ++iterPlugins) { + for (auto iterSettings=iterPlugins->begin(); iterSettings!=iterPlugins->end(); ++iterSettings) { + const auto key = iterPlugins.key() + "/" + iterSettings.key(); + set(m_Settings, "Plugins", key, iterSettings.value()); + } + } -const GeometrySettings& Settings::geometry() const -{ - return m_Geometry; + writePluginBlacklist(); } -ColorSettings& Settings::colors() -{ - return m_Colors; -} -const ColorSettings& Settings::colors() const +PathSettings::PathSettings(QSettings& settings) + : m_Settings(settings) { - return m_Colors; } -PluginSettings& Settings::plugins() +std::map PathSettings::recent() const { - return m_Plugins; -} + std::map map; -const PluginSettings& Settings::plugins() const -{ - return m_Plugins; -} + ScopedReadArray sra(m_Settings, "RecentDirectories"); -QSettings::Status Settings::sync() const -{ - m_Settings.sync(); - return m_Settings.status(); -} + sra.for_each([&] { + const QVariant name = sra.get("name"); + const QVariant dir = sra.get("directory"); -void Settings::dump() const -{ - static const QStringList ignore({ - "username", "password", "nexus_api_key" + if (name.isValid() && dir.isValid()) { + map.emplace(name.toString(), dir.toString()); + } }); - log::debug("settings:"); + return map; +} - { - ScopedGroup sg(m_Settings, "Settings"); +void PathSettings::setRecent(const std::map& map) +{ + removeSection(m_Settings, "RecentDirectories"); - for (auto k : m_Settings.allKeys()) { - if (ignore.contains(k, Qt::CaseInsensitive)) { - continue; - } + ScopedWriteArray swa(m_Settings, "recentDirectories"); - log::debug(" . {}={}", k, m_Settings.value(k).toString()); - } - } + for (auto&& p : map) { + swa.next(); - log::debug("servers:"); + swa.set("name", p.first); + swa.set("directory", p.second); + } +} - for (const auto& server : getServers()) { - QString lastDownloads; - for (auto speed : server.lastDownloads()) { - lastDownloads += QString("%1 ").arg(speed); - } +QString PathSettings::getConfigurablePath(const QString &key, + const QString &def, + bool resolve) const +{ + QString result = QDir::fromNativeSeparators( + get(m_Settings, "Settings", key, QString("%BASE_DIR%/") + def)); - log::debug( - " . {} premium={} lastSeen={} preferred={} lastDownloads={}", - server.name(), - server.isPremium() ? "yes" : "no", - server.lastSeen().toString(Qt::ISODate), - server.preferred(), - lastDownloads.trimmed()); + if (resolve) { + result.replace("%BASE_DIR%", base()); } -} + return result; +} -GeometrySettings::GeometrySettings(QSettings& s) - : m_Settings(s), m_Reset(false) +void PathSettings::setConfigurablePath(const QString &key, const QString& path) { + if (path.isEmpty()) { + remove(m_Settings, "Settings", key); + } else { + set(m_Settings, "Settings", key, path); + } } -void GeometrySettings::requestReset() +QString PathSettings::base() const { - m_Reset = true; + return QDir::fromNativeSeparators(get(m_Settings, + "Settings", "base_directory", qApp->property("dataPath").toString())); } -void GeometrySettings::resetIfNeeded() +QString PathSettings::downloads(bool resolve) const { - if (!m_Reset) { - return; - } - - removeSection(m_Settings, "Geometry"); + return getConfigurablePath( + "download_directory", + ToQString(AppConfig::downloadPath()), + resolve); } -void GeometrySettings::saveGeometry(const QWidget* w) +QString PathSettings::cache(bool resolve) const { - set(m_Settings, "Geometry", geoSettingName(w), w->saveGeometry()); + return getConfigurablePath( + "cache_directory", + ToQString(AppConfig::cachePath()), + resolve); } -bool GeometrySettings::restoreGeometry(QWidget* w) const +QString PathSettings::mods(bool resolve) const { - if (auto v=getOptional(m_Settings, "Geometry", geoSettingName(w))) { - w->restoreGeometry(*v); - return true; - } + return getConfigurablePath( + "mod_directory", + ToQString(AppConfig::modsPath()), + resolve); +} - return false; +QString PathSettings::profiles(bool resolve) const +{ + return getConfigurablePath( + "profiles_directory", + ToQString(AppConfig::profilesPath()), + resolve); } -void GeometrySettings::saveState(const QMainWindow* w) +QString PathSettings::overwrite(bool resolve) const { - set(m_Settings, "Geometry", stateSettingName(w), w->saveState()); + return getConfigurablePath( + "overwrite_directory", + ToQString(AppConfig::overwritePath()), + resolve); } -bool GeometrySettings::restoreState(QMainWindow* w) const +void PathSettings::setBase(const QString& path) { - if (auto v=getOptional(m_Settings, "Geometry", stateSettingName(w))) { - w->restoreState(*v); - return true; + if (path.isEmpty()) { + remove(m_Settings, "Settings", "base_directory"); + } else { + set(m_Settings, "Settings", "base_directory", path); } - - return false; } -void GeometrySettings::saveState(const QHeaderView* w) +void PathSettings::setDownloads(const QString& path) { - set(m_Settings, "Geometry", stateSettingName(w), w->saveState()); + setConfigurablePath("download_directory", path); } -bool GeometrySettings::restoreState(QHeaderView* w) const +void PathSettings::setMods(const QString& path) { - if (auto v=getOptional(m_Settings, "Geometry", stateSettingName(w))) { - w->restoreState(*v); - return true; - } - - return false; + setConfigurablePath("mod_directory", path); } -void GeometrySettings::saveState(const QSplitter* w) +void PathSettings::setCache(const QString& path) { - set(m_Settings, "Geometry", stateSettingName(w), w->saveState()); + setConfigurablePath("cache_directory", path); } -bool GeometrySettings::restoreState(QSplitter* w) const +void PathSettings::setProfiles(const QString& path) { - if (auto v=getOptional(m_Settings, "Geometry", stateSettingName(w))) { - w->restoreState(*v); - return true; - } - - return false; + setConfigurablePath("profiles_directory", path); } -void GeometrySettings::saveState(const ExpanderWidget* expander) +void PathSettings::setOverwrite(const QString& path) { - set(m_Settings, "Geometry", stateSettingName(expander), expander->saveState()); + setConfigurablePath("overwrite_directory", path); } -bool GeometrySettings::restoreState(ExpanderWidget* expander) const -{ - if (auto v=getOptional(m_Settings, "Geometry", stateSettingName(expander))) { - expander->restoreState(*v); - return true; - } - return false; +NetworkSettings::NetworkSettings(QSettings& settings) + : m_Settings(settings) +{ } -void GeometrySettings::saveVisibility(const QWidget* w) +bool NetworkSettings::offlineMode() const { - set(m_Settings, "Geometry", visibilitySettingName(w), w->isVisible()); + return get(m_Settings, "Settings", "offline_mode", false); } -bool GeometrySettings::restoreVisibility(QWidget* w, std::optional def) const +void NetworkSettings::setOfflineMode(bool b) { - if (auto v=getOptional(m_Settings, "Geometry", visibilitySettingName(w), def)) { - w->setVisible(*v); - return true; - } + set(m_Settings, "Settings", "offline_mode", b); +} - return false; +bool NetworkSettings::useProxy() const +{ + return get(m_Settings, "Settings", "use_proxy", false); } -void GeometrySettings::restoreToolbars(QMainWindow* w) const +void NetworkSettings::setUseProxy(bool b) { - // all toolbars have the same size and button style settings - const auto size = getOptional(m_Settings, "Geometry", "toolbar_size"); - const auto style = getOptional(m_Settings, "Geometry", "toolbar_button_style"); + set(m_Settings, "Settings", "use_proxy", b); +} - for (auto* tb : w->findChildren()) { - if (size) { - tb->setIconSize(*size); - } +void NetworkSettings::setDownloadSpeed(const QString& name, int bytesPerSecond) +{ + auto current = servers(); - if (style) { - tb->setToolButtonStyle(static_cast(*style)); + for (auto& server : current) { + if (server.name() == name) { + server.addDownload(bytesPerSecond); + updateServers(current); + return; } - - restoreVisibility(tb); } + + log::error( + "server '{}' not found while trying to add a download with bps {}", + name, bytesPerSecond); } -void GeometrySettings::saveToolbars(const QMainWindow* w) +ServerList NetworkSettings::servers() const { - const auto tbs = w->findChildren(); + // servers used to be a map of byte arrays until 2.2.1, it's now an array of + // individual values instead + // + // 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 + { + const QStringList keys = ScopedGroup(m_Settings, "Servers").keys(); - // save visibility for all - for (auto* tb : tbs) { - saveVisibility(tb); + if (!keys.empty() && keys[0] != "size") { + // old format + return serversFromOldMap(); + } } - // all toolbars have the same size and button style settings, just save the - // first one - if (!tbs.isEmpty()) { - const auto* tb = tbs[0]; - set(m_Settings, "Geometry", "toolbar_size", tb->iconSize()); - set(m_Settings, "Geometry", "toolbar_button_style", static_cast(tb->toolButtonStyle())); - } -} + // post 2.2.1 format, array of values -QStringList GeometrySettings::getModInfoTabOrder() const -{ - QStringList v; + ServerList list; - if (m_Settings.contains("mod_info_tabs")) { - // old byte array from 2.2.0 - QDataStream stream(m_Settings.value("mod_info_tabs").toByteArray()); + { + ScopedReadArray sra(m_Settings, "Servers"); - int count = 0; - stream >> count; + sra.for_each([&] { + ServerInfo::SpeedList lastDownloads; - for (int i=0; i> s; - v.push_back(s); - } - } else { - // string list since 2.2.1 - QString string = m_Settings.value("mod_info_tab_order").toString(); - QTextStream stream(&string); + const auto lastDownloadsString = sra.get("lastDownloads", ""); - while (!stream.atEnd()) { - QString s; - stream >> s; - v.push_back(s); - } + for (const auto& s : lastDownloadsString.split(" ")) { + const auto bytesPerSecond = s.toInt(); + if (bytesPerSecond > 0) { + lastDownloads.push_back(bytesPerSecond); + } + } + + ServerInfo server( + 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 v; + return list; } -void GeometrySettings::setModInfoTabOrder(const QString& names) +ServerList NetworkSettings::serversFromOldMap() const { - set(m_Settings, "Geometry", "mod_info_tab_order", names); -} + // for 2.2.1 and before -void GeometrySettings::centerOnMainWindowMonitor(QWidget* w) -{ - const auto monitor = getOptional( - m_Settings, "Geometry", "MainWindow_monitor"); + ServerList list; + const ScopedGroup sg(m_Settings, "Servers"); - QPoint center; + sg.for_each([&](auto&& serverKey) { + QVariantMap data = sg.get(serverKey); - if (monitor && QGuiApplication::screens().size() > *monitor) { - center = QGuiApplication::screens().at(*monitor)->geometry().center(); - } else { - center = QGuiApplication::primaryScreen()->geometry().center(); - } + ServerInfo server( + serverKey, + data["premium"].toBool(), + data["lastSeen"].toDate(), + data["preferred"].toInt(), + {}); - w->move(center - w->rect().center()); -} + // ignoring download count and speed, it's now a list of values instead of + // a total -void GeometrySettings::saveMainWindowMonitor(const QMainWindow* w) -{ - if (auto* handle=w->windowHandle()) { - if (auto* screen = handle->screen()) { - const int screenId = QGuiApplication::screens().indexOf(screen); - set(m_Settings, "Geometry", "MainWindow_monitor", screenId); - } - } + list.add(std::move(server)); + }); + + return list; } -Qt::Orientation dockOrientation(const QMainWindow* mw, const QDockWidget* d) +void NetworkSettings::updateServers(ServerList servers) { - // docks in these areas are horizontal - const auto horizontalAreas = - Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea; + // clean up unavailable servers + servers.cleanup(); - if (mw->dockWidgetArea(const_cast(d)) & horizontalAreas) { - return Qt::Horizontal; - } else { - return Qt::Vertical; - } -} + removeSection(m_Settings, "Servers"); -void GeometrySettings::saveDocks(const QMainWindow* mw) -{ - // this attempts to fix https://bugreports.qt.io/browse/QTBUG-46620 where dock - // sizes are not restored when the main window is maximized; it is used in - // MainWindow::readSettings() and MainWindow::storeSettings() - // - // there's also https://stackoverflow.com/questions/44005852, which has what - // seems to be a popular fix, but it breaks the restored size of the window - // by setting it to the desktop's resolution, so that doesn't work - // - // the only fix I could find is to remember the sizes of the docks and manually - // setting them back; saving is straightforward, but restoring is messy - // - // this also depends on the window being visible before the timer in restore() - // is fired and the timer must be processed by application.exec(); therefore, - // the splash screen _must_ be closed before readSettings() is called, because - // it has its own event loop, which seems to interfere with this - // - // all of this should become unnecessary when QTBUG-46620 is fixed - // + { + ScopedWriteArray swa(m_Settings, "Servers"); - // saves the size of each dock - for (const auto* dock : mw->findChildren()) { - int size = 0; + for (const auto& server : servers) { + swa.next(); - // save the width for horizontal docks, or the height for vertical - if (dockOrientation(mw, dock) == Qt::Horizontal) { - size = dock->size().width(); - } else { - size = dock->size().height(); - } + swa.set("name", server.name()); + swa.set("premium", server.isPremium()); + swa.set("lastSeen", server.lastSeen().toString(Qt::ISODate)); + swa.set("preferred", server.preferred()); - set(m_Settings, "Geometry", dockSettingName(dock), size); + QString lastDownloads; + for (const auto& speed : server.lastDownloads()) { + if (speed > 0) { + lastDownloads += QString("%1 ").arg(speed); + } + } + + swa.set("lastDownloads", lastDownloads.trimmed()); + } } } -void GeometrySettings::restoreDocks(QMainWindow* mw) const +void NetworkSettings::dump() const { - struct DockInfo - { - QDockWidget* d; - int size = 0; - Qt::Orientation ori; - }; - - std::vector dockInfos; + log::debug("servers:"); - // for each dock - for (auto* dock : mw->findChildren()) { - if (auto size=getOptional(m_Settings, "Geometry", dockSettingName(dock))) { - // remember this dock, its size and orientation - dockInfos.push_back({dock, *size, dockOrientation(mw, dock)}); + for (const auto& server : servers()) { + QString lastDownloads; + for (auto speed : server.lastDownloads()) { + lastDownloads += QString("%1 ").arg(speed); } - } - // the main window must have had time to process the settings from - // readSettings() or it seems to override whatever is set here - // - // some people said a single processEvents() call is enough, but it doesn't - // look like it - QTimer::singleShot(5, [=] { - for (const auto& info : dockInfos) { - mw->resizeDocks({info.d}, {info.size}, info.ori); - } - }); + log::debug( + " . {} premium={} lastSeen={} preferred={} lastDownloads={}", + server.name(), + server.isPremium() ? "yes" : "no", + server.lastSeen().toString(Qt::ISODate), + server.preferred(), + lastDownloads.trimmed()); + } } -ColorSettings::ColorSettings(QSettings& s) - : m_Settings(s) +NexusSettings::NexusSettings(Settings& parent, QSettings& settings) + : m_Parent(parent), m_Settings(settings) { } -QColor ColorSettings::modlistOverwrittenLoose() const +bool NexusSettings::automaticLoginEnabled() const { - return get( - m_Settings, "Settings", "overwrittenLooseFilesColor", - QColor(0, 255, 0, 64)); + return get(m_Settings, "Settings", "nexus_login", false); } -void ColorSettings::setModlistOverwrittenLoose(const QColor& c) +bool NexusSettings::apiKey(QString &apiKey) const { - set(m_Settings, "Settings", "overwrittenLooseFilesColor", c); + QString tempKey = getWindowsCredential("APIKEY"); + if (tempKey.isEmpty()) + return false; + + apiKey = tempKey; + return true; } -QColor ColorSettings::modlistOverwritingLoose() const +bool NexusSettings::setApiKey(const QString& apiKey) { - return get( - m_Settings, "Settings", "overwritingLooseFilesColor", - QColor(255, 0, 0, 64)); + if (!setWindowsCredential("APIKEY", apiKey)) { + const auto e = GetLastError(); + log::error("Storing API key failed: {}", formatSystemMessage(e)); + return false; + } + + return true; } -void ColorSettings::setModlistOverwritingLoose(const QColor& c) +bool NexusSettings::clearApiKey() { - set(m_Settings, "Settings", "overwritingLooseFilesColor", c); + return setApiKey(""); } -QColor ColorSettings::modlistOverwrittenArchive() const +bool NexusSettings::hasApiKey() const { - return get( - m_Settings, "Settings", "overwrittenArchiveFilesColor", - QColor(0, 255, 255, 64)); + return !getWindowsCredential("APIKEY").isEmpty(); } -void ColorSettings::setModlistOverwrittenArchive(const QColor& c) +bool NexusSettings::endorsementIntegration() const { - set(m_Settings, "Settings", "overwrittenArchiveFilesColor", c); + return get(m_Settings, "Settings", "endorsement_integration", true); } -QColor ColorSettings::modlistOverwritingArchive() const +void NexusSettings::setEndorsementIntegration(bool b) const { - return get( - m_Settings, "Settings", "overwritingArchiveFilesColor", - QColor(255, 0, 255, 64)); + set(m_Settings, "Settings", "endorsement_integration", b); } -void ColorSettings::setModlistOverwritingArchive(const QColor& c) +EndorsementState NexusSettings::endorsementState() const { - set(m_Settings, "Settings", "overwritingArchiveFilesColor", c); + return endorsementStateFromString( + get(m_Settings, "General", "endorse_state", "")); } -QColor ColorSettings::modlistContainsPlugin() const +void NexusSettings::setEndorsementState(EndorsementState s) { - return get( - m_Settings, "Settings", "containsPluginColor", - QColor(0, 0, 255, 64)); + const auto v = toString(s); + + if (v.isEmpty()) { + remove(m_Settings, "General", "endorse_state"); + } else { + set(m_Settings, "General", "endorse_state", v); + } } -void ColorSettings::setModlistContainsPlugin(const QColor& c) +void NexusSettings::registerAsNXMHandler(bool force) { - set(m_Settings, "Settings", "containsPluginColor", c); + const auto nxmPath = QCoreApplication::applicationDirPath() + "/nxmhandler.exe"; + const auto executable = QCoreApplication::applicationFilePath(); + + QString mode = force ? "forcereg" : "reg"; + QString parameters = mode + " " + m_Parent.game().plugin()->gameShortName(); + for (const QString& altGame : m_Parent.game().plugin()->validShortNames()) { + parameters += "," + altGame; + } + parameters += " \"" + executable + "\""; + + if (!shell::Execute(nxmPath, parameters)) { + QMessageBox::critical( + nullptr, QObject::tr("Failed"), + QObject::tr("Failed to start the helper application")); + } } -QColor ColorSettings::pluginListContained() const + +SteamSettings::SteamSettings(Settings& parent, QSettings& settings) + : m_Parent(parent), m_Settings(settings) { - return get( - m_Settings, "Settings", "containedColor", - QColor(0, 0, 255, 64)); } -void ColorSettings::setPluginListContained(const QColor& c) +QString SteamSettings::appID() const { - set(m_Settings, "Settings", "containedColor", c); + return get( + m_Settings, "Settings", "app_id", m_Parent.game().plugin()->steamAPPId()); } - -PluginSettings::PluginSettings(QSettings& settings) - : m_Settings(settings) +void SteamSettings::setAppID(const QString& id) { + if (id.isEmpty()) { + remove(m_Settings, "Settings", "app_id"); + } else { + set(m_Settings, "Settings", "app_id", id); + } } -void PluginSettings::clearPlugins() +bool SteamSettings::login(QString &username, QString &password) const { - m_Plugins.clear(); - m_PluginSettings.clear(); - - m_PluginBlacklist.clear(); + username = get(m_Settings, "Settings", "steam_username", ""); + password = getWindowsCredential("steam_password"); - ScopedReadArray sra(m_Settings, "pluginBlacklist"); - sra.for_each([&]{ - m_PluginBlacklist.insert(sra.get("name")); - }); + return !username.isEmpty() && !password.isEmpty(); } -void PluginSettings::registerPlugin(IPlugin *plugin) +void SteamSettings::setLogin(QString username, QString password) { - m_Plugins.push_back(plugin); - m_PluginSettings.insert(plugin->name(), QVariantMap()); - m_PluginDescriptions.insert(plugin->name(), QVariantMap()); + if (username == "") { + remove(m_Settings, "Settings", "steam_username"); + password = ""; + } else { + set(m_Settings, "Settings", "steam_username", username); + } - for (const PluginSetting &setting : plugin->settings()) { - const QString settingName = plugin->name() + "/" + setting.key; + if (!setWindowsCredential("steam_password", password)) { + const auto e = GetLastError(); + log::error("Storing or deleting password failed: {}", formatSystemMessage(e)); + } +} - 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()); +InterfaceSettings::InterfaceSettings(QSettings& settings) + : m_Settings(settings) +{ +} - temp = setting.defaultValue; - } +bool InterfaceSettings::lockGUI() const +{ + return get(m_Settings, "Settings", "lock_gui", true); +} - m_PluginSettings[plugin->name()][setting.key] = temp; +void InterfaceSettings::setLockGUI(bool b) +{ + set(m_Settings, "Settings", "lock_gui", b); +} - m_PluginDescriptions[plugin->name()][setting.key] = QString("%1 (default: %2)") - .arg(setting.description) - .arg(setting.defaultValue.toString()); - } +std::optional InterfaceSettings::styleName() const +{ + return getOptional(m_Settings, "Settings", "style"); } -bool PluginSettings::pluginBlacklisted(const QString &fileName) const +void InterfaceSettings::setStyleName(const QString& name) { - return m_PluginBlacklist.contains(fileName); + set(m_Settings, "Settings", "style", name); } -QVariant PluginSettings::pluginSetting(const QString &pluginName, const QString &key) const +bool InterfaceSettings::compactDownloads() const { - auto iterPlugin = m_PluginSettings.find(pluginName); - if (iterPlugin == m_PluginSettings.end()) { - return QVariant(); - } + return get(m_Settings, "Settings", "compact_downloads", false); +} - auto iterSetting = iterPlugin->find(key); - if (iterSetting == iterPlugin->end()) { - return QVariant(); - } +void InterfaceSettings::setCompactDownloads(bool b) +{ + set(m_Settings, "Settings", "compact_downloads", b); +} - return *iterSetting; +bool InterfaceSettings::metaDownloads() const +{ + return get(m_Settings, "Settings", "meta_downloads", false); } -void PluginSettings::setPluginSetting(const QString &pluginName, const QString &key, const QVariant &value) +void InterfaceSettings::setMetaDownloads(bool b) { - auto iterPlugin = m_PluginSettings.find(pluginName); + set(m_Settings, "Settings", "meta_downloads", b); +} - if (iterPlugin == m_PluginSettings.end()) { - throw MyException( - QObject::tr("attempt to store setting for unknown plugin \"%1\"") - .arg(pluginName)); - } +bool InterfaceSettings::hideAPICounter() const +{ + return get(m_Settings, "Settings", "hide_api_counter", false); +} - // store the new setting both in memory and in the ini - m_PluginSettings[pluginName][key] = value; - set(m_Settings, "Plugins", pluginName + "/" + key, value); +void InterfaceSettings::setHideAPICounter(bool b) +{ + set(m_Settings, "Settings", "hide_api_counter", b); } -QVariant PluginSettings::pluginPersistent(const QString &pluginName, const QString &key, const QVariant &def) const +bool InterfaceSettings::displayForeign() const { - if (!m_PluginSettings.contains(pluginName)) { - return def; - } + return get(m_Settings, "Settings", "display_foreign", true); +} - return get(m_Settings, "PluginPersistance", pluginName + "/" + key, def); +void InterfaceSettings::setDisplayForeign(bool b) +{ + set(m_Settings, "Settings", "display_foreign", b); } -void PluginSettings::setPluginPersistent( - const QString &pluginName, const QString &key, const QVariant &value, bool sync) +QString InterfaceSettings::language() { - if (!m_PluginSettings.contains(pluginName)) { - throw MyException( - QObject::tr("attempt to store setting for unknown plugin \"%1\"") - .arg(pluginName)); - } + QString result = get(m_Settings, "Settings", "language", ""); - set(m_Settings, "PluginPersistance", pluginName + "/" + key, value); + if (result.isEmpty()) { + QStringList languagePreferences = QLocale::system().uiLanguages(); - if (sync) { - m_Settings.sync(); + if (languagePreferences.length() > 0) { + // the users most favoritest language + result = languagePreferences.at(0); + } else { + // fallback system locale + result = QLocale::system().name(); + } } + + return result; } -void PluginSettings::addBlacklistPlugin(const QString &fileName) +void InterfaceSettings::setLanguage(const QString& name) { - m_PluginBlacklist.insert(fileName); - writePluginBlacklist(); + set(m_Settings, "Settings", "language", name); } -void PluginSettings::writePluginBlacklist() +bool InterfaceSettings::isTutorialCompleted(const QString& windowName) const { - removeSection(m_Settings, "PluginBlacklist"); - - ScopedWriteArray swa(m_Settings, "PluginBlacklist"); - - for (const QString &plugin : m_PluginBlacklist) { - swa.next(); - swa.set("name", plugin); - } + return get(m_Settings, "CompletedWindowTutorials", windowName, false); } -QVariantMap PluginSettings::pluginSettings(const QString &pluginName) const +void InterfaceSettings::setTutorialCompleted(const QString& windowName, bool b) { - return m_PluginSettings[pluginName]; + set(m_Settings, "CompletedWindowTutorials", windowName, b); } -void PluginSettings::setPluginSettings(const QString &pluginName, const QVariantMap& map) + +DiagnosticsSettings::DiagnosticsSettings(QSettings& settings) + : m_Settings(settings) { - m_PluginSettings[pluginName] = map; } -QVariantMap PluginSettings::pluginDescriptions(const QString &pluginName) const +log::Levels DiagnosticsSettings::logLevel() const { - return m_PluginDescriptions[pluginName]; + return get(m_Settings, "Settings", "log_level", log::Levels::Info); } -void PluginSettings::pluginDescriptions(const QString &pluginName, const QVariantMap& map) +void DiagnosticsSettings::setLogLevel(log::Levels level) { - m_PluginDescriptions[pluginName] = map; + set(m_Settings, "Settings", "log_level", level); } -const QSet& PluginSettings::pluginBlacklist() const +CrashDumpsType DiagnosticsSettings::crashDumpsType() const { - return m_PluginBlacklist; + return get(m_Settings, + "Settings", "crash_dumps_type", CrashDumpsType::Mini); } -void PluginSettings::setPluginBlacklist(const QStringList& pluginNames) +void DiagnosticsSettings::setCrashDumpsType(CrashDumpsType type) { - m_PluginBlacklist.clear(); - - for (const auto& name : pluginNames) { - m_PluginBlacklist.insert(name); - } + set(m_Settings, "Settings", "crash_dumps_type", type); } -void PluginSettings::save() +int DiagnosticsSettings::crashDumpsMax() const { - for (auto iterPlugins=m_PluginSettings.begin(); iterPlugins!=m_PluginSettings.end(); ++iterPlugins) { - for (auto iterSettings=iterPlugins->begin(); iterSettings!=iterPlugins->end(); ++iterSettings) { - const auto key = iterPlugins.key() + "/" + iterSettings.key(); - set(m_Settings, "Plugins", key, iterSettings.value()); - } - } + return get(m_Settings, "Settings", "crash_dumps_max", 5); +} - writePluginBlacklist(); +void DiagnosticsSettings::setCrashDumpsMax(int n) +{ + set(m_Settings, "Settings", "crash_dumps_max", n); } diff --git a/src/settings.h b/src/settings.h index 403c2d71..5c0a2542 100644 --- a/src/settings.h +++ b/src/settings.h @@ -25,6 +25,10 @@ along with Mod Organizer. If not, see . #include #include +#ifdef interface + #undef interface +#endif + namespace MOBase { class IPlugin; class IPluginGame; @@ -50,6 +54,58 @@ private: }; +class GameSettings +{ +public: + GameSettings(QSettings& setting); + + const MOBase::IPluginGame* plugin(); + void setPlugin(const MOBase::IPluginGame* gamePlugin); + + /** + * whether files of the core game are forced-enabled so the user can't + * accidentally disable them + */ + bool forceEnableCoreFiles() const; + void setForceEnableCoreFiles(bool b); + + /** + * the directory where the managed game is stored (with native separators) + **/ + std::optional directory() const; + void setDirectory(const QString& path); + + std::optional name() const; + void setName(const QString& name); + + std::optional edition() const; + void setEdition(const QString& name); + + std::optional selectedProfileName() const; + void setSelectedProfileName(const QString& name); + + /** + * @return the load mechanism to be used + **/ + LoadMechanism::EMechanism loadMechanismType() const; + void setLoadMechanism(LoadMechanism::EMechanism m); + const LoadMechanism& loadMechanism() const; + void setupLoadMechanism(); + + /** + * @return true if the user wants unchecked plugins (esp, esm) should be hidden from + * the virtual data directory + **/ + bool hideUncheckedPlugins() const; + void setHideUncheckedPlugins(bool b); + +private: + QSettings& m_Settings; + const MOBase::IPluginGame* m_GamePlugin; + LoadMechanism m_LoadMechanism; +}; + + class GeometrySettings { public: @@ -83,7 +139,7 @@ public: void saveDocks(const QMainWindow* w); void restoreDocks(QMainWindow* w) const; - QStringList getModInfoTabOrder() const; + QStringList modInfoTabOrder() const; void setModInfoTabOrder(const QString& names); void centerOnMainWindowMonitor(QWidget* w); @@ -95,6 +151,40 @@ private: }; +class WidgetSettings +{ +public: + WidgetSettings(QSettings& s); + + std::optional index(const QComboBox* cb) const; + void saveIndex(const QComboBox* cb); + void restoreIndex(QComboBox* cb, std::optional def={}) const; + + std::optional index(const QTabWidget* w) const; + void saveIndex(const QTabWidget* w); + void restoreIndex(QTabWidget* w, std::optional def={}) const; + + std::optional checked(const QAbstractButton* w) const; + void saveChecked(const QAbstractButton* w); + void restoreChecked(QAbstractButton* w, std::optional def={}) const; + + MOBase::QuestionBoxMemory::Button questionButton( + const QString& windowName, const QString& filename) const; + + void setQuestionWindowButton( + const QString& windowName, MOBase::QuestionBoxMemory::Button button); + + void setQuestionFileButton( + const QString& windowName, const QString& filename, + MOBase::QuestionBoxMemory::Button choice); + + void resetQuestionButtons(); + +private: + QSettings& m_Settings; +}; + + class ColorSettings { public: @@ -120,6 +210,19 @@ public: QColor pluginListContained() const; void setPluginListContained(const QColor& c) ; + std::optional previousSeparatorColor() const; + void setPreviousSeparatorColor(const QColor& c) const; + void removePreviousSeparatorColor(); + + /** + * @brief color the scrollbar of the mod list for custom separator colors? + * @return the state of the setting + */ + bool colorSeparatorScrollbar() const; + void setColorSeparatorScrollbar(bool b); + + static QColor idealTextColor(const QColor& rBackgroundColor); + private: QSettings& m_Settings; }; @@ -165,210 +268,229 @@ private: }; -enum class EndorsementState -{ - Accepted = 1, - Refused, - NoDecision -}; - -EndorsementState endorsementStateFromString(const QString& s); -QString toString(EndorsementState s); - - -/** - * manages the settings for Mod Organizer. The settings are not cached - * inside the class but read/written directly from/to disc - **/ -class Settings : public QObject +class PathSettings { - Q_OBJECT; - public: - Settings(const QString& path); - ~Settings(); + PathSettings(QSettings& settings); - static Settings &instance(); + QString base() const; + QString downloads(bool resolve = true) const; + QString mods(bool resolve = true) const; + QString cache(bool resolve = true) const; + QString profiles(bool resolve = true) const; + QString overwrite(bool resolve = true) const; - void processUpdates( - const QVersionNumber& currentVersion, const QVersionNumber& lastVersion); + void setBase(const QString& path); + void setDownloads(const QString& path); + void setMods(const QString& path); + void setCache(const QString& path); + void setProfiles(const QString& path); + void setOverwrite(const QString& path); - QString getFilename() const; + std::map recent() const; + void setRecent(const std::map& map); - /** - * @return true if the user wants unchecked plugins (esp, esm) should be hidden from - * the virtual dat adirectory - **/ - bool hideUncheckedPlugins() const; - void setHideUncheckedPlugins(bool b); +private: + QSettings& m_Settings; - /** - * @return true if files of the core game are forced-enabled so the user can't accidentally disable them - */ - bool forceEnableCoreFiles() const; - void setForceEnableCoreFiles(bool b); + QString getConfigurablePath(const QString &key, const QString &def, bool resolve) const; + void setConfigurablePath(const QString &key, const QString& path); +}; - /** - * @return true if the GUI should be locked when running executables - */ - bool lockGUI() const; - void setLockGUI(bool b); - /** - * the steam appid is assigned by the steam platform to each product sold there. - * The appid may differ between different versions of a game so it may be impossible - * for Mod Organizer to automatically recognize it, though usually it does - * @return the steam appid for the game - **/ - QString getSteamAppID() const; - void setSteamAppID(const QString& id); - - QString getBaseDirectory() const; - QString getDownloadDirectory(bool resolve = true) const; - QString getModDirectory(bool resolve = true) const; - QString getCacheDirectory(bool resolve = true) const; - QString getProfileDirectory(bool resolve = true) const; - QString getOverwriteDirectory(bool resolve = true) const; - - void setBaseDirectory(const QString& path); - void setDownloadDirectory(const QString& path); - void setModDirectory(const QString& path); - void setCacheDirectory(const QString& path); - void setProfileDirectory(const QString& path); - void setOverwriteDirectory(const QString& path); +class NetworkSettings +{ +public: + NetworkSettings(QSettings& settings); /** - * retrieve the directory where the managed game is stored (with native separators) - **/ - std::optional getManagedGameDirectory() const; - void setManagedGameDirectory(const QString& path); - - std::optional getManagedGameName() const; - void setManagedGameName(const QString& name); - - std::optional getManagedGameEdition() const; - void setManagedGameEdition(const QString& name); + * @return true if the user disabled internet features + */ + bool offlineMode() const; + void setOfflineMode(bool b); - std::optional getSelectedProfileName() const; - void setSelectedProfileName(const QString& name); + /** + * @return true if the user configured the use of a network proxy + */ + bool useProxy() const; + void setUseProxy(bool b); - std::optional getStyleName() const; - void setStyleName(const QString& name); + void setDownloadSpeed(const QString &serverName, int bytesPerSecond); + ServerList servers() const; + void updateServers(ServerList servers); - std::optional getVersion() const; + void dump() const; - bool getFirstStart() const; - void setFirstStart(bool b); +private: + QSettings& m_Settings; - std::optional getPreviousSeparatorColor() const; - void setPreviousSeparatorColor(const QColor& c) const; - void removePreviousSeparatorColor(); + ServerList serversFromOldMap() const; +}; - std::map getRecentDirectories() const; - void setRecentDirectories(const std::map& map); - std::vector> getExecutables() const; - void setExecutables(const std::vector>& v); +enum class EndorsementState +{ + Accepted = 1, + Refused, + NoDecision +}; - bool isTutorialCompleted(const QString& windowName) const; - void setTutorialCompleted(const QString& windowName, bool b=true); +EndorsementState endorsementStateFromString(const QString& s); +QString toString(EndorsementState s); - bool keepBackupOnInstall() const; - void setKeepBackupOnInstall(bool b); +class NexusSettings +{ +public: + NexusSettings(Settings& parent, QSettings& settings); - MOBase::QuestionBoxMemory::Button getQuestionButton( - const QString& windowName, const QString& filename) const; + /** + * @return true if the user has set up automatic login to nexus + **/ + bool automaticLoginEnabled() const; - void setQuestionWindowButton( - const QString& windowName, MOBase::QuestionBoxMemory::Button button); + /** + * @brief retrieve the login information for nexus + * + * @param username (out) receives the user name for nexus + * @param password (out) received the password for nexus + * @return true if automatic login is active, false otherwise + **/ + bool apiKey(QString &apiKey) const; - void setQuestionFileButton( - const QString& windowName, const QString& filename, - MOBase::QuestionBoxMemory::Button choice); + /** + * @brief set the nexus login information + * + * @param username username + * @param password password + */ + bool setApiKey(const QString& apiKey); - void resetQuestionButtons(); + /** + * @brief clears the nexus login information + */ + bool clearApiKey(); - std::optional getIndex(const QComboBox* cb) const; - void saveIndex(const QComboBox* cb); - void restoreIndex(QComboBox* cb, std::optional def={}) const; + /** + * @brief returns whether an API key is currently stored + */ + bool hasApiKey() const; - std::optional getIndex(const QTabWidget* w) const; - void saveIndex(const QTabWidget* w); - void restoreIndex(QTabWidget* w, std::optional def={}) const; + /** + * @return true if endorsement integration is enabled + */ + bool endorsementIntegration() const; + void setEndorsementIntegration(bool b) const; - std::optional getChecked(const QAbstractButton* w) const; - void saveChecked(const QAbstractButton* w); - void restoreChecked(QAbstractButton* w, std::optional def={}) const; + EndorsementState endorsementState() const; + void setEndorsementState(EndorsementState s); - GeometrySettings& geometry(); - const GeometrySettings& geometry() const; + /** + * @brief register MO as the handler for nxm links + * @param force set to true to enforce the registration dialog to show up, + * even if the user said earlier not to + */ + void registerAsNXMHandler(bool force); - ColorSettings& colors(); - const ColorSettings& colors() const; +private: + Settings& m_Parent; + QSettings& m_Settings; +}; - PluginSettings& plugins(); - const PluginSettings& plugins() const; +class SteamSettings +{ +public: + SteamSettings(Settings& parent, QSettings& settings); /** - * @return true if the user has set up automatic login to nexus - **/ - bool automaticLoginEnabled() const; + * the steam appid is assigned by the steam platform to each product sold there. + * The appid may differ between different versions of a game so it may be impossible + * for Mod Organizer to automatically recognize it, though usually it does + * @return the steam appid for the game + **/ + QString appID() const; + void setAppID(const QString& id); /** - * @brief retrieve the login information for nexus - * - * @param username (out) receives the user name for nexus - * @param password (out) received the password for nexus - * @return true if automatic login is active, false otherwise - **/ - bool getNexusApiKey(QString &apiKey) const; + * @brief retrieve the login information for steam + * + * @param username (out) receives the user name for nexus + * @param password (out) received the password for nexus + * @return true if a username has been specified, false otherwise + **/ + bool login(QString &username, QString &password) const; /** - * @brief set the nexus login information + * @brief set the steam login information * * @param username username * @param password password */ - bool setNexusApiKey(const QString& apiKey); + void setLogin(QString username, QString password); - /** - * @brief clears the nexus login information - */ - bool clearNexusApiKey(); +private: + Settings& m_Parent; + QSettings& m_Settings; +}; - /** - * @brief returns whether an API key is currently stored - */ - bool hasNexusApiKey() const; - /** - * @brief retrieve the login information for steam - * - * @param username (out) receives the user name for nexus - * @param password (out) received the password for nexus - * @return true if a username has been specified, false otherwise - **/ - bool getSteamLogin(QString &username, QString &password) const; +class InterfaceSettings +{ +public: + InterfaceSettings(QSettings& settings); /** - * @return true if the user disabled internet features - */ - bool offlineMode() const; - void setOfflineMode(bool b); + * @return true if the GUI should be locked when running executables + */ + bool lockGUI() const; + void setLockGUI(bool b); + + std::optional styleName() const; + void setStyleName(const QString& name); /** - * @return true if the user chose compact downloads - */ + * @return true if the user chose compact downloads + */ bool compactDownloads() const; void setCompactDownloads(bool b); /** - * @return true if the user chose meta downloads - */ + * @return true if the user chose meta downloads + */ bool metaDownloads() const; void setMetaDownloads(bool b); + /** + * @return true if the API counter should be hidden + */ + bool hideAPICounter() const; + void setHideAPICounter(bool b); + + /** + * @return true if the user wants to see non-official plugins installed outside MO in his mod list + */ + bool displayForeign() const; + void setDisplayForeign(bool b); + + /** + * @return short code of the configured language (corresponding to the translation files) + */ + QString language(); + void setLanguage(const QString& name); + + bool isTutorialCompleted(const QString& windowName) const; + void setTutorialCompleted(const QString& windowName, bool b=true); + +private: + QSettings& m_Settings; +}; + + +class DiagnosticsSettings +{ +public: + DiagnosticsSettings(QSettings& settings); + MOBase::log::Levels logLevel() const; void setLogLevel(MOBase::log::Levels level); @@ -378,60 +500,48 @@ public: int crashDumpsMax() const; void setCrashDumpsMax(int n); - QString executablesBlacklist() const; - void setExecutablesBlacklist(const QString& s); +private: + QSettings& m_Settings; +}; - /** - * @brief set the steam login information - * - * @param username username - * @param password password - */ - void setSteamLogin(QString username, QString password); - /** - * @return the load mechanism to be used - **/ - LoadMechanism::EMechanism getLoadMechanism() const; - void setLoadMechanism(LoadMechanism::EMechanism m); - /** - * @brief activate the load mechanism selected by the user - **/ - void setupLoadMechanism(); +/** + * manages the settings for Mod Organizer. The settings are not cached + * inside the class but read/written directly from/to disc + **/ +class Settings : public QObject +{ + Q_OBJECT; - /** - * @return true if the user configured the use of a network proxy - */ - bool getUseProxy() const; - void setUseProxy(bool b); +public: + Settings(const QString& path); + ~Settings(); - /** - * @return true if endorsement integration is enabled - */ - bool endorsementIntegration() const; - void setEndorsementIntegration(bool b) const; + static Settings &instance(); - EndorsementState endorsementState() const; - void setEndorsementState(EndorsementState s); + QString filename() const; - /** - * @return true if the API counter should be hidden - */ - bool hideAPICounter() const; - void setHideAPICounter(bool b); + std::optional version() const; + void processUpdates(const QVersionNumber& current, const QVersionNumber& last); - /** - * @return true if the user wants to see non-official plugins installed outside MO in his mod list - */ - bool displayForeign() const; - void setDisplayForeign(bool b); + bool firstStart() const; + void setFirstStart(bool b); + + std::vector> executables() const; + void setExecutables(const std::vector>& v); + + bool keepBackupOnInstall() const; + void setKeepBackupOnInstall(bool b); + + QString executablesBlacklist() const; + void setExecutablesBlacklist(const QString& s); /** * @brief sets the new motd hash **/ - unsigned int getMotDHash() const; - void setMotDHash(unsigned int hash); + unsigned int motdHash() const; + void setMotdHash(unsigned int hash); /** * @return true if the user wants to have archives being parsed to show conflicts and contents @@ -439,41 +549,45 @@ public: bool archiveParsing() const; void setArchiveParsing(bool b); - /** - * @return short code of the configured language (corresponding to the translation files) - */ - QString language(); - void setLanguage(const QString& name); - - void setDownloadSpeed(const QString &serverName, int bytesPerSecond); - ServerList getServers() const; - ServerList getServersFromOldMap() const; - void updateServers(ServerList servers); - bool usePrereleases() const; void setUsePrereleases(bool b); - /** - * @brief register MO as the handler for nxm links - * @param force set to true to enforce the registration dialog to show up, - * even if the user said earlier not to - */ - void registerAsNXMHandler(bool force); - /** - * @brief color the scrollbar of the mod list for custom separator colors? - * @return the state of the setting - */ - bool colorSeparatorScrollbar() const; - void setColorSeparatorScrollbar(bool b); + GameSettings& game(); + const GameSettings& game() const; + + GeometrySettings& geometry(); + const GeometrySettings& geometry() const; - static QColor getIdealTextColor(const QColor& rBackgroundColor); + WidgetSettings& widgets(); + const WidgetSettings& widgets() const; - MOBase::IPluginGame const *gamePlugin() { return m_GamePlugin; } - const LoadMechanism& loadMechanism() const { return m_LoadMechanism; } + ColorSettings& colors(); + const ColorSettings& colors() const; - QSettings::Status sync() const; + PluginSettings& plugins(); + const PluginSettings& plugins() const; + + PathSettings& paths(); + const PathSettings& paths() const; + + NetworkSettings& network(); + const NetworkSettings& network() const; + + NexusSettings& nexus(); + const NexusSettings& nexus() const; + + SteamSettings& steam(); + const SteamSettings& steam() const; + InterfaceSettings& interface(); + const InterfaceSettings& interface() const; + + DiagnosticsSettings& diagnostics(); + const DiagnosticsSettings& diagnostics() const; + + + QSettings::Status sync() const; void dump() const; public slots: @@ -485,18 +599,19 @@ signals: private: static Settings *s_Instance; - MOBase::IPluginGame const *m_GamePlugin; mutable QSettings m_Settings; + + GameSettings m_Game; GeometrySettings m_Geometry; + WidgetSettings m_Widgets; ColorSettings m_Colors; PluginSettings m_Plugins; - LoadMechanism m_LoadMechanism; - - static bool obfuscate(const QString key, const QString data); - static QString deObfuscate(const QString key); - - QString getConfigurablePath(const QString &key, const QString &def, bool resolve) const; - void setConfigurablePath(const QString &key, const QString& path); + PathSettings m_Paths; + NetworkSettings m_Network; + NexusSettings m_Nexus; + SteamSettings m_Steam; + InterfaceSettings m_Interface; + DiagnosticsSettings m_Diagnostics; }; #endif // SETTINGS_H diff --git a/src/settingsdialog.cpp b/src/settingsdialog.cpp index 35d14644..1d3d4a39 100644 --- a/src/settingsdialog.cpp +++ b/src/settingsdialog.cpp @@ -51,11 +51,11 @@ int SettingsDialog::exec() { GeometrySaver gs(m_settings, this); - m_settings.restoreIndex(ui->tabWidget); + m_settings.widgets().restoreIndex(ui->tabWidget); auto ret = TutorableDialog::exec(); - m_settings.saveIndex(ui->tabWidget); + m_settings.widgets().saveIndex(ui->tabWidget); if (ret == QDialog::Accepted) { for (auto&& tab : m_tabs) { @@ -109,7 +109,7 @@ void SettingsDialog::accept() if ((QDir::fromNativeSeparators(newModPath) != QDir::fromNativeSeparators( - Settings::instance().getModDirectory(true))) && + Settings::instance().paths().mods(true))) && (QMessageBox::question( nullptr, tr("Confirm"), tr("Changing the mod directory affects all your profiles! " diff --git a/src/settingsdialogdiagnostics.cpp b/src/settingsdialogdiagnostics.cpp index 278da0bf..386c7425 100644 --- a/src/settingsdialogdiagnostics.cpp +++ b/src/settingsdialogdiagnostics.cpp @@ -12,7 +12,7 @@ DiagnosticsSettingsTab::DiagnosticsSettingsTab(Settings& s, SettingsDialog& d) setLevelsBox(); setCrashDumpTypesBox(); - ui->dumpsMaxEdit->setValue(settings().crashDumpsMax()); + ui->dumpsMaxEdit->setValue(settings().diagnostics().crashDumpsMax()); QString logsPath = qApp->property("dataPath").toString() + "/" + QString::fromStdWString(AppConfig::logPath()); @@ -36,7 +36,7 @@ void DiagnosticsSettingsTab::setLevelsBox() ui->logLevelBox->addItem(QObject::tr("Error"), log::Error); for (int i=0; ilogLevelBox->count(); ++i) { - if (ui->logLevelBox->itemData(i) == settings().logLevel()) { + if (ui->logLevelBox->itemData(i) == settings().diagnostics().logLevel()) { ui->logLevelBox->setCurrentIndex(i); break; } @@ -56,7 +56,8 @@ void DiagnosticsSettingsTab::setCrashDumpTypesBox() add(QObject::tr("Data"), CrashDumpsType::Data); add(QObject::tr("Full"), CrashDumpsType::Full); - const auto current = static_cast(settings().crashDumpsType()); + const auto current = static_cast( + settings().diagnostics().crashDumpsType()); for (int i=0; idumpsTypeBox->count(); ++i) { if (ui->dumpsTypeBox->itemData(i) == current) { @@ -68,11 +69,11 @@ void DiagnosticsSettingsTab::setCrashDumpTypesBox() void DiagnosticsSettingsTab::update() { - settings().setLogLevel( + settings().diagnostics().setLogLevel( static_cast(ui->logLevelBox->currentData().toInt())); - settings().setCrashDumpsType( + settings().diagnostics().setCrashDumpsType( static_cast(ui->dumpsTypeBox->currentData().toInt())); - settings().setCrashDumpsMax(ui->dumpsMaxEdit->value()); + settings().diagnostics().setCrashDumpsMax(ui->dumpsMaxEdit->value()); } diff --git a/src/settingsdialoggeneral.cpp b/src/settingsdialoggeneral.cpp index e3d73037..3f7ece38 100644 --- a/src/settingsdialoggeneral.cpp +++ b/src/settingsdialoggeneral.cpp @@ -11,7 +11,7 @@ GeneralSettingsTab::GeneralSettingsTab(Settings& s, SettingsDialog& d) { addLanguages(); { - QString languageCode = settings().language(); + QString languageCode = settings().interface().language(); int currentID = ui->languageBox->findData(languageCode); // I made a mess. :( Most languages are stored with only the iso country // code (2 characters like "de") but chinese @@ -29,7 +29,7 @@ GeneralSettingsTab::GeneralSettingsTab(Settings& s, SettingsDialog& d) { const int currentID = ui->styleBox->findData( - settings().getStyleName().value_or("")); + settings().interface().styleName().value_or("")); if (currentID != -1) { ui->styleBox->setCurrentIndex(currentID); @@ -51,10 +51,10 @@ GeneralSettingsTab::GeneralSettingsTab(Settings& s, SettingsDialog& d) setContainsColor(settings().colors().modlistContainsPlugin()); setContainedColor(settings().colors().pluginListContained()); - ui->compactBox->setChecked(settings().compactDownloads()); - ui->showMetaBox->setChecked(settings().metaDownloads()); + ui->compactBox->setChecked(settings().interface().compactDownloads()); + ui->showMetaBox->setChecked(settings().interface().metaDownloads()); ui->usePrereleaseBox->setChecked(settings().usePrereleases()); - ui->colorSeparatorsBox->setChecked(settings().colorSeparatorScrollbar()); + ui->colorSeparatorsBox->setChecked(settings().colors().colorSeparatorScrollbar()); QObject::connect(ui->overwritingArchiveBtn, &QPushButton::clicked, [&]{ on_overwritingArchiveBtn_clicked(); }); QObject::connect(ui->overwritingBtn, &QPushButton::clicked, [&]{ on_overwritingBtn_clicked(); }); @@ -69,18 +69,18 @@ GeneralSettingsTab::GeneralSettingsTab(Settings& s, SettingsDialog& d) void GeneralSettingsTab::update() { - const QString oldLanguage = settings().language(); + const QString oldLanguage = settings().interface().language(); const QString newLanguage = ui->languageBox->itemData(ui->languageBox->currentIndex()).toString(); if (newLanguage != oldLanguage) { - settings().setLanguage(newLanguage); + settings().interface().setLanguage(newLanguage); emit settings().languageChanged(newLanguage); } - const QString oldStyle = settings().getStyleName().value_or(""); + const QString oldStyle = settings().interface().styleName().value_or(""); const QString newStyle = ui->styleBox->itemData(ui->styleBox->currentIndex()).toString(); if (oldStyle != newStyle) { - settings().setStyleName(newStyle); + settings().interface().setStyleName(newStyle); emit settings().styleChanged(newStyle); } @@ -91,10 +91,10 @@ void GeneralSettingsTab::update() settings().colors().setModlistContainsPlugin(getContainsColor()); settings().colors().setPluginListContained(getContainedColor()); - settings().setCompactDownloads(ui->compactBox->isChecked()); - settings().setMetaDownloads(ui->showMetaBox->isChecked()); + settings().interface().setCompactDownloads(ui->compactBox->isChecked()); + settings().interface().setMetaDownloads(ui->showMetaBox->isChecked()); settings().setUsePrereleases(ui->usePrereleaseBox->isChecked()); - settings().setColorSeparatorScrollbar(ui->colorSeparatorsBox->isChecked()); + settings().colors().setColorSeparatorScrollbar(ui->colorSeparatorsBox->isChecked()); } void GeneralSettingsTab::addLanguages() @@ -145,7 +145,7 @@ void GeneralSettingsTab::addStyles() void GeneralSettingsTab::resetDialogs() { - settings().resetQuestionButtons(); + settings().widgets().resetQuestionButtons(); } void GeneralSettingsTab::setButtonColor(QPushButton *button, const QColor &color) @@ -161,7 +161,7 @@ void GeneralSettingsTab::setButtonColor(QPushButton *button, const QColor &color .arg(color.green()) .arg(color.blue()) .arg(color.alpha()) - .arg(Settings::getIdealTextColor(color).name()) + .arg(ColorSettings::idealTextColor(color).name()) ); }; diff --git a/src/settingsdialognexus.cpp b/src/settingsdialognexus.cpp index 8822200e..0b08f13f 100644 --- a/src/settingsdialognexus.cpp +++ b/src/settingsdialognexus.cpp @@ -74,13 +74,13 @@ private: NexusSettingsTab::NexusSettingsTab(Settings& s, SettingsDialog& d) : SettingsTab(s, d) { - ui->offlineBox->setChecked(settings().offlineMode()); - ui->proxyBox->setChecked(settings().getUseProxy()); - ui->endorsementBox->setChecked(settings().endorsementIntegration()); - ui->hideAPICounterBox->setChecked(settings().hideAPICounter()); + ui->offlineBox->setChecked(settings().network().offlineMode()); + ui->proxyBox->setChecked(settings().network().useProxy()); + ui->endorsementBox->setChecked(settings().nexus().endorsementIntegration()); + ui->hideAPICounterBox->setChecked(settings().interface().hideAPICounter()); // display server preferences - for (const auto& server : s.getServers()) { + for (const auto& server : s.network().servers()) { QString descriptor = server.name(); if (!descriptor.compare("CDN", Qt::CaseInsensitive)) { @@ -117,12 +117,12 @@ NexusSettingsTab::NexusSettingsTab(Settings& s, SettingsDialog& d) void NexusSettingsTab::update() { - settings().setOfflineMode(ui->offlineBox->isChecked()); - settings().setUseProxy(ui->proxyBox->isChecked()); - settings().setEndorsementIntegration(ui->endorsementBox->isChecked()); - settings().setHideAPICounter(ui->hideAPICounterBox->isChecked()); + settings().network().setOfflineMode(ui->offlineBox->isChecked()); + settings().network().setUseProxy(ui->proxyBox->isChecked()); + settings().nexus().setEndorsementIntegration(ui->endorsementBox->isChecked()); + settings().interface().setHideAPICounter(ui->hideAPICounterBox->isChecked()); - auto servers = settings().getServers(); + auto servers = settings().network().servers(); // store server preference for (int i = 0; i < ui->knownServersList->count(); ++i) { @@ -167,7 +167,7 @@ void NexusSettingsTab::update() } } - settings().updateServers(servers); + settings().network().updateServers(servers); } void NexusSettingsTab::on_nexusConnect_clicked() @@ -225,13 +225,13 @@ void NexusSettingsTab::on_nexusDisconnect_clicked() void NexusSettingsTab::on_clearCacheButton_clicked() { - QDir(Settings::instance().getCacheDirectory()).removeRecursively(); + QDir(Settings::instance().paths().cache()).removeRecursively(); NexusInterface::instance(dialog().m_PluginContainer)->clearCache(); } void NexusSettingsTab::on_associateButton_clicked() { - Settings::instance().registerAsNXMHandler(true); + Settings::instance().nexus().registerAsNXMHandler(true); } void NexusSettingsTab::validateKey(const QString& key) @@ -312,7 +312,7 @@ void NexusSettingsTab::addNexusLog(const QString& s) bool NexusSettingsTab::setKey(const QString& key) { dialog().m_keyChanged = true; - const bool ret = settings().setNexusApiKey(key); + const bool ret = settings().nexus().setApiKey(key); updateNexusState(); return ret; } @@ -320,7 +320,7 @@ bool NexusSettingsTab::setKey(const QString& key) bool NexusSettingsTab::clearKey() { dialog().m_keyChanged = true; - const auto ret = settings().clearNexusApiKey(); + const auto ret = settings().nexus().clearApiKey(); NexusInterface::instance(dialog().m_PluginContainer)->getAccessManager()->clearApiKey(); updateNexusState(); @@ -352,7 +352,7 @@ void NexusSettingsTab::updateNexusButtons() ui->nexusManualKey->setText(QObject::tr("Cancel")); ui->nexusManualKey->setEnabled(true); } - else if (settings().hasNexusApiKey()) { + else if (settings().nexus().hasApiKey()) { // api key is present ui->nexusConnect->setText(QObject::tr("Connect to Nexus")); ui->nexusConnect->setEnabled(false); diff --git a/src/settingsdialogpaths.cpp b/src/settingsdialogpaths.cpp index 32aaf4bf..aeb4dd5d 100644 --- a/src/settingsdialogpaths.cpp +++ b/src/settingsdialogpaths.cpp @@ -6,17 +6,23 @@ PathsSettingsTab::PathsSettingsTab(Settings& s, SettingsDialog& d) : SettingsTab(s, d) { - ui->baseDirEdit->setText(settings().getBaseDirectory()); - ui->managedGameDirEdit->setText(settings().gamePlugin()->gameDirectory().absoluteFilePath(settings().gamePlugin()->binaryName())); - QString basePath = settings().getBaseDirectory(); + ui->baseDirEdit->setText(settings().paths().base()); + + ui->managedGameDirEdit->setText( + settings().game().plugin()->gameDirectory().absoluteFilePath( + settings().game().plugin()->binaryName())); + + QString basePath = settings().paths().base(); QDir baseDir(basePath); + for (const auto &dir : { - std::make_pair(ui->downloadDirEdit, settings().getDownloadDirectory(false)), - std::make_pair(ui->modDirEdit, settings().getModDirectory(false)), - std::make_pair(ui->cacheDirEdit, settings().getCacheDirectory(false)), - std::make_pair(ui->profilesDirEdit, settings().getProfileDirectory(false)), - std::make_pair(ui->overwriteDirEdit, settings().getOverwriteDirectory(false)) + std::make_pair(ui->downloadDirEdit, settings().paths().downloads(false)), + std::make_pair(ui->modDirEdit, settings().paths().mods(false)), + std::make_pair(ui->cacheDirEdit, settings().paths().cache(false)), + std::make_pair(ui->profilesDirEdit, settings().paths().profiles(false)), + std::make_pair(ui->overwriteDirEdit, settings().paths().overwrite(false)) }) { + QString storePath = baseDir.relativeFilePath(dir.second); storePath = dir.second; dir.first->setText(storePath); @@ -40,17 +46,17 @@ PathsSettingsTab::PathsSettingsTab(Settings& s, SettingsDialog& d) void PathsSettingsTab::update() { - using Setter = void (Settings::*)(const QString&); + using Setter = void (PathSettings::*)(const QString&); using Directory = std::tuple; - QString basePath = settings().getBaseDirectory(); + QString basePath = settings().paths().base(); for (const Directory &dir :{ - Directory{ui->downloadDirEdit->text(), &Settings::setDownloadDirectory, AppConfig::downloadPath()}, - Directory{ui->cacheDirEdit->text(), &Settings::setCacheDirectory, AppConfig::cachePath()}, - Directory{ui->modDirEdit->text(), &Settings::setModDirectory, AppConfig::modsPath()}, - Directory{ui->overwriteDirEdit->text(), &Settings::setOverwriteDirectory, AppConfig::overwritePath()}, - Directory{ui->profilesDirEdit->text(), &Settings::setProfileDirectory, AppConfig::profilesPath()} + Directory{ui->downloadDirEdit->text(), &PathSettings::setDownloads, AppConfig::downloadPath()}, + Directory{ui->cacheDirEdit->text(), &PathSettings::setCache, AppConfig::cachePath()}, + Directory{ui->modDirEdit->text(), &PathSettings::setMods, AppConfig::modsPath()}, + Directory{ui->overwriteDirEdit->text(), &PathSettings::setOverwrite, AppConfig::overwritePath()}, + Directory{ui->profilesDirEdit->text(), &PathSettings::setProfiles, AppConfig::profilesPath()} }) { QString path; Setter setter; @@ -70,22 +76,26 @@ void PathsSettingsTab::update() } if (QFileInfo(realPath) != QFileInfo(basePath + "/" + QString::fromStdWString(defaultName))) { - (settings().*setter)(path); + (settings().paths().*setter)(path); } else { - (settings().*setter)(""); + (settings().paths().*setter)(""); } } if (QFileInfo(ui->baseDirEdit->text()) != QFileInfo(qApp->property("dataPath").toString())) { - settings().setBaseDirectory(ui->baseDirEdit->text()); + settings().paths().setBase(ui->baseDirEdit->text()); } else { - settings().setBaseDirectory(""); + settings().paths().setBase(""); } - QFileInfo oldGameExe(settings().gamePlugin()->gameDirectory().absoluteFilePath(settings().gamePlugin()->binaryName())); + QFileInfo oldGameExe( + settings().game().plugin()->gameDirectory().absoluteFilePath( + settings().game().plugin()->binaryName())); + QFileInfo newGameExe(ui->managedGameDirEdit->text()); + if (oldGameExe != newGameExe) { - settings().setManagedGameDirectory(newGameExe.absolutePath()); + settings().game().setDirectory(newGameExe.absolutePath()); } } diff --git a/src/settingsdialogsteam.cpp b/src/settingsdialogsteam.cpp index 9ed93e47..3c4c5de6 100644 --- a/src/settingsdialogsteam.cpp +++ b/src/settingsdialogsteam.cpp @@ -5,7 +5,7 @@ SteamSettingsTab::SteamSettingsTab(Settings& s, SettingsDialog& d) : SettingsTab(s, d) { QString username, password; - settings().getSteamLogin(username, password); + settings().steam().login(username, password); ui->steamUserEdit->setText(username); ui->steamPassEdit->setText(password); @@ -13,5 +13,5 @@ SteamSettingsTab::SteamSettingsTab(Settings& s, SettingsDialog& d) void SteamSettingsTab::update() { - settings().setSteamLogin(ui->steamUserEdit->text(), ui->steamPassEdit->text()); + settings().steam().setLogin(ui->steamUserEdit->text(), ui->steamPassEdit->text()); } diff --git a/src/settingsdialogworkarounds.cpp b/src/settingsdialogworkarounds.cpp index b06bd77c..4d811e40 100644 --- a/src/settingsdialogworkarounds.cpp +++ b/src/settingsdialogworkarounds.cpp @@ -6,12 +6,12 @@ WorkaroundsSettingsTab::WorkaroundsSettingsTab(Settings& s, SettingsDialog& d) : SettingsTab(s, d) { - ui->appIDEdit->setText(settings().getSteamAppID()); + ui->appIDEdit->setText(settings().steam().appID()); - LoadMechanism::EMechanism mechanismID = settings().getLoadMechanism(); + LoadMechanism::EMechanism mechanismID = settings().game().loadMechanismType(); int index = 0; - if (settings().loadMechanism().isDirectLoadingSupported()) { + if (settings().game().loadMechanism().isDirectLoadingSupported()) { ui->mechanismBox->addItem(QObject::tr("Mod Organizer"), LoadMechanism::LOAD_MODORGANIZER); if (mechanismID == LoadMechanism::LOAD_MODORGANIZER) { index = ui->mechanismBox->count() - 1; @@ -20,10 +20,10 @@ WorkaroundsSettingsTab::WorkaroundsSettingsTab(Settings& s, SettingsDialog& d) ui->mechanismBox->setCurrentIndex(index); - ui->hideUncheckedBox->setChecked(settings().hideUncheckedPlugins()); - ui->forceEnableBox->setChecked(settings().forceEnableCoreFiles()); - ui->displayForeignBox->setChecked(settings().displayForeign()); - ui->lockGUIBox->setChecked(settings().lockGUI()); + ui->hideUncheckedBox->setChecked(settings().game().hideUncheckedPlugins()); + ui->forceEnableBox->setChecked(settings().game().forceEnableCoreFiles()); + ui->displayForeignBox->setChecked(settings().interface().displayForeign()); + ui->lockGUIBox->setChecked(settings().interface().lockGUI()); ui->enableArchiveParsingBox->setChecked(settings().archiveParsing()); setExecutableBlacklist(settings().executablesBlacklist()); @@ -35,19 +35,19 @@ WorkaroundsSettingsTab::WorkaroundsSettingsTab(Settings& s, SettingsDialog& d) void WorkaroundsSettingsTab::update() { - if (ui->appIDEdit->text() != settings().gamePlugin()->steamAPPId()) { - settings().setSteamAppID(ui->appIDEdit->text()); + if (ui->appIDEdit->text() != settings().game().plugin()->steamAPPId()) { + settings().steam().setAppID(ui->appIDEdit->text()); } else { - settings().setSteamAppID(""); + settings().steam().setAppID(""); } - settings().setLoadMechanism(static_cast( + settings().game().setLoadMechanism(static_cast( ui->mechanismBox->itemData(ui->mechanismBox->currentIndex()).toInt())); - settings().setHideUncheckedPlugins(ui->hideUncheckedBox->isChecked()); - settings().setForceEnableCoreFiles(ui->forceEnableBox->isChecked()); - settings().setDisplayForeign(ui->displayForeignBox->isChecked()); - settings().setLockGUI(ui->lockGUIBox->isChecked()); + settings().game().setHideUncheckedPlugins(ui->hideUncheckedBox->isChecked()); + settings().game().setForceEnableCoreFiles(ui->forceEnableBox->isChecked()); + settings().interface().setDisplayForeign(ui->displayForeignBox->isChecked()); + settings().interface().setLockGUI(ui->lockGUIBox->isChecked()); settings().setArchiveParsing(ui->enableArchiveParsingBox->isChecked()); settings().setExecutablesBlacklist(getExecutableBlacklist()); } diff --git a/src/statusbar.cpp b/src/statusbar.cpp index d22010a5..3734aa87 100644 --- a/src/statusbar.cpp +++ b/src/statusbar.cpp @@ -129,7 +129,7 @@ void StatusBar::setUpdateAvailable(bool b) void StatusBar::checkSettings(const Settings& settings) { - m_api->setVisible(!settings.hideAPICounter()); + m_api->setVisible(!settings.interface().hideAPICounter()); } void StatusBar::showEvent(QShowEvent*) diff --git a/src/usvfsconnector.cpp b/src/usvfsconnector.cpp index 41f58308..4315ed92 100644 --- a/src/usvfsconnector.cpp +++ b/src/usvfsconnector.cpp @@ -163,8 +163,8 @@ QString toString(CrashDumpsType t) UsvfsConnector::UsvfsConnector() { USVFSParameters params; - LogLevel level = toUsvfsLogLevel(Settings::instance().logLevel()); - CrashDumpsType dumpType = Settings::instance().crashDumpsType(); + LogLevel level = toUsvfsLogLevel(Settings::instance().diagnostics().logLevel()); + CrashDumpsType dumpType = Settings::instance().diagnostics().crashDumpsType(); std::string dumpPath = MOShared::ToString(OrganizerCore::crashDumpsPath(), true); USVFSInitParameters(¶ms, SHMID, false, level, dumpType, dumpPath.c_str()); -- cgit v1.3.1 From 3757aa3f532c943f8a47e997d0a4f250d9dacdd3 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Mon, 2 Sep 2019 15:07:35 -0400 Subject: split into settingsutilities --- src/CMakeLists.txt | 9 +- src/settings.cpp | 452 +--------------------------------------------- src/settings.h | 3 - src/settingsutilities.cpp | 247 +++++++++++++++++++++++++ src/settingsutilities.h | 266 +++++++++++++++++++++++++++ 5 files changed, 522 insertions(+), 455 deletions(-) create mode 100644 src/settingsutilities.cpp create mode 100644 src/settingsutilities.h (limited to 'src/settings.cpp') diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index d8316e7e..ea27184b 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -45,6 +45,7 @@ SET(organizer_SRCS settingsdialogsteam.cpp settingsdialogworkarounds.cpp settings.cpp + settingsutilities.cpp selfupdater.cpp selectiondialog.cpp queryoverwritedialog.cpp @@ -166,6 +167,7 @@ SET(organizer_HDRS settingsdialogsteam.h settingsdialogworkarounds.h settings.h + settingsutilities.h selfupdater.h selectiondialog.h queryoverwritedialog.h @@ -444,6 +446,10 @@ set(profiles set(settings settings + settingsutilities +) + +set(settingsdialog settingsdialog settingsdialogdiagnostics settingsdialoggeneral @@ -490,7 +496,8 @@ set(widgets set(src_filters application core browser dialogs downloads env executables locking modinfo - modinfo\\dialog modlist plugins previews profiles settings utilities widgets + modinfo\\dialog modlist plugins previews profiles settings settingsdialog + utilities widgets ) foreach(filter in list ${src_filters}) diff --git a/src/settings.cpp b/src/settings.cpp index 8b063efb..14189be3 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -18,6 +18,7 @@ along with Mod Organizer. If not, see . */ #include "settings.h" +#include "settingsutilities.h" #include "serverinfo.h" #include "executableslist.h" #include "appconfig.h" @@ -27,310 +28,6 @@ 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_name(name) - { - m_settings.beginGroup(m_name); - } - - ~ScopedGroup() - { - m_settings.endGroup(); - } - - 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& section) - : m_settings(s), m_count(0) - { - m_count = m_settings.beginReadArray(section); - } - - ~ScopedReadArray() - { - m_settings.endArray(); - } - - 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; -}; - - -class ScopedWriteArray -{ -public: - ScopedWriteArray(QSettings& s, const QString& section) - : m_settings(s), m_section(section), m_i(0) - { - m_settings.beginWriteArray(section); - } - - ~ScopedWriteArray() - { - m_settings.endArray(); - } - - ScopedWriteArray(const ScopedWriteArray&) = delete; - ScopedWriteArray& operator=(const ScopedWriteArray&) = delete; - - void next() - { - m_settings.setArrayIndex(m_i); - ++m_i; - } - - template - void set(const QString& key, const T& value) - { - const auto displayName = QString("%1/%2\\%3") - .arg(m_section) - .arg(m_i) - .arg(key); - - setImpl(m_settings, displayName, "", key, value); - } - -private: - QSettings& m_settings; - QString m_section; - int m_i; -}; - EndorsementState endorsementStateFromString(const QString& s) { @@ -360,153 +57,6 @@ QString toString(EndorsementState s) } -QString widgetNameWithTopLevel(const QWidget* widget) -{ - QStringList components; - - auto* tl = widget->window(); - - if (tl == widget) { - // this is a top level widget, such as a dialog - components.push_back(widget->objectName()); - } else { - // this is a widget - const auto toplevelName = tl->objectName(); - if (!toplevelName.isEmpty()) { - components.push_back(toplevelName); - } - - const auto widgetName = widget->objectName(); - if (!widgetName.isEmpty()) { - components.push_back(widgetName); - } - } - - if (components.isEmpty()) { - // can't do much - return "unknown_widget"; - } - - return components.join("_"); -} - -QString widgetName(const QMainWindow* w) -{ - return w->objectName(); -} - -QString widgetName(const QHeaderView* w) -{ - return widgetNameWithTopLevel(w->parentWidget()); -} - -QString widgetName(const ExpanderWidget* w) -{ - return widgetNameWithTopLevel(w->button()); -} - -QString widgetName(const QWidget* w) -{ - return widgetNameWithTopLevel(w); -} - -template -QString geoSettingName(const Widget* widget) -{ - return widgetName(widget) + "_geometry"; -} - -template -QString stateSettingName(const Widget* widget) -{ - return widgetName(widget) + "_state"; -} - -template -QString visibilitySettingName(const Widget* widget) -{ - return widgetName(widget) + "_visibility"; -} - -QString dockSettingName(const QDockWidget* dock) -{ - return "MainWindow_docks_" + dock->objectName() + "_size"; -} - -QString indexSettingName(const QWidget* widget) -{ - return widgetNameWithTopLevel(widget) + "_index"; -} - -QString checkedSettingName(const QAbstractButton* b) -{ - return widgetNameWithTopLevel(b) + "_checked"; -} - -void warnIfNotCheckable(const QAbstractButton* b) -{ - if (!b->isCheckable()) { - log::warn( - "button '{}' used in the settings as a checkbox or radio button " - "but is not checkable", b->objectName()); - } -} - - -bool setWindowsCredential(const QString key, const QString data) -{ - QString finalKey("ModOrganizer2_" + key); - wchar_t* keyData = new wchar_t[finalKey.size()+1]; - finalKey.toWCharArray(keyData); - keyData[finalKey.size()] = L'\0'; - bool result = false; - if (data.isEmpty()) { - result = CredDeleteW(keyData, CRED_TYPE_GENERIC, 0); - if (!result) - if (GetLastError() == ERROR_NOT_FOUND) - result = true; - } else { - wchar_t* charData = new wchar_t[data.size()]; - data.toWCharArray(charData); - - CREDENTIALW cred = {}; - cred.Flags = 0; - cred.Type = CRED_TYPE_GENERIC; - cred.TargetName = keyData; - cred.CredentialBlob = (LPBYTE)charData; - cred.CredentialBlobSize = sizeof(wchar_t) * data.size(); - cred.Persist = CRED_PERSIST_LOCAL_MACHINE; - - result = CredWriteW(&cred, 0); - delete[] charData; - } - delete[] keyData; - return result; -} - -QString getWindowsCredential(const QString key) -{ - QString result; - QString finalKey("ModOrganizer2_" + key); - wchar_t* keyData = new wchar_t[finalKey.size()+1]; - finalKey.toWCharArray(keyData); - keyData[finalKey.size()] = L'\0'; - PCREDENTIALW creds; - if (CredReadW(keyData, 1, 0, &creds)) { - wchar_t *charData = (wchar_t *)creds->CredentialBlob; - result = QString::fromWCharArray(charData, creds->CredentialBlobSize / sizeof(wchar_t)); - CredFree(creds); - } else { - const auto e = GetLastError(); - if (e != ERROR_NOT_FOUND) { - log::error("Retrieving encrypted data failed: {}", formatSystemMessage(e)); - } - } - delete[] keyData; - return result; -} - - Settings *Settings::s_Instance = nullptr; Settings::Settings(const QString& path) : diff --git a/src/settings.h b/src/settings.h index 5c0a2542..68cfb9b7 100644 --- a/src/settings.h +++ b/src/settings.h @@ -36,8 +36,6 @@ namespace MOBase { class QSplitter; -class PluginContainer; -class ServerInfo; class ServerList; class Settings; class ExpanderWidget; @@ -505,7 +503,6 @@ private: }; - /** * manages the settings for Mod Organizer. The settings are not cached * inside the class but read/written directly from/to disc diff --git a/src/settingsutilities.cpp b/src/settingsutilities.cpp new file mode 100644 index 00000000..7ac95b5f --- /dev/null +++ b/src/settingsutilities.cpp @@ -0,0 +1,247 @@ +#include "settingsutilities.h" +#include "expanderwidget.h" +#include + +using namespace MOBase; + +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; + } + } +} + +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)); +} + +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, ""); +} + + +ScopedGroup::ScopedGroup(QSettings& s, const QString& name) + : m_settings(s), m_name(name) +{ + m_settings.beginGroup(m_name); +} + +ScopedGroup::~ScopedGroup() +{ + m_settings.endGroup(); +} + +void ScopedGroup::remove(const QString& key) +{ + removeImpl(m_settings, settingName(m_name, key), "", key); +} + +QStringList ScopedGroup::keys() const +{ + return m_settings.childKeys(); +} + + +ScopedReadArray::ScopedReadArray(QSettings& s, const QString& section) + : m_settings(s), m_count(0) +{ + m_count = m_settings.beginReadArray(section); +} + +ScopedReadArray::~ScopedReadArray() +{ + m_settings.endArray(); +} + +int ScopedReadArray::count() const +{ + return m_count; +} + +QStringList ScopedReadArray::keys() const +{ + return m_settings.childKeys(); +} + + +ScopedWriteArray::ScopedWriteArray(QSettings& s, const QString& section) + : m_settings(s), m_section(section), m_i(0) +{ + m_settings.beginWriteArray(section); +} + +ScopedWriteArray::~ScopedWriteArray() +{ + m_settings.endArray(); +} + +void ScopedWriteArray::next() +{ + m_settings.setArrayIndex(m_i); + ++m_i; +} + + +QString widgetNameWithTopLevel(const QWidget* widget) +{ + QStringList components; + + auto* tl = widget->window(); + + if (tl == widget) { + // this is a top level widget, such as a dialog + components.push_back(widget->objectName()); + } else { + // this is a widget + const auto toplevelName = tl->objectName(); + if (!toplevelName.isEmpty()) { + components.push_back(toplevelName); + } + + const auto widgetName = widget->objectName(); + if (!widgetName.isEmpty()) { + components.push_back(widgetName); + } + } + + if (components.isEmpty()) { + // can't do much + return "unknown_widget"; + } + + return components.join("_"); +} + +QString widgetName(const QMainWindow* w) +{ + return w->objectName(); +} + +QString widgetName(const QHeaderView* w) +{ + return widgetNameWithTopLevel(w->parentWidget()); +} + +QString widgetName(const ExpanderWidget* w) +{ + return widgetNameWithTopLevel(w->button()); +} + +QString widgetName(const QWidget* w) +{ + return widgetNameWithTopLevel(w); +} + +QString dockSettingName(const QDockWidget* dock) +{ + return "MainWindow_docks_" + dock->objectName() + "_size"; +} + +QString indexSettingName(const QWidget* widget) +{ + return widgetNameWithTopLevel(widget) + "_index"; +} + +QString checkedSettingName(const QAbstractButton* b) +{ + return widgetNameWithTopLevel(b) + "_checked"; +} + +void warnIfNotCheckable(const QAbstractButton* b) +{ + if (!b->isCheckable()) { + log::warn( + "button '{}' used in the settings as a checkbox or radio button " + "but is not checkable", b->objectName()); + } +} + + +bool setWindowsCredential(const QString key, const QString data) +{ + QString finalKey("ModOrganizer2_" + key); + wchar_t* keyData = new wchar_t[finalKey.size()+1]; + finalKey.toWCharArray(keyData); + keyData[finalKey.size()] = L'\0'; + bool result = false; + if (data.isEmpty()) { + result = CredDeleteW(keyData, CRED_TYPE_GENERIC, 0); + if (!result) + if (GetLastError() == ERROR_NOT_FOUND) + result = true; + } else { + wchar_t* charData = new wchar_t[data.size()]; + data.toWCharArray(charData); + + CREDENTIALW cred = {}; + cred.Flags = 0; + cred.Type = CRED_TYPE_GENERIC; + cred.TargetName = keyData; + cred.CredentialBlob = (LPBYTE)charData; + cred.CredentialBlobSize = sizeof(wchar_t) * data.size(); + cred.Persist = CRED_PERSIST_LOCAL_MACHINE; + + result = CredWriteW(&cred, 0); + delete[] charData; + } + delete[] keyData; + return result; +} + +QString getWindowsCredential(const QString key) +{ + QString result; + QString finalKey("ModOrganizer2_" + key); + wchar_t* keyData = new wchar_t[finalKey.size()+1]; + finalKey.toWCharArray(keyData); + keyData[finalKey.size()] = L'\0'; + PCREDENTIALW creds; + if (CredReadW(keyData, 1, 0, &creds)) { + wchar_t *charData = (wchar_t *)creds->CredentialBlob; + result = QString::fromWCharArray(charData, creds->CredentialBlobSize / sizeof(wchar_t)); + CredFree(creds); + } else { + const auto e = GetLastError(); + if (e != ERROR_NOT_FOUND) { + log::error("Retrieving encrypted data failed: {}", formatSystemMessage(e)); + } + } + delete[] keyData; + return result; +} diff --git a/src/settingsutilities.h b/src/settingsutilities.h new file mode 100644 index 00000000..b70e55ef --- /dev/null +++ b/src/settingsutilities.h @@ -0,0 +1,266 @@ +#ifndef SETTINGSUTILITIES_H +#define SETTINGSUTILITIES_H + +#include + +class ExpanderWidget; + +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); + + +QString settingName(const QString& section, const QString& 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); + + +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); +void removeSection(QSettings& settings, const QString& section); + + +class ScopedGroup +{ +public: + ScopedGroup(QSettings& s, const QString& name); + ~ScopedGroup(); + + 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); + + QStringList keys() const; + + 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& section); + ~ScopedReadArray(); + + 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; + QStringList keys() const; + +private: + QSettings& m_settings; + int m_count; +}; + + +class ScopedWriteArray +{ +public: + ScopedWriteArray(QSettings& s, const QString& section); + ~ScopedWriteArray(); + + ScopedWriteArray(const ScopedWriteArray&) = delete; + ScopedWriteArray& operator=(const ScopedWriteArray&) = delete; + + void next(); + + template + void set(const QString& key, const T& value) + { + const auto displayName = QString("%1/%2\\%3") + .arg(m_section) + .arg(m_i) + .arg(key); + + setImpl(m_settings, displayName, "", key, value); + } + +private: + QSettings& m_settings; + QString m_section; + int m_i; +}; + + +QString widgetNameWithTopLevel(const QWidget* widget); +QString widgetName(const QMainWindow* w); +QString widgetName(const QHeaderView* w); +QString widgetName(const ExpanderWidget* w); +QString widgetName(const QWidget* w); + +template +QString geoSettingName(const Widget* widget) +{ + return widgetName(widget) + "_geometry"; +} + +template +QString stateSettingName(const Widget* widget) +{ + return widgetName(widget) + "_state"; +} + +template +QString visibilitySettingName(const Widget* widget) +{ + return widgetName(widget) + "_visibility"; +} + +QString dockSettingName(const QDockWidget* dock); +QString indexSettingName(const QWidget* widget); +QString checkedSettingName(const QAbstractButton* b); + +void warnIfNotCheckable(const QAbstractButton* b); + +bool setWindowsCredential(const QString key, const QString data); +QString getWindowsCredential(const QString key); + +#endif // SETTINGSUTILITIES_H -- cgit v1.3.1 From 209c27c7a27e2f6cb34f122a929c15eb3d1e60b7 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Mon, 2 Sep 2019 15:47:21 -0400 Subject: only remove section when the array is larger, prevents logging changes when nothing actually changed changed back section names that were originally lowercase, arrays end up in two different sections --- src/settings.cpp | 69 ++++++++++++++++++++++++++++++----------------- src/settingsutilities.cpp | 8 +++--- src/settingsutilities.h | 4 ++- 3 files changed, 52 insertions(+), 29 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/settings.cpp b/src/settings.cpp index 14189be3..8ae7c343 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -221,9 +221,19 @@ std::vector> Settings::executables() const void Settings::setExecutables(const std::vector>& v) { - removeSection(m_Settings, "customExecutables"); + const auto current = executables(); - ScopedWriteArray swa(m_Settings, "customExecutables"); + if (current == v) { + // no change + return; + } + + if (current.size() > v.size()) { + // Qt can't remove array elements, the section must be cleared + removeSection(m_Settings, "customExecutables"); + } + + ScopedWriteArray swa(m_Settings, "customExecutables", v.size()); for (const auto& map : v) { swa.next(); @@ -1156,9 +1166,9 @@ void PluginSettings::addBlacklistPlugin(const QString &fileName) void PluginSettings::writePluginBlacklist() { - removeSection(m_Settings, "PluginBlacklist"); + removeSection(m_Settings, "pluginBlacklist"); - ScopedWriteArray swa(m_Settings, "PluginBlacklist"); + ScopedWriteArray swa(m_Settings, "pluginBlacklist"); for (const QString &plugin : m_PluginBlacklist) { swa.next(); @@ -1222,7 +1232,7 @@ std::map PathSettings::recent() const { std::map map; - ScopedReadArray sra(m_Settings, "RecentDirectories"); + ScopedReadArray sra(m_Settings, "recentDirectories"); sra.for_each([&] { const QVariant name = sra.get("name"); @@ -1238,9 +1248,14 @@ std::map PathSettings::recent() const void PathSettings::setRecent(const std::map& map) { - removeSection(m_Settings, "RecentDirectories"); + const auto current = recent(); - ScopedWriteArray swa(m_Settings, "recentDirectories"); + if (current.size() > map.size()) { + // Qt can't remove array elements, the section must be cleared + removeSection(m_Settings, "recentDirectories"); + } + + ScopedWriteArray swa(m_Settings, "recentDirectories", map.size()); for (auto&& p : map) { swa.next(); @@ -1472,33 +1487,37 @@ ServerList NetworkSettings::serversFromOldMap() const return list; } -void NetworkSettings::updateServers(ServerList servers) +void NetworkSettings::updateServers(ServerList newServers) { // clean up unavailable servers - servers.cleanup(); + newServers.cleanup(); - removeSection(m_Settings, "Servers"); + const auto current = servers(); - { - ScopedWriteArray swa(m_Settings, "Servers"); + if (current.size() > newServers.size()) { + // Qt can't remove array elements, the section must be cleared + removeSection(m_Settings, "Servers"); + } - for (const auto& server : servers) { - swa.next(); - swa.set("name", server.name()); - swa.set("premium", server.isPremium()); - swa.set("lastSeen", server.lastSeen().toString(Qt::ISODate)); - swa.set("preferred", server.preferred()); + ScopedWriteArray swa(m_Settings, "Servers", newServers.size()); - QString lastDownloads; - for (const auto& speed : server.lastDownloads()) { - if (speed > 0) { - lastDownloads += QString("%1 ").arg(speed); - } - } + for (const auto& server : newServers) { + swa.next(); - swa.set("lastDownloads", lastDownloads.trimmed()); + 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()) { + if (speed > 0) { + lastDownloads += QString("%1 ").arg(speed); + } } + + swa.set("lastDownloads", lastDownloads.trimmed()); } } diff --git a/src/settingsutilities.cpp b/src/settingsutilities.cpp index 7ac95b5f..d5e2dd9a 100644 --- a/src/settingsutilities.cpp +++ b/src/settingsutilities.cpp @@ -100,10 +100,12 @@ QStringList ScopedReadArray::keys() const } -ScopedWriteArray::ScopedWriteArray(QSettings& s, const QString& section) - : m_settings(s), m_section(section), m_i(0) +ScopedWriteArray::ScopedWriteArray( + QSettings& s, const QString& section, std::size_t size) + : m_settings(s), m_section(section), m_i(0) { - m_settings.beginWriteArray(section); + m_settings.beginWriteArray( + section, size == NoSize ? -1 : static_cast(size)); } ScopedWriteArray::~ScopedWriteArray() diff --git a/src/settingsutilities.h b/src/settingsutilities.h index b70e55ef..ca754759 100644 --- a/src/settingsutilities.h +++ b/src/settingsutilities.h @@ -204,7 +204,9 @@ private: class ScopedWriteArray { public: - ScopedWriteArray(QSettings& s, const QString& section); + static const auto NoSize = std::numeric_limits::max(); + + ScopedWriteArray(QSettings& s, const QString& section, std::size_t size=NoSize); ~ScopedWriteArray(); ScopedWriteArray(const ScopedWriteArray&) = delete; -- cgit v1.3.1 From 7f0fa1069f07d90a92be7073b11bab86bac7b2d2 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Mon, 2 Sep 2019 16:09:31 -0400 Subject: don't log widget and geometry setting changes fixed mod info dialog tab order using different settings for read and write mod info dialog now doesn't complain when no tab order exists in the settings only remove section when the array is larger, prevents logging changes when nothing actually changed --- src/modinfodialog.cpp | 9 ++++++--- src/settings.cpp | 27 ++++++++++++++++++++------- src/settings.h | 2 +- src/settingsutilities.cpp | 18 ++++++++++++++++++ src/settingsutilities.h | 6 ++++++ 5 files changed, 51 insertions(+), 11 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/modinfodialog.cpp b/src/modinfodialog.cpp index 2178ef34..c7e071ad 100644 --- a/src/modinfodialog.cpp +++ b/src/modinfodialog.cpp @@ -383,9 +383,12 @@ void ModInfoDialog::reAddTabs( // ordered tab names from settings const auto orderedNames = m_core->settings().geometry().modInfoTabOrder(); - // whether the tabs can be sorted; if the object name of a tab widget is not - // found in orderedNames, the list cannot be sorted safely - bool canSort = true; + // whether the tabs can be sorted + // + // if the object name of a tab widget is not found in orderedNames, the list + // cannot be sorted safely; if the list is empty, it's probably a first run + // and there's nothing to sort + bool canSort = !orderedNames.empty(); // gathering visible tabs std::vector visibleTabs; diff --git a/src/settings.cpp b/src/settings.cpp index 8ae7c343..a33005b6 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -210,7 +210,7 @@ std::vector> Settings::executables() const std::map map; for (auto&& key : sra.keys()) { - map[key] = m_Settings.value(key); + map[key] = sra.get(key); } v.push_back(map); @@ -693,7 +693,7 @@ QStringList GeometrySettings::modInfoTabOrder() const } } else { // string list since 2.2.1 - QString string = m_Settings.value("mod_info_tab_order").toString(); + QString string = get(m_Settings, "Widgets", "ModInfoTabOrder", ""); QTextStream stream(&string); while (!stream.atEnd()) { @@ -708,7 +708,7 @@ QStringList GeometrySettings::modInfoTabOrder() const void GeometrySettings::setModInfoTabOrder(const QString& names) { - set(m_Settings, "Geometry", "mod_info_tab_order", names); + set(m_Settings, "Widgets", "ModInfoTabOrder", names); } void GeometrySettings::centerOnMainWindowMonitor(QWidget* w) @@ -1061,13 +1061,21 @@ void PluginSettings::clearPlugins() { m_Plugins.clear(); m_PluginSettings.clear(); - m_PluginBlacklist.clear(); + m_PluginBlacklist = readPluginBlacklist(); +} + +QSet PluginSettings::readPluginBlacklist() const +{ + QSet set; + ScopedReadArray sra(m_Settings, "pluginBlacklist"); sra.for_each([&]{ - m_PluginBlacklist.insert(sra.get("name")); + set.insert(sra.get("name")); }); + + return set; } void PluginSettings::registerPlugin(IPlugin *plugin) @@ -1166,9 +1174,14 @@ void PluginSettings::addBlacklistPlugin(const QString &fileName) void PluginSettings::writePluginBlacklist() { - removeSection(m_Settings, "pluginBlacklist"); + const auto current = readPluginBlacklist(); + + if (current.size() > m_PluginBlacklist.size()) { + // Qt can't remove array elements, the section must be cleared + removeSection(m_Settings, "pluginBlacklist"); + } - ScopedWriteArray swa(m_Settings, "pluginBlacklist"); + ScopedWriteArray swa(m_Settings, "pluginBlacklist", m_PluginBlacklist.size()); for (const QString &plugin : m_PluginBlacklist) { swa.next(); diff --git a/src/settings.h b/src/settings.h index 68cfb9b7..2ff8da1c 100644 --- a/src/settings.h +++ b/src/settings.h @@ -261,8 +261,8 @@ private: QMap m_PluginDescriptions; QSet m_PluginBlacklist; - void readPluginBlacklist(); void writePluginBlacklist(); + QSet readPluginBlacklist() const; }; diff --git a/src/settingsutilities.cpp b/src/settingsutilities.cpp index d5e2dd9a..7a9dcc35 100644 --- a/src/settingsutilities.cpp +++ b/src/settingsutilities.cpp @@ -4,8 +4,26 @@ using namespace MOBase; +bool shouldLogSetting(const QString& displayName) +{ + // don't log Geometry/ and Widgets/, too noisy and not very useful + static const QStringList ignorePrefixes = {"Geometry/", "Widgets/"}; + + for (auto&& prefix : ignorePrefixes) { + if (displayName.startsWith(prefix, Qt::CaseInsensitive)) { + return false; + } + } + + return true; +} + void logRemoval(const QString& name) { + if (!shouldLogSetting(name)) { + return; + } + log::debug("setting '{}' removed", name); } diff --git a/src/settingsutilities.h b/src/settingsutilities.h index ca754759..d99abb06 100644 --- a/src/settingsutilities.h +++ b/src/settingsutilities.h @@ -24,10 +24,16 @@ struct ValueConverter>> }; +bool shouldLogSetting(const QString& displayName); + template void logChange( const QString& displayName, std::optional oldValue, const T& newValue) { + if (!shouldLogSetting(displayName)) { + return; + } + using VC = ValueConverter; if (oldValue) { -- cgit v1.3.1 From 2a2af36a380c83043ff57ea312e7705bb77e6971 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sun, 8 Sep 2019 00:27:45 -0400 Subject: documentation for settings renamed some PluginSettings members and moved them around --- src/organizercore.cpp | 10 +-- src/plugincontainer.cpp | 4 +- src/settings.cpp | 130 +++++++++++++++--------------- src/settings.h | 181 +++++++++++++++++++++++++++++++++--------- src/settingsdialogplugins.cpp | 10 +-- 5 files changed, 222 insertions(+), 113 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/organizercore.cpp b/src/organizercore.cpp index 1a89641d..91e16716 100644 --- a/src/organizercore.cpp +++ b/src/organizercore.cpp @@ -866,26 +866,26 @@ void OrganizerCore::modDataChanged(MOBase::IModInterface *) QVariant OrganizerCore::pluginSetting(const QString &pluginName, const QString &key) const { - return m_Settings.plugins().pluginSetting(pluginName, key); + return m_Settings.plugins().setting(pluginName, key); } void OrganizerCore::setPluginSetting(const QString &pluginName, const QString &key, const QVariant &value) { - m_Settings.plugins().setPluginSetting(pluginName, key, value); + m_Settings.plugins().setSetting(pluginName, key, value); } QVariant OrganizerCore::persistent(const QString &pluginName, const QString &key, const QVariant &def) const { - return m_Settings.plugins().pluginPersistent(pluginName, key, def); + return m_Settings.plugins().persistent(pluginName, key, def); } void OrganizerCore::setPersistent(const QString &pluginName, const QString &key, const QVariant &value, bool sync) { - m_Settings.plugins().setPluginPersistent(pluginName, key, value, sync); + m_Settings.plugins().setPersistent(pluginName, key, value, sync); } QString OrganizerCore::pluginDataPath() const @@ -2580,7 +2580,7 @@ void OrganizerCore::prepareStart() m_CurrentProfile->writeModlist(); m_CurrentProfile->createTweakedIniFile(); saveCurrentLists(); - m_Settings.game().setupLoadMechanism(); + m_Settings.game().loadMechanism().activate(m_Settings.game().loadMechanismType()); storeSettings(); } diff --git a/src/plugincontainer.cpp b/src/plugincontainer.cpp index 16a77387..c0706ba8 100644 --- a/src/plugincontainer.cpp +++ b/src/plugincontainer.cpp @@ -266,7 +266,7 @@ void PluginContainer::loadPlugins() "(Please note: If this is the first time you see this message for this plugin you may want to give it another try. " "The plugin may be able to recover from the problem)").arg(fileName), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) == QMessageBox::Yes) { - m_Organizer->settings().plugins().addBlacklistPlugin(fileName); + m_Organizer->settings().plugins().addBlacklist(fileName); } loadCheck.close(); } @@ -279,7 +279,7 @@ void PluginContainer::loadPlugins() while (iter.hasNext()) { iter.next(); - if (m_Organizer->settings().plugins().pluginBlacklisted(iter.fileName())) { + if (m_Organizer->settings().plugins().blacklisted(iter.fileName())) { log::debug("plugin \"{}\" blacklisted", iter.fileName()); continue; } diff --git a/src/settings.cpp b/src/settings.cpp index a33005b6..ce9676ea 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -512,9 +512,9 @@ const LoadMechanism& GameSettings::loadMechanism() const return m_LoadMechanism; } -void GameSettings::setupLoadMechanism() +LoadMechanism& GameSettings::loadMechanism() { - m_LoadMechanism.activate(loadMechanismType()); + return m_LoadMechanism; } bool GameSettings::hideUncheckedPlugins() const @@ -1063,19 +1063,7 @@ void PluginSettings::clearPlugins() m_PluginSettings.clear(); m_PluginBlacklist.clear(); - m_PluginBlacklist = readPluginBlacklist(); -} - -QSet PluginSettings::readPluginBlacklist() const -{ - QSet set; - - ScopedReadArray sra(m_Settings, "pluginBlacklist"); - sra.for_each([&]{ - set.insert(sra.get("name")); - }); - - return set; + m_PluginBlacklist = readBlacklist(); } void PluginSettings::registerPlugin(IPlugin *plugin) @@ -1106,12 +1094,12 @@ void PluginSettings::registerPlugin(IPlugin *plugin) } } -bool PluginSettings::pluginBlacklisted(const QString &fileName) const +std::vector PluginSettings::plugins() const { - return m_PluginBlacklist.contains(fileName); + return m_Plugins; } -QVariant PluginSettings::pluginSetting(const QString &pluginName, const QString &key) const +QVariant PluginSettings::setting(const QString &pluginName, const QString &key) const { auto iterPlugin = m_PluginSettings.find(pluginName); if (iterPlugin == m_PluginSettings.end()) { @@ -1126,7 +1114,7 @@ QVariant PluginSettings::pluginSetting(const QString &pluginName, const QString return *iterSetting; } -void PluginSettings::setPluginSetting(const QString &pluginName, const QString &key, const QVariant &value) +void PluginSettings::setSetting(const QString &pluginName, const QString &key, const QVariant &value) { auto iterPlugin = m_PluginSettings.find(pluginName); @@ -1141,7 +1129,27 @@ void PluginSettings::setPluginSetting(const QString &pluginName, const QString & set(m_Settings, "Plugins", pluginName + "/" + key, value); } -QVariant PluginSettings::pluginPersistent(const QString &pluginName, const QString &key, const QVariant &def) const +QVariantMap PluginSettings::settings(const QString &pluginName) const +{ + return m_PluginSettings[pluginName]; +} + +void PluginSettings::setSettings(const QString &pluginName, const QVariantMap& map) +{ + m_PluginSettings[pluginName] = map; +} + +QVariantMap PluginSettings::descriptions(const QString &pluginName) const +{ + return m_PluginDescriptions[pluginName]; +} + +void PluginSettings::setDescriptions(const QString &pluginName, const QVariantMap& map) +{ + m_PluginDescriptions[pluginName] = map; +} + +QVariant PluginSettings::persistent(const QString &pluginName, const QString &key, const QVariant &def) const { if (!m_PluginSettings.contains(pluginName)) { return def; @@ -1150,7 +1158,7 @@ QVariant PluginSettings::pluginPersistent(const QString &pluginName, const QStri return get(m_Settings, "PluginPersistance", pluginName + "/" + key, def); } -void PluginSettings::setPluginPersistent( +void PluginSettings::setPersistent( const QString &pluginName, const QString &key, const QVariant &value, bool sync) { if (!m_PluginSettings.contains(pluginName)) { @@ -1165,74 +1173,70 @@ void PluginSettings::setPluginPersistent( m_Settings.sync(); } } - -void PluginSettings::addBlacklistPlugin(const QString &fileName) +void PluginSettings::addBlacklist(const QString &fileName) { m_PluginBlacklist.insert(fileName); - writePluginBlacklist(); + writeBlacklist(); } -void PluginSettings::writePluginBlacklist() +bool PluginSettings::blacklisted(const QString &fileName) const { - const auto current = readPluginBlacklist(); - - if (current.size() > m_PluginBlacklist.size()) { - // Qt can't remove array elements, the section must be cleared - removeSection(m_Settings, "pluginBlacklist"); - } + return m_PluginBlacklist.contains(fileName); +} - ScopedWriteArray swa(m_Settings, "pluginBlacklist", m_PluginBlacklist.size()); +void PluginSettings::setBlacklist(const QStringList& pluginNames) +{ + m_PluginBlacklist.clear(); - for (const QString &plugin : m_PluginBlacklist) { - swa.next(); - swa.set("name", plugin); + for (const auto& name : pluginNames) { + m_PluginBlacklist.insert(name); } } -QVariantMap PluginSettings::pluginSettings(const QString &pluginName) const +const QSet& PluginSettings::blacklist() const { - return m_PluginSettings[pluginName]; + return m_PluginBlacklist; } -void PluginSettings::setPluginSettings(const QString &pluginName, const QVariantMap& map) +void PluginSettings::save() { - m_PluginSettings[pluginName] = map; -} + for (auto iterPlugins=m_PluginSettings.begin(); iterPlugins!=m_PluginSettings.end(); ++iterPlugins) { + for (auto iterSettings=iterPlugins->begin(); iterSettings!=iterPlugins->end(); ++iterSettings) { + const auto key = iterPlugins.key() + "/" + iterSettings.key(); + set(m_Settings, "Plugins", key, iterSettings.value()); + } + } -QVariantMap PluginSettings::pluginDescriptions(const QString &pluginName) const -{ - return m_PluginDescriptions[pluginName]; + writeBlacklist(); } -void PluginSettings::pluginDescriptions(const QString &pluginName, const QVariantMap& map) +void PluginSettings::writeBlacklist() { - m_PluginDescriptions[pluginName] = map; -} + const auto current = readBlacklist(); -const QSet& PluginSettings::pluginBlacklist() const -{ - return m_PluginBlacklist; -} + if (current.size() > m_PluginBlacklist.size()) { + // Qt can't remove array elements, the section must be cleared + removeSection(m_Settings, "pluginBlacklist"); + } -void PluginSettings::setPluginBlacklist(const QStringList& pluginNames) -{ - m_PluginBlacklist.clear(); + ScopedWriteArray swa(m_Settings, "pluginBlacklist", m_PluginBlacklist.size()); - for (const auto& name : pluginNames) { - m_PluginBlacklist.insert(name); + for (const QString &plugin : m_PluginBlacklist) { + swa.next(); + swa.set("name", plugin); } } -void PluginSettings::save() +QSet PluginSettings::readBlacklist() const { - for (auto iterPlugins=m_PluginSettings.begin(); iterPlugins!=m_PluginSettings.end(); ++iterPlugins) { - for (auto iterSettings=iterPlugins->begin(); iterSettings!=iterPlugins->end(); ++iterSettings) { - const auto key = iterPlugins.key() + "/" + iterSettings.key(); - set(m_Settings, "Plugins", key, iterSettings.value()); - } - } + QSet set; - writePluginBlacklist(); + ScopedReadArray sra(m_Settings, "pluginBlacklist"); + sra.for_each([&]{ + set.insert(sra.get("name")); + }); + + return set; } diff --git a/src/settings.h b/src/settings.h index 2ff8da1c..d3926d72 100644 --- a/src/settings.h +++ b/src/settings.h @@ -40,6 +40,10 @@ class ServerList; class Settings; class ExpanderWidget; + +// helper class that calls restoreGeometry() in the constructor and +// saveGeometry() in the destructor +// class GeometrySaver { public: @@ -52,48 +56,57 @@ private: }; +// setting for the currently managed game +// class GameSettings { public: GameSettings(QSettings& setting); + // game plugin + // const MOBase::IPluginGame* plugin(); void setPlugin(const MOBase::IPluginGame* gamePlugin); - /** - * whether files of the core game are forced-enabled so the user can't - * accidentally disable them - */ + // whether files of the core game are forced-enabled so the user can't + // accidentally disable them + // bool forceEnableCoreFiles() const; void setForceEnableCoreFiles(bool b); - /** - * the directory where the managed game is stored (with native separators) - **/ + // the directory where the managed game is stored + // std::optional directory() const; void setDirectory(const QString& path); + // the name of the managed game + // std::optional name() const; void setName(const QString& name); + // the edition of the managed game + // std::optional edition() const; void setEdition(const QString& name); + // the current profile name + // std::optional selectedProfileName() const; void setSelectedProfileName(const QString& name); - /** - * @return the load mechanism to be used - **/ + // load mechanism type + // LoadMechanism::EMechanism loadMechanismType() const; void setLoadMechanism(LoadMechanism::EMechanism m); + + // load mechanism object + // const LoadMechanism& loadMechanism() const; - void setupLoadMechanism(); + LoadMechanism& loadMechanism(); - /** - * @return true if the user wants unchecked plugins (esp, esm) should be hidden from - * the virtual data directory - **/ + // whether the user wants unchecked plugins (esp, esm) to be hidden from + // the virtual data directory + // bool hideUncheckedPlugins() const; void setHideUncheckedPlugins(bool b); @@ -104,11 +117,26 @@ private: }; +// geometry settings for various widgets; this should contain any setting that +// can get invalid through UI changes or when users change display settings +// (resolution, monitors, etc.); see WidgetSettings for the counterpart +// +// all these settings are stored under [Geometry] and get wiped when the +// "reset geometry settings" button is clicked in the settings +// +// saveGeometry(), restoreGeometry(), saveState() and restoreState() call the +// same functions on the given widget +// class GeometrySettings { public: GeometrySettings(QSettings& s); + // asks the settings to get reset + // + // this gets called from the settings dialog and gets picked up in + // resetIfNeeded(), called from runApplication() just before exiting + // void requestReset(); void resetIfNeeded(); @@ -137,10 +165,18 @@ public: void saveDocks(const QMainWindow* w); void restoreDocks(QMainWindow* w) const; + // this should be a generic "tab order" setting, but it only happens for the + // mod info dialog right now + // QStringList modInfoTabOrder() const; void setModInfoTabOrder(const QString& names); + // assumes the given widget is a top-level + // void centerOnMainWindowMonitor(QWidget* w); + + // saves the monitor number of the given window + // void saveMainWindowMonitor(const QMainWindow* w); private: @@ -149,33 +185,52 @@ private: }; +// widget settings that should stay valid regardless of UI changes or when users +// change display settings (resolution, monitors, etc.); see GeometrySettings +// for the counterpart +// class WidgetSettings { public: WidgetSettings(QSettings& s); + // selected index for a combobox + // std::optional index(const QComboBox* cb) const; void saveIndex(const QComboBox* cb); void restoreIndex(QComboBox* cb, std::optional def={}) const; + // selected tab index for a tab widget + // std::optional index(const QTabWidget* w) const; void saveIndex(const QTabWidget* w); void restoreIndex(QTabWidget* w, std::optional def={}) const; + // check state for a checkable button + // std::optional checked(const QAbstractButton* w) const; void saveChecked(const QAbstractButton* w); void restoreChecked(QAbstractButton* w, std::optional def={}) const; + // returns the remembered button for a question dialog, or NoButton if the + // user hasn't saved the choice + // MOBase::QuestionBoxMemory::Button questionButton( const QString& windowName, const QString& filename) const; + // sets the button to be remembered for the given window + // void setQuestionWindowButton( const QString& windowName, MOBase::QuestionBoxMemory::Button button); + // sets the button to be remembered for the given file + // void setQuestionFileButton( const QString& windowName, const QString& filename, MOBase::QuestionBoxMemory::Button choice); + // wipes all the remembered buttons + // void resetQuestionButtons(); private: @@ -183,13 +238,13 @@ private: }; +// various color settings +// class ColorSettings { public: ColorSettings(QSettings& s); - void setCrashDumpsMax(int i) const; - QColor modlistOverwrittenLoose() const; void setModlistOverwrittenLoose(const QColor& c); @@ -212,46 +267,91 @@ public: void setPreviousSeparatorColor(const QColor& c) const; void removePreviousSeparatorColor(); - /** - * @brief color the scrollbar of the mod list for custom separator colors? - * @return the state of the setting - */ + // whether the scrollbar of the mod list should have colors for custom + // separator colors + // bool colorSeparatorScrollbar() const; void setColorSeparatorScrollbar(bool b); - static QColor idealTextColor(const QColor& rBackgroundColor); + // returns a color with a good contrast for the given background + // + static QColor idealTextColor(const QColor& rBackgroundColor); private: QSettings& m_Settings; }; +// settings about plugins +// class PluginSettings { public: PluginSettings(QSettings& settings); + + // forgets all the plugins + // void clearPlugins(); + + // adds the given plugin to the list and loads all of its settings + // void registerPlugin(MOBase::IPlugin *plugin); - void addPluginSettings(const std::vector &plugins); - QVariant pluginSetting(const QString &pluginName, const QString &key) const; - void setPluginSetting(const QString &pluginName, const QString &key, const QVariant &value); - QVariant pluginPersistent(const QString &pluginName, const QString &key, const QVariant &def) const; - void setPluginPersistent(const QString &pluginName, const QString &key, const QVariant &value, bool sync); - void addBlacklistPlugin(const QString &fileName); - bool pluginBlacklisted(const QString &fileName) const; - void setPluginBlacklist(const QStringList& pluginNames); - std::vector plugins() const { return m_Plugins; } + // returns all the registered plugins + // + std::vector plugins() const; + + + // returns the plugin setting for the given key + // + QVariant setting(const QString &pluginName, const QString &key) const; + + // sets the plugin setting for the given key + // + void setSetting(const QString &pluginName, const QString &key, const QVariant &value); + + // returns all settings + // + QVariantMap settings(const QString &pluginName) const; + + // overwrites all settings + // + void setSettings(const QString &pluginName, const QVariantMap& map); + + // returns all descriptions + // + QVariantMap descriptions(const QString &pluginName) const; - QVariantMap pluginSettings(const QString &pluginName) const; - void setPluginSettings(const QString &pluginName, const QVariantMap& map); + // overwrites all descriptions + // + void setDescriptions(const QString &pluginName, const QVariantMap& map); - QVariantMap pluginDescriptions(const QString &pluginName) const; - void pluginDescriptions(const QString &pluginName, const QVariantMap& map); - const QSet& pluginBlacklist() const; + // ? + QVariant persistent(const QString &pluginName, const QString &key, const QVariant &def) const; + void setPersistent(const QString &pluginName, const QString &key, const QVariant &value, bool sync); + + // adds the given plugin to the blacklist + // + void addBlacklist(const QString &fileName); + + // returns whether the given plugin is blacklisted + // + bool blacklisted(const QString &fileName) const; + + // overwrites the whole blacklist + // + void setBlacklist(const QStringList& pluginNames); + + // returns the blacklist + // + const QSet& blacklist() const; + + + // commits all the settings to the ini + // void save(); private: @@ -261,8 +361,13 @@ private: QMap m_PluginDescriptions; QSet m_PluginBlacklist; - void writePluginBlacklist(); - QSet readPluginBlacklist() const; + // commits the blacklist to the ini + // + void writeBlacklist(); + + // reads the blacklist from the ini + // + QSet readBlacklist() const; }; diff --git a/src/settingsdialogplugins.cpp b/src/settingsdialogplugins.cpp index 956971fe..c84d0556 100644 --- a/src/settingsdialogplugins.cpp +++ b/src/settingsdialogplugins.cpp @@ -17,14 +17,14 @@ PluginsSettingsTab::PluginsSettingsTab(Settings& s, SettingsDialog& d) continue; QListWidgetItem *listItem = new QListWidgetItem(plugin->name(), ui->pluginsList); listItem->setData(Qt::UserRole, QVariant::fromValue((void*)plugin)); - listItem->setData(Qt::UserRole + 1, settings().plugins().pluginSettings(plugin->name())); - listItem->setData(Qt::UserRole + 2, settings().plugins().pluginDescriptions(plugin->name())); + listItem->setData(Qt::UserRole + 1, settings().plugins().settings(plugin->name())); + listItem->setData(Qt::UserRole + 2, settings().plugins().descriptions(plugin->name())); ui->pluginsList->addItem(listItem); handledNames.insert(plugin->name()); } // display plugin blacklist - for (const QString &pluginName : settings().plugins().pluginBlacklist()) { + for (const QString &pluginName : settings().plugins().blacklist()) { ui->pluginBlacklist->addItem(pluginName); } @@ -42,7 +42,7 @@ void PluginsSettingsTab::update() // transfer plugin settings to in-memory structure for (int i = 0; i < ui->pluginsList->count(); ++i) { QListWidgetItem *item = ui->pluginsList->item(i); - settings().plugins().setPluginSettings( + settings().plugins().setSettings( item->text(), item->data(Qt::UserRole + 1).toMap()); } @@ -52,7 +52,7 @@ void PluginsSettingsTab::update() names.push_back(item->text()); } - settings().plugins().setPluginBlacklist(names); + settings().plugins().setBlacklist(names); settings().plugins().save(); } -- cgit v1.3.1 From c9397c3909cf3b2aa6c2ba5b185799a552ed3485 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sun, 8 Sep 2019 00:53:10 -0400 Subject: more documentation for settings removed unused automaticLoginEnabled() --- src/settings.cpp | 7 +- src/settings.h | 231 +++++++++++++++++++++++++++++++++---------------------- 2 files changed, 138 insertions(+), 100 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/settings.cpp b/src/settings.cpp index ce9676ea..7c8c34be 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -1564,12 +1564,7 @@ NexusSettings::NexusSettings(Settings& parent, QSettings& settings) { } -bool NexusSettings::automaticLoginEnabled() const -{ - return get(m_Settings, "Settings", "nexus_login", false); -} - -bool NexusSettings::apiKey(QString &apiKey) const +bool NexusSettings::apiKey(QString& apiKey) const { QString tempKey = getWindowsCredential("APIKEY"); if (tempKey.isEmpty()) diff --git a/src/settings.h b/src/settings.h index d3926d72..9dccf41d 100644 --- a/src/settings.h +++ b/src/settings.h @@ -371,25 +371,38 @@ private: }; +// paths for the game and various components +// +// if the 'resolve' parameter is true, %BASE_DIR% is expanded; it's set to +// false mostly in the settings dialog +// class PathSettings { public: PathSettings(QSettings& settings); QString base() const; - QString downloads(bool resolve = true) const; - QString mods(bool resolve = true) const; - QString cache(bool resolve = true) const; - QString profiles(bool resolve = true) const; - QString overwrite(bool resolve = true) const; - void setBase(const QString& path); + + QString downloads(bool resolve = true) const; void setDownloads(const QString& path); + + QString mods(bool resolve = true) const; void setMods(const QString& path); + + QString cache(bool resolve = true) const; void setCache(const QString& path); + + QString profiles(bool resolve = true) const; void setProfiles(const QString& path); + + QString overwrite(bool resolve = true) const; void setOverwrite(const QString& path); + + // map of names to directories, used to remember the last directory used in + // various file pickers + // std::map recent() const; void setRecent(const std::map& map); @@ -406,20 +419,28 @@ class NetworkSettings public: NetworkSettings(QSettings& settings); - /** - * @return true if the user disabled internet features - */ + // whether the user has disabled online features + // bool offlineMode() const; void setOfflineMode(bool b); - /** - * @return true if the user configured the use of a network proxy - */ + // whether the user wants to use the system proxy + // bool useProxy() const; void setUseProxy(bool b); + // add a new download speed to the list for the given server; each server + // remembers the last couple of download speeds and displays the average in + // the network settings + // void setDownloadSpeed(const QString &serverName, int bytesPerSecond); + + // known servers + // ServerList servers() const; + + // sets the servers + // void updateServers(ServerList servers); void dump() const; @@ -427,6 +448,8 @@ public: private: QSettings& m_Settings; + // for pre 2.2.1 ini files + // ServerList serversFromOldMap() const; }; @@ -441,57 +464,45 @@ enum class EndorsementState EndorsementState endorsementStateFromString(const QString& s); QString toString(EndorsementState s); + class NexusSettings { public: NexusSettings(Settings& parent, QSettings& settings); - /** - * @return true if the user has set up automatic login to nexus - **/ - bool automaticLoginEnabled() const; - - /** - * @brief retrieve the login information for nexus - * - * @param username (out) receives the user name for nexus - * @param password (out) received the password for nexus - * @return true if automatic login is active, false otherwise - **/ - bool apiKey(QString &apiKey) const; - - /** - * @brief set the nexus login information - * - * @param username username - * @param password password - */ + // if the key exists from the credentials store, puts it in `apiKey` and + // returns true; otherwise, returns false and leaves `apiKey` untouched + // + bool apiKey(QString& apiKey) const; + + // sets the api key in the credentials store, removes it if empty; returns + // false on errors + // bool setApiKey(const QString& apiKey); - /** - * @brief clears the nexus login information - */ + // removes the api key from the credentials store; returns false on errors + // bool clearApiKey(); - /** - * @brief returns whether an API key is currently stored - */ + // returns whether an API key is currently stored + // bool hasApiKey() const; - /** - * @return true if endorsement integration is enabled - */ + // returns whether endorsement integration is enabled + // bool endorsementIntegration() const; void setEndorsementIntegration(bool b) const; + // returns the endorsement state of MO itself + // EndorsementState endorsementState() const; void setEndorsementState(EndorsementState s); - /** - * @brief register MO as the handler for nxm links - * @param force set to true to enforce the registration dialog to show up, - * even if the user said earlier not to - */ + // registers MO as the handler for nxm links + // + // if 'force' is true, the registration dialog will be shown even if the user + // said earlier not to + // void registerAsNXMHandler(bool force); private: @@ -505,30 +516,34 @@ class SteamSettings public: SteamSettings(Settings& parent, QSettings& settings); - /** - * the steam appid is assigned by the steam platform to each product sold there. - * The appid may differ between different versions of a game so it may be impossible - * for Mod Organizer to automatically recognize it, though usually it does - * @return the steam appid for the game - **/ + // the steam appid is assigned by the steam platform to each product sold + // there. + // + // the appid may differ between different versions of a game so it may be + // impossible for MO to automatically recognize it, though usually it does + // QString appID() const; void setAppID(const QString& id); - /** - * @brief retrieve the login information for steam - * - * @param username (out) receives the user name for nexus - * @param password (out) received the password for nexus - * @return true if a username has been specified, false otherwise - **/ + // the steam username is stored in the ini, but the password is in the + // windows credentials store; both values are independent and either can be + // empty + // + // if the username exists in the ini, it is assigned to `username`; if not + // `username` is set to an empty string + // + // if the password exists in the credentials store, it is assigned to + // `password`; if not, `password` is set to an empty string + // + // returns whether _both_ the username and password have a value + // bool login(QString &username, QString &password) const; - /** - * @brief set the steam login information - * - * @param username username - * @param password password - */ + // sets the steam login; the username is saved in the ini file and the + // password in the credentials store + // + // if a value is empty, it is removed from its backing store + // void setLogin(QString username, QString password); private: @@ -542,45 +557,45 @@ class InterfaceSettings public: InterfaceSettings(QSettings& settings); - /** - * @return true if the GUI should be locked when running executables - */ + // whether the GUI should be locked when running executables + // bool lockGUI() const; void setLockGUI(bool b); + // filename of the theme + // std::optional styleName() const; void setStyleName(const QString& name); - /** - * @return true if the user chose compact downloads - */ + // whether to show compact downloads + // bool compactDownloads() const; void setCompactDownloads(bool b); - /** - * @return true if the user chose meta downloads - */ + // whether to show meta information for downloads + // bool metaDownloads() const; void setMetaDownloads(bool b); - /** - * @return true if the API counter should be hidden - */ + // whether the API counter should be hidden + // bool hideAPICounter() const; void setHideAPICounter(bool b); - /** - * @return true if the user wants to see non-official plugins installed outside MO in his mod list - */ + // whether the user wants to see non-official plugins installed outside MO in + // the mod list + // bool displayForeign() const; void setDisplayForeign(bool b); - /** - * @return short code of the configured language (corresponding to the translation files) - */ + // short code of the configured language (corresponding to the translation + // files) + // QString language(); void setLanguage(const QString& name); + // whether the given tutorial has been completed + // bool isTutorialCompleted(const QString& windowName) const; void setTutorialCompleted(const QString& windowName, bool b=true); @@ -594,12 +609,18 @@ class DiagnosticsSettings public: DiagnosticsSettings(QSettings& settings); + // log level for both MO and usvfs + // MOBase::log::Levels logLevel() const; void setLogLevel(MOBase::log::Levels level); + // crash dump type for both MO and usvfs + // CrashDumpsType crashDumpsType() const; void setCrashDumpsType(CrashDumpsType type); + // maximum number of dump files keps, for both MO and usvfs + // int crashDumpsMax() const; void setCrashDumpsMax(int n); @@ -608,10 +629,9 @@ private: }; -/** - * manages the settings for Mod Organizer. The settings are not cached - * inside the class but read/written directly from/to disc - **/ +// manages the settings for MO; the settings are accessed directly through a +// QSettings and so are not cached here +// class Settings : public QObject { Q_OBJECT; @@ -622,35 +642,52 @@ public: static Settings &instance(); + // name of the ini file + // QString filename() const; + // version of MO stored in the ini; this may be different from the current + // version if the user just updated + // std::optional version() const; + + // updates the settings to bring them up to date + // void processUpdates(const QVersionNumber& current, const QVersionNumber& last); + // whether MO has been started for the first time + // bool firstStart() const; void setFirstStart(bool b); + // configured executables + // std::vector> executables() const; void setExecutables(const std::vector>& v); + // whether to backup existing mods on install + // bool keepBackupOnInstall() const; void setKeepBackupOnInstall(bool b); + // blacklisted executables do not get hooked by usvfs; this list is managed + // by MO but given to usvfs when starting an executable + // QString executablesBlacklist() const; void setExecutablesBlacklist(const QString& s); - /** - * @brief sets the new motd hash - **/ + // ? looks obsolete, only used by dead code + // unsigned int motdHash() const; void setMotdHash(unsigned int hash); - /** - * @return true if the user wants to have archives being parsed to show conflicts and contents - */ + // whether archives should be parsed to show conflicts and contents + // bool archiveParsing() const; void setArchiveParsing(bool b); + // whether the user wants to upgrade to pre-releases + // bool usePrereleases() const; void setUsePrereleases(bool b); @@ -688,14 +725,20 @@ public: DiagnosticsSettings& diagnostics(); const DiagnosticsSettings& diagnostics() const; - + // makes sure the ini file is written to disk + // QSettings::Status sync() const; + void dump() const; public slots: + // this slot is connected to by various parts of MO + // void managedGameChanged(MOBase::IPluginGame const *gamePlugin); signals: + // these are fired from outside the settings, mostly by the settings dialog + // void languageChanged(const QString &newLanguage); void styleChanged(const QString &newStyle); -- cgit v1.3.1 From 4df40baea64d2355f4cb976aaf00f651e7cb4f60 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sun, 8 Sep 2019 01:23:17 -0400 Subject: clean up old settings when updating --- src/settings.cpp | 51 +++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 45 insertions(+), 6 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/settings.cpp b/src/settings.cpp index 7c8c34be..1288e92d 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -94,7 +94,22 @@ void Settings::processUpdates( return; } - if (lastVersion < QVersionNumber(2, 2, 0)) { + if (currentVersion == lastVersion) { + return; + } + + log::info( + "updating from {} to {}", + lastVersion.toString(), currentVersion.toString()); + + auto version = [&](const QVersionNumber& v, auto&& f) { + if (lastVersion < v) { + log::info("processing updates for {}", v.toString()); + f(); + } + }; + + version({2, 2, 0}, [&]{ remove(m_Settings, "Settings", "steam_password"); remove(m_Settings, "Settings", "nexus_username"); remove(m_Settings, "Settings", "nexus_password"); @@ -104,9 +119,9 @@ void Settings::processUpdates( remove(m_Settings, "Settings", "nmm_version"); removeSection(m_Settings, "Servers"); - } + }); - if (lastVersion < QVersionNumber(2, 2, 1)) { + version({2, 2, 1}, [&]{ remove(m_Settings, "General", "mod_info_tabs"); remove(m_Settings, "General", "mod_info_conflict_expanders"); remove(m_Settings, "General", "mod_info_conflicts"); @@ -114,15 +129,39 @@ void Settings::processUpdates( 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)) { + version({2, 2, 2}, [&]{ // log splitter is gone, it's a dock now remove(m_Settings, "General", "log_split"); - } + + // moved to widgets + remove(m_Settings, "General", "mod_info_conflicts_tab"); + remove(m_Settings, "General", "mod_info_conflicts_general_expanders"); + remove(m_Settings, "General", "mod_info_conflicts_general_overwrite"); + remove(m_Settings, "General", "mod_info_conflicts_general_noconflict"); + remove(m_Settings, "General", "mod_info_conflicts_general_overwritten"); + remove(m_Settings, "General", "mod_info_conflicts_advanced_list"); + remove(m_Settings, "General", "mod_info_conflicts_advanced_options"); + remove(m_Settings, "General", "mod_info_tab_order"); + remove(m_Settings, "General", "mod_info_dialog_images_show_dds"); + + // moved to geometry + remove(m_Settings, "General", "window_geometry"); + remove(m_Settings, "General", "window_state"); + remove(m_Settings, "General", "toolbar_size"); + remove(m_Settings, "General", "toolbar_button_style"); + remove(m_Settings, "General", "menubar_visible"); + remove(m_Settings, "General", "window_split"); + remove(m_Settings, "General", "window_monitor"); + remove(m_Settings, "General", "browser_geometry"); + remove(m_Settings, "General", "filters_visible"); + }); //save version in all case set(m_Settings, "General", "version", currentVersion.toString()); + + log::debug("updating done"); } QString Settings::filename() const -- cgit v1.3.1 From da212968ca404dd1840dc39a8c8cf41090a551a7 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sun, 8 Sep 2019 03:10:43 -0400 Subject: change the old servers map while processing updates instead of on-demand statusbar_visible is not used anymore --- src/settings.cpp | 99 +++++++++++++++++++++++++++++++------------------------- src/settings.h | 4 +++ 2 files changed, 59 insertions(+), 44 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/settings.cpp b/src/settings.cpp index 1288e92d..4a149726 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -104,7 +104,7 @@ void Settings::processUpdates( auto version = [&](const QVersionNumber& v, auto&& f) { if (lastVersion < v) { - log::info("processing updates for {}", v.toString()); + log::debug("processing updates for {}", v.toString()); f(); } }; @@ -152,10 +152,13 @@ void Settings::processUpdates( remove(m_Settings, "General", "toolbar_size"); remove(m_Settings, "General", "toolbar_button_style"); remove(m_Settings, "General", "menubar_visible"); + remove(m_Settings, "General", "statusbar_visible"); remove(m_Settings, "General", "window_split"); remove(m_Settings, "General", "window_monitor"); remove(m_Settings, "General", "browser_geometry"); remove(m_Settings, "General", "filters_visible"); + + m_Network.updateFromOldMap(); }); //save version in all case @@ -1469,23 +1472,6 @@ void NetworkSettings::setDownloadSpeed(const QString& name, int bytesPerSecond) ServerList NetworkSettings::servers() const { - // servers used to be a map of byte arrays until 2.2.1, it's now an array of - // individual values instead - // - // 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 - { - const QStringList keys = ScopedGroup(m_Settings, "Servers").keys(); - - if (!keys.empty() && keys[0] != "size") { - // old format - return serversFromOldMap(); - } - } - - - // post 2.2.1 format, array of values - ServerList list; { @@ -1517,32 +1503,6 @@ ServerList NetworkSettings::servers() const return list; } -ServerList NetworkSettings::serversFromOldMap() const -{ - // for 2.2.1 and before - - ServerList list; - const ScopedGroup sg(m_Settings, "Servers"); - - sg.for_each([&](auto&& serverKey) { - QVariantMap data = sg.get(serverKey); - - ServerInfo server( - serverKey, - data["premium"].toBool(), - data["lastSeen"].toDate(), - data["preferred"].toInt(), - {}); - - // ignoring download count and speed, it's now a list of values instead of - // a total - - list.add(std::move(server)); - }); - - return list; -} - void NetworkSettings::updateServers(ServerList newServers) { // clean up unavailable servers @@ -1577,6 +1537,57 @@ void NetworkSettings::updateServers(ServerList newServers) } } +void NetworkSettings::updateFromOldMap() +{ + // servers used to be a map of byte arrays until 2.2.1, it's now an array of + // individual values instead + // + // 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 + + // sanity check that this is really 2.2.1 + { + const QStringList keys = ScopedGroup(m_Settings, "Servers").keys(); + + for (auto&& k : keys) { + if (k == "size") { + // this looks like an array, so the upgrade was probably already done + return; + } + } + } + + const auto servers = serversFromOldMap(); + removeSection(m_Settings, "Servers"); + updateServers(servers); +} + +ServerList NetworkSettings::serversFromOldMap() const +{ + // for 2.2.1 and before + + ServerList list; + const ScopedGroup sg(m_Settings, "Servers"); + + sg.for_each([&](auto&& serverKey) { + QVariantMap data = sg.get(serverKey); + + ServerInfo server( + serverKey, + data["premium"].toBool(), + data["lastSeen"].toDate(), + data["preferred"].toInt(), + {}); + + // ignoring download count and speed, it's now a list of values instead of + // a total + + list.add(std::move(server)); + }); + + return list; +} + void NetworkSettings::dump() const { log::debug("servers:"); diff --git a/src/settings.h b/src/settings.h index 9dccf41d..91b87e29 100644 --- a/src/settings.h +++ b/src/settings.h @@ -443,6 +443,10 @@ public: // void updateServers(ServerList servers); + // for 2.2.1 and before, rewrites the old byte array map to the new format + // + void updateFromOldMap(); + void dump() const; private: -- cgit v1.3.1 From d863e62c6e2f3c0daa50e16a0206f59558a7bb7e Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sun, 8 Sep 2019 08:09:38 -0400 Subject: really remove ask_for_nexuspw, the 2.2.0 update code was using the wrong section --- src/settings.cpp | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src/settings.cpp') diff --git a/src/settings.cpp b/src/settings.cpp index 4a149726..1f066100 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -158,6 +158,10 @@ void Settings::processUpdates( remove(m_Settings, "General", "browser_geometry"); remove(m_Settings, "General", "filters_visible"); + // this was supposed to have been removed above when updating from 2.2.0, + // but it wasn't in Settings, it was in General + remove(m_Settings, "General", "ask_for_nexuspw"); + m_Network.updateFromOldMap(); }); -- cgit v1.3.1 From 12e1a91e4fe8de291fbe72c23031f3e79613c0dd Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sun, 8 Sep 2019 04:58:17 -0400 Subject: log desktop geometry log more info on game plugin --- src/env.cpp | 5 +++++ src/envmetrics.cpp | 12 ++++++++++++ src/envmetrics.h | 4 ++++ src/main.cpp | 5 ++++- src/settings.cpp | 1 + 5 files changed, 26 insertions(+), 1 deletion(-) (limited to 'src/settings.cpp') diff --git a/src/env.cpp b/src/env.cpp index 4628e3f4..411443c5 100644 --- a/src/env.cpp +++ b/src/env.cpp @@ -109,6 +109,11 @@ void Environment::dump(const Settings& s) const log::debug(" . {}", d.toString()); } + const auto r = m_metrics->desktopGeometry(); + log::debug( + "desktop geometry: ({},{})-({},{})", + r.left(), r.top(), r.right(), r.bottom()); + dumpDisks(s); } diff --git a/src/envmetrics.cpp b/src/envmetrics.cpp index b1b9bd2e..5fb80449 100644 --- a/src/envmetrics.cpp +++ b/src/envmetrics.cpp @@ -4,6 +4,7 @@ #include #include #include +#include namespace env { @@ -225,6 +226,17 @@ const std::vector& Metrics::displays() const return m_displays; } +QRect Metrics::desktopGeometry() const +{ + QRect r; + + for (auto* s : QGuiApplication::screens()) { + r = r.united(s->geometry()); + } + + return r; +} + void Metrics::getDisplays() { // don't bother if it goes over 100 diff --git a/src/envmetrics.h b/src/envmetrics.h index c5d2765a..8dfdb087 100644 --- a/src/envmetrics.h +++ b/src/envmetrics.h @@ -66,6 +66,10 @@ public: // const std::vector& displays() const; + // full resolution + // + QRect desktopGeometry() const; + private: std::vector m_displays; diff --git a/src/main.cpp b/src/main.cpp index 04bc423b..9cb8c08d 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -648,7 +648,10 @@ int runApplication(MOApplication &application, SingleInstance &instance, game->setGameVariant(edition); - log::info("managing game at {}", game->gameDirectory().absolutePath()); + log::info( + "using game plugin '{}' ('{}', steam id '{}') at {}", + game->gameName(), game->gameShortName(), game->steamAPPId(), + game->gameDirectory().absolutePath()); organizer.updateExecutablesList(); diff --git a/src/settings.cpp b/src/settings.cpp index 1f066100..7fdda2bf 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -1219,6 +1219,7 @@ void PluginSettings::setPersistent( m_Settings.sync(); } } + void PluginSettings::addBlacklist(const QString &fileName) { m_PluginBlacklist.insert(fileName); -- cgit v1.3.1 From a5db7ed864ac58657bf9bfbbc292cdccbeeaa38b Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Thu, 19 Sep 2019 11:23:21 -0400 Subject: added Settings::isExecutableBlacklisted() moved blacklisted confirmation to dialogs --- src/settings.cpp | 11 +++++++++++ src/settings.h | 1 + src/spawn.cpp | 29 ++++++++++++++++------------- 3 files changed, 28 insertions(+), 13 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/settings.cpp b/src/settings.cpp index 7fdda2bf..ae487c18 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -222,6 +222,17 @@ QString Settings::executablesBlacklist() const return get(m_Settings, "Settings", "executable_blacklist", def); } +bool Settings::isExecutableBlacklisted(const QString& s) const +{ + for (auto exec : executablesBlacklist().split(";")) { + if (exec.compare(s, Qt::CaseInsensitive) == 0) { + return true; + } + } + + return false; +} + void Settings::setExecutablesBlacklist(const QString& s) { set(m_Settings, "Settings", "executable_blacklist", s); diff --git a/src/settings.h b/src/settings.h index 815ed160..cd478a5b 100644 --- a/src/settings.h +++ b/src/settings.h @@ -678,6 +678,7 @@ public: // by MO but given to usvfs when starting an executable // QString executablesBlacklist() const; + bool isExecutableBlacklisted(const QString& s) const; void setExecutablesBlacklist(const QString& s); // ? looks obsolete, only used by dead code diff --git a/src/spawn.cpp b/src/spawn.cpp index c9025d98..45324d79 100644 --- a/src/spawn.cpp +++ b/src/spawn.cpp @@ -345,6 +345,20 @@ bool eventLogNotRunning( return (r != QDialogButtonBox::No); } +bool confirmBlacklisted(QWidget* parent, const SpawnParameters& sp) +{ + const auto r = QuestionBoxMemory::query( + parent, QString("blacklistedExecutable"), sp.binary.fileName(), + QObject::tr("Blacklisted Executable"), + QObject::tr("The executable you are attempted to launch is blacklisted in the virtual file" + " system. This will likely prevent the executable, and any executables that are" + " launched by this one, from seeing any mods. This could extend to INI files, save" + " games and any other virtualized files.\n\nContinue launching %1?").arg(sp.binary.fileName()), + QDialogButtonBox::Yes | QDialogButtonBox::No); + + return (r != QDialogButtonBox::No); +} + } // namespace @@ -652,18 +666,8 @@ bool checkEnvironment(QWidget* parent, const SpawnParameters& sp) bool checkBlacklist(QWidget* parent, const SpawnParameters& sp, const Settings& settings) { - for (auto exec : settings.executablesBlacklist().split(";")) { - if (exec.compare(sp.binary.fileName(), Qt::CaseInsensitive) == 0) { - if (QuestionBoxMemory::query(parent, QString("blacklistedExecutable"), sp.binary.fileName(), - QObject::tr("Blacklisted Executable"), - QObject::tr("The executable you are attempted to launch is blacklisted in the virtual file" - " system. This will likely prevent the executable, and any executables that are" - " launched by this one, from seeing any mods. This could extend to INI files, save" - " games and any other virtualized files.\n\nContinue launching %1?").arg(sp.binary.fileName()), - QDialogButtonBox::Yes | QDialogButtonBox::No) == QDialogButtonBox::No) { - return false; - } - } + if (settings.isExecutableBlacklisted(sp.binary.fileName())) { + return dialogs::confirmBlacklisted(parent, sp); } return true; @@ -779,7 +783,6 @@ bool backdateBSAs(const std::wstring &moPath, const std::wstring &dataPath) return helperExec(moPath, commandLine, FALSE); } - bool adminLaunch(const std::wstring &moPath, const std::wstring &moFile, const std::wstring &workingDir) { const std::wstring commandLine = fmt::format( -- cgit v1.3.1 From 9bac57e3e864bd300fadccfaa194a6f3d28c9de2 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Thu, 19 Sep 2019 15:03:03 -0400 Subject: steam confirmation now using TaskDialog fixed dialog choices not remembering files --- src/settings.cpp | 2 +- src/settingsdialog.ui | 2 +- src/spawn.cpp | 95 ++++++++++++++++++++++++++++++++++----------------- 3 files changed, 65 insertions(+), 34 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/settings.cpp b/src/settings.cpp index ae487c18..7cea52fb 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -946,7 +946,7 @@ QuestionBoxMemory::Button WidgetSettings::questionButton( if (!filename.isEmpty()) { const auto fileSetting = windowName + "/" + filename; - if (auto v=getOptional(m_Settings, sectionName, filename)) { + if (auto v=getOptional(m_Settings, sectionName, fileSetting)) { return static_cast(*v); } } diff --git a/src/settingsdialog.ui b/src/settingsdialog.ui index 1a3726fb..40079441 100644 --- a/src/settingsdialog.ui +++ b/src/settingsdialog.ui @@ -191,7 +191,7 @@ p, li { white-space: pre-wrap; } This will make all dialogs show up again where you checked the "Remember selection"-box. - Reset Dialogs + Reset Dialog Choices
diff --git a/src/spawn.cpp b/src/spawn.cpp index 45324d79..e18e6bb3 100644 --- a/src/spawn.cpp +++ b/src/spawn.cpp @@ -183,6 +183,7 @@ QMessageBox::StandardButton badSteamReg( "The path to the Steam executable cannot be found. You might try " "reinstalling Steam.")) .details(details) + .icon(QMessageBox::Critical) .button({ QObject::tr("Continue without starting Steam"), QObject::tr("The program may fail to launch."), @@ -203,6 +204,7 @@ QMessageBox::StandardButton startSteamFailed( .main(QObject::tr("Cannot start Steam")) .content(makeContent(sp, e)) .details(details) + .icon(QMessageBox::Critical) .button({ QObject::tr("Continue without starting Steam"), QObject::tr("The program may fail to launch."), @@ -232,6 +234,7 @@ void spawnFailed(const SpawnParameters& sp, DWORD code) .main(mainText) .content(makeContent(sp, code)) .details(details) + .icon(QMessageBox::Critical) .exec(); } @@ -261,6 +264,7 @@ void helperFailed( .main(mainText) .content(makeContent(sp, code)) .details(details) + .icon(QMessageBox::Critical) .exec(); } @@ -295,26 +299,45 @@ bool confirmRestartAsAdmin(const SpawnParameters& sp) .main(mainText) .content(content) .details(details) + .icon(QMessageBox::Question) .button({ - QObject::tr("Restart Mod Organizer as administrator"), - QObject::tr("You must allow \"helper.exe\" to make changes to the system."), - QMessageBox::Yes}) + QObject::tr("Restart Mod Organizer as administrator"), + QObject::tr("You must allow \"helper.exe\" to make changes to the system."), + QMessageBox::Yes}) .button({ - QObject::tr("Cancel"), - QMessageBox::Cancel}) + QObject::tr("Cancel"), + QMessageBox::Cancel}) .exec(); return (r == QMessageBox::Yes); } -QuestionBoxMemory::Button confirmStartSteam(QWidget* parent, const SpawnParameters& sp) +QMessageBox::StandardButton confirmStartSteam( + QWidget* window, const SpawnParameters& sp, const QString& details) { - return QuestionBoxMemory::query( - parent, "steamQuery", sp.binary.fileName(), - QObject::tr("Start Steam?"), - QObject::tr("Steam is required to be running already to correctly start the game. " - "Should MO try to start steam now?"), - QDialogButtonBox::Yes | QDialogButtonBox::No | QDialogButtonBox::Cancel); + const auto title = QObject::tr("Launch Steam"); + const auto mainText = QObject::tr("This program requires Steam"); + const auto content = QObject::tr( + "Mod Organizer has detected that this program likely requires Steam to be " + "running to function properly."); + + return MOBase::TaskDialog(window, title) + .main(mainText) + .content(content) + .details(details) + .icon(QMessageBox::Question) + .button({ + QObject::tr("Start Steam"), + QMessageBox::Yes}) + .button({ + QObject::tr("Continue without starting Steam"), + QObject::tr("The program might fail to run."), + QMessageBox::No}) + .button({ + QObject::tr("Cancel"), + QMessageBox::Cancel}) + .remember("steamQuery", sp.binary.fileName()) + .exec(); } QuestionBoxMemory::Button confirmRestartAsAdminForSteam(QWidget* parent, const SpawnParameters& sp) @@ -561,27 +584,14 @@ bool startSteam(QWidget* parent) return true; } -bool gameRequiresSteam(const QDir& gameDirectory, const Settings& settings) -{ - static const std::vector files = { - "steam_api.dll", "steam_api64.dll" - }; - - for (const auto& file : files) { - const QFileInfo fi(gameDirectory.absoluteFilePath(file)); - if (fi.exists()) { - log::debug("found '{}'", fi.absoluteFilePath()); - return true; - } - } - - return false; -} - bool checkSteam( QWidget* parent, const SpawnParameters& sp, const QDir& gameDirectory, const QString &steamAppID, const Settings& settings) { + static const std::vector steamFiles = { + "steam_api.dll", "steam_api64.dll" + }; + log::debug("checking steam"); if (!steamAppID.isEmpty()) { @@ -590,16 +600,37 @@ bool checkSteam( env::set("SteamAPPId", settings.steam().appID()); } - if (!gameRequiresSteam(gameDirectory, settings)) { - log::debug("games doesn't seem to require steam"); + + bool steamRequired = false; + QString details; + + for (const auto& file : steamFiles) { + const QFileInfo fi(gameDirectory.absoluteFilePath(file)); + if (fi.exists()) { + details = QString( + "managed game is located at '%1' and file '%2' exists") + .arg(gameDirectory.absolutePath()) + .arg(fi.absoluteFilePath()); + + log::debug("{}", details); + steamRequired = true; + + break; + } + } + + if (!steamRequired) { + log::debug("program doesn't seem to require steam"); return true; } + auto ss = getSteamStatus(); if (!ss.running) { log::debug("steam isn't running, asking to start steam"); - const auto c = dialogs::confirmStartSteam(parent, sp); + + const auto c = dialogs::confirmStartSteam(parent, sp, details); if (c == QDialogButtonBox::Yes) { log::debug("user wants to start steam"); -- cgit v1.3.1 From 829124d8b899101370e55eb2a9cb9164ffd68a55 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Mon, 23 Sep 2019 17:52:46 -0400 Subject: ensure windows are on screen --- src/settings.cpp | 90 ++++++++++++++++++++++++++++++++++++++++++++------------ src/settings.h | 51 ++++++++++++++++++++++---------- 2 files changed, 107 insertions(+), 34 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/settings.cpp b/src/settings.cpp index 7cea52fb..19eca5ec 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -22,7 +22,9 @@ along with Mod Organizer. If not, see . #include "serverinfo.h" #include "executableslist.h" #include "appconfig.h" -#include "expanderwidget.h" +#include "env.h" +#include "envmetrics.h" +#include #include #include @@ -604,21 +606,80 @@ void GeometrySettings::resetIfNeeded() removeSection(m_Settings, "Geometry"); } -void GeometrySettings::saveGeometry(const QWidget* w) +void GeometrySettings::saveGeometry(const QMainWindow* w) +{ + saveWindowGeometry(w); +} + +bool GeometrySettings::restoreGeometry(QMainWindow* w) const +{ + return restoreWindowGeometry(w); +} + +void GeometrySettings::saveGeometry(const QDialog* d) +{ + saveWindowGeometry(d); +} + +bool GeometrySettings::restoreGeometry(QDialog* d) const +{ + return restoreWindowGeometry(d); +} + +void GeometrySettings::saveWindowGeometry(const QWidget* w) { set(m_Settings, "Geometry", geoSettingName(w), w->saveGeometry()); } -bool GeometrySettings::restoreGeometry(QWidget* w) const +bool GeometrySettings::restoreWindowGeometry(QWidget* w) const { if (auto v=getOptional(m_Settings, "Geometry", geoSettingName(w))) { w->restoreGeometry(*v); + ensureWindowOnScreen(w); return true; } return false; } +void GeometrySettings::ensureWindowOnScreen(QWidget* w) const +{ + // users report that the main window and/or dialogs are displayed off-screen; + // the usual workaround is keyboard navigation to move it + // + // qt should have code that deals with multiple monitors and off-screen + // geometries, but there seems to be bugs or inconsistencies that can't be + // reproduced + // + // the closest would probably be https://bugreports.qt.io/browse/QTBUG-64498, + // which is about multiple monitors and high dpi, but it seems fixed as of + // 5.12.4, which is shipped with 2.2.1 + // + // without being to reproduce the problem, some simple checks are made in a + // timer, which may mitigate the issues + + QTimer::singleShot(100, w, [w] { + const auto borders = 20; + + // desktop geometry, made smaller to make sure there isn't just a few pixels + const auto originalDg = env::Environment().metrics().desktopGeometry(); + const auto dg = originalDg.adjusted(borders, borders, -borders, -borders); + + const auto g = w->geometry(); + + if (!dg.intersects(g)) { + log::warn( + "window '{}' is offscreen, moving to main monitor; geo={}, desktop={}", + w->objectName(), g, originalDg); + + // widget is off-screen, center it on main monitor + centerOnMonitor(w, -1); + + log::warn("window '{}' now at {}", w->objectName(), w->geometry()); + } + }); +} + void GeometrySettings::saveState(const QMainWindow* w) { set(m_Settings, "Geometry", stateSettingName(w), w->saveState()); @@ -771,12 +832,17 @@ void GeometrySettings::setModInfoTabOrder(const QString& names) void GeometrySettings::centerOnMainWindowMonitor(QWidget* w) { const auto monitor = getOptional( - m_Settings, "Geometry", "MainWindow_monitor"); + m_Settings, "Geometry", "MainWindow_monitor").value_or(-1); + + centerOnMonitor(w, monitor); +} +void GeometrySettings::centerOnMonitor(QWidget* w, int monitor) +{ QPoint center; - if (monitor && QGuiApplication::screens().size() > *monitor) { - center = QGuiApplication::screens().at(*monitor)->geometry().center(); + if (monitor >= 0 && monitor < QGuiApplication::screens().size()) { + center = QGuiApplication::screens().at(monitor)->geometry().center(); } else { center = QGuiApplication::primaryScreen()->geometry().center(); } @@ -1887,15 +1953,3 @@ void DiagnosticsSettings::setCrashDumpsMax(int n) { set(m_Settings, "Settings", "crash_dumps_max", n); } - - -GeometrySaver::GeometrySaver(Settings& s, QDialog* dialog) - : m_settings(s), m_dialog(dialog) -{ - m_settings.geometry().restoreGeometry(m_dialog); -} - -GeometrySaver::~GeometrySaver() -{ - m_settings.geometry().saveGeometry(m_dialog); -} diff --git a/src/settings.h b/src/settings.h index cd478a5b..b5366911 100644 --- a/src/settings.h +++ b/src/settings.h @@ -41,20 +41,6 @@ class ServerList; class Settings; -// helper class that calls restoreGeometry() in the constructor and -// saveGeometry() in the destructor -// -class GeometrySaver -{ -public: - GeometrySaver(Settings& s, QDialog* dialog); - ~GeometrySaver(); - -private: - Settings& m_settings; - QDialog* m_dialog; -}; - // setting for the currently managed game // @@ -141,8 +127,11 @@ public: void resetIfNeeded(); - void saveGeometry(const QWidget* w); - bool restoreGeometry(QWidget* w) const; + void saveGeometry(const QMainWindow* w); + bool restoreGeometry(QMainWindow* w) const; + + void saveGeometry(const QDialog* d); + bool restoreGeometry(QDialog* d) const; void saveState(const QMainWindow* window); bool restoreState(QMainWindow* window) const; @@ -182,6 +171,12 @@ public: private: QSettings& m_Settings; bool m_Reset; + + void saveWindowGeometry(const QWidget* w); + bool restoreWindowGeometry(QWidget* w) const; + + void ensureWindowOnScreen(QWidget* w) const; + static void centerOnMonitor(QWidget* w, int monitor); }; @@ -764,4 +759,28 @@ private: DiagnosticsSettings m_Diagnostics; }; + +// helper class that calls restoreGeometry() in the constructor and +// saveGeometry() in the destructor +// +template +class GeometrySaver +{ +public: + GeometrySaver(Settings& s, W* w) + : m_settings(s), m_widget(w) + { + m_settings.geometry().restoreGeometry(m_widget); + } + + ~GeometrySaver() + { + m_settings.geometry().saveGeometry(m_widget); + } + +private: + Settings& m_settings; + W* m_widget; +}; + #endif // SETTINGS_H -- cgit v1.3.1 From 200b5283eb5a0eff5ed18e772930b99eea5e11ef Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Mon, 23 Sep 2019 18:21:39 -0400 Subject: added center dialogs option moved download list options to their own group box renamed confusing "Download Meta Information" to "Show Meta Information" --- src/settings.cpp | 34 ++++++- src/settings.h | 6 ++ src/settingsdialog.ui | 208 ++++++++++++++++++++++-------------------- src/settingsdialoggeneral.cpp | 2 + 4 files changed, 149 insertions(+), 101 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/settings.cpp b/src/settings.cpp index 19eca5ec..c3e8781e 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -623,7 +623,13 @@ void GeometrySettings::saveGeometry(const QDialog* d) bool GeometrySettings::restoreGeometry(QDialog* d) const { - return restoreWindowGeometry(d); + const auto r = restoreWindowGeometry(d); + + if (centerDialogs()) { + centerOnParent(d); + } + + return r; } void GeometrySettings::saveWindowGeometry(const QWidget* w) @@ -829,6 +835,16 @@ void GeometrySettings::setModInfoTabOrder(const QString& names) set(m_Settings, "Widgets", "ModInfoTabOrder", names); } +bool GeometrySettings::centerDialogs() const +{ + return get(m_Settings, "Settings", "center_dialogs", false); +} + +void GeometrySettings::setCenterDialogs(bool b) +{ + set(m_Settings, "Settings", "center_dialogs", b); +} + void GeometrySettings::centerOnMainWindowMonitor(QWidget* w) { const auto monitor = getOptional( @@ -850,6 +866,22 @@ void GeometrySettings::centerOnMonitor(QWidget* w, int monitor) w->move(center - w->rect().center()); } +void GeometrySettings::centerOnParent(QWidget* w, QWidget* parent) +{ + if (!parent) { + parent = w->parentWidget(); + + if (!parent) { + parent = qApp->activeWindow(); + } + } + + if (parent && parent->isVisible()) { + const auto pr = parent->geometry(); + w->move(pr.center() - w->rect().center()); + } +} + void GeometrySettings::saveMainWindowMonitor(const QMainWindow* w) { if (auto* handle=w->windowHandle()) { diff --git a/src/settings.h b/src/settings.h index b5366911..ee6ff3fe 100644 --- a/src/settings.h +++ b/src/settings.h @@ -160,6 +160,11 @@ public: QStringList modInfoTabOrder() const; void setModInfoTabOrder(const QString& names); + // whether dialogs should be centered on their parent + // + bool centerDialogs() const; + void setCenterDialogs(bool b); + // assumes the given widget is a top-level // void centerOnMainWindowMonitor(QWidget* w); @@ -177,6 +182,7 @@ private: void ensureWindowOnScreen(QWidget* w) const; static void centerOnMonitor(QWidget* w, int monitor); + static void centerOnParent(QWidget* w, QWidget* parent=nullptr); }; diff --git a/src/settingsdialog.ui b/src/settingsdialog.ui index 40079441..9d1e4da1 100644 --- a/src/settingsdialog.ui +++ b/src/settingsdialog.ui @@ -86,97 +86,23 @@ p, li { white-space: pre-wrap; } - User interface + User Interface - - - - - Colors - - - - - - When this is enabled, the color defined for a separator will be shown on the mod list scrollbar at the location of the separator. This can be useful for quick navigation between separator sections or to a specific separator section. - - - When this is enabled, the color defined for a separator will be shown on the mod list scrollbar at the location of the separator. This can be useful for quick navigation between separator sections or to a specific separator section. - - - Show mod list separator colors on the scrollbar - - - true - - - - - - - Plugin is Contained in selected Mod - - - - - - - Is overwritten (loose files) - - - - - - - Is overwriting (loose files) - - - - - - - Reset Colors - - - - - - - Mod Contains selected Plugin - - - - - - - Is overwritten (archive files) - - - - - - - Is overwriting (archive files) - - - - - - - - - - Modify the categories available to arrange your mods. + + + + + Dialogs will always be centered on the main window, but will remember their size. - Modify the categories available to arrange your mods. + Dialogs will always be centered on the main window, but will remember their size. - Configure Mod Categories + Always center dialogs - + @@ -195,36 +121,119 @@ p, li { white-space: pre-wrap; } - - + + - If checked, the download interface will be more compact. + Modify the categories available to arrange your mods. + + + Modify the categories available to arrange your mods. - Compact Download Interface + Configure Mod Categories - - - - Qt::Vertical + + + + + + + Download List + + + + + + If checked, the download interface will be more compact. - - - 20 - 40 - + + Compact List - + - + If checked, the download list will display meta information instead of file names. - Download Meta Information + Show Meta Information + + + + + + + + + + Colors + + + + + + When this is enabled, the color defined for a separator will be shown on the mod list scrollbar at the location of the separator. This can be useful for quick navigation between separator sections or to a specific separator section. + + + When this is enabled, the color defined for a separator will be shown on the mod list scrollbar at the location of the separator. This can be useful for quick navigation between separator sections or to a specific separator section. + + + Show mod list separator colors on the scrollbar + + + true + + + + + + + Plugin is Contained in selected Mod + + + + + + + Is overwritten (loose files) + + + + + + + Is overwriting (loose files) + + + + + + + Reset Colors + + + + + + + Mod Contains selected Plugin + + + + + + + Is overwritten (archive files) + + + + + + + Is overwriting (archive files) @@ -1411,7 +1420,6 @@ programs you are intentionally running. styleBox logLevelBox usePrereleaseBox - compactBox categoriesBtn baseDirEdit browseBaseDirBtn diff --git a/src/settingsdialoggeneral.cpp b/src/settingsdialoggeneral.cpp index 8ecdcbb9..ae924393 100644 --- a/src/settingsdialoggeneral.cpp +++ b/src/settingsdialoggeneral.cpp @@ -51,6 +51,7 @@ GeneralSettingsTab::GeneralSettingsTab(Settings& s, SettingsDialog& d) setContainsColor(settings().colors().modlistContainsPlugin()); setContainedColor(settings().colors().pluginListContained()); + ui->centerDialogs->setChecked(settings().geometry().centerDialogs()); ui->compactBox->setChecked(settings().interface().compactDownloads()); ui->showMetaBox->setChecked(settings().interface().metaDownloads()); ui->usePrereleaseBox->setChecked(settings().usePrereleases()); @@ -91,6 +92,7 @@ void GeneralSettingsTab::update() settings().colors().setModlistContainsPlugin(getContainsColor()); settings().colors().setPluginListContained(getContainedColor()); + settings().geometry().setCenterDialogs(ui->centerDialogs->isChecked()); settings().interface().setCompactDownloads(ui->compactBox->isChecked()); settings().interface().setMetaDownloads(ui->showMetaBox->isChecked()); settings().setUsePrereleases(ui->usePrereleaseBox->isChecked()); -- cgit v1.3.1 From 088f27fe48cd8f218052090a97e8187eedf0c06e Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Mon, 23 Sep 2019 19:10:19 -0400 Subject: changed the layout of the general settings tab added option to disable checking for updates removed online check, just try it and see --- src/mainwindow.cpp | 16 ++++ src/mainwindow.h | 1 + src/organizercore.cpp | 36 ++------ src/organizercore.h | 1 + src/selfupdater.cpp | 12 ++- src/selfupdater.h | 14 ++- src/settings.cpp | 10 +++ src/settings.h | 5 ++ src/settingsdialog.ui | 203 ++++++++++++++++++++++++++---------------- src/settingsdialoggeneral.cpp | 2 + 10 files changed, 187 insertions(+), 113 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 42cbe919..cd650d2f 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -263,6 +263,7 @@ MainWindow::MainWindow(Settings &settings setupToolbar(); toggleMO2EndorseState(); + toggleUpdateAction(); TaskProgressManager::instance().tryCreateTaskbar(); @@ -5007,6 +5008,7 @@ void MainWindow::on_actionSettings_triggered() bool oldDisplayForeign(settings.interface().displayForeign()); bool proxy = settings.network().useProxy(); DownloadManager *dlManager = m_OrganizerCore.downloadManager(); + const bool oldCheckForUpdates = settings.checkForUpdates(); SettingsDialog dialog(&m_PluginContainer, settings, this); @@ -5084,6 +5086,14 @@ void MainWindow::on_actionSettings_triggered() m_OrganizerCore.cycleDiagnostics(); toggleMO2EndorseState(); + + if (oldCheckForUpdates != settings.checkForUpdates()) { + toggleUpdateAction(); + + if (settings.checkForUpdates()) { + m_OrganizerCore.checkForUpdates(); + } + } } void MainWindow::on_actionNexus_triggered() @@ -5596,6 +5606,12 @@ void MainWindow::toggleMO2EndorseState() ui->actionEndorseMO->setStatusTip(text); } +void MainWindow::toggleUpdateAction() +{ + const auto& s = m_OrganizerCore.settings(); + ui->actionUpdate->setVisible(s.checkForUpdates()); +} + void MainWindow::nxmEndorsementsAvailable(QVariant userData, QVariant resultData, int) { QVariantList data = resultData.toList(); diff --git a/src/mainwindow.h b/src/mainwindow.h index 1f997ab1..524e2b6e 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -313,6 +313,7 @@ private: void sendSelectedPluginsToPriority(int newPriority); void toggleMO2EndorseState(); + void toggleUpdateAction(); private: diff --git a/src/organizercore.cpp b/src/organizercore.cpp index 0da5b604..a4a89c99 100644 --- a/src/organizercore.cpp +++ b/src/organizercore.cpp @@ -74,25 +74,6 @@ using namespace MOBase; //static CrashDumpsType OrganizerCore::m_globalCrashDumpsType = CrashDumpsType::None; -static bool isOnline() -{ - const auto runningFlags = - QNetworkInterface::IsUp | QNetworkInterface::IsRunning; - - for (auto&& i : QNetworkInterface::allInterfaces()) { - if (!(i.flags() & QNetworkInterface::IsLoopBack)) { - if (i.flags() & runningFlags) { - auto addresses = i.addressEntries(); - if (!addresses.empty()) { - return true; - } - } - } - } - - return false; -} - static std::wstring getProcessName(HANDLE process) { wchar_t buffer[MAX_PATH]; @@ -307,14 +288,15 @@ void OrganizerCore::setUserInterface(IUserInterface *userInterface, m_InstallationManager.setParentWidget(widget); m_Updater.setUserInterface(widget); - if (userInterface != nullptr) { - // this currently wouldn't work reliably if the ui isn't initialized yet to - // display the result - if (isOnline() && !m_Settings.network().offlineMode()) { - m_Updater.testForUpdate(); - } else { - log::debug("user doesn't seem to be connected to the internet"); - } + checkForUpdates(); +} + +void OrganizerCore::checkForUpdates() +{ + // this currently wouldn't work reliably if the ui isn't initialized yet to + // display the result + if (m_UserInterface != nullptr) { + m_Updater.testForUpdate(m_Settings); } } diff --git a/src/organizercore.h b/src/organizercore.h index a14d79a9..5de550df 100644 --- a/src/organizercore.h +++ b/src/organizercore.h @@ -109,6 +109,7 @@ public: void updateExecutablesList(); + void checkForUpdates(); void startMOUpdate(); Settings &settings(); diff --git a/src/selfupdater.cpp b/src/selfupdater.cpp index 0ca39b19..8887927a 100644 --- a/src/selfupdater.cpp +++ b/src/selfupdater.cpp @@ -122,8 +122,18 @@ void SelfUpdater::setPluginContainer(PluginContainer *pluginContainer) m_Interface->setPluginContainer(pluginContainer); } -void SelfUpdater::testForUpdate() +void SelfUpdater::testForUpdate(const Settings& settings) { + if (settings.network().offlineMode()) { + log::debug("not checking for updates, in offline mode"); + return; + } + + if (!settings.checkForUpdates()) { + log::debug("not checking for updates, disabled"); + return; + } + // TODO: if prereleases are disabled we could just request the latest release // directly try { diff --git a/src/selfupdater.h b/src/selfupdater.h index bce49495..0c81efc5 100644 --- a/src/selfupdater.h +++ b/src/selfupdater.h @@ -37,7 +37,7 @@ namespace MOBase { class IPluginGame; } class QNetworkReply; class QProgressDialog; - +class Settings; /** * @brief manages updates for Mod Organizer itself @@ -80,6 +80,11 @@ public: void setPluginContainer(PluginContainer *pluginContainer); + /** + * @brief request information about the current version + **/ + void testForUpdate(const Settings& settings); + /** * @brief start the update process * @note this should not be called if there is no update available @@ -91,13 +96,6 @@ public: **/ MOBase::VersionInfo getVersion() const { return m_MOVersion; } -public slots: - - /** - * @brief request information about the current version - **/ - void testForUpdate(); - signals: /** diff --git a/src/settings.cpp b/src/settings.cpp index c3e8781e..462cd92a 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -178,6 +178,16 @@ QString Settings::filename() const return m_Settings.fileName(); } +bool Settings::checkForUpdates() const +{ + return get(m_Settings, "Settings", "check_for_updates", true); +} + +void Settings::setCheckForUpdates(bool b) +{ + set(m_Settings, "Settings", "check_for_updates", b); +} + bool Settings::usePrereleases() const { return get(m_Settings, "Settings", "use_prereleases", false); diff --git a/src/settings.h b/src/settings.h index ee6ff3fe..1556ba1e 100644 --- a/src/settings.h +++ b/src/settings.h @@ -692,6 +692,11 @@ public: bool archiveParsing() const; void setArchiveParsing(bool b); + // whether the user wants to check for updates + // + bool checkForUpdates() const; + void setCheckForUpdates(bool b); + // whether the user wants to upgrade to pre-releases // bool usePrereleases() const; diff --git a/src/settingsdialog.ui b/src/settingsdialog.ui index 9d1e4da1..78bae6d7 100644 --- a/src/settingsdialog.ui +++ b/src/settingsdialog.ui @@ -7,7 +7,7 @@ 0 0 586 - 486 + 491 @@ -23,75 +23,67 @@ General - - - - - - - Language - - - - - - - The display language - - - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> -<html><head><meta name="qrichtext" content="1" /><style type="text/css"> -p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">The display language. This will only displaye languages for which you have a translation installed.</span></p></body></html> - - - - - - - - - - - Style - - - - - - - graphical style - - - graphical style of the MO user interface - - - - - - - - - Update to non-stable releases. - - - If this is enabled, the integrated update mechanism will notify of all releases, including pre-releases (alphas, betas). Please use this only if you're sufficiently tech-savvy to investigate issues, look for known problems in the issue tracker and create meaningful reports. + + + + + Qt::Vertical - - Install Pre-releases (Betas) + + + 0 + 0 + - + - + User Interface - - + + + + + Style + + + + + + + Language + + + + + + + The display language + + + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">The display language. This will only displaye languages for which you have a translation installed.</span></p></body></html> + + + + + + + graphical style + + + graphical style of the MO user interface + + + + - + Dialogs will always be centered on the main window, but will remember their size. @@ -102,7 +94,7 @@ p, li { white-space: pre-wrap; } - + @@ -121,7 +113,7 @@ p, li { white-space: pre-wrap; } - + Modify the categories available to arrange your mods. @@ -137,36 +129,49 @@ p, li { white-space: pre-wrap; } - + Download List - + - + - If checked, the download interface will be more compact. + If checked, the download list will display meta information instead of file names. - Compact List + Show Meta Information - + - If checked, the download list will display meta information instead of file names. + If checked, the download interface will be more compact. - Show Meta Information + Compact List + + + + Qt::Vertical + + + + 0 + 0 + + + + - + Colors @@ -240,6 +245,54 @@ p, li { white-space: pre-wrap; } + + + + Updates + + + + + + Mod Organizer checks for updates on Github on startup. + + + Mod Organizer checks for updates on Github on startup. + + + Check for updates + + + + + + + Update to non-stable releases. + + + If this is enabled, the integrated update mechanism will notify of all releases, including pre-releases (alphas, betas). Please use this only if you're sufficiently tech-savvy to investigate issues, look for known problems in the issue tracker and create meaningful reports. + + + Install Pre-releases (Betas) + + + + + + + Qt::Vertical + + + + 0 + 0 + + + + + + + @@ -1416,11 +1469,7 @@ programs you are intentionally running. - languageBox - styleBox logLevelBox - usePrereleaseBox - categoriesBtn baseDirEdit browseBaseDirBtn downloadDirEdit diff --git a/src/settingsdialoggeneral.cpp b/src/settingsdialoggeneral.cpp index ae924393..07aff4a1 100644 --- a/src/settingsdialoggeneral.cpp +++ b/src/settingsdialoggeneral.cpp @@ -54,6 +54,7 @@ GeneralSettingsTab::GeneralSettingsTab(Settings& s, SettingsDialog& d) ui->centerDialogs->setChecked(settings().geometry().centerDialogs()); ui->compactBox->setChecked(settings().interface().compactDownloads()); ui->showMetaBox->setChecked(settings().interface().metaDownloads()); + ui->checkForUpdates->setChecked(settings().checkForUpdates()); ui->usePrereleaseBox->setChecked(settings().usePrereleases()); ui->colorSeparatorsBox->setChecked(settings().colors().colorSeparatorScrollbar()); @@ -95,6 +96,7 @@ void GeneralSettingsTab::update() settings().geometry().setCenterDialogs(ui->centerDialogs->isChecked()); settings().interface().setCompactDownloads(ui->compactBox->isChecked()); settings().interface().setMetaDownloads(ui->showMetaBox->isChecked()); + settings().setCheckForUpdates(ui->checkForUpdates->isChecked()); settings().setUsePrereleases(ui->usePrereleaseBox->isChecked()); settings().colors().setColorSeparatorScrollbar(ui->colorSeparatorsBox->isChecked()); } -- cgit v1.3.1 From c4dd23abb7a37531040d6348c491dc868919013c Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Fri, 4 Oct 2019 09:40:37 -0400 Subject: added error messages to FileRenamer and a few more fixes for shell functions changing names --- src/downloadmanager.cpp | 10 +++++----- src/filerenamer.cpp | 42 +++++++++++++++++++++++++++++------------- src/filerenamer.h | 8 ++++++-- src/mainwindow.cpp | 36 ++++++++++++++++++------------------ src/modinfodialogconflicts.cpp | 2 +- src/modinfodialogfiletree.cpp | 8 ++++---- src/modinfodialogimages.cpp | 2 +- src/modinfodialognexus.cpp | 6 +++--- src/motddialog.cpp | 2 +- src/nxmaccessmanager.cpp | 2 +- src/overwriteinfodialog.cpp | 4 ++-- src/problemsdialog.cpp | 2 +- src/selfupdater.cpp | 7 +++++-- src/settings.cpp | 6 ++++-- src/settingsdialognexus.cpp | 2 +- src/texteditor.cpp | 2 +- 16 files changed, 83 insertions(+), 58 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/downloadmanager.cpp b/src/downloadmanager.cpp index 35f60d7a..b4a7b57d 100644 --- a/src/downloadmanager.cpp +++ b/src/downloadmanager.cpp @@ -1059,11 +1059,11 @@ void DownloadManager::openFile(int index) QDir path = QDir(m_OutputDirectory); if (path.exists(getFileName(index))) { - shell::OpenFile(getFilePath(index)); + shell::Open(getFilePath(index)); return; } - shell::ExploreFile(m_OutputDirectory); + shell::Explore(m_OutputDirectory); return; } @@ -1077,18 +1077,18 @@ void DownloadManager::openInDownloadsFolder(int index) const auto path = getFilePath(index); if (QFile::exists(path)) { - shell::ExploreFile(path); + shell::Explore(path); return; } else { const auto unfinished = path + ".unfinished"; if (QFile::exists(unfinished)) { - shell::ExploreFile(unfinished); + shell::Explore(unfinished); return; } } - shell::ExploreFile(m_OutputDirectory); + shell::Explore(m_OutputDirectory); } diff --git a/src/filerenamer.cpp b/src/filerenamer.cpp index a97d7742..7fc90eb2 100644 --- a/src/filerenamer.cpp +++ b/src/filerenamer.cpp @@ -1,4 +1,5 @@ #include "filerenamer.h" +#include #include #include #include @@ -37,10 +38,13 @@ FileRenamer::RenameResults FileRenamer::rename(const QString& oldName, const QSt log::debug("removing {}", newName); // user wants to replace the file, so remove it - if (!QFile(newName).remove()) { - log::warn("failed to remove '{}'", newName); + const auto r = shell::Delete(newName); + + if (!r.success()) { + log::error("failed to remove '{}': {}", newName, r.toString()); + // removal failed, warn the user and allow canceling - if (!removeFailed(newName)) { + if (!removeFailed(newName, r)) { log::debug("canceling {}", oldName); // user wants to cancel return RESULT_CANCEL; @@ -64,12 +68,15 @@ FileRenamer::RenameResults FileRenamer::rename(const QString& oldName, const QSt } // target either didn't exist or was removed correctly + const auto r = shell::Rename(oldName, newName); - if (!QFile::rename(oldName, newName)) { - log::warn("failed to rename '{}' to '{}'", oldName, newName); + if (!r.success()) { + log::error( + "failed to rename '{}' to '{}': {}", + oldName, newName, r.toString()); // renaming failed, warn the user and allow canceling - if (!renameFailed(oldName, newName)) { + if (!renameFailed(oldName, newName, r)) { // user wants to cancel log::debug("canceling"); return RESULT_CANCEL; @@ -144,7 +151,7 @@ FileRenamer::RenameDecision FileRenamer::confirmReplace(const QString& newName) } } -bool FileRenamer::removeFailed(const QString& name) +bool FileRenamer::removeFailed(const QString& name, const shell::Result& r) { QMessageBox::StandardButtons buttons = QMessageBox::Ok; if (m_flags & MULTIPLE) { @@ -153,8 +160,9 @@ bool FileRenamer::removeFailed(const QString& name) } const auto answer = QMessageBox::critical( - m_parent, QObject::tr("File operation failed"), - QObject::tr("Failed to remove \"%1\". Maybe you lack the required file permissions?").arg(name), + m_parent, + QObject::tr("File operation failed"), + QObject::tr("Failed to remove \"%1\": %2").arg(name).arg(r.toString()), buttons); if (answer == QMessageBox::Cancel) { @@ -168,7 +176,8 @@ bool FileRenamer::removeFailed(const QString& name) return true; } -bool FileRenamer::renameFailed(const QString& oldName, const QString& newName) +bool FileRenamer::renameFailed( + const QString& oldName, const QString& newName, const shell::Result& r) { QMessageBox::StandardButtons buttons = QMessageBox::Ok; if (m_flags & MULTIPLE) { @@ -177,9 +186,16 @@ bool FileRenamer::renameFailed(const QString& oldName, const QString& newName) } const auto answer = QMessageBox::critical( - m_parent, QObject::tr("File operation failed"), - QObject::tr("failed to rename %1 to %2").arg(oldName).arg(QDir::toNativeSeparators(newName)), - buttons); + m_parent, + QObject::tr("File operation failed"), + QObject::tr( + "Failed to rename file: %1.\r\n\r\n" + "Source:\r\n\"%2\"\r\n\r\n" + "Destination:\r\n\"%3\"") + .arg(r.toString()) + .arg(QDir::toNativeSeparators(oldName)) + .arg(QDir::toNativeSeparators(newName)), + buttons); if (answer == QMessageBox::Cancel) { // user wants to stop diff --git a/src/filerenamer.h b/src/filerenamer.h index cd57244c..5583ecbd 100644 --- a/src/filerenamer.h +++ b/src/filerenamer.h @@ -3,6 +3,8 @@ #include +namespace MOBase::shell { class Result; } + /** * Renames individual files and handles dialog boxes to confirm replacements and * failures with the user @@ -126,7 +128,7 @@ private: * @param name The name of the file that failed to be removed * @return true to continue, false to stop **/ - bool removeFailed(const QString& name); + bool removeFailed(const QString& name, const MOBase::shell::Result& r); /** * renaming a file failed, ask the user to continue or cancel @@ -134,7 +136,9 @@ private: * @param newName new filename * @return true to continue, false to stop **/ - bool renameFailed(const QString& oldName, const QString& newName); + bool renameFailed( + const QString& oldName, const QString& newName, + const MOBase::shell::Result& r); }; #endif // FILERENAMER_H diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 8ab28d22..b29ae11c 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -3313,12 +3313,12 @@ void MainWindow::openExplorer_clicked() if (selection->hasSelection() && selection->selectedRows().count() > 1) { for (QModelIndex idx : selection->selectedRows()) { ModInfo::Ptr info = ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt()); - shell::ExploreFile(info->absolutePath()); + shell::Explore(info->absolutePath()); } } else { ModInfo::Ptr modInfo = ModInfo::getByIndex(m_ContextRow); - shell::ExploreFile(modInfo->absolutePath()); + shell::Explore(modInfo->absolutePath()); } } @@ -3333,14 +3333,14 @@ void MainWindow::openPluginOriginExplorer_clicked() continue; } ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); - shell::ExploreFile(modInfo->absolutePath()); + shell::Explore(modInfo->absolutePath()); } } else { QModelIndex idx = selection->currentIndex(); QString fileName = idx.data().toString(); ModInfo::Ptr modInfo = ModInfo::getByIndex(ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(fileName))); - shell::ExploreFile(modInfo->absolutePath()); + shell::Explore(modInfo->absolutePath()); } } @@ -3355,7 +3355,7 @@ void MainWindow::openExplorer_activated() std::vector flags = modInfo->getFlags(); if (modInfo->isRegular() || (std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end())) { - shell::ExploreFile(modInfo->absolutePath()); + shell::Explore(modInfo->absolutePath()); } } @@ -3376,7 +3376,7 @@ void MainWindow::openExplorer_activated() std::vector flags = modInfo->getFlags(); if (modInfo->isRegular() || (std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end())) { - shell::ExploreFile(modInfo->absolutePath()); + shell::Explore(modInfo->absolutePath()); } } } @@ -4344,61 +4344,61 @@ void MainWindow::disableVisibleMods() void MainWindow::openInstanceFolder() { QString dataPath = qApp->property("dataPath").toString(); - shell::ExploreFile(dataPath); + shell::Explore(dataPath); } void MainWindow::openLogsFolder() { QString logsPath = qApp->property("dataPath").toString() + "/" + QString::fromStdWString(AppConfig::logPath()); - shell::ExploreFile(logsPath); + shell::Explore(logsPath); } void MainWindow::openInstallFolder() { - shell::ExploreFile(qApp->applicationDirPath()); + shell::Explore(qApp->applicationDirPath()); } void MainWindow::openPluginsFolder() { QString pluginsPath = QCoreApplication::applicationDirPath() + "/" + ToQString(AppConfig::pluginPath()); - shell::ExploreFile(pluginsPath); + shell::Explore(pluginsPath); } void MainWindow::openProfileFolder() { - shell::ExploreFile(m_OrganizerCore.currentProfile()->absolutePath()); + shell::Explore(m_OrganizerCore.currentProfile()->absolutePath()); } void MainWindow::openIniFolder() { if (m_OrganizerCore.currentProfile()->localSettingsEnabled()) { - shell::ExploreFile(m_OrganizerCore.currentProfile()->absolutePath()); + shell::Explore(m_OrganizerCore.currentProfile()->absolutePath()); } else { - shell::ExploreFile(m_OrganizerCore.managedGame()->documentsDirectory()); + shell::Explore(m_OrganizerCore.managedGame()->documentsDirectory()); } } void MainWindow::openDownloadsFolder() { - shell::ExploreFile(m_OrganizerCore.settings().paths().downloads()); + shell::Explore(m_OrganizerCore.settings().paths().downloads()); } void MainWindow::openModsFolder() { - shell::ExploreFile(m_OrganizerCore.settings().paths().mods()); + shell::Explore(m_OrganizerCore.settings().paths().mods()); } void MainWindow::openGameFolder() { - shell::ExploreFile(m_OrganizerCore.managedGame()->gameDirectory()); + shell::Explore(m_OrganizerCore.managedGame()->gameDirectory()); } void MainWindow::openMyGamesFolder() { - shell::ExploreFile(m_OrganizerCore.managedGame()->documentsDirectory()); + shell::Explore(m_OrganizerCore.managedGame()->documentsDirectory()); } @@ -5391,7 +5391,7 @@ void MainWindow::openDataOriginExplorer_clicked() const auto fullPath = m_ContextItem->data(0, Qt::UserRole).toString(); log::debug("opening in explorer: {}", fullPath); - shell::ExploreFile(fullPath); + shell::Explore(fullPath); } void MainWindow::updateAvailable() diff --git a/src/modinfodialogconflicts.cpp b/src/modinfodialogconflicts.cpp index 3a71b405..36559a75 100644 --- a/src/modinfodialogconflicts.cpp +++ b/src/modinfodialogconflicts.cpp @@ -547,7 +547,7 @@ void ConflictsTab::exploreItems(QTreeView* tree) // the menu item is only shown for a single selection, but handle all of them // in case this changes for_each_in_selection(tree, [&](const ConflictItem* item) { - shell::ExploreFile(item->fileName()); + shell::Explore(item->fileName()); return true; }); } diff --git a/src/modinfodialogfiletree.cpp b/src/modinfodialogfiletree.cpp index 207c792d..71ea9210 100644 --- a/src/modinfodialogfiletree.cpp +++ b/src/modinfodialogfiletree.cpp @@ -128,7 +128,7 @@ void FileTreeTab::onOpen() return; } - shell::OpenFile(m_fs->filePath(selection)); + shell::Open(m_fs->filePath(selection)); } void FileTreeTab::onPreview() @@ -146,9 +146,9 @@ void FileTreeTab::onExplore() auto selection = singleSelection(); if (selection.isValid()) { - shell::ExploreFile(m_fs->filePath(selection)); + shell::Explore(m_fs->filePath(selection)); } else { - shell::ExploreFile(mod().absolutePath()); + shell::Explore(mod().absolutePath()); } } @@ -204,7 +204,7 @@ void FileTreeTab::onUnhide() void FileTreeTab::onOpenInExplorer() { - shell::ExploreFile(mod().absolutePath()); + shell::Explore(mod().absolutePath()); } bool FileTreeTab::deleteFile(const QModelIndex& index) diff --git a/src/modinfodialogimages.cpp b/src/modinfodialogimages.cpp index 9d347f57..c5b04538 100644 --- a/src/modinfodialogimages.cpp +++ b/src/modinfodialogimages.cpp @@ -547,7 +547,7 @@ void ImagesTab::showTooltip(QHelpEvent* e) void ImagesTab::onExplore() { if (auto* f=m_files.selectedFile()) { - MOBase::shell::ExploreFile(f->path()); + shell::Explore(f->path()); } } diff --git a/src/modinfodialognexus.cpp b/src/modinfodialognexus.cpp index 95e62328..59bfe930 100644 --- a/src/modinfodialognexus.cpp +++ b/src/modinfodialognexus.cpp @@ -95,7 +95,7 @@ void NexusTab::update() connect( page, &NexusTabWebpage::linkClicked, - [&](const QUrl& url){ shell::OpenLink(url); }); + [&](const QUrl& url){ shell::Open(url); }); ui->endorse->setEnabled( (mod().endorsedState() == ModInfo::ENDORSED_FALSE) || @@ -363,7 +363,7 @@ void NexusTab::onVisitNexus() const QString nexusLink = NexusInterface::instance(&plugin()) ->getModURL(modID, mod().getGameName()); - shell::OpenLink(QUrl(nexusLink)); + shell::Open(QUrl(nexusLink)); } } @@ -412,6 +412,6 @@ void NexusTab::onVisitCustomURL() { const auto url = mod().parseCustomURL(); if (url.isValid()) { - shell::OpenLink(url); + shell::Open(url); } } diff --git a/src/motddialog.cpp b/src/motddialog.cpp index ca1e60ad..eee80205 100644 --- a/src/motddialog.cpp +++ b/src/motddialog.cpp @@ -47,5 +47,5 @@ void MotDDialog::on_okButton_clicked() void MotDDialog::linkClicked(const QUrl &url) { - shell::OpenLink(url); + shell::Open(url); } diff --git a/src/nxmaccessmanager.cpp b/src/nxmaccessmanager.cpp index c6ef7bc7..3cc1b7d9 100644 --- a/src/nxmaccessmanager.cpp +++ b/src/nxmaccessmanager.cpp @@ -286,7 +286,7 @@ void NexusSSOLogin::onMessage(const QString& s) // open browser const auto url = NexusSSOPage.arg(m_guid); - shell::OpenLink(url); + shell::Open(url); m_timeout.stop(); setState(WaitingForBrowser); diff --git a/src/overwriteinfodialog.cpp b/src/overwriteinfodialog.cpp index fe1d8825..078bcfc9 100644 --- a/src/overwriteinfodialog.cpp +++ b/src/overwriteinfodialog.cpp @@ -229,7 +229,7 @@ void OverwriteInfoDialog::renameTriggered() void OverwriteInfoDialog::openFile(const QModelIndex &index) { - shell::OpenFile(m_FileSystemModel->filePath(index)); + shell::Open(m_FileSystemModel->filePath(index)); } @@ -270,7 +270,7 @@ void OverwriteInfoDialog::createDirectoryTriggered() void OverwriteInfoDialog::on_explorerButton_clicked() { - shell::ExploreFile(m_ModInfo->absolutePath()); + shell::Explore(m_ModInfo->absolutePath()); } void OverwriteInfoDialog::on_filesView_customContextMenuRequested(const QPoint &pos) diff --git a/src/problemsdialog.cpp b/src/problemsdialog.cpp index 63d58295..ea23beec 100644 --- a/src/problemsdialog.cpp +++ b/src/problemsdialog.cpp @@ -112,5 +112,5 @@ void ProblemsDialog::startFix() void ProblemsDialog::urlClicked(const QUrl &url) { - shell::OpenLink(url); + shell::Open(url); } diff --git a/src/selfupdater.cpp b/src/selfupdater.cpp index 8887927a..5a70568e 100644 --- a/src/selfupdater.cpp +++ b/src/selfupdater.cpp @@ -341,11 +341,14 @@ void SelfUpdater::downloadCancel() void SelfUpdater::installUpdate() { const QString parameters = "/DIR=\"" + qApp->applicationDirPath() + "\" "; + const auto r = shell::Execute(m_UpdateFile.fileName(), parameters); - if (shell::Execute(m_UpdateFile.fileName(), parameters)) { + if (r.success()) { QCoreApplication::quit(); } else { - reportError(tr("Failed to start %1").arg(m_UpdateFile.fileName())); + reportError(tr("Failed to start %1: %2") + .arg(m_UpdateFile.fileName()) + .arg(r.toString())); } m_UpdateFile.remove(); diff --git a/src/settings.cpp b/src/settings.cpp index 462cd92a..15bc801a 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -1808,10 +1808,12 @@ void NexusSettings::registerAsNXMHandler(bool force) } parameters += " \"" + executable + "\""; - if (!shell::Execute(nxmPath, parameters)) { + const auto r = shell::Execute(nxmPath, parameters); + + if (!r.success()) { QMessageBox::critical( nullptr, QObject::tr("Failed"), - QObject::tr("Failed to start the helper application")); + QObject::tr("Failed to start the helper application: %1").arg(r.toString())); } } diff --git a/src/settingsdialognexus.cpp b/src/settingsdialognexus.cpp index 826075c0..2021bdc1 100644 --- a/src/settingsdialognexus.cpp +++ b/src/settingsdialognexus.cpp @@ -49,7 +49,7 @@ public: void openBrowser() { - shell::OpenLink(QUrl("https://www.nexusmods.com/users/myaccount?tab=api")); + shell::Open(QUrl("https://www.nexusmods.com/users/myaccount?tab=api")); } void paste() diff --git a/src/texteditor.cpp b/src/texteditor.cpp index 0c0eb1cc..4a8080f4 100644 --- a/src/texteditor.cpp +++ b/src/texteditor.cpp @@ -199,7 +199,7 @@ void TextEditor::explore() return; } - MOBase::shell::ExploreFile(m_filename); + shell::Explore(m_filename); } void TextEditor::onModified(bool b) -- cgit v1.3.1 From a082c029b25dcbf0877f318092eae925d177f223 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Mon, 7 Oct 2019 07:04:56 -0400 Subject: added spawn delay setting, not exposed --- src/settings.cpp | 11 +++++++++++ src/settings.h | 3 +++ src/usvfsconnector.cpp | 11 +++++++---- 3 files changed, 21 insertions(+), 4 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/settings.cpp b/src/settings.cpp index 15bc801a..5aeb82fe 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -1997,3 +1997,14 @@ void DiagnosticsSettings::setCrashDumpsMax(int n) { set(m_Settings, "Settings", "crash_dumps_max", n); } + +std::chrono::seconds DiagnosticsSettings::spawnDelay() const +{ + return std::chrono::seconds( + get(m_Settings, "Settings", "spawn_delay", 0)); +} + +void DiagnosticsSettings::setSpawnDelay(std::chrono::seconds t) +{ + set(m_Settings, "Settings", "spawn_delay", t.count()); +} diff --git a/src/settings.h b/src/settings.h index 1556ba1e..d604823a 100644 --- a/src/settings.h +++ b/src/settings.h @@ -629,6 +629,9 @@ public: int crashDumpsMax() const; void setCrashDumpsMax(int n); + std::chrono::seconds spawnDelay() const; + void setSpawnDelay(std::chrono::seconds t); + private: QSettings& m_Settings; }; diff --git a/src/usvfsconnector.cpp b/src/usvfsconnector.cpp index 4315ed92..3ea811be 100644 --- a/src/usvfsconnector.cpp +++ b/src/usvfsconnector.cpp @@ -162,12 +162,15 @@ QString toString(CrashDumpsType t) UsvfsConnector::UsvfsConnector() { + const auto& s = Settings::instance(); + USVFSParameters params; - LogLevel level = toUsvfsLogLevel(Settings::instance().diagnostics().logLevel()); - CrashDumpsType dumpType = Settings::instance().diagnostics().crashDumpsType(); + const LogLevel level = toUsvfsLogLevel(s.diagnostics().logLevel()); + const CrashDumpsType dumpType = s.diagnostics().crashDumpsType(); + const auto delay = s.diagnostics().spawnDelay(); std::string dumpPath = MOShared::ToString(OrganizerCore::crashDumpsPath(), true); - USVFSInitParameters(¶ms, SHMID, false, level, dumpType, dumpPath.c_str()); + USVFSInitParameters(¶ms, SHMID, false, level, dumpType, dumpPath.c_str(), delay); InitLogging(false); log::debug( @@ -183,7 +186,7 @@ UsvfsConnector::UsvfsConnector() CreateVFS(¶ms); ClearExecutableBlacklist(); - for (auto exec : Settings::instance().executablesBlacklist().split(";")) { + for (auto exec : s.executablesBlacklist().split(";")) { std::wstring buf = exec.toStdWString(); BlacklistExecutable(buf.data()); } -- cgit v1.3.1 From 8fcaea9de32b888ec8839ef6b7f394556383275e Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Fri, 22 Nov 2019 07:44:09 -0500 Subject: added loot log level option --- src/loot.cpp | 79 +++++++++++++--------- src/settings.cpp | 11 +++ src/settings.h | 5 ++ src/settingsdialog.ui | 136 ++++++++++++++++++-------------------- src/settingsdialogdiagnostics.cpp | 36 +++++++++- src/settingsdialogdiagnostics.h | 3 +- 6 files changed, 164 insertions(+), 106 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/loot.cpp b/src/loot.cpp index 7184cce8..c5df8c9d 100644 --- a/src/loot.cpp +++ b/src/loot.cpp @@ -6,6 +6,30 @@ using namespace MOBase; +log::Levels levelFromLoot(lootcli::LogLevels level) +{ + using LC = lootcli::LogLevels; + + switch (level) + { + case LC::Trace: // fall-through + case LC::Debug: + return log::Debug; + + case LC::Info: + return log::Info; + + case LC::Warning: + return log::Warning; + + case LC::Error: + return log::Error; + + default: + return log::Info; + } +} + class LootDialog : public QDialog { @@ -15,6 +39,7 @@ public: m_label(nullptr), m_progress(nullptr), m_buttons(nullptr), m_finished(false) { createUI(); + m_progress->setMaximum(0); QObject::connect( &m_loot, &Loot::output, this, @@ -45,6 +70,11 @@ public: void setProgress(lootcli::Progress p) { setText(progressToString(p)); + + if (p == lootcli::Progress::Done) { + m_progress->setRange(0, 1); + m_progress->setValue(1); + } } QString progressToString(lootcli::Progress p) @@ -65,13 +95,12 @@ public: } } - void setIndeterminate() - { - m_progress->setMaximum(0); - } - void addOutput(const QString& s) { + if (m_core.settings().diagnostics().lootLogLevel() > lootcli::LogLevels::Debug) { + return; + } + const auto lines = s.split(QRegExp("[\\r\\n]"), QString::SkipEmptyParts); for (auto&& line : lines) { @@ -101,17 +130,7 @@ public: int exec() override { - QDialog::exec(); - - if (m_errorMessages.length() > 0) { - QMessageBox *warn = new QMessageBox( - QMessageBox::Warning, tr("Errors occurred"), - m_errorMessages, QMessageBox::Ok, parentWidget()); - - warn->exec(); - } - - return 0; + return QDialog::exec(); } void onError(const QString& s) @@ -126,8 +145,6 @@ private: QProgressBar* m_progress; QDialogButtonBox* m_buttons; QPlainTextEdit* m_output; - QString m_lastLine; - QString m_errorMessages; bool m_finished; void createUI() @@ -146,11 +163,14 @@ private: ly->addWidget(m_progress); m_output = new QPlainTextEdit; + m_output->setWordWrapMode(QTextOption::NoWrap); ly->addWidget(m_output); m_buttons = new QDialogButtonBox(QDialogButtonBox::Cancel); connect(m_buttons, &QDialogButtonBox::clicked, [&](auto* b){ onButton(b); }); ly->addWidget(m_buttons); + + resize(700, 400); } void closeEvent(QCloseEvent* e) override @@ -173,7 +193,6 @@ private: void addLineOutput(const QString& line) { m_output->appendPlainText(line); - m_lastLine = line; } void onFinished() @@ -183,14 +202,12 @@ private: void log(log::Levels lv, const QString& s) { - if (lv == log::Levels::Error) { - MOBase::log::error("{}", s); - - if (!m_errorMessages.isEmpty()) { - m_errorMessages += "\n"; - } + if (lv >= log::Levels::Warning) { + log::log(lv, "{}", s); + } - m_errorMessages += s; + if (m_core.settings().diagnostics().lootLogLevel() > lootcli::LogLevels::Debug) { + addLineOutput(QString("[%1] %2").arg(log::levelToString(lv)).arg(s)); } } }; @@ -210,11 +227,14 @@ bool Loot::start(QWidget* parent, OrganizerCore& core, bool didUpdateMasterList) { m_outPath = QDir::temp().absoluteFilePath("lootreport.json"); + const auto logLevel = core.settings().diagnostics().lootLogLevel(); + QStringList parameters; parameters << "--game" << core.managedGame()->gameShortName() << "--gamePath" << QString("\"%1\"").arg(core.managedGame()->gameDirectory().absolutePath()) << "--pluginListPath" << QString("\"%1/loadorder.txt\"").arg(core.profilePath()) + << "--logLevel" << QString::fromStdString(lootcli::logLevelToString(logLevel)) << "--out" << QString("\"%1\"").arg(m_outPath); if (didUpdateMasterList) { @@ -406,7 +426,7 @@ void Loot::processMessage(const lootcli::Message& m) { case lootcli::MessageType::Log: { - if (m.logLevel == spdlog::level::err) { + if (m.logLevel == lootcli::LogLevels::Error) { std::smatch match; if (std::regex_match(m.log, match, exRequires)) { @@ -422,10 +442,10 @@ void Loot::processMessage(const lootcli::Message& m) QString::fromStdString(modName), tr("incompatible with \"%1\"").arg(dependency.c_str())); } else { - emit log(log::levelFromSpdlog(m.logLevel), QString::fromStdString(m.log)); + emit log(levelFromLoot(m.logLevel), QString::fromStdString(m.log)); } } else { - emit log(log::levelFromSpdlog(m.logLevel), QString::fromStdString(m.log)); + emit log(levelFromLoot(m.logLevel), QString::fromStdString(m.log)); } break; @@ -657,7 +677,6 @@ bool runLoot(QWidget* parent, OrganizerCore& core, bool didUpdateMasterList) loot.start(parent, core, didUpdateMasterList); dialog.setText(QObject::tr("Please wait while LOOT is running")); - dialog.setIndeterminate(); dialog.exec(); return dialog.result(); diff --git a/src/settings.cpp b/src/settings.cpp index 5aeb82fe..b533b400 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -1977,6 +1977,17 @@ void DiagnosticsSettings::setLogLevel(log::Levels level) set(m_Settings, "Settings", "log_level", level); } +lootcli::LogLevels DiagnosticsSettings::lootLogLevel() const +{ + return get( + m_Settings, "Settings", "loot_log_level", lootcli::LogLevels::Info); +} + +void DiagnosticsSettings::setLootLogLevel(lootcli::LogLevels level) +{ + set(m_Settings, "Settings", "loot_log_level", level); +} + CrashDumpsType DiagnosticsSettings::crashDumpsType() const { return get(m_Settings, diff --git a/src/settings.h b/src/settings.h index d604823a..d71fabf4 100644 --- a/src/settings.h +++ b/src/settings.h @@ -21,6 +21,7 @@ along with Mod Organizer. If not, see . #define SETTINGS_H #include "loadmechanism.h" +#include #include #include #include @@ -619,6 +620,10 @@ public: MOBase::log::Levels logLevel() const; void setLogLevel(MOBase::log::Levels level); + // log level for loot + lootcli::LogLevels lootLogLevel() const; + void setLootLogLevel(lootcli::LogLevels level); + // crash dump type for both MO and usvfs // CrashDumpsType crashDumpsType() const; diff --git a/src/settingsdialog.ui b/src/settingsdialog.ui index 0ecbd101..b88c8b71 100644 --- a/src/settingsdialog.ui +++ b/src/settingsdialog.ui @@ -1386,44 +1386,23 @@ programs you are intentionally running. Diagnostics - - - - - - Max Dumps To Keep - - - - - - - Qt::Horizontal - - - - 60 - 20 - - - - - - - - Maximum number of crash dumps to keep on disk. Use 0 for unlimited. - - - - Maximum number of crash dumps to keep on disk. Use 0 for unlimited. - Set "Crash Dumps" above to None to disable crash dump collection. - - - - - - + + + Qt::Vertical + + + QSizePolicy::Expanding + + + + 20 + 232 + + + + + Hint: right click link and copy link location @@ -1444,16 +1423,42 @@ programs you are intentionally running. - - - + + + + QFormLayout::ExpandingFieldsGrow + + + 12 + + + + + Log Level + + + + + + + Decides the amount of data printed to "ModOrganizer.log" + + + + Decides the amount of data printed to "ModOrganizer.log". + "Debug" produces very useful information for finding problems. There is usually no noteworthy performance impact but the file may become rather large. If this is a problem you may prefer the "Info" level for regular use. On the "Error" level the log file usually remains empty. + + + + + Crash Dumps - + Decides which type of crash dumps are collected when injected processes crash. @@ -1469,46 +1474,36 @@ programs you are intentionally running. - - - - - - Qt::Vertical - - - QSizePolicy::Expanding - - - - 20 - 232 - - - - - - - - + + - Log Level + Max Dumps To Keep - - + + - Decides the amount of data printed to "ModOrganizer.log" + Maximum number of crash dumps to keep on disk. Use 0 for unlimited. - Decides the amount of data printed to "ModOrganizer.log". - "Debug" produces very useful information for finding problems. There is usually no noteworthy performance impact but the file may become rather large. If this is a problem you may prefer the "Info" level for regular use. On the "Error" level the log file usually remains empty. + Maximum number of crash dumps to keep on disk. Use 0 for unlimited. + Set "Crash Dumps" above to None to disable crash dump collection. + + + + LOOT Log Level + + + + + + @@ -1589,9 +1584,6 @@ programs you are intentionally running. bsaDateBtn execBlacklistBtn resetGeometryBtn - logLevelBox - dumpsTypeBox - dumpsMaxEdit diff --git a/src/settingsdialogdiagnostics.cpp b/src/settingsdialogdiagnostics.cpp index 386c7425..74cadaa9 100644 --- a/src/settingsdialogdiagnostics.cpp +++ b/src/settingsdialogdiagnostics.cpp @@ -9,7 +9,8 @@ using namespace MOBase; DiagnosticsSettingsTab::DiagnosticsSettingsTab(Settings& s, SettingsDialog& d) : SettingsTab(s, d) { - setLevelsBox(); + setLogLevel(); + setLootLogLevel(); setCrashDumpTypesBox(); ui->dumpsMaxEdit->setValue(settings().diagnostics().crashDumpsMax()); @@ -26,7 +27,7 @@ DiagnosticsSettingsTab::DiagnosticsSettingsTab(Settings& s, SettingsDialog& d) ); } -void DiagnosticsSettingsTab::setLevelsBox() +void DiagnosticsSettingsTab::setLogLevel() { ui->logLevelBox->clear(); @@ -35,14 +36,40 @@ void DiagnosticsSettingsTab::setLevelsBox() ui->logLevelBox->addItem(QObject::tr("Warning"), log::Warning); ui->logLevelBox->addItem(QObject::tr("Error"), log::Error); + const auto sel = settings().diagnostics().logLevel(); + for (int i=0; ilogLevelBox->count(); ++i) { - if (ui->logLevelBox->itemData(i) == settings().diagnostics().logLevel()) { + if (ui->logLevelBox->itemData(i) == sel) { ui->logLevelBox->setCurrentIndex(i); break; } } } +void DiagnosticsSettingsTab::setLootLogLevel() +{ + using L = lootcli::LogLevels; + + auto v = [](L level) { return QVariant(static_cast(level)); }; + + ui->lootLogLevel->clear(); + + ui->lootLogLevel->addItem(QObject::tr("Trace"), v(L::Trace)); + ui->lootLogLevel->addItem(QObject::tr("Debug"), v(L::Debug)); + ui->lootLogLevel->addItem(QObject::tr("Info (recommended)"), v(L::Info)); + ui->lootLogLevel->addItem(QObject::tr("Warning"), v(L::Warning)); + ui->lootLogLevel->addItem(QObject::tr("Error"), v(L::Error)); + + const auto sel = settings().diagnostics().lootLogLevel(); + + for (int i=0; ilootLogLevel->count(); ++i) { + if (ui->lootLogLevel->itemData(i) == v(sel)) { + ui->lootLogLevel->setCurrentIndex(i); + break; + } + } +} + void DiagnosticsSettingsTab::setCrashDumpTypesBox() { ui->dumpsTypeBox->clear(); @@ -76,4 +103,7 @@ void DiagnosticsSettingsTab::update() static_cast(ui->dumpsTypeBox->currentData().toInt())); settings().diagnostics().setCrashDumpsMax(ui->dumpsMaxEdit->value()); + + settings().diagnostics().setLootLogLevel( + static_cast(ui->lootLogLevel->currentData().toInt())); } diff --git a/src/settingsdialogdiagnostics.h b/src/settingsdialogdiagnostics.h index f0fbf770..e01ee22f 100644 --- a/src/settingsdialogdiagnostics.h +++ b/src/settingsdialogdiagnostics.h @@ -12,7 +12,8 @@ public: void update(); private: - void setLevelsBox(); + void setLogLevel(); + void setLootLogLevel(); void setCrashDumpTypesBox(); }; -- cgit v1.3.1 From 9194bfa16bb78c10bc4e23abd26ba16c33956794 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Tue, 26 Nov 2019 08:59:04 -0500 Subject: added option to hide confirmation when switching instances --- src/mainwindow.cpp | 16 ++++++++++------ src/settings.cpp | 10 ++++++++++ src/settings.h | 5 +++++ src/settingsdialog.ui | 7 +++++++ src/settingsdialoggeneral.cpp | 2 ++ 5 files changed, 34 insertions(+), 6 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 9ea554a2..844456a6 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -6139,14 +6139,18 @@ void MainWindow::on_actionNotifications_triggered() void MainWindow::on_actionChange_Game_triggered() { - const auto r = QMessageBox::question( - this, tr("Are you sure?"), tr("This will restart MO, continue?"), - QMessageBox::Yes | QMessageBox::Cancel); + if (m_OrganizerCore.settings().interface().showChangeGameConfirmation()) { + const auto r = QMessageBox::question( + this, tr("Are you sure?"), tr("This will restart MO, continue?"), + QMessageBox::Yes | QMessageBox::Cancel); - if (r == QMessageBox::Yes) { - InstanceManager::instance().clearCurrentInstance(); - ExitModOrganizer(Exit::Restart); + if (r != QMessageBox::Yes) { + return; + } } + + InstanceManager::instance().clearCurrentInstance(); + ExitModOrganizer(Exit::Restart); } void MainWindow::setCategoryListVisible(bool visible) diff --git a/src/settings.cpp b/src/settings.cpp index b533b400..e1e5c2da 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -1961,6 +1961,16 @@ void InterfaceSettings::setTutorialCompleted(const QString& windowName, bool b) set(m_Settings, "CompletedWindowTutorials", windowName, b); } +bool InterfaceSettings::showChangeGameConfirmation() const +{ + return get(m_Settings, "Settings", "show_change_game_confirmation", true); +} + +void InterfaceSettings::setShowChangeGameConfirmation(bool b) const +{ + set(m_Settings, "Settings", "show_change_game_confirmation", b); +} + DiagnosticsSettings::DiagnosticsSettings(QSettings& settings) : m_Settings(settings) diff --git a/src/settings.h b/src/settings.h index d71fabf4..870e0fc4 100644 --- a/src/settings.h +++ b/src/settings.h @@ -605,6 +605,11 @@ public: bool isTutorialCompleted(const QString& windowName) const; void setTutorialCompleted(const QString& windowName, bool b=true); + // whether to show the confirmation when switching instances + // + bool showChangeGameConfirmation() const; + void setShowChangeGameConfirmation(bool b) const; + private: QSettings& m_Settings; }; diff --git a/src/settingsdialog.ui b/src/settingsdialog.ui index b88c8b71..e63ca692 100644 --- a/src/settingsdialog.ui +++ b/src/settingsdialog.ui @@ -108,6 +108,13 @@
+ + + + Show confirmation when changing instance + + + diff --git a/src/settingsdialoggeneral.cpp b/src/settingsdialoggeneral.cpp index e21fc5d0..b0e64305 100644 --- a/src/settingsdialoggeneral.cpp +++ b/src/settingsdialoggeneral.cpp @@ -17,6 +17,7 @@ GeneralSettingsTab::GeneralSettingsTab(Settings& s, SettingsDialog& d) ui->colorTable->load(s); ui->centerDialogs->setChecked(settings().geometry().centerDialogs()); + ui->changeGameConfirmation->setChecked(settings().interface().showChangeGameConfirmation()); ui->compactBox->setChecked(settings().interface().compactDownloads()); ui->showMetaBox->setChecked(settings().interface().metaDownloads()); ui->checkForUpdates->setChecked(settings().checkForUpdates()); @@ -59,6 +60,7 @@ void GeneralSettingsTab::update() ui->colorTable->commitColors(); settings().geometry().setCenterDialogs(ui->centerDialogs->isChecked()); + settings().interface().setShowChangeGameConfirmation(ui->changeGameConfirmation->isChecked()); settings().interface().setCompactDownloads(ui->compactBox->isChecked()); settings().interface().setMetaDownloads(ui->showMetaBox->isChecked()); settings().setCheckForUpdates(ui->checkForUpdates->isChecked()); -- cgit v1.3.1 From a0fa896e68856ec5204e7f74db775bdb3595010a Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Wed, 4 Dec 2019 12:42:15 -0500 Subject: added open previews on double-click option implemented for filetree --- src/modinfodialogfiletree.cpp | 42 +++++++++++++++++++++++++++++++++--------- src/settings.cpp | 12 +++++++++++- src/settings.h | 7 ++++++- src/settingsdialog.ui | 10 ++++++++++ src/settingsdialoggeneral.cpp | 2 ++ 5 files changed, 62 insertions(+), 11 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/modinfodialogfiletree.cpp b/src/modinfodialogfiletree.cpp index e94b0a4f..c79a5264 100644 --- a/src/modinfodialogfiletree.cpp +++ b/src/modinfodialogfiletree.cpp @@ -32,10 +32,6 @@ FileTreeTab::FileTreeTab(ModInfoDialogTabContext cx) m_actions.hide = new QAction(tr("&Hide"), ui->filetree); m_actions.unhide = new QAction(tr("&Unhide"), ui->filetree); - auto bold = m_actions.open->font(); - bold.setBold(true); - m_actions.open->setFont(bold); - connect(m_actions.newFolder, &QAction::triggered, [&]{ onCreateDirectory(); }); connect(m_actions.open, &QAction::triggered, [&]{ onOpen(); }); connect(m_actions.runHooked, &QAction::triggered, [&]{ onRunHooked(); }); @@ -152,10 +148,17 @@ void FileTreeTab::onOpen() return; } - core().processRunner() - .setFromFile(parentWidget(), m_fs->filePath(selection)) - .setWaitForCompletion() - .run(); + const auto path = m_fs->filePath(selection); + const auto tryPreview = core().settings().interface().doubleClicksOpenPreviews(); + + if (tryPreview && canPreviewFile(plugin(), false, path)) { + core().previewFile(parentWidget(), mod().name(), path); + } else { + core().processRunner() + .setFromFile(parentWidget(), path) + .setWaitForCompletion() + .run(); + } } void FileTreeTab::onRunHooked() @@ -408,7 +411,6 @@ void FileTreeTab::onContextMenu(const QPoint &pos) // this is a multiple selection, don't show open or explore actions so users // don't open a thousand files enableNewFolder = true; - enablePreview = true; enableDelete = true; if (selection.size() < max_scan_for_context_menu) { @@ -446,6 +448,28 @@ void FileTreeTab::onContextMenu(const QPoint &pos) menu.addAction(m_actions.preview); m_actions.preview->setEnabled(enablePreview); + auto bold = m_actions.preview->font(); + bold.setBold(true); + auto notBold = m_actions.preview->font(); + notBold.setBold(false); + + // preview is bold if the file is previewable and [the preview on double-click + // option is enabled or the file can't be opened]; open is bold if the file + // can be opened and cannot be previewed + if (enablePreview && core().settings().interface().doubleClicksOpenPreviews()) { + m_actions.open->setFont(notBold); + m_actions.preview->setFont(bold); + } else if (enableOpen) { + m_actions.open->setFont(bold); + m_actions.preview->setFont(notBold); + } else if (enablePreview) { + m_actions.open->setFont(notBold); + m_actions.preview->setFont(bold); + } else { + m_actions.open->setFont(notBold); + m_actions.preview->setFont(notBold); + } + menu.addAction(m_actions.explore); m_actions.explore->setEnabled(enableExplore); diff --git a/src/settings.cpp b/src/settings.cpp index e1e5c2da..68dc19d9 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -1966,11 +1966,21 @@ bool InterfaceSettings::showChangeGameConfirmation() const return get(m_Settings, "Settings", "show_change_game_confirmation", true); } -void InterfaceSettings::setShowChangeGameConfirmation(bool b) const +void InterfaceSettings::setShowChangeGameConfirmation(bool b) { set(m_Settings, "Settings", "show_change_game_confirmation", b); } +bool InterfaceSettings::doubleClicksOpenPreviews() const +{ + return get(m_Settings, "Settings", "double_click_previews", false); +} + +void InterfaceSettings::setDoubleClicksOpenPreviews(bool b) +{ + set(m_Settings, "Settings", "double_click_previews", b); +} + DiagnosticsSettings::DiagnosticsSettings(QSettings& settings) : m_Settings(settings) diff --git a/src/settings.h b/src/settings.h index 870e0fc4..0e5238b1 100644 --- a/src/settings.h +++ b/src/settings.h @@ -608,7 +608,12 @@ public: // whether to show the confirmation when switching instances // bool showChangeGameConfirmation() const; - void setShowChangeGameConfirmation(bool b) const; + void setShowChangeGameConfirmation(bool b); + + // whether double-clicks on files should try to open previews first + // + bool doubleClicksOpenPreviews() const; + void setDoubleClicksOpenPreviews(bool b); private: QSettings& m_Settings; diff --git a/src/settingsdialog.ui b/src/settingsdialog.ui index bc59d635..8e175312 100644 --- a/src/settingsdialog.ui +++ b/src/settingsdialog.ui @@ -101,6 +101,9 @@ + + https://www.transifex.com/tannin/mod-organizer/ + <a href="https://www.transifex.com/tannin/mod-organizer/">Help translate Mod Organizer</a> @@ -132,6 +135,13 @@ + + + + Open previews on double-click + + + diff --git a/src/settingsdialoggeneral.cpp b/src/settingsdialoggeneral.cpp index dca4410b..58871cee 100644 --- a/src/settingsdialoggeneral.cpp +++ b/src/settingsdialoggeneral.cpp @@ -21,6 +21,7 @@ GeneralSettingsTab::GeneralSettingsTab(Settings& s, SettingsDialog& d) ui->centerDialogs->setChecked(settings().geometry().centerDialogs()); ui->changeGameConfirmation->setChecked(settings().interface().showChangeGameConfirmation()); + ui->doubleClickPreviews->setChecked(settings().interface().doubleClicksOpenPreviews()); ui->compactBox->setChecked(settings().interface().compactDownloads()); ui->showMetaBox->setChecked(settings().interface().metaDownloads()); ui->checkForUpdates->setChecked(settings().checkForUpdates()); @@ -63,6 +64,7 @@ void GeneralSettingsTab::update() settings().geometry().setCenterDialogs(ui->centerDialogs->isChecked()); settings().interface().setShowChangeGameConfirmation(ui->changeGameConfirmation->isChecked()); + settings().interface().setDoubleClicksOpenPreviews(ui->doubleClickPreviews->isChecked()); settings().interface().setCompactDownloads(ui->compactBox->isChecked()); settings().interface().setMetaDownloads(ui->showMetaBox->isChecked()); settings().setCheckForUpdates(ui->checkForUpdates->isChecked()); -- cgit v1.3.1 From 8c3a3e8257e63328298c91c71740ac3a550b70d6 Mon Sep 17 00:00:00 2001 From: Al Date: Sun, 8 Dec 2019 21:05:58 +0100 Subject: Changed default behavior for "Open Previews on double click" to true since it's probably the most desirable option. --- src/settings.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/settings.cpp') diff --git a/src/settings.cpp b/src/settings.cpp index 68dc19d9..5170a5de 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -1973,7 +1973,7 @@ void InterfaceSettings::setShowChangeGameConfirmation(bool b) bool InterfaceSettings::doubleClicksOpenPreviews() const { - return get(m_Settings, "Settings", "double_click_previews", false); + return get(m_Settings, "Settings", "double_click_previews", true); } void InterfaceSettings::setDoubleClicksOpenPreviews(bool b) -- cgit v1.3.1