From b7cb63ddb1e2b263d5e485c97faea527c7c0af44 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Fri, 6 Nov 2020 11:37:12 -0500 Subject: removed some redundant functions in InstanceManager, made them all non-static documentation --- src/instancemanager.cpp | 98 +++++++++++++++++++++++++------------------------ 1 file changed, 51 insertions(+), 47 deletions(-) (limited to 'src/instancemanager.cpp') diff --git a/src/instancemanager.cpp b/src/instancemanager.cpp index 8163149b..e7c2a611 100644 --- a/src/instancemanager.cpp +++ b/src/instancemanager.cpp @@ -79,7 +79,7 @@ QString Instance::profileName() const QString Instance::iniPath() const { - return InstanceManager::iniPath(m_dir); + return InstanceManager::singleton().iniPath(m_dir); } bool Instance::isPortable() const @@ -96,6 +96,7 @@ Instance::SetupResults Instance::setup(PluginContainer& plugins) return SetupResults::BadIni; } + // game name and directory are from ini unless overridden by setGame() if (m_gameName.isEmpty()) { if (auto v=s.game().name()) m_gameName = *v; @@ -106,11 +107,13 @@ Instance::SetupResults Instance::setup(PluginContainer& plugins) m_gameDir = *v; } + // getting game plugin const auto r = getGamePlugin(plugins); if (r != SetupResults::Ok) { return r; } + // getting game variant, error if it's missing and required by the plugin if (m_gameVariant.isEmpty()) { if (auto v=s.game().edition()) { m_gameVariant = *v; @@ -123,15 +126,22 @@ Instance::SetupResults Instance::setup(PluginContainer& plugins) m_plugin->setGameVariant(m_gameVariant); } + // figuring out profile from ini if it's missing getProfile(s); + // updating the settings since some of these values might have been missing s.game().setName(m_gameName); s.game().setDirectory(m_gameDir); s.game().setSelectedProfileName(m_profile); - if (!m_gameVariant.isEmpty()) + if (!m_gameVariant.isEmpty()) { + // don't write a variant to the ini if the plugin doesn't require one s.game().setEdition(m_gameVariant); + } + // the game directory may be different than what the plugin detected, the user + // can change it in the settings and might have multiple versions of the game + // installed m_plugin->setGamePath(m_gameDir); return SetupResults::Ok; @@ -299,31 +309,27 @@ InstanceManager &InstanceManager::singleton() void InstanceManager::overrideInstance(const QString& instanceName) { m_overrideInstanceName = instanceName; - m_overrideInstance = true; } void InstanceManager::overrideProfile(const QString& profileName) { m_overrideProfileName = profileName; - m_overrideProfile = true; } std::optional InstanceManager::currentInstance() const { - const QString profile = m_overrideProfile ? m_overrideProfileName : ""; + const QString profile = m_overrideProfileName ? + *m_overrideProfileName : ""; + + const QString name = m_overrideInstanceName ? + *m_overrideInstanceName : GlobalSettings::currentInstance(); - if (portableInstallIsLocked()) { + + if (!allowedToChangeInstance()) { // force portable instance return Instance(QDir(portablePath()), true, profile); } - QString name; - - if (m_overrideInstance) - name = m_overrideInstanceName; - else - name = GlobalSettings::currentInstance(); - if (name.isEmpty()) { if (portableInstanceExists()) { // use portable @@ -340,7 +346,7 @@ std::optional InstanceManager::currentInstance() const void InstanceManager::clearCurrentInstance() { setCurrentInstance(""); - m_overrideInstance = false; + m_overrideInstanceName = {}; } void InstanceManager::setCurrentInstance(const QString &name) @@ -350,27 +356,27 @@ void InstanceManager::setCurrentInstance(const QString &name) QString InstanceManager::instancePath(const QString& instanceName) const { - return QDir::fromNativeSeparators(instancesPath() + "/" + instanceName); + return QDir::fromNativeSeparators(globalInstancesRootPath() + "/" + instanceName); } -QString InstanceManager::instancesPath() const +QString InstanceManager::globalInstancesRootPath() const { return QDir::fromNativeSeparators( QStandardPaths::writableLocation(QStandardPaths::DataLocation)); } -QString InstanceManager::iniPath(const QDir& instanceDir) +QString InstanceManager::iniPath(const QDir& instanceDir) const { return instanceDir.filePath(QString::fromStdWString(AppConfig::iniFileName())); } -std::vector InstanceManager::instancePaths() const +std::vector InstanceManager::globalInstancePaths() const { const std::set ignore = { "cache", "qtwebengine", }; - const QDir root(instancesPath()); + const QDir root(globalInstancesRootPath()); const auto dirs = root.entryList(QDir::Dirs | QDir::NoDotAndDotDot); std::vector list; @@ -384,24 +390,12 @@ std::vector InstanceManager::instancePaths() const return list; } -QStringList InstanceManager::instanceNames() const -{ - QStringList list; - - for (auto&& d : instancePaths()) { - list.push_back(d.dirName()); - } - - return list; -} - - -bool InstanceManager::isPortablePath(const QString& dataPath) +bool InstanceManager::hasAnyInstances() const { - return (dataPath == portablePath()); + return portableInstanceExists() || !globalInstancePaths().empty(); } -QString InstanceManager::portablePath() +QString InstanceManager::portablePath() const { return qApp->applicationDirPath(); } @@ -412,16 +406,13 @@ bool InstanceManager::portableInstanceExists() const QString::fromStdWString(AppConfig::iniFileName())); } - -bool InstanceManager::portableInstallIsLocked() const -{ - return QFile::exists(qApp->applicationDirPath() + "/" + - QString::fromStdWString(AppConfig::portableLockFileName())); -} - bool InstanceManager::allowedToChangeInstance() const { - return !portableInstallIsLocked(); + const auto lockFile = + qApp->applicationDirPath() + "/" + + QString::fromStdWString(AppConfig::portableLockFileName()); + + return !QFile::exists(lockFile); } const MOBase::IPluginGame* InstanceManager::gamePluginForDirectory( @@ -429,6 +420,7 @@ const MOBase::IPluginGame* InstanceManager::gamePluginForDirectory( { const QString ini = iniPath(instanceDir); + // reading ini Settings s(ini); if (s.iniStatus() != QSettings::NoError) @@ -437,6 +429,7 @@ const MOBase::IPluginGame* InstanceManager::gamePluginForDirectory( return nullptr; } + // using game name from ini, if available const auto instanceGameName = s.game().name(); if (instanceGameName && !instanceGameName->isEmpty()) @@ -448,7 +441,7 @@ const MOBase::IPluginGame* InstanceManager::gamePluginForDirectory( } log::error( - "no plugin reports game name '{}' found in ini {}", + "no plugin has game name '{}' that was found in ini {}", *instanceGameName, ini); } else @@ -457,8 +450,7 @@ const MOBase::IPluginGame* InstanceManager::gamePluginForDirectory( } - log::error("falling back on looksValid check"); - + // using game directory from ini, if available const auto gameDir = s.game().directory(); if (gameDir && !gameDir->isEmpty()) @@ -470,7 +462,7 @@ const MOBase::IPluginGame* InstanceManager::gamePluginForDirectory( } log::error( - "no plugins appear to support game directory '{}' from ini {}", + "no plugin appears to support game directory '{}' from ini {}", *gameDir, ini); } else @@ -478,6 +470,17 @@ const MOBase::IPluginGame* InstanceManager::gamePluginForDirectory( log::error("no game directory found in ini {}", ini); } + + // looking for a plugin that can handle the directory + log::debug("falling back on looksValid check"); + + for (const IPluginGame* game : plugins.plugins()) { + if (game->looksValid(instanceDir)) { + return game; + } + } + + return nullptr; } @@ -485,6 +488,7 @@ QString InstanceManager::makeUniqueName(const QString& instanceName) const { const QString sanitized = sanitizeInstanceName(instanceName); + // trying "name (N)" QString name = sanitized; for (int i=2; i<100; ++i) { if (!instanceExists(name)) { @@ -499,7 +503,7 @@ QString InstanceManager::makeUniqueName(const QString& instanceName) const bool InstanceManager::instanceExists(const QString& instanceName) const { - const QDir root = instancesPath(); + const QDir root = globalInstancesRootPath(); return root.exists(instanceName); } -- cgit v1.3.1 From dc2ada2a4249917f538938298deb193ed1dd6bb9 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Fri, 6 Nov 2020 13:56:04 -0500 Subject: added ... to the "Delete Instance" button to make it less scary merged InstanceInfo into Instance, most of it was redundant added logging before deleting instance added Instance::readFromIni(), contains stuff that used to be in setup(), used by instance dialog replaced QDir with QString in a few places, I hate QDir --- src/instancemanager.cpp | 278 +++++++++++++++++++++++++++++---- src/instancemanager.h | 109 ++++++++++--- src/instancemanagerdialog.cpp | 347 +++++------------------------------------- src/instancemanagerdialog.h | 80 +++++++++- src/instancemanagerdialog.ui | 2 +- src/main.cpp | 8 +- 6 files changed, 456 insertions(+), 368 deletions(-) (limited to 'src/instancemanager.cpp') diff --git a/src/instancemanager.cpp b/src/instancemanager.cpp index e7c2a611..fbafc6e8 100644 --- a/src/instancemanager.cpp +++ b/src/instancemanager.cpp @@ -38,7 +38,7 @@ along with Mod Organizer. If not, see . using namespace MOBase; -Instance::Instance(QDir dir, bool portable, QString profileName) : +Instance::Instance(QString dir, bool portable, QString profileName) : m_dir(std::move(dir)), m_portable(portable), m_plugin(nullptr), m_profile(std::move(profileName)) { @@ -49,7 +49,7 @@ QString Instance::name() const if (isPortable()) return QObject::tr("Portable"); else - return m_dir.dirName(); + return QDir(m_dir).dirName(); } QString Instance::gameName() const @@ -62,11 +62,16 @@ QString Instance::gameDirectory() const return m_gameDir; } -QDir Instance::directory() const +QString Instance::directory() const { return m_dir; } +QString Instance::baseDirectory() const +{ + return m_baseDir; +} + MOBase::IPluginGame* Instance::gamePlugin() const { return m_plugin; @@ -87,13 +92,29 @@ bool Instance::isPortable() const return m_portable; } -Instance::SetupResults Instance::setup(PluginContainer& plugins) +bool Instance::isActive() const +{ + auto& m = InstanceManager::singleton(); + + if (auto i=m.currentInstance()) + { + if (m_portable) { + return i->isPortable(); + } else { + return (i->name() == name()); + } + } + + return false; +} + +bool Instance::readFromIni() { Settings s(iniPath()); if (s.iniStatus() != QSettings::NoError) { log::error("can't read ini {}", iniPath()); - return SetupResults::BadIni; + return false; } // game name and directory are from ini unless overridden by setGame() @@ -107,27 +128,61 @@ Instance::SetupResults Instance::setup(PluginContainer& plugins) m_gameDir = *v; } - // getting game plugin - const auto r = getGamePlugin(plugins); - if (r != SetupResults::Ok) { - return r; - } - - // getting game variant, error if it's missing and required by the plugin if (m_gameVariant.isEmpty()) { if (auto v=s.game().edition()) { m_gameVariant = *v; } } + if (m_baseDir.isEmpty()) { + m_baseDir = s.paths().base(); + } + + // figuring out profile from ini if it's missing + getProfile(s); + + return true; +} + +Instance::SetupResults Instance::setup(PluginContainer& plugins) +{ + // read initial values from the ini + if (!readFromIni()) { + return SetupResults::BadIni; + } + + // getting game plugin + const auto r = getGamePlugin(plugins); + if (r != SetupResults::Ok) { + return r; + } + + // error if the variant missing and required by the plugin if (m_gameVariant.isEmpty() && m_plugin->gameVariants().size() > 1) { return SetupResults::MissingVariant; } else { m_plugin->setGameVariant(m_gameVariant); } - // figuring out profile from ini if it's missing - getProfile(s); + // update the ini in case anything was missing + updateIni(); + + // the game directory may be different than what the plugin detected, the user + // can change it in the settings and might have multiple versions of the game + // installed + m_plugin->setGamePath(m_gameDir); + + return SetupResults::Ok; +} + +void Instance::updateIni() +{ + Settings s(iniPath()); + + if (s.iniStatus() != QSettings::NoError) { + log::error("can't open ini {}", iniPath()); + return; + } // updating the settings since some of these values might have been missing s.game().setName(m_gameName); @@ -138,13 +193,6 @@ Instance::SetupResults Instance::setup(PluginContainer& plugins) // don't write a variant to the ini if the plugin doesn't require one s.game().setEdition(m_gameVariant); } - - // the game directory may be different than what the plugin detected, the user - // can change it in the settings and might have multiple versions of the game - // installed - m_plugin->setGamePath(m_gameDir); - - return SetupResults::Ok; } void Instance::setGame(const QString& name, const QString& dir) @@ -272,7 +320,6 @@ Instance::SetupResults Instance::getGamePlugin(PluginContainer& plugins) } } - void Instance::getProfile(const Settings& s) { if (!m_profile.isEmpty()) { @@ -294,6 +341,176 @@ void Instance::getProfile(const Settings& s) iniPath(), m_profile); } +// returns a list of files and folders that must be deleted when deleting +// this instance +// +std::vector Instance::objectsForDeletion() const +{ + // native separators and ending slash + auto prettyDir = [](auto s) { + if (!s.endsWith("/") || !s.endsWith("\\")) { + s += "/"; + } + + return QDir::toNativeSeparators(s); + }; + + // native separators + auto prettyFile = [](auto s) { + return QDir::toNativeSeparators(s); + }; + + + // lowercase, native separators and ending slash + auto canonicalDir = [](QString s) { + s = s.toLower(); + + if (!s.endsWith("/") || !s.endsWith("\\")) { + s += "/"; + } + + return QDir::toNativeSeparators(s); + }; + + // lower and native separators + auto canonicalFile = [](auto s) { + return QDir::toNativeSeparators(s.toLower()); + }; + + + + // whether the given directory is contained in the root + auto dirInRoot = [&](const QString& root, const QString& dir) { + return canonicalDir(dir).startsWith(canonicalDir(root)); + }; + + // whether the given file is contained in the root + auto fileInRoot = [&](const QString& root, const QString& file) { + return canonicalFile(file).startsWith(canonicalDir(root)); + }; + + + Settings settings(iniPath()); + + if (settings.iniStatus() != QSettings::NoError) { + log::error("can't read ini {}", iniPath()); + return {}; + } + + + + const QString loc = directory(); + const QString base = settings.paths().base(); + + + // directories that might contain the individual files and directories + // set in the path settings + std::vector roots; + + // a portable instance has its location in the installation directory, + // don't delete that + if (!isPortable()) { + if (QDir(loc).exists()) { + roots.push_back({loc, true}); + } + } + + // the base directory is the location directory by default, don't add it + // if it's the same + if (canonicalDir(base) != canonicalDir(loc)) { + if (QDir(base).exists()) { + roots.push_back({base, false}); + } + } + + + // all the directories that are part of an instance; none of them are + // mandatory for deletion + const std::vector dirs = { + settings.paths().downloads(), + settings.paths().mods(), + settings.paths().cache(), + settings.paths().profiles(), + settings.paths().overwrite(), + QDir(m_dir).filePath(QString::fromStdWString(AppConfig::dumpsDir())), + QDir(m_dir).filePath(QString::fromStdWString(AppConfig::logPath())), + }; + + // all the files that are part of an instance + const std::vector files = { + {iniPath(), true}, // the ini file must be deleted + }; + + + // this will contain the root directories, plus all the individual + // directories that are not inside these roots + std::vector cleanDirs; + + for (const auto& f : dirs) { + bool inRoots = false; + + for (const auto& root : roots) { + if (dirInRoot(root.path, f.path)) { + inRoots = true; + break; + } + } + + if (!inRoots) { + // not in roots, this is a path that was changed by the user; make + // sure it exists + if (QDir(f.path).exists()) { + cleanDirs.push_back({prettyDir(f.path), f.mandatoryDelete}); + } + } + } + + // prepending the roots + for (auto itor=roots.rbegin(); itor!=roots.rend(); ++itor) { + cleanDirs.insert( + cleanDirs.begin(), + {prettyDir(itor->path), itor->mandatoryDelete}); + } + + + + // this will contain the individual files that are not inside the roots; + // not that this only contains the INI file for now, so most of this is + // useless + std::vector cleanFiles; + + for (const auto& f : files) { + bool inRoots = false; + + for (const auto& root : roots) { + if (fileInRoot(root.path, f.path)) { + inRoots = true; + break; + } + } + + if (!inRoots) { + // not in roots, this is a path that was changed by the user; make + // sure it exists + if (QFileInfo(f.path).exists()) { + cleanFiles.push_back({prettyFile(f.path), f.mandatoryDelete}); + } + } + } + + + // contains all the directories and files to be deleted + std::vector all; + all.insert(all.end(), cleanDirs.begin(), cleanDirs.end()); + all.insert(all.end(), cleanFiles.begin(), cleanFiles.end()); + + // mandatory on top + std::stable_sort(all.begin(), all.end()); + + return all; +} + + InstanceManager::InstanceManager() { @@ -327,20 +544,20 @@ std::optional InstanceManager::currentInstance() const if (!allowedToChangeInstance()) { // force portable instance - return Instance(QDir(portablePath()), true, profile); + return Instance(portablePath(), true, profile); } if (name.isEmpty()) { if (portableInstanceExists()) { // use portable - return Instance(QDir(portablePath()), true, profile); + return Instance(portablePath(), true, profile); } else { // no instance set return {}; } } - return Instance(QDir(instancePath(name)), false, profile); + return Instance(instancePath(name), false, profile); } void InstanceManager::clearCurrentInstance() @@ -365,12 +582,13 @@ QString InstanceManager::globalInstancesRootPath() const QStandardPaths::writableLocation(QStandardPaths::DataLocation)); } -QString InstanceManager::iniPath(const QDir& instanceDir) const +QString InstanceManager::iniPath(const QString& instanceDir) const { - return instanceDir.filePath(QString::fromStdWString(AppConfig::iniFileName())); + return QDir(instanceDir).filePath( + QString::fromStdWString(AppConfig::iniFileName())); } -std::vector InstanceManager::globalInstancePaths() const +std::vector InstanceManager::globalInstancePaths() const { const std::set ignore = { "cache", "qtwebengine", @@ -379,7 +597,7 @@ std::vector InstanceManager::globalInstancePaths() const const QDir root(globalInstancesRootPath()); const auto dirs = root.entryList(QDir::Dirs | QDir::NoDotAndDotDot); - std::vector list; + std::vector list; for (auto&& d : dirs) { if (!ignore.contains(QFileInfo(d).fileName().toLower())) { @@ -416,7 +634,7 @@ bool InstanceManager::allowedToChangeInstance() const } const MOBase::IPluginGame* InstanceManager::gamePluginForDirectory( - const QDir& instanceDir, const PluginContainer& plugins) const + const QString& instanceDir, const PluginContainer& plugins) const { const QString ini = iniPath(instanceDir); diff --git a/src/instancemanager.h b/src/instancemanager.h index e2ceb743..161df739 100644 --- a/src/instancemanager.h +++ b/src/instancemanager.h @@ -55,15 +55,64 @@ public: }; + // a file or directory owned by this instance, used by objectsForDeletion() + // + struct Object + { + // path to the file or directory + QString path; + + // whether this object must be deleted to properly delete the instance; + // typically true only for the instance directory itself, but not for the + // base directory, etc. + bool mandatoryDelete; + + + Object(QString p, bool d=false) + : path(std::move(p)), mandatoryDelete(d) + { + } + + // puts mandatory delete on top + // + bool operator<(const Object& o) const + { + if (mandatoryDelete && !o.mandatoryDelete) { + return true; + } else if (!mandatoryDelete && o.mandatoryDelete) { + return false; + } + + return false; + } + }; + + + // an instance that lives in the given directory; `portable` must be `true` // if this is a portable instance // // `profileName` can be given to override what's in the INI; this typically // happens when the profile is overriden on the command line // - Instance(QDir dir, bool portable, QString profileName={}); + Instance(QString dir, bool portable, QString profileName={}); + + + // reads in values from the INI if they were not given yet: + // - game name + // - game directory + // - game variant + // - profile name + // + // note that setup() already calls this + // + // returns false if the ini couldn't be read from + // + bool readFromIni(); + - // finds the appropriate game plugin and sets it up so MO can use it + // finds the appropriate game plugin and sets it up so MO can use it; this + // calls readFromIni() first // // setup() tries to recover from some errors, but can fail for a variety of // reasons, see SetupResults @@ -88,22 +137,32 @@ public: QString name() const; // returns either: - // 1) the game name from the INI, - // 2) gameName() from the game plugin if it was missing, or - // 3) whatever was given in setGame() + // 1) the game name from the INI, if readFromIni() was called; + // 2) gameName() from the game plugin if it was missing and setup() was + // called; or + // 3) whatever was given in setGame() // QString gameName() const; // returns either: - // 1) the game directory from the INI, - // 2) gameDirectory() from the game plugin if it was missing, or - // 3) whatever was given in setGame() + // 1) the game directory from the INI, if readFromIni() was called; + // 2) gameDirectory() from the game plugin if it was missing and setup() + // was called; or + // 3) whatever was given in setGame() // QString gameDirectory() const; - // returns the instance directory; can be called without setup() + // returns the instance directory as given in the constructor // - QDir directory() const; + QString directory() const; + + // returns the base directory; empty if readFromIni() hasn't been called + // + QString baseDirectory() const; + + // returns whether this is a portable instance, as given in the constructor + // + bool isPortable() const; // returns the selected game plugin; will return null if setup() hasn't been // called, or if it failed @@ -111,8 +170,8 @@ public: MOBase::IPluginGame* gamePlugin() const; // returns either: - // 1) the profile name given in the constructor, - // 2) the profile name from the INI, or + // 1) the profile name given in the constructor if not empty; + // 2) the profile name from the INI if readFromIni() was called, or // 3) the default profile name if it's missing (see // AppConfig::defaultProfileName()) // @@ -123,15 +182,21 @@ public: // QString iniPath() const; - // returns whether this is a portable instance; this is the flag given in the - // constructor + // whether this is the currently active instance in MO // - bool isPortable() const; + bool isActive() const; + + // returns a list of files and directories that must be deleted when deleting + // this instance; this will read the INI and fail if it's not accessible + // + // returns an empty list on failure + // + std::vector objectsForDeletion() const; private: - QDir m_dir; + QString m_dir; bool m_portable; - QString m_gameName, m_gameDir, m_gameVariant; + QString m_gameName, m_gameDir, m_gameVariant, m_baseDir; MOBase::IPluginGame* m_plugin; QString m_profile; @@ -142,6 +207,10 @@ private: // figures out the profile name for this instance // void getProfile(const Settings& s); + + // updates the ini with the given values and the ones found by setup() + // + void updateIni(); }; @@ -175,7 +244,7 @@ public: // returns null if all of this fails // const MOBase::IPluginGame* gamePluginForDirectory( - const QDir& dir, const PluginContainer& plugins) const; + const QString& dir, const PluginContainer& plugins) const; // clears the instance name from the registry; on restart, this will make MO // either select the portable instance if it exists, or display the instance @@ -221,7 +290,7 @@ public: // returns the list of absolute path to all existing global instances; this // does not include the portable instance // - std::vector globalInstancePaths() const; + std::vector globalInstancePaths() const; // returns `name` modified so that it is a valid instance name // @@ -253,7 +322,7 @@ public: // returns the absolute path to the INI file for the given instance directory; // the file may not exist // - QString iniPath(const QDir& instanceDir) const; + QString iniPath(const QString& instanceDir) const; private: InstanceManager(); diff --git a/src/instancemanagerdialog.cpp b/src/instancemanagerdialog.cpp index c2108f9d..c199fa7b 100644 --- a/src/instancemanagerdialog.cpp +++ b/src/instancemanagerdialog.cpp @@ -13,292 +13,19 @@ using namespace MOBase; -class InstanceInfo -{ -public: - struct Object - { - QString path; - bool mandatoryDelete; - - Object(QString p, bool d=false) - : path(std::move(p)), mandatoryDelete(d) - { - } - - bool operator<(const Object& o) const - { - if (mandatoryDelete && !o.mandatoryDelete) { - return true; - } else if (!mandatoryDelete && o.mandatoryDelete) { - return false; - } - - return false; - } - }; - - - InstanceInfo(QDir dir, bool isPortable) - : m_portable(isPortable) - { - setDir(dir); - } - - void setDir(const QDir& dir) - { - m_dir = dir; - m_settings.reset(new Settings(InstanceManager::singleton().iniPath(dir))); - } - - QString name() const - { - if (m_portable) { - return QObject::tr("Portable"); - } else { - return m_dir.dirName(); - } - } - - QString gameName() const - { - if (auto n=m_settings->game().name()) { - if (auto e=m_settings->game().edition()) { - if (!e->isEmpty()) { - return *n + " (" + *e + ")"; - } - } - - return *n; - } else { - return {}; - } - } - - QString gamePath() const - { - if (auto n=m_settings->game().directory()) { - return QDir::toNativeSeparators(*n); - } else { - return {}; - } - } - - QString location() const - { - return QDir::toNativeSeparators(m_dir.path()); - } - - QString baseDirectory() const - { - return QDir::toNativeSeparators(m_settings->paths().base()); - } - - QString iniFile() const - { - return InstanceManager::singleton().iniPath(m_dir); - } - - QIcon icon(const PluginContainer& plugins) const - { - const auto* game = InstanceManager::singleton().gamePluginForDirectory( - m_dir, plugins); - - if (game) - return game->gameIcon(); - - QPixmap empty(32, 32); - empty.fill(QColor(0, 0, 0, 0)); - return QIcon(empty); - } - - bool isPortable() const - { - return m_portable; - } - - bool isActive() const - { - auto& m = InstanceManager::singleton(); - - if (auto i=m.currentInstance()) - { - if (m_portable) { - return i->isPortable(); - } else { - return (i->name() == name()); - } - } - - return false; - } - - // returns a list of files and folders that must be deleted when deleting - // this instance - // - std::vector objectsForDeletion() const - { - // native separators and ending slash - auto prettyDir = [](auto s) { - if (!s.endsWith("/") || !s.endsWith("\\")) { - s += "/"; - } - - return QDir::toNativeSeparators(s); - }; - - // native separators - auto prettyFile = [](auto s) { - return QDir::toNativeSeparators(s); - }; - - - // lowercase, native separators and ending slash - auto canonicalDir = [](auto s) { - s = s.toLower(); - if (!s.endsWith("/") || !s.endsWith("\\")) { - s += "/"; - } - - return QDir::toNativeSeparators(s); - }; - - // lower and native separators - auto canonicalFile = [](auto s) { - return QDir::toNativeSeparators(s.toLower()); - }; - - - - // whether the given directory is contained in the root - auto dirInRoot = [&](auto root, auto dir) { - return canonicalDir(dir).startsWith(canonicalDir(root)); - }; - - // whether the given file is contained in the root - auto fileInRoot = [&](auto root, auto file) { - return canonicalFile(file).startsWith(canonicalDir(root)); - }; - +QIcon instanceIcon(const PluginContainer& pc, const Instance& i) +{ + const auto* game = InstanceManager::singleton() + .gamePluginForDirectory(i.directory(), pc); + if (game) + return game->gameIcon(); - const auto loc = location(); - const auto base = m_settings->paths().base(); - - - // directories that might contain the individual files and directories - // set in the path settings - std::vector roots; - - // a portable instance has its location in the installation directory, - // don't delete that - if (!isPortable()) { - if (QDir(loc).exists()) { - roots.push_back({loc, true}); - } - } - - // the base directory is the location directory by default, don't add it - // if it's the same - if (canonicalDir(base) != canonicalDir(loc)) { - if (QDir(base).exists()) { - roots.push_back({base, false}); - } - } - - - // all the directories that are part of an instance; none of them are - // mandatory for deletion - const std::vector dirs = { - m_settings->paths().downloads(), - m_settings->paths().mods(), - m_settings->paths().cache(), - m_settings->paths().profiles(), - m_settings->paths().overwrite(), - m_dir.filePath(QString::fromStdWString(AppConfig::dumpsDir())), - m_dir.filePath(QString::fromStdWString(AppConfig::logPath())), - }; - - // all the files that are part of an instance - const std::vector files = { - {iniFile(), true}, // the ini file must be deleted - }; - - - // this will contain the root directories, plus all the individual - // directories that are not inside these roots - std::vector cleanDirs; - - for (const auto& f : dirs) { - bool inRoots = false; - - for (const auto& root : roots) { - if (dirInRoot(root.path, f.path)) { - inRoots = true; - break; - } - } - - if (!inRoots) { - // not in roots, this is a path that was changed by the user; make - // sure it exists - if (QDir(f.path).exists()) { - cleanDirs.push_back({prettyDir(f.path), f.mandatoryDelete}); - } - } - } - - // prepending the roots - for (auto itor=roots.rbegin(); itor!=roots.rend(); ++itor) { - cleanDirs.insert( - cleanDirs.begin(), - {prettyDir(itor->path), itor->mandatoryDelete}); - } - - - - // this will contain the individual files that are not inside the roots; - // not that this only contains the INI file for now, so most of this is - // useless - std::vector cleanFiles; - - for (const auto& f : files) { - bool inRoots = false; - - for (const auto& root : roots) { - if (fileInRoot(root.path, f.path)) { - inRoots = true; - break; - } - } - - if (!inRoots) { - // not in roots, this is a path that was changed by the user; make - // sure it exists - if (QFileInfo(f.path).exists()) { - cleanFiles.push_back({prettyFile(f.path), f.mandatoryDelete}); - } - } - } - - - // contains all the directories and files to be deleted - std::vector all; - all.insert(all.end(), cleanDirs.begin(), cleanDirs.end()); - all.insert(all.end(), cleanFiles.begin(), cleanFiles.end()); - - // mandatory on top - std::stable_sort(all.begin(), all.end()); - - return all; - } - -private: - const bool m_portable; - QDir m_dir; - std::unique_ptr m_settings; -}; + QPixmap empty(32, 32); + empty.fill(QColor(0, 0, 0, 0)); + return QIcon(empty); +} InstanceManagerDialog::~InstanceManagerDialog() = default; @@ -352,7 +79,7 @@ void InstanceManagerDialog::updateInstances() m_instances.clear(); for (auto&& d : m.globalInstancePaths()) { - m_instances.push_back(std::make_unique(d, false)); + m_instances.push_back(std::make_unique(d, false)); } // sort first, prepend portable after so it's always on top @@ -363,7 +90,12 @@ void InstanceManagerDialog::updateInstances() if (m.portableInstanceExists()) { m_instances.insert( m_instances.begin(), - std::make_unique(m.portablePath(), true)); + std::make_unique(m.portablePath(), true)); + } + + // read all inis, ignore errors + for (auto&& i : m_instances) { + i->readFromIni(); } } @@ -381,7 +113,7 @@ void InstanceManagerDialog::updateList() const auto& ii = *m_instances[i]; auto* item = new QStandardItem(ii.name()); - item->setIcon(ii.icon(m_pc)); + item->setIcon(instanceIcon(m_pc, ii)); m_model->appendRow(item); @@ -568,9 +300,9 @@ void InstanceManagerDialog::rename() return; } - const QString src = i->location(); + const QString src = i->directory(); const QString dest = QDir::toNativeSeparators( - QFileInfo(i->location()).dir().path() + "/" + newName); + QFileInfo(src).dir().path() + "/" + newName); const auto r = shell::Rename(src, dest, false); if (!r) { @@ -582,15 +314,19 @@ void InstanceManagerDialog::rename() return; } + auto newInstance = std::make_unique(dest, false); + i = newInstance.get(); + m_model->item(selIndex)->setText(newName); - i->setDir(dest); + m_instances[selIndex] = std::move(newInstance); + fillData(*i); } void InstanceManagerDialog::exploreLocation() { if (const auto* i=singleSelection()) { - shell::Explore(i->location()); + shell::Explore(i->directory()); } } @@ -604,14 +340,14 @@ void InstanceManagerDialog::exploreBaseDirectory() void InstanceManagerDialog::exploreGame() { if (const auto* i=singleSelection()) { - shell::Explore(i->gamePath()); + shell::Explore(i->gameDirectory()); } } void InstanceManagerDialog::openINI() { if (const auto* i=singleSelection()) { - shell::Open(i->iniFile()); + shell::Open(i->iniPath()); } } @@ -707,6 +443,15 @@ void InstanceManagerDialog::setRestartOnSelect(bool b) bool InstanceManagerDialog::doDelete(const QStringList& files, bool recycle) { + // logging + for (auto&& f : files) { + if (recycle) { + log::info("will recycle {}", f); + } else { + log::info("will delete {}", f); + } + } + if (MOBase::shellDelete(files, recycle, this)) { return true; } @@ -771,17 +516,7 @@ std::size_t InstanceManagerDialog::singleSelectionIndex() const return static_cast(sel.indexes()[0].row()); } -InstanceInfo* InstanceManagerDialog::singleSelection() -{ - const auto i = singleSelectionIndex(); - if (i == NoSelection) { - return nullptr; - } - - return m_instances[i].get(); -} - -const InstanceInfo* InstanceManagerDialog::singleSelection() const +const Instance* InstanceManagerDialog::singleSelection() const { const auto i = singleSelectionIndex(); if (i == NoSelection) { @@ -791,13 +526,13 @@ const InstanceInfo* InstanceManagerDialog::singleSelection() const return m_instances[i].get(); } -void InstanceManagerDialog::fillData(const InstanceInfo& ii) +void InstanceManagerDialog::fillData(const Instance& ii) { ui->name->setText(ii.name()); - ui->location->setText(ii.location()); + ui->location->setText(ii.directory()); ui->baseDirectory->setText(ii.baseDirectory()); ui->gameName->setText(ii.gameName()); - ui->gameDir->setText(ii.gamePath()); + ui->gameDir->setText(ii.gameDirectory()); setButtonsEnabled(true); const auto& m = InstanceManager::singleton(); diff --git a/src/instancemanagerdialog.h b/src/instancemanagerdialog.h index 5b08ffc2..94f379ca 100644 --- a/src/instancemanagerdialog.h +++ b/src/instancemanagerdialog.h @@ -6,9 +6,11 @@ namespace Ui { class InstanceManagerDialog; }; -class InstanceInfo; +class Instance; class PluginContainer; +// a dialog to manage existing instances +// class InstanceManagerDialog : public QDialog { Q_OBJECT @@ -19,21 +21,61 @@ public: ~InstanceManagerDialog(); + // selects the instance having the given index in the list + // void select(std::size_t i); + + // selects the instance by name + // void select(const QString& name); + + // select the instance that is currently in use in MO + // void selectActiveInstance(); + + // switches to the selected instance; restarts MO, unless + // was called setRestartOnSelect(false) + // void openSelectedInstance(); + + // renames the currently selected instance + // void rename(); + + // explores the directory of the selected instance + // void exploreLocation(); + + // explores the base directory of the selected instance + // void exploreBaseDirectory(); + + // explores the game directory of the selected instance + // void exploreGame(); + + // converts the selected, portable instance to a global one; not implemented + // void convertToGlobal(); + + // converts the selected, global instance to a portable one; not implemented + // void convertToPortable(); + + // opens the ini of the selected instance in the shell + // void openINI(); + + // deletes the selected instance + // void deleteInstance(); + + // sets whether the dialog should restart MO when selecting an instance; this + // is false on startup when no instances exist + // void setRestartOnSelect(bool b); private: @@ -41,27 +83,51 @@ private: std::unique_ptr ui; const PluginContainer& m_pc; - std::vector> m_instances; + std::vector> m_instances; MOBase::FilterWidget m_filter; QStandardItemModel* m_model; bool m_restartOnSelect; + // refreshes the list instances from disk + // void updateInstances(); + // updates the ui for the selected instance + // void onSelection(); + + // opens the create instance dialog + // void createNew(); + + // returns the index of selected instance, NoSelection if none + // std::size_t singleSelectionIndex() const; - InstanceInfo* singleSelection(); - const InstanceInfo* singleSelection() const; + // returns the InstanceInfo associated with the selected instance, null if + // none + // + const Instance* singleSelection() const; + + // fills the instance list on the ui + // void updateList(); - void fillData(const InstanceInfo& ii); + + // fills the ui for the selected instance + // + void fillData(const Instance& ii); + + // clears the ui when there's no selection + // void clearData(); + + // enables/disables buttons like rename, explore... + // void setButtonsEnabled(bool b); - bool deletePortable(const InstanceInfo& ii); - bool deleteGlobal(const InstanceInfo& ii); + // deletes the given files, returns false on error + // bool doDelete(const QStringList& files, bool recycle); }; diff --git a/src/instancemanagerdialog.ui b/src/instancemanagerdialog.ui index 410b58c1..45b99e21 100644 --- a/src/instancemanagerdialog.ui +++ b/src/instancemanagerdialog.ui @@ -330,7 +330,7 @@ - Delete instance + Delete instance... diff --git a/src/main.cpp b/src/main.cpp index 7f0886f6..a2653685 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -662,17 +662,17 @@ int doOneRun( } else { - if (!currentInstance->directory().exists()) { + if (!QDir(currentInstance->directory()).exists()) { // the previously used instance doesn't exist anymore if (m.hasAnyInstances()) { criticalOnTop(QObject::tr( "Instance at '%1' not found. Select another instance.") - .arg(currentInstance->directory().absolutePath())); + .arg(currentInstance->directory())); } else { criticalOnTop(QObject::tr( "Instance at '%1' not found. You must create a new instance") - .arg(currentInstance->directory().absolutePath())); + .arg(currentInstance->directory())); } currentInstance = selectInstance(); @@ -682,7 +682,7 @@ int doOneRun( } } - const QString dataPath = currentInstance->directory().path(); + const QString dataPath = currentInstance->directory(); application.setProperty("dataPath", dataPath); setExceptionHandlers(); -- cgit v1.3.1 From d288587b002b19c54dc08d08ae267d301aa2ac81 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sat, 7 Nov 2020 16:51:55 -0500 Subject: moved instance setup/selection to instancemanager.cpp comments --- src/instancemanager.cpp | 157 +++++++++++++++++++++++++++++++++++++- src/instancemanager.h | 37 +++++++++ src/main.cpp | 181 +------------------------------------------- src/shared/error_report.cpp | 10 +++ src/shared/error_report.h | 8 ++ 5 files changed, 214 insertions(+), 179 deletions(-) (limited to 'src/instancemanager.cpp') diff --git a/src/instancemanager.cpp b/src/instancemanager.cpp index fbafc6e8..b68d715b 100644 --- a/src/instancemanager.cpp +++ b/src/instancemanager.cpp @@ -21,9 +21,14 @@ along with Mod Organizer. If not, see . #include "instancemanager.h" #include "selectiondialog.h" #include "settings.h" -#include "shared/appconfig.h" #include "plugincontainer.h" +#include "nexusinterface.h" +#include "createinstancedialog.h" +#include "instancemanagerdialog.h" +#include "createinstancedialogpages.h" +#include "shared/appconfig.h" #include "shared/util.h" +#include "shared/error_report.h" #include #include #include @@ -751,3 +756,153 @@ bool InstanceManager::validInstanceName(const QString& instanceName) const return (instanceName == sanitizeInstanceName(instanceName)); } + + + +std::optional selectInstance() +{ + auto& m = InstanceManager::singleton(); + + NexusInterface ni(nullptr); + PluginContainer pc(nullptr); + pc.loadPlugins(); + + if (!m.hasAnyInstances()) { + // no instances configured + CreateInstanceDialog dlg(pc, nullptr); + if (dlg.exec() != QDialog::Accepted) { + return {}; + } + + return m.currentInstance(); + } + + + InstanceManagerDialog dlg(pc); + dlg.setRestartOnSelect(false); + + dlg.show(); + dlg.activateWindow(); + dlg.raise(); + + if (dlg.exec() != QDialog::Accepted) { + return {}; + } + + return m.currentInstance(); +} + +SetupInstanceResults setupInstance(Instance& instance, PluginContainer& pc) +{ + const auto setupResult = instance.setup(pc); + + switch (setupResult) + { + case Instance::SetupResults::Ok: + { + return SetupInstanceResults::Ok; + } + + case Instance::SetupResults::BadIni: + { + MOShared::criticalOnTop( + QObject::tr("Cannot open instance '%1', failed to read INI file %2.") + .arg(instance.name()).arg(instance.iniPath())); + + return SetupInstanceResults::SelectAnother; + } + + case Instance::SetupResults::IniMissingGame: + { + MOShared::criticalOnTop( + QObject::tr( + "Cannot open instance '%1', the managed game was not found in the INI " + "file %2. Select the game managed by this instance.") + .arg(instance.name()).arg(instance.iniPath())); + + CreateInstanceDialog dlg(pc, nullptr); + dlg.setSinglePage(instance.name()); + + dlg.show(); + dlg.activateWindow(); + dlg.raise(); + + if (dlg.exec() != QDialog::Accepted) { + return SetupInstanceResults::Exit; + } + + instance.setGame( + dlg.creationInfo().game->gameName(), + dlg.creationInfo().gameLocation); + + return SetupInstanceResults::TryAgain; + } + + case Instance::SetupResults::PluginGone: + { + MOShared::criticalOnTop( + QObject::tr( + "Cannot open instance '%1', the game plugin '%2' doesn't exist. It " + "may have been deleted by an antivirus. Select another instance.") + .arg(instance.name()).arg(instance.gameName())); + + return SetupInstanceResults::SelectAnother; + } + + case Instance::SetupResults::GameGone: + { + MOShared::criticalOnTop( + QObject::tr( + "Cannot open instance '%1', the game directory '%2' doesn't exist or " + "the game plugin '%3' doesn't recognize it. Select the game managed " + "by this instance.") + .arg(instance.name()) + .arg(instance.gameDirectory()) + .arg(instance.gameName())); + + CreateInstanceDialog dlg(pc, nullptr); + dlg.setSinglePage(instance.name()); + + dlg.show(); + dlg.activateWindow(); + dlg.raise(); + + if (dlg.exec() != QDialog::Accepted) { + return SetupInstanceResults::Exit; + } + + instance.setGame( + dlg.creationInfo().game->gameName(), + dlg.creationInfo().gameLocation); + + return SetupInstanceResults::TryAgain; + } + + case Instance::SetupResults::MissingVariant: + { + CreateInstanceDialog dlg(pc, nullptr); + + dlg.getPage()->select( + instance.gamePlugin(), instance.gameDirectory()); + + dlg.setSinglePage(instance.name()); + + dlg.show(); + dlg.activateWindow(); + dlg.raise(); + + if (dlg.exec() != QDialog::Accepted) { + return SetupInstanceResults::Exit; + } + + instance.setVariant(dlg.creationInfo().gameVariant); + + return SetupInstanceResults::TryAgain; + } + + default: + { + return SetupInstanceResults::Exit; + } + } +} diff --git a/src/instancemanager.h b/src/instancemanager.h index 161df739..d75a46f4 100644 --- a/src/instancemanager.h +++ b/src/instancemanager.h @@ -332,4 +332,41 @@ private: std::optional m_overrideProfileName; }; + +// see setupInstance() +// +enum class SetupInstanceResults +{ + Ok, + TryAgain, + SelectAnother, + Exit +}; + +// if there are no instances configured, global or portable, shows the +// create instance dialog and returns the new instance or empty if the user +// cancelled +// +// if there is at least one instance available, unconditionally show the +// instance manager dialog and returns the selected instnace or empty if the +// user cancelled +// +std::optional selectInstance(); + +// calls instance.setup() tries to handle problems by itself: +// +// - if the ini is missing some information, will show dialogs and ask the user +// to fill in what's required (such as the game directory, variant, etc.); +// if successful, returns TryAgain and setupInstance() can be called again +// with the same instance +// +// - if the instance cannot be used (no game plugin found for it, ini can't +// be read, etc.), returns SelectAnother +// +// - if the user cancels at any point, returns Exit +// +// - if the instance has been set up correctly, returns Ok +// +SetupInstanceResults setupInstance(Instance& instance, PluginContainer& pc); + #endif // MODORGANIZER_INSTANCEMANAGER_INCLUDED diff --git a/src/main.cpp b/src/main.cpp index a8ea2601..fdd09872 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -34,20 +34,13 @@ along with Mod Organizer. If not, see . #include "commandline.h" #include "shared/util.h" #include "shared/appconfig.h" - +#include "shared/error_report.h" #include #include #include #include #include -// see addDllsToPath() below -#pragma comment(linker, "/manifestDependency:\"" \ - "name='dlls' " \ - "processorArchitecture='x86' " \ - "version='1.0.0.0' " \ - "type='win32' \"") - using namespace MOBase; using namespace MOShared; @@ -171,174 +164,6 @@ std::optional handleCommandLine( return {}; } -std::optional selectInstance() -{ - auto& m = InstanceManager::singleton(); - - NexusInterface ni(nullptr); - PluginContainer pc(nullptr); - pc.loadPlugins(); - - if (!m.hasAnyInstances()) { - // no instances configured - CreateInstanceDialog dlg(pc, nullptr); - if (dlg.exec() != QDialog::Accepted) { - return {}; - } - - return m.currentInstance(); - } - - - InstanceManagerDialog dlg(pc); - dlg.setRestartOnSelect(false); - - dlg.show(); - dlg.activateWindow(); - dlg.raise(); - - if (dlg.exec() != QDialog::Accepted) { - return {}; - } - - return m.currentInstance(); -} - -enum class SetupInstanceResults -{ - Ok, - TryAgain, - SelectAnother, - Exit -}; - - -void criticalOnTop(const QString& message) -{ - QMessageBox mb(QMessageBox::Critical, QObject::tr("Mod Organizer"), message); - - mb.show(); - mb.activateWindow(); - mb.raise(); - mb.exec(); -} - - -SetupInstanceResults setupInstance(Instance& instance, PluginContainer& pc) -{ - const auto setupResult = instance.setup(pc); - - switch (setupResult) - { - case Instance::SetupResults::Ok: - { - return SetupInstanceResults::Ok; - } - - case Instance::SetupResults::BadIni: - { - criticalOnTop( - QObject::tr("Cannot open instance '%1', failed to read INI file %2.") - .arg(instance.name()).arg(instance.iniPath())); - - return SetupInstanceResults::SelectAnother; - } - - case Instance::SetupResults::IniMissingGame: - { - criticalOnTop( - QObject::tr( - "Cannot open instance '%1', the managed game was not found in the INI " - "file %2. Select the game managed by this instance.") - .arg(instance.name()).arg(instance.iniPath())); - - CreateInstanceDialog dlg(pc, nullptr); - dlg.setSinglePage(instance.name()); - - dlg.show(); - dlg.activateWindow(); - dlg.raise(); - - if (dlg.exec() != QDialog::Accepted) { - return SetupInstanceResults::Exit; - } - - instance.setGame( - dlg.creationInfo().game->gameName(), - dlg.creationInfo().gameLocation); - - return SetupInstanceResults::TryAgain; - } - - case Instance::SetupResults::PluginGone: - { - criticalOnTop( - QObject::tr( - "Cannot open instance '%1', the game plugin '%2' doesn't exist. It " - "may have been deleted by an antivirus. Select another instance.") - .arg(instance.name()).arg(instance.gameName())); - - return SetupInstanceResults::SelectAnother; - } - - case Instance::SetupResults::GameGone: - { - criticalOnTop( - QObject::tr( - "Cannot open instance '%1', the game directory '%2' doesn't exist or " - "the game plugin '%3' doesn't recognize it. Select the game managed " - "by this instance.") - .arg(instance.name()) - .arg(instance.gameDirectory()) - .arg(instance.gameName())); - - CreateInstanceDialog dlg(pc, nullptr); - dlg.setSinglePage(instance.name()); - - dlg.show(); - dlg.activateWindow(); - dlg.raise(); - - if (dlg.exec() != QDialog::Accepted) { - return SetupInstanceResults::Exit; - } - - instance.setGame( - dlg.creationInfo().game->gameName(), - dlg.creationInfo().gameLocation); - - return SetupInstanceResults::TryAgain; - } - - case Instance::SetupResults::MissingVariant: - { - CreateInstanceDialog dlg(pc, nullptr); - - dlg.getPage()->select( - instance.gamePlugin(), instance.gameDirectory()); - - dlg.setSinglePage(instance.name()); - - dlg.show(); - dlg.activateWindow(); - dlg.raise(); - - if (dlg.exec() != QDialog::Accepted) { - return SetupInstanceResults::Exit; - } - - instance.setVariant(dlg.creationInfo().gameVariant); - - return SetupInstanceResults::TryAgain; - } - - default: - { - return SetupInstanceResults::Exit; - } - } -} - int runApplication( MOApplication &application, const cl::CommandLine& cl, SingleInstance &instance, const QString &dataPath, @@ -561,11 +386,11 @@ int doOneRun( // the previously used instance doesn't exist anymore if (m.hasAnyInstances()) { - criticalOnTop(QObject::tr( + MOShared::criticalOnTop(QObject::tr( "Instance at '%1' not found. Select another instance.") .arg(currentInstance->directory())); } else { - criticalOnTop(QObject::tr( + MOShared::criticalOnTop(QObject::tr( "Instance at '%1' not found. You must create a new instance") .arg(currentInstance->directory())); } diff --git a/src/shared/error_report.cpp b/src/shared/error_report.cpp index 4185b544..09fdcb49 100644 --- a/src/shared/error_report.cpp +++ b/src/shared/error_report.cpp @@ -51,4 +51,14 @@ void reportError(LPCWSTR format, ...) MessageBoxW(nullptr, buffer, L"Error", MB_OK | MB_ICONERROR); } +void criticalOnTop(const QString& message) +{ + QMessageBox mb(QMessageBox::Critical, QObject::tr("Mod Organizer"), message); + + mb.show(); + mb.activateWindow(); + mb.raise(); + mb.exec(); +} + } // namespace MOShared diff --git a/src/shared/error_report.h b/src/shared/error_report.h index da07c728..9343d3da 100644 --- a/src/shared/error_report.h +++ b/src/shared/error_report.h @@ -31,6 +31,14 @@ namespace MOShared void reportError(LPCSTR format, ...); void reportError(LPCWSTR format, ...); +// shows a critical message box that's raised to the top of the zorder, useful +// for messages without a main window, which sometimes makes them pop up behind +// all other windows +// +// the dialog is not topmost, it's just raised once when shown +// +void criticalOnTop(const QString& message); + } // namespace MOShared #endif // MODORGANIZER_SHARED_ERROR_REPORT_INCLUDED -- cgit v1.3.1 From 1bf24c7daad1eb954dc160784802de58f9809fa1 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sat, 7 Nov 2020 17:05:29 -0500 Subject: refactored setupInstance(), comments ok -> okay --- src/instancemanager.cpp | 173 ++++++++++++++++++++++++++++++------------------ src/instancemanager.h | 8 +-- src/main.cpp | 2 +- 3 files changed, 114 insertions(+), 69 deletions(-) (limited to 'src/instancemanager.cpp') diff --git a/src/instancemanager.cpp b/src/instancemanager.cpp index b68d715b..4191f850 100644 --- a/src/instancemanager.cpp +++ b/src/instancemanager.cpp @@ -158,7 +158,7 @@ Instance::SetupResults Instance::setup(PluginContainer& plugins) // getting game plugin const auto r = getGamePlugin(plugins); - if (r != SetupResults::Ok) { + if (r != SetupResults::Okay) { return r; } @@ -177,7 +177,7 @@ Instance::SetupResults Instance::setup(PluginContainer& plugins) // installed m_plugin->setGamePath(m_gameDir); - return SetupResults::Ok; + return SetupResults::Okay; } void Instance::updateIni() @@ -248,7 +248,7 @@ Instance::SetupResults Instance::getGamePlugin(PluginContainer& plugins) } m_plugin = game; - return SetupResults::Ok; + return SetupResults::Okay; } } @@ -272,7 +272,7 @@ Instance::SetupResults Instance::getGamePlugin(PluginContainer& plugins) m_plugin = game; m_gameName = game->gameName(); - return SetupResults::Ok; + return SetupResults::Okay; } } @@ -301,7 +301,7 @@ Instance::SetupResults Instance::getGamePlugin(PluginContainer& plugins) m_plugin = game; m_gameDir = game->gameDirectory().absolutePath(); - return SetupResults::Ok; + return SetupResults::Okay; } else { log::warn( "found plugin {} that matches name in ini {}, but no game install " @@ -763,48 +763,126 @@ std::optional selectInstance() { auto& m = InstanceManager::singleton(); + // since there is no instance currently active, load plugins with a null + // OrganizerCore; see PluginContainer::initPlugin() NexusInterface ni(nullptr); PluginContainer pc(nullptr); pc.loadPlugins(); - if (!m.hasAnyInstances()) { - // no instances configured + if (m.hasAnyInstances()) { + // there is at least one instance available, show the instance manager + // dialog + InstanceManagerDialog dlg(pc); + + // the dialog normally restarts MO when an instance is selected, but this + // is not necessary here since MO hasn't really started yet + dlg.setRestartOnSelect(false); + + dlg.show(); + dlg.activateWindow(); + dlg.raise(); + + if (dlg.exec() != QDialog::Accepted) { + return {}; + } + + } else { + // no instances configured, ask the user to create one CreateInstanceDialog dlg(pc, nullptr); + if (dlg.exec() != QDialog::Accepted) { return {}; } + } - return m.currentInstance(); + // return the new instance or the selection + return m.currentInstance(); +} + +// shows the game selection page of the create instance dialog so the user can +// pick which game is managed by this instance +// +// this is used below in setupInstance() when the game directory is gone or +// no plugins can recognize it +// +SetupInstanceResults selectGame(Instance& instance, PluginContainer& pc) +{ + CreateInstanceDialog dlg(pc, nullptr); + + // only show the game page + dlg.setSinglePage(instance.name()); + + dlg.show(); + dlg.activateWindow(); + dlg.raise(); + + if (dlg.exec() != QDialog::Accepted) { + // cancelled + return SetupInstanceResults::Exit; } + // this info will be used instead of the ini, which should fix this + // particular problem + instance.setGame( + dlg.creationInfo().game->gameName(), + dlg.creationInfo().gameLocation); + + return SetupInstanceResults::TryAgain; +} + +// shows the game variant page of the create instance dialog so the user can +// pick which game variant is installed +// +// this is used below in setupInstance() when there is no variant in the ini +// but the game plugin requires one; this can happen when the ini is broken +// or when a new variant has become supported by the plugin for a game the +// user already has an instance for +// +SetupInstanceResults selectVariant(Instance& instance, PluginContainer& pc) +{ + CreateInstanceDialog dlg(pc, nullptr); + + // the variant page uses the game page to know which game was selected, so + // set it manually + dlg.getPage()->select( + instance.gamePlugin(), instance.gameDirectory()); - InstanceManagerDialog dlg(pc); - dlg.setRestartOnSelect(false); + // only show the variant page + dlg.setSinglePage(instance.name()); dlg.show(); dlg.activateWindow(); dlg.raise(); if (dlg.exec() != QDialog::Accepted) { - return {}; + return SetupInstanceResults::Exit; } - return m.currentInstance(); + // this info will be used instead of the ini, which should fix this + // particular problem + instance.setVariant(dlg.creationInfo().gameVariant); + + return SetupInstanceResults::TryAgain; } SetupInstanceResults setupInstance(Instance& instance, PluginContainer& pc) { + // set up the instance const auto setupResult = instance.setup(pc); switch (setupResult) { - case Instance::SetupResults::Ok: + case Instance::SetupResults::Okay: { - return SetupInstanceResults::Ok; + // all good + return SetupInstanceResults::Okay; } case Instance::SetupResults::BadIni: { + // unreadable ini, there's not much that can be done, select another + // instance + MOShared::criticalOnTop( QObject::tr("Cannot open instance '%1', failed to read INI file %2.") .arg(instance.name()).arg(instance.iniPath())); @@ -814,32 +892,26 @@ SetupInstanceResults setupInstance(Instance& instance, PluginContainer& pc) case Instance::SetupResults::IniMissingGame: { + // both the game name and directory are missing from the ini; although + // this shouldn't happen, setup() is able to handle when either is + // missing, but not both + // + // ask the user for the game managed by this instance + MOShared::criticalOnTop( QObject::tr( "Cannot open instance '%1', the managed game was not found in the INI " "file %2. Select the game managed by this instance.") .arg(instance.name()).arg(instance.iniPath())); - CreateInstanceDialog dlg(pc, nullptr); - dlg.setSinglePage(instance.name()); - - dlg.show(); - dlg.activateWindow(); - dlg.raise(); - - if (dlg.exec() != QDialog::Accepted) { - return SetupInstanceResults::Exit; - } - - instance.setGame( - dlg.creationInfo().game->gameName(), - dlg.creationInfo().gameLocation); - - return SetupInstanceResults::TryAgain; + return selectGame(instance, pc); } case Instance::SetupResults::PluginGone: { + // there is no plugin that can handle the game name/directory from the + // ini, so this instance is unusable + MOShared::criticalOnTop( QObject::tr( "Cannot open instance '%1', the game plugin '%2' doesn't exist. It " @@ -851,6 +923,9 @@ SetupInstanceResults setupInstance(Instance& instance, PluginContainer& pc) case Instance::SetupResults::GameGone: { + // the game directory doesn't exist or the plugin doesn't recognize it; + // ask the user for the game managed by this instance + MOShared::criticalOnTop( QObject::tr( "Cannot open instance '%1', the game directory '%2' doesn't exist or " @@ -860,48 +935,18 @@ SetupInstanceResults setupInstance(Instance& instance, PluginContainer& pc) .arg(instance.gameDirectory()) .arg(instance.gameName())); - CreateInstanceDialog dlg(pc, nullptr); - dlg.setSinglePage(instance.name()); - - dlg.show(); - dlg.activateWindow(); - dlg.raise(); - - if (dlg.exec() != QDialog::Accepted) { - return SetupInstanceResults::Exit; - } - - instance.setGame( - dlg.creationInfo().game->gameName(), - dlg.creationInfo().gameLocation); - - return SetupInstanceResults::TryAgain; + return selectGame(instance, pc); } case Instance::SetupResults::MissingVariant: { - CreateInstanceDialog dlg(pc, nullptr); - - dlg.getPage()->select( - instance.gamePlugin(), instance.gameDirectory()); - - dlg.setSinglePage(instance.name()); - - dlg.show(); - dlg.activateWindow(); - dlg.raise(); - - if (dlg.exec() != QDialog::Accepted) { - return SetupInstanceResults::Exit; - } - - instance.setVariant(dlg.creationInfo().gameVariant); - - return SetupInstanceResults::TryAgain; + // the game variant is missing from the ini, ask the user for it + return selectVariant(instance, pc); } default: { + // shouldn't happen return SetupInstanceResults::Exit; } } diff --git a/src/instancemanager.h b/src/instancemanager.h index d75a46f4..4f8b01c7 100644 --- a/src/instancemanager.h +++ b/src/instancemanager.h @@ -32,7 +32,7 @@ public: enum class SetupResults { // instance is ready to be used - Ok, + Okay, // error while reading the INI BadIni, @@ -337,7 +337,7 @@ private: // enum class SetupInstanceResults { - Ok, + Okay, TryAgain, SelectAnother, Exit @@ -348,7 +348,7 @@ enum class SetupInstanceResults // cancelled // // if there is at least one instance available, unconditionally show the -// instance manager dialog and returns the selected instnace or empty if the +// instance manager dialog and returns the selected instance or empty if the // user cancelled // std::optional selectInstance(); @@ -365,7 +365,7 @@ std::optional selectInstance(); // // - if the user cancels at any point, returns Exit // -// - if the instance has been set up correctly, returns Ok +// - if the instance has been set up correctly, returns Okay // SetupInstanceResults setupInstance(Instance& instance, PluginContainer& pc); diff --git a/src/main.cpp b/src/main.cpp index fdd09872..e0326b27 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -237,7 +237,7 @@ int runApplication( { const auto setupResult = setupInstance(currentInstance, *pluginContainer); - if (setupResult == SetupInstanceResults::Ok) { + if (setupResult == SetupInstanceResults::Okay) { break; } else if (setupResult == SetupInstanceResults::TryAgain) { continue; -- cgit v1.3.1