aboutsummaryrefslogtreecommitdiff
path: root/libs/installer_fomod_csharp/src
diff options
context:
space:
mode:
authorSulfurNitride <SulfurNitride@users.noreply.github.com>2026-02-11 02:37:39 -0600
committerSulfurNitride <SulfurNitride@users.noreply.github.com>2026-02-11 02:37:39 -0600
commit7ee008e150bc5bcf76082d726f719ee0fdfda982 (patch)
tree27fb39be241fdb5ac2734c574de678977d1856d0 /libs/installer_fomod_csharp/src
Fluorine Manager: full Linux port of Mod Organizer 2
Complete native Linux port with FUSE-based virtual filesystem, Proton/umu-run integration, and Flatpak packaging. Key features: - FUSE VFS replacing Windows USVFS (in-process + standalone helper for Flatpak) - Proton/GE-Proton/umu-run launcher with env var forwarding - Flatpak support (sandbox-aware VFS, NXM handler, umu-run) - Wine prefix management UI - Case-insensitive path resolution for Linux filesystems - QSettings-safe INI handling (avoids Bethesda INI corruption) - Portable instance support with auto-generated launcher scripts Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Diffstat (limited to 'libs/installer_fomod_csharp/src')
-rw-r--r--libs/installer_fomod_csharp/src/CMakeLists.txt11
-rw-r--r--libs/installer_fomod_csharp/src/base_script.cpp685
-rw-r--r--libs/installer_fomod_csharp/src/base_script.h552
-rw-r--r--libs/installer_fomod_csharp/src/csharp_interface.cpp157
-rw-r--r--libs/installer_fomod_csharp/src/csharp_interface.h40
-rw-r--r--libs/installer_fomod_csharp/src/csharp_utils.h41
-rw-r--r--libs/installer_fomod_csharp/src/installer_fomod_csharp.cpp193
-rw-r--r--libs/installer_fomod_csharp/src/installer_fomod_csharp.h84
-rw-r--r--libs/installer_fomod_csharp/src/installer_fomod_csharp_en.ts125
-rw-r--r--libs/installer_fomod_csharp/src/installer_fomod_csharp_postdialog.ui99
-rw-r--r--libs/installer_fomod_csharp/src/installer_fomod_csharp_predialog.ui89
-rw-r--r--libs/installer_fomod_csharp/src/installer_fomod_postdialog.h87
-rw-r--r--libs/installer_fomod_csharp/src/installer_fomod_predialog.h72
-rw-r--r--libs/installer_fomod_csharp/src/psettings.h108
-rw-r--r--libs/installer_fomod_csharp/src/xml_info_reader.h140
15 files changed, 2483 insertions, 0 deletions
diff --git a/libs/installer_fomod_csharp/src/CMakeLists.txt b/libs/installer_fomod_csharp/src/CMakeLists.txt
new file mode 100644
index 0000000..09b3015
--- /dev/null
+++ b/libs/installer_fomod_csharp/src/CMakeLists.txt
@@ -0,0 +1,11 @@
+cmake_minimum_required(VERSION 3.16)
+
+find_package(mo2-cmake CONFIG REQUIRED)
+find_package(mo2-uibase CONFIG REQUIRED)
+
+add_library(installer_fomod_csharp SHARED)
+mo2_configure_plugin(installer_fomod_csharp WARNINGS OFF CLI ON)
+target_link_libraries(installer_fomod_csharp PRIVATE mo2::uibase)
+mo2_install_plugin(installer_fomod_csharp)
+
+set_target_properties(installer_fomod_csharp PROPERTIES CXX_STANDARD 20)
diff --git a/libs/installer_fomod_csharp/src/base_script.cpp b/libs/installer_fomod_csharp/src/base_script.cpp
new file mode 100644
index 0000000..e3aa4a7
--- /dev/null
+++ b/libs/installer_fomod_csharp/src/base_script.cpp
@@ -0,0 +1,685 @@
+/*
+Copyright (C) 2020 Holt59. All rights reserved.
+
+Mod Organizer is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+Mod Organizer is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Mod Organizer. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "base_script.h"
+
+#include <filesystem>
+#include <map>
+
+#include <QCheckBox>
+#include <QDialogButtonBox>
+#include <QInputDialog>
+#include <QLabel>
+#include <QMessageBox>
+#include <QPushButton>
+#include <QRadioButton>
+#include <QSettings>
+#include <QVBoxLayout>
+#include <QVersionNumber>
+
+#include <uibase/game_features/igamefeatures.h>
+#include <uibase/game_features/scriptextender.h>
+#include <uibase/iinstallationmanager.h>
+#include <uibase/imoinfo.h>
+#include <uibase/iplugingame.h>
+#include <uibase/ipluginlist.h>
+#include <uibase/log.h>
+
+#include "csharp_interface.h"
+#include "csharp_utils.h"
+#include "installer_fomod_postdialog.h"
+#include "psettings.h"
+
+using namespace MOBase;
+
+// clang-format off
+
+namespace CSharp {
+
+ // Pointer to object:
+ static MOBase::IOrganizer* g_Organizer = nullptr;
+
+ // Per-install globals:
+ struct Globals {
+ IInstallationManager* InstallManager;
+ QWidget* ParentWidget;
+ std::shared_ptr<const IFileTree> SourceTree;
+ std::shared_ptr<IFileTree> DestinationTree;
+
+ // Map from path in destination entry to the original entry:
+ std::map<std::shared_ptr<const FileTreeEntry>,
+ std::shared_ptr<const FileTreeEntry>> InstalledEntries;
+
+ // Map extracted entries (in the original tree) to (temporary) paths:
+ std::map<std::shared_ptr<const FileTreeEntry>, QString> ExtractedEntries;
+
+ // Map creted entries (in the destination tree) to (temporary) paths:
+ std::map<std::shared_ptr<const FileTreeEntry>, QString> CreatedEntries;
+
+ // List of modified settings values:
+ std::map<QString, PSettings> Settings;
+
+ Globals() { }
+ Globals(
+ IPlugin const* plugin, MOBase::IInstallationManager* manager, QWidget* parentWidget,
+ std::shared_ptr<MOBase::IFileTree> tree, std::map<std::shared_ptr<const FileTreeEntry>, QString> entries) :
+ m_Plugin(plugin), InstallManager(manager), ParentWidget(parentWidget), SourceTree(tree), DestinationTree(tree->createOrphanTree()), ExtractedEntries(std::move(entries)) {
+
+ }
+
+ Globals(Globals const&) = delete;
+ Globals(Globals&&) = default;
+
+ Globals& operator=(Globals const&) = delete;
+ Globals& operator=(Globals&&) = default;
+
+ private:
+ IPlugin const* m_Plugin;
+ };
+ static Globals g;
+
+
+
+ void init(MOBase::IOrganizer* moInfo) {
+
+ // Do this only once:
+ if (g_Organizer == nullptr) {
+ Application::EnableVisualStyles();
+ Application::SetCompatibleTextRenderingDefault(false);
+ }
+
+ g_Organizer = moInfo;
+ }
+
+ void beforeInstall(IPlugin const* plugin, MOBase::IInstallationManager* manager, QWidget* parentWidget,
+ std::shared_ptr<MOBase::IFileTree> tree, std::map<std::shared_ptr<const FileTreeEntry>, QString> entries) {
+ g = { plugin, manager, parentWidget, tree, std::move(entries) };
+ }
+
+ IPluginInstaller::EInstallResult postInstall(std::shared_ptr<MOBase::IFileTree>& tree) {
+
+ if (!g.Settings.empty()) {
+
+ InstallerFomodPostDialog* dialog = new InstallerFomodPostDialog(g.ParentWidget);
+
+ dialog->setIniSettings(g.Settings);
+
+ // Installation cancelled:
+ if (dialog->exec() == QDialog::Rejected) {
+ return IPluginInstaller::EInstallResult::RESULT_CANCELED;
+ }
+
+ switch (dialog->result()) {
+
+ // Discard, nothing do to:
+ case InstallerFomodPostDialog::Result::DISCARD: break;
+
+ // Apply, must fetch the profile INI settings and apply the settings:
+ case InstallerFomodPostDialog::Result::APPLY: {
+ for (auto& p : g.Settings) {
+ QDir path(g_Organizer->profilePath());
+ if (!g_Organizer->profile()->localSettingsEnabled()) {
+ path = QDir(g_Organizer->managedGame()->documentsDirectory());
+ }
+
+ QSettings settings(path.filePath(p.first), QSettings::IniFormat);
+
+ if (settings.status() != QSettings::NoError) {
+ return IPluginInstaller::EInstallResult::RESULT_FAILED;
+ }
+
+ p.second.update(settings);
+ }
+ } break;
+
+ // Move, must create the INI files and apply the settings:
+ case InstallerFomodPostDialog::Result::MOVE: {
+ for (auto& p : g.Settings) {
+ auto e = g.DestinationTree->addFile("INI Tweaks/" + p.first, false);
+ if (e == nullptr) {
+ return IPluginInstaller::EInstallResult::RESULT_FAILED;
+ }
+ QString path = g.InstallManager->createFile(e);
+ if (path.isEmpty()) {
+ return IPluginInstaller::EInstallResult::RESULT_FAILED;
+ }
+ QSettings settings(path, QSettings::IniFormat);
+ if (settings.status() != QSettings::NoError) {
+ return IPluginInstaller::EInstallResult::RESULT_FAILED;
+ }
+ p.second.update(settings);
+ }
+ } break;
+ }
+
+ }
+
+ tree = g.DestinationTree;
+
+ // Clear up:
+ g = Globals();
+
+
+ return IPluginInstaller::EInstallResult::RESULT_SUCCESS;
+ }
+
+}
+
+namespace CSharp {
+
+ using namespace System::IO;
+
+ bool isFomodEntry(std::shared_ptr<const FileTreeEntry> entry) {
+ return entry->pathFrom(g.SourceTree).compare("fomod", Qt::CaseInsensitive) == 0;
+ }
+
+ bool BaseScriptImpl::PerformBasicInstall() {
+ for (auto e : *g.SourceTree) {
+ if (!isFomodEntry(e)) {
+ auto ce = g.DestinationTree->copy(e, "", IFileTree::InsertPolicy::MERGE);
+ g.InstalledEntries[ce] = e;
+ }
+ }
+ return true;
+ }
+
+ bool BaseScriptImpl::InstallFileFromMod(String^ p_strFrom, String^ p_strTo) {
+ auto sourceEntry = g.SourceTree->find(to_qstring(p_strFrom));
+
+ if (!sourceEntry) {
+ log::warn("File '{}' not found in the archive.", to_wstring(p_strFrom));
+ return false;
+ }
+
+ if (auto ce = g.DestinationTree->copy(sourceEntry, to_qstring(p_strTo)); ce != nullptr) {
+ g.InstalledEntries[ce] = sourceEntry;
+ return true;
+ }
+
+ return false;
+ }
+
+ array<String^>^ BaseScriptImpl::GetModFileList() {
+ // Cannot directly fill a, e.g., List<String^>^ because I cannot capture it:
+ std::vector<QString> paths;
+ g.SourceTree->walk([&](QString const& path, std::shared_ptr<const FileTreeEntry> entry) {
+ // Discard fomod folder:
+ if (isFomodEntry(entry)) {
+ return IFileTree::WalkReturn::SKIP;
+ }
+ if (entry->isFile()) {
+ paths.push_back(path + entry->name());
+ }
+ return IFileTree::WalkReturn::CONTINUE;
+ }, "/");
+
+ // Convert to C#:
+ const auto size = static_cast<int>(paths.size());
+ array<String^>^ result = gcnew array<String^>(size);
+ for (int i = 0; i < size; ++i) {
+ result[i] = from_string(paths[i].toStdWString());
+ }
+
+ return result;
+ }
+
+
+ /**
+ * @brief Extract the given entry.
+ *
+ * If the entry has already been extracted, the existing paths is returned.
+ *
+ * @param entry The entry to extract.
+ *
+ * @return path to the temporary file corresponding to the entry.
+ */
+ QString extractFile(std::shared_ptr<const FileTreeEntry> entry) {
+
+ QString qPath;
+ if (auto it = g.ExtractedEntries.find(entry); it != g.ExtractedEntries.end()) {
+ qPath = it->second;
+ }
+ else {
+ qPath = g.InstallManager->extractFile(entry, true);
+
+ if (qPath.isEmpty()) {
+ return QString();
+ }
+
+ g.ExtractedEntries[entry] = qPath;
+ }
+
+ return qPath;
+ }
+
+ array<Byte>^ BaseScriptImpl::GetFileFromMod(String^ p_strFile) {
+ auto entry = g.SourceTree->find(to_qstring(p_strFile));
+
+ if (!entry) {
+ return gcnew array<Byte>(0);
+ }
+
+ QString qPath = extractFile(entry);
+ if (qPath.isEmpty()) {
+ return gcnew array<Byte>(0);
+ }
+
+ String^ path = from_string(qPath.toStdWString());
+ return File::ReadAllBytes(path);
+ }
+
+ QStringList getDataFiles(QString folder, QString pattern, bool allFolders) {
+ QStringList files = g_Organizer->findFiles(folder, [pattern](QString const& filepath) {
+ return QDir::match(pattern, QFileInfo(filepath).fileName());
+ });
+ if (allFolders) {
+ QStringList directories = g_Organizer->listDirectories(folder);
+ for (QString directory : directories) {
+ // MO2 does not like path with . or / (I think), so creating the path manually:
+ files.append(getDataFiles((folder.isEmpty() ? "" : folder + QDir::separator()) + directory, pattern, allFolders));
+ }
+ }
+ return files;
+ }
+
+ array<String^>^ BaseScriptImpl::GetExistingDataFileList(String^ p_strPath, String^ p_strPattern, bool p_booAllFolders) {
+ QStringList files = getDataFiles(to_qstring(p_strPath), to_qstring(p_strPattern), p_booAllFolders);
+ array<String^>^ result = gcnew array<String^>(files.size());
+
+ QDir modsDir(g_Organizer->modsPath());
+ for (int i = 0; i < files.size(); ++i) {
+ // We need to trim the path to the actual folder containing the mod (did not find a better way):
+ QString rpath = modsDir.relativeFilePath(files[i]).replace("/", QDir::separator());
+ result[i] = from_string(rpath.mid(rpath.indexOf(QDir::separator()) + 1).toStdWString());
+ }
+ return result;
+ }
+
+ /**
+ * @brief Find the data-file path corresponding to the given path.
+ *
+ * This methods first lookup the file in the destination tree of the mod (for files
+ * that have been extracted / created by the mod), and if it does not find it there
+ * lookup files from other mods.
+ *
+ * @param p_strPath Path to the file to lookup, relative to the data folder.
+ *
+ * @return a path to an actual corresponding file, or a null pointer if the
+ * file was not found.
+ */
+ String^ getDataFilePath(String^ p_strPath) {
+
+ // Check if the file is in the output tree:
+ QString qPath = to_qstring(p_strPath);
+ if (auto e = g.DestinationTree->find(qPath); e != nullptr) {
+
+ // Check if it's a created entry:
+ if (auto it = g.CreatedEntries.find(e); it != g.CreatedEntries.end()) {
+ return from_string(g.CreatedEntries[e]);
+ }
+
+ // Find the source entry - We need to check for parent:
+ std::shared_ptr<const FileTreeEntry> originalEntry;
+ if (auto it = g.InstalledEntries.find(e); it != g.InstalledEntries.end()) {
+ originalEntry = it->second;
+ }
+ else {
+ std::shared_ptr<const IFileTree> tree = e->parent();
+ decltype(tree) oTree = nullptr;
+ while (oTree == nullptr && tree != nullptr) {
+ auto it = g.InstalledEntries.find(tree);
+ if (it != g.InstalledEntries.end()) {
+ oTree = it->second->astree();
+ }
+ else {
+ tree = tree->parent();
+ }
+ }
+ originalEntry = oTree->find(e->pathFrom(tree));
+ }
+ QString path = extractFile(originalEntry);
+ if (path.isEmpty()) {
+ return nullptr;
+ }
+ return from_string(path);
+ }
+
+ // Convert to path and normalize separator:
+ auto path = std::filesystem::path(qPath.toStdWString()).make_preferred();
+ QStringList paths = g_Organizer->findFiles(ToQString(path.parent_path().native()), [name = ToQString(path.filename())](QString const& filepath) {
+ return QFileInfo(filepath).fileName().compare(name, Qt::CaseInsensitive) == 0;
+ });
+
+ if (paths.isEmpty()) {
+ return nullptr;
+ }
+
+ return from_string(paths[0]);
+ }
+
+ bool BaseScriptImpl::DataFileExists(String^ p_strPath) {
+ return getDataFilePath(p_strPath) != nullptr;
+ }
+
+ array<Byte>^ BaseScriptImpl::GetExistingDataFile(String^ p_strPath) {
+
+ // Convert to path and normalize separator:
+ String^ datapath = getDataFilePath(p_strPath);
+
+ if (datapath == nullptr) {
+ return nullptr;
+ }
+
+ // Read the first file (should be only one):
+ return File::ReadAllBytes(datapath);
+ }
+
+ bool BaseScriptImpl::GenerateDataFile(String^ p_strPath, array<Byte>^ p_bteData) {
+
+ // Check if we already have created an entry for this:
+ QString qPath = to_qstring(p_strPath);
+ auto entry = g.DestinationTree->find(qPath);
+
+ QString qAbsPath;
+ // If the entry is in the list of created files (note: if the entry does not exist,
+ // find return a nullptr, which is never in g.CreatedEntries).
+ if (auto it = g.CreatedEntries.find(entry); it != g.CreatedEntries.end()) {
+ qAbsPath = g.CreatedEntries.at(entry);
+ }
+ // Otherwize: Create the entry and the temporary file:
+ else {
+ entry = g.DestinationTree->addFile(qPath, true);
+ qAbsPath = g.InstallManager->createFile(entry);
+ if (qAbsPath.isEmpty()) {
+ // Remove the entry from the tree:
+ entry->detach();
+ return false;
+ }
+
+ // Store the created entry:
+ g.CreatedEntries[entry] = qAbsPath;
+ }
+
+ String^ absPath = from_string(qAbsPath);
+ File::WriteAllBytes(absPath, p_bteData);
+ return true;
+ }
+
+ // UI methods:
+
+ DialogResult BaseScriptImpl::ExtendedMessageBox(String^ p_strMessage, String^ p_strTitle, String^ p_strDetails, MessageBoxButtons p_mbbButtons, MessageBoxIcon p_mdiIcon) {
+ QMessageBox messageBox(g.ParentWidget);
+ if (!String::IsNullOrEmpty(p_strTitle)) {
+ messageBox.setWindowTitle(to_qstring(p_strTitle));
+ }
+ messageBox.setText(to_qstring(p_strMessage));
+
+ if (!String::IsNullOrEmpty(p_strDetails)) {
+ messageBox.setDetailedText(to_qstring(p_strDetails));
+ }
+
+ // For whatever reason MessageBoxIcon has duplicated entries...
+ switch (p_mdiIcon) {
+ case MessageBoxIcon::Error:
+ // case MessageBoxIcon::Stop:
+ messageBox.setIcon(QMessageBox::Icon::Critical);
+ break;
+ case MessageBoxIcon::Asterisk:
+ // case MessageBoxIcon::Information:
+ messageBox.setIcon(QMessageBox::Icon::Information);
+ break;
+ case MessageBoxIcon::Question:
+ messageBox.setIcon(QMessageBox::Icon::Question);
+ break;
+ case MessageBoxIcon::Exclamation:
+ // case MessageBoxIcon::Hand:
+ // case MessageBoxIcon::Warning:
+ // case MessageBoxIcon::None:
+ messageBox.setIcon(QMessageBox::Icon::Warning);
+ case MessageBoxIcon::None:
+ messageBox.setIcon(QMessageBox::Icon::NoIcon);
+ break;
+ }
+
+ QMessageBox::StandardButtons buttons;
+
+ switch (p_mbbButtons) {
+ case MessageBoxButtons::AbortRetryIgnore:
+ buttons = QMessageBox::StandardButton::Abort | QMessageBox::StandardButton::Retry | QMessageBox::StandardButton::Ignore;
+ break;
+ case MessageBoxButtons::OK:
+ buttons = QMessageBox::StandardButton::Ok;
+ break;
+ case MessageBoxButtons::OKCancel:
+ buttons = QMessageBox::StandardButton::Ok | QMessageBox::Cancel;
+ break;
+ case MessageBoxButtons::RetryCancel:
+ buttons = QMessageBox::StandardButton::Cancel | QMessageBox::StandardButton::Retry;
+ break;
+ case MessageBoxButtons::YesNoCancel:
+ buttons = QMessageBox::StandardButton::Yes | QMessageBox::No | QMessageBox::Cancel;
+ break;
+ case MessageBoxButtons::YesNo:
+ buttons = QMessageBox::StandardButton::Yes | QMessageBox::No;
+ break;
+ }
+
+ messageBox.setStandardButtons(buttons);
+
+ // Only some case are possible here:
+ switch (messageBox.exec()) {
+ case QMessageBox::Button::Abort:
+ return DialogResult::Abort;
+ case QMessageBox::Button::Cancel:
+ return DialogResult::Cancel;
+ case QMessageBox::Button::Ignore:
+ return DialogResult::Ignore;
+ case QMessageBox::Button::No:
+ return DialogResult::No;
+ case QMessageBox::Button::Ok:
+ return DialogResult::OK;
+ case QMessageBox::Button::Retry:
+ return DialogResult::Retry;
+ case QMessageBox::Button::Yes:
+ return DialogResult::Yes;
+ }
+
+ return DialogResult::None;
+ }
+
+
+ array<int>^ BaseScriptImpl::Select(array<SelectOption^>^ p_sopOptions, String^ p_strTitle, bool p_booSelectMany) {
+ using namespace System::Collections::Generic;
+
+ QDialog* inputDialog = new QDialog();
+ QVBoxLayout* layout = new QVBoxLayout(inputDialog);
+ inputDialog->setWindowTitle(to_qstring(p_strTitle));
+ inputDialog->setLayout(layout);
+
+ layout->setSizeConstraint(QLayout::SetFixedSize);
+
+ if (p_booSelectMany) {
+ layout->addWidget(new QLabel(QObject::tr("Choose any:"), inputDialog));
+ }
+ else {
+ layout->addWidget(new QLabel(QObject::tr("Choose one:"), inputDialog));
+ }
+
+ QList<QAbstractButton*> items;
+ for each (SelectOption ^ opt in p_sopOptions) {
+ QAbstractButton* btn;
+ if (p_booSelectMany) {
+ btn = new QCheckBox(to_qstring(opt->Item), inputDialog);
+ }
+ else {
+ btn = new QRadioButton(to_qstring(opt->Item), inputDialog);
+ }
+
+ if (!String::IsNullOrEmpty(opt->Desc)) {
+ btn->setToolTip(to_qstring(opt->Desc));
+ }
+
+ layout->addWidget(btn);
+ items.append(btn);
+ }
+
+ if (!p_booSelectMany && items.size() > 0) {
+ items[0]->setChecked(true);
+ }
+
+ QDialogButtonBox* buttonBox = new QDialogButtonBox(
+ QDialogButtonBox::Cancel | QDialogButtonBox::Ok, inputDialog);
+ layout->addWidget(buttonBox);
+
+ // Using old signal/slot syntax since the new one does not work here (probably
+ // due to the C++/CLR nature):
+ QObject::connect(buttonBox, SIGNAL(accepted()), inputDialog, SLOT(accept()));
+ QObject::connect(buttonBox, SIGNAL(rejected()), inputDialog, SLOT(reject()));
+
+ inputDialog->setModal(true);
+ if (inputDialog->exec() != QDialog::Accepted) {
+ return gcnew array<int>(0);
+ }
+
+ List<int>^ selected = gcnew List<int>(items.size());
+ for (int i = 0; i < items.size(); ++i) {
+ if (items[i]->isChecked()) {
+ selected->Add(i);
+ }
+ }
+
+ return selected->ToArray();
+ }
+
+ // Versioning / INIs:
+
+ // Convert to Version^ from a MO2 version:
+ inline System::Version^ make_version(VersionInfo version) {
+ auto qversion = version.asQVersionNumber();
+ return gcnew System::Version(qversion.majorVersion(), qversion.minorVersion(), qversion.microVersion());
+
+ }
+
+ System::Version^ BaseScriptImpl::GetModManagerVersion() {
+ const auto version = g_Organizer->version();
+ return gcnew System::Version(version.major(), version.minor(), version.patch());
+ }
+
+ System::Version^ BaseScriptImpl::GetGameVersion() {
+ return make_version(g_Organizer->managedGame()->gameVersion());
+ }
+
+ System::Version^ BaseScriptImpl::GetScriptExtenderVersion() {
+ auto scriptExtender = g_Organizer->gameFeatures()->gameFeature<ScriptExtender>();
+
+ if (!scriptExtender || !scriptExtender->isInstalled()) {
+ return nullptr;
+ }
+
+ return gcnew System::Version(msclr::interop::marshal_as<String^>(scriptExtender->getExtenderVersion().toStdString()));
+ }
+
+ bool BaseScriptImpl::ScriptExtenderPresent() {
+ auto scriptExtender = g_Organizer->gameFeatures()->gameFeature<ScriptExtender>();
+ return scriptExtender && scriptExtender->isInstalled();
+ }
+
+ // Plugins:
+ array<String^>^ BaseScriptImpl::GetAllPlugins() {
+ QStringList names = g_Organizer->pluginList()->pluginNames();
+ array<String^>^ result = gcnew array<String^>(names.size());
+ for (int i = 0; i < names.size(); ++i) {
+ result[i] = from_string(names[i].toStdString());
+ }
+ return result;
+ }
+
+ array<String^>^ BaseScriptImpl::GetActivePlugins() {
+ auto pluginList = g_Organizer->pluginList();
+ QStringList names = pluginList->pluginNames();
+ QStringList activeNames;
+ for (auto& name : names) {
+ if (pluginList->state(name) == IPluginList::STATE_ACTIVE) {
+ activeNames.append(name);
+ }
+ }
+ array<String^>^ result = gcnew array<String^>(activeNames.size());
+ for (int i = 0; i < activeNames.size(); ++i) {
+ result[i] = from_string(activeNames[i].toStdString());
+ }
+ return result;
+ }
+
+ // INIs:
+ String^ BaseScriptImpl::GetIniString(String^ settingsFileName, String^ section, String^ key) {
+
+ // Check if we have already set this within this installation:
+ auto fIt = g.Settings.find(to_qstring(settingsFileName));
+ if (fIt != g.Settings.end()) {
+ QString value = fIt->second.value(to_qstring(section), to_qstring(key));
+ if (!value.isEmpty()) {
+ return from_string(value);
+ }
+ }
+
+ // Otherwize, look-up the file:
+ QDir path(g_Organizer->profilePath());
+ if (!g_Organizer->profile()->localSettingsEnabled()) {
+ path = QDir(g_Organizer->managedGame()->documentsDirectory());
+ }
+
+ QSettings settings(path.filePath(to_qstring(settingsFileName)), QSettings::IniFormat);
+
+ if (settings.status() != QSettings::NoError) {
+ return nullptr;
+ }
+
+ QString name = to_qstring(section + "/" + key);
+ if (section->Equals("General", System::StringComparison::CurrentCultureIgnoreCase)) {
+ name = to_qstring(key);
+ }
+
+ QVariant value = settings.value(name);
+ if (!value.isValid()) {
+ return nullptr;
+ }
+
+ return from_string(value.toString().toStdString());
+ }
+
+ int BaseScriptImpl::GetIniInt(String^ settingsFileName, String^ section, String^ key) {
+ return Convert::ToInt32(GetIniString(settingsFileName, section, key));
+ }
+
+ bool BaseScriptImpl::EditIni(String^ p_strSettingsFileName, String^ p_strSection, String^ p_strKey, String^ p_strValue) {
+ // Check that the file is supported:
+ bool iniFound = false;
+ for (auto ini : g_Organizer->managedGame()->iniFiles()) {
+ if (ini.compare(to_qstring(p_strSettingsFileName), Qt::CaseInsensitive) == 0) {
+ iniFound = true;
+ }
+ }
+
+ if (!iniFound) {
+ return false;
+ }
+
+ g.Settings[to_qstring(p_strSettingsFileName)].setValue(to_qstring(p_strSection), to_qstring(p_strKey), to_qstring(p_strValue));
+ return true;
+ }
+
+}
diff --git a/libs/installer_fomod_csharp/src/base_script.h b/libs/installer_fomod_csharp/src/base_script.h
new file mode 100644
index 0000000..abfa152
--- /dev/null
+++ b/libs/installer_fomod_csharp/src/base_script.h
@@ -0,0 +1,552 @@
+/*
+Copyright (C) 2020 Holt59. All rights reserved.
+
+Mod Organizer is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+Mod Organizer is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Mod Organizer. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+// clang-format off
+
+#ifndef BASE_SCRIPT_H
+#define BASE_SCRIPT_H
+
+#using <System.dll>
+#using <System.Drawing.dll>
+#using <System.Windows.Forms.dll>
+
+#include <uibase/iplugininstaller.h>
+
+/**
+ * Note: The specification of BaseScript where taken from the Nexus-Mods installer_fomod extension
+ * for Vortex: https://github.com/Nexus-Mods/fomod-installer
+ */
+namespace CSharp {
+
+ using namespace System;
+ using namespace System::Drawing;
+ using namespace System::Windows::Forms;
+
+ /// <summary>
+ /// Describes the options to display in a select form.
+ /// </summary>
+ public ref struct SelectOption {
+ public:
+ /// <summary>
+ /// The name of the selection item.
+ /// </summary>
+ String^ Item;
+
+ /// <summary>
+ /// The path to the preview image of the item.
+ /// </summary>
+ String^ Preview;
+
+ /// <summary>
+ /// The description of the selection item.
+ /// </summary>
+ String^ Desc;
+
+ /// <summary>
+ /// A simple constructor that initializes the struct with the given values.
+ /// </summary>
+ /// <param name="item">The name of the selection item.</param>
+ /// <param name="preview">The path to the preview image of the item.</param>
+ /// <param name="desc">The description of the selection item.</param>
+ SelectOption(String^ item, String^ preview, String^ desc) {
+ Item = item;
+ Preview = preview;
+ Desc = desc;
+ }
+ };
+
+ /// <summary>
+ /// The base class for C# scripts.
+ /// </summary>
+ public ref class BaseScriptImpl {
+ public:
+
+ static String^ LastError;
+
+ /// <summary>
+ /// Returns the last error that occurred.
+ /// </summary>
+ /// <returns>The last error that occurred.</returns>
+ static String^ GetLastError() {
+ return LastError;
+ }
+
+ /// <summary>
+ /// Performs a basic install of the mod.
+ /// </summary>
+ /// <remarks>
+ /// A basic install installs all of the file in the mod to the Data directory
+ /// or activates all esp and esm files.
+ /// </remarks>
+ /// <returns><c>true</c> if the installation succeed;
+ /// <c>false</c> otherwise.</returns>
+ static bool PerformBasicInstall();
+
+ /// <summary>
+ /// Installs the specified file from the mod to the specified location on the file system.
+ /// </summary>
+ /// <remarks>
+ /// This is the legacy form of <see cref="InstallFileFromMod(string, string)"/>. It now just calls
+ /// <see cref="InstallFileFromMod(string, string)"/>.
+ /// </remarks>
+ /// <param name="p_strFrom">The path of the file in the mod to install.</param>
+ /// <param name="p_strTo">The path on the file system where the file is to be created.</param>
+ /// <returns><c>true</c> if the file was written; <c>false</c> otherwise.</returns>
+ /// <seealso cref="InstallFileFromMod(string, string)"/>
+ static bool CopyDataFile(String^ p_strFrom, String^ p_strTo) {
+ return InstallFileFromMod(p_strFrom, p_strTo);
+ }
+
+ /// <summary>
+ /// Installs the specified file from the mod to the specified location on the file system.
+ /// </summary>
+ /// <param name="p_strFrom">The path of the file in the mod to install.</param>
+ /// <param name="p_strTo">The path on the file system where the file is to be created.</param>
+ /// <returns><c>true</c> if the file was written; <c>false</c> otherwise.</returns>
+ static bool InstallFileFromMod(String^ p_strFrom, String^ p_strTo);
+
+ /// <summary>
+ /// Installs the speified file from the mod to the file system.
+ /// </summary>
+ /// <param name="p_strFile">The path of the file to install.</param>
+ /// <returns><c>true</c> if the file was written; <c>false</c> otherwise.</returns>
+ static bool InstallFileFromMod(String^ p_strFile) {
+ return InstallFileFromMod(p_strFile, p_strFile);
+ }
+
+ /// <summary>
+ /// Installs the specified file from the mod to the specified location on the file system.
+ /// </summary>
+ /// <param name="p_strFrom">The path of the file in the mod to install.</param>
+ /// <param name="p_strTo">The path on the file system where the file is to be created.</param>
+ /// <returns><c>true</c> if the file was written; <c>false</c> otherwise.</returns>
+ static bool InstallFileFromFomod(String^ p_strFrom, String^ p_strTo) {
+ return InstallFileFromMod(p_strFrom, p_strTo);
+ }
+
+ /// <summary>
+ /// Installs the speified file from the mod to the file system.
+ /// </summary>
+ /// <param name="p_strFile">The path of the file to install.</param>
+ /// <returns><c>true</c> if the file was written; <c>false</c> otherwise.</returns>
+ static bool InstallFileFromFomod(String^ p_strFile) {
+ return InstallFileFromMod(p_strFile, p_strFile);
+ }
+
+ /// <summary>
+ /// Retrieves the list of files in the mod.
+ /// </summary>
+ /// <returns>The list of files in the mod.</returns>
+ static array<String^>^ GetModFileList();
+
+ /// <summary>
+ /// Retrieves the list of files in the mod.
+ /// </summary>
+ /// <returns>The list of files in the mod.</returns>
+ static array<String^>^ GetFomodFileList() {
+ return GetModFileList();
+ }
+
+ /// <summary>
+ /// Retrieves the specified file from the mod.
+ /// </summary>
+ /// <param name="p_strFile">The file to retrieve.</param>
+ /// <returns>The requested file data.</returns>
+ static array<Byte>^ GetFileFromMod(String^ p_strFile);
+
+ /// <summary>
+ /// Retrieves the specified file from the mod.
+ /// </summary>
+ /// <param name="p_strFile">The file to retrieve.</param>
+ /// <returns>The requested file data.</returns>
+ static array<Byte>^ GetFileFromFomod(String^ p_strFile) {
+ return GetFileFromMod(p_strFile);
+ }
+
+ /// <summary>
+ /// Gets a filtered list of all files in a user's Data directory.
+ /// </summary>
+ /// <param name="p_strPath">The subdirectory of the Data directory from which to get the listing.</param>
+ /// <param name="p_strPattern">The pattern against which to filter the file paths.</param>
+ /// <param name="p_booAllFolders">Whether or not to search through subdirectories.</param>
+ /// <returns>A filtered list of all files in a user's Data directory.</returns>
+ static array<String^>^ GetExistingDataFileList(String^ p_strPath, String^ p_strPattern, bool p_booAllFolders);
+
+ /// <summary>
+ /// Determines if the specified file exists in the user's Data directory.
+ /// </summary>
+ /// <param name="p_strPath">The path of the file whose existence is to be verified.</param>
+ /// <returns><c>true</c> if the specified file exists; <c>false</c>
+ /// otherwise.</returns>
+ static bool DataFileExists(String^ p_strPath);
+
+ /// <summary>
+ /// Gets the speified file from the user's Data directory.
+ /// </summary>
+ /// <param name="p_strPath">The path of the file to retrieve.</param>
+ /// <returns>The specified file, or <c>null</c> if the file does not exist.</returns>
+ static array<Byte>^ GetExistingDataFile(String^ p_strPath);
+
+ /// <summary>
+ /// Writes the file represented by the given byte array to the given path.
+ /// </summary>
+ /// <remarks>
+ /// This method writes the given data as a file at the given path. If the file
+ /// already exists the user is prompted to overwrite the file.
+ /// </remarks>
+ /// <param name="p_strPath">The path where the file is to be created.</param>
+ /// <param name="p_bteData">The data that is to make up the file.</param>
+ /// <returns><c>true</c> if the file was written; <c>false</c> otherwise.</returns>
+ static bool GenerateDataFile(String^ p_strPath, array<Byte>^ p_bteData);
+
+ /// <summary>
+ /// Shows a message box with the given message.
+ /// </summary>
+ /// <param name="p_strMessage">The message to display in the message box.</param>
+ static void MessageBox(String^ p_strMessage) {
+ MessageBox(p_strMessage, nullptr);
+ }
+
+ /// <summary>
+ /// Shows a message box with the given message and title.
+ /// </summary>
+ /// <param name="p_strMessage">The message to display in the message box.</param>
+ /// <param name="p_strTitle">The message box's title, display in the title bar.</param>
+ static void MessageBox(String^ p_strMessage, String^ p_strTitle) {
+ MessageBox(p_strMessage, p_strTitle, MessageBoxButtons::OK);
+ }
+
+ /// <summary>
+ /// Shows a message box with the given message, title, and buttons.
+ /// </summary>
+ /// <param name="p_strMessage">The message to display in the message box.</param>
+ /// <param name="p_strTitle">The message box's title, display in the title bar.</param>
+ /// <param name="p_mbbButtons">The buttons to show in the message box.</param>
+ static DialogResult MessageBox(String^ p_strMessage, String^ p_strTitle, MessageBoxButtons p_mbbButtons) {
+ return MessageBox(p_strMessage, p_strTitle, p_mbbButtons, MessageBoxIcon::Information);
+ }
+
+ static DialogResult MessageBox(String^ p_strMessage, String^ p_strTitle, MessageBoxButtons p_mbbButtons, MessageBoxIcon p_mdiIcon) {
+ return ExtendedMessageBox(p_strMessage, p_strTitle, nullptr, p_mbbButtons, p_mdiIcon);
+ }
+
+ /// <summary>
+ /// Shows an extended message box with the given message, title, details, buttons, and icon.
+ /// </summary>
+ /// <param name="p_strMessage">The message to display in the message box.</param>
+ /// <param name="p_strTitle">The message box's title, displayed in the title bar.</param>
+ /// <param name="p_strDetails">The message box's details, displayed in the details area.</param>
+ /// <param name="p_mbbButtons">The buttons to show in the message box.</param>
+ /// <param name="p_mdiIcon">The icon to display in the message box.</param>
+ static DialogResult ExtendedMessageBox(String^ p_strMessage, String^ p_strTitle, String^ p_strDetails, MessageBoxButtons p_mbbButtons, MessageBoxIcon p_mdiIcon);
+
+ /// <summary>
+ /// Displays a selection form to the user.
+ /// </summary>
+ /// <param name="p_sopOptions">The options from which to select.</param>
+ /// <param name="p_strTitle">The title of the selection form.</param>
+ /// <param name="p_booSelectMany">Whether more than one item can be selected.</param>
+ /// <returns>The indices of the selected items.</returns>
+ static array<int>^ Select(array<SelectOption^>^ p_sopOptions, String^ p_strTitle, bool p_booSelectMany);
+
+ /// <summary>
+ /// Displays a selection form to the user.
+ /// </summary>
+ /// <remarks>
+ /// The items, previews, and descriptions are repectively ordered. In other words,
+ /// the i-th item in <paramref name="p_strItems"/> uses the i-th preview in
+ /// <paramref name="p_strPreviewPaths"/> and the i-th description in <paramref name="p_strDescriptions"/>.
+ ///
+ /// Similarly, the idices return as results correspond to the indices of the items in
+ /// <paramref name="p_strItems"/>.
+ /// </remarks>
+ /// <param name="p_strItems">The items from which to select.</param>
+ /// <param name="p_strPreviewPaths">The preview image file names for the items.</param>
+ /// <param name="p_strDescriptions">The descriptions of the items.</param>
+ /// <param name="p_strTitle">The title of the selection form.</param>
+ /// <param name="p_booSelectMany">Whether more than one item can be selected.</param>
+ /// <returns>The indices of the selected items.</returns>
+ static array<int>^ Select(array<String^>^ p_strItems, array<String^>^ p_strPreviewPaths, array<String^>^ p_strDescriptions, String^ p_strTitle, bool p_booSelectMany) {
+ const int size = p_strItems->GetLength(0);
+ array<SelectOption^>^ options = gcnew array<SelectOption^>(size);
+ for (int i = 0; i < size; ++i) {
+ options[i] = gcnew SelectOption(p_strItems[i], p_strPreviewPaths[i], p_strDescriptions[i]);
+ }
+ return Select(options, p_strTitle, p_booSelectMany);
+ }
+
+ /// <summary>
+ /// Displays a selection form to the user.
+ /// </summary>
+ /// <remarks>
+ /// The items, previews, and descriptions are repectively ordered. In other words,
+ /// the i-th item in <paramref name="p_strItems"/> uses the i-th preview in
+ /// <paramref name="p_imgPreviews"/> and the i-th description in <paramref name="p_strDescriptions"/>.
+ ///
+ /// Similarly, the idices return as results correspond to the indices of the items in
+ /// <paramref name="p_strItems"/>.
+ /// </remarks>
+ /// <param name="p_strItems">The items from which to select.</param>
+ /// <param name="p_imgPreviews">The preview images for the items.</param>
+ /// <param name="p_strDescriptions">The descriptions of the items.</param>
+ /// <param name="p_strTitle">The title of the selection form.</param>
+ /// <param name="p_booSelectMany">Whether more than one item can be selected.</param>
+ /// <returns>The indices of the selected items.</returns>
+ static array<int>^ ImageSelect(array<String^>^ p_strItems, array<Image^>^ /* p_imgPreviews */, array<String^>^ p_strDescriptions, String^ p_strTitle, bool p_booSelectMany) {
+ return Select(p_strItems, gcnew array<String^>(p_strItems->Length), p_strDescriptions, p_strTitle, p_booSelectMany);
+ }
+
+ /// <summary>
+ /// Creates a form that can be used in custom mod scripts.
+ /// </summary>
+ /// <returns>A form that can be used in custom mod scripts.</returns>
+ static Form^ CreateCustomForm() {
+ Form^ form = gcnew Form;
+ return form;
+ }
+
+ /// <summary>
+ /// Gets the version of the mod manager.
+ /// </summary>
+ /// <returns>The version of the mod manager.</returns>
+ static System::Version^ GetModManagerVersion();
+
+ /// <summary>
+ /// Gets the version of the game that is installed.
+ /// </summary>
+ /// <returns>The version of the game, or <c>null</c> if Fallout
+ /// is not installed.</returns>
+ static System::Version^ GetGameVersion();
+
+ // This is not in the spec., but I do not see a point in checking each
+ // script extender in a different way.
+ static System::Version^ GetScriptExtenderVersion();
+
+ /// <summary>
+ /// Gets the script extender version or null if it's not installed
+ /// </summary>
+ /// <returns></returns>
+ static System::Version^ GetSkseVersion() {
+ return GetScriptExtenderVersion();
+ }
+
+ /// <summary>
+ /// Gets the script extender version or null if it's not installed
+ /// </summary>
+ /// <returns></returns>
+ static System::Version^ GetFoseVersion() {
+ return GetScriptExtenderVersion();
+ }
+
+ /// <summary>
+ /// Gets the script extender version or null if it's not installed
+ /// </summary>
+ /// <returns></returns>
+ static System::Version^ GetNvseVersion() {
+ return GetScriptExtenderVersion();
+ }
+
+ /// <summary>
+ /// Gets the version of the mod manager.
+ /// </summary>
+ /// <returns>The version of the mod manager.</returns>
+ static System::Version^ GetFommVersion() {
+ return GetModManagerVersion();
+ }
+
+ /// <summary>
+ /// Gets the version of the game that is installed.
+ /// </summary>
+ /// <returns>The version of the game, or <c>null</c> if Fallout
+ /// is not installed.</returns>
+ static System::Version^ GetFalloutVersion() {
+ // I think this is an old function... What Fallout anyway? So just going
+ // to return the game version, whatever current game.
+ return GetGameVersion();
+ }
+
+ /// <summary>
+ /// Determins if the script extender for the game is installed
+ /// (this checks for the script extender of the game for which the
+ /// mod is being installed)
+ /// </summary>
+ /// <returns></returns>
+ static bool ScriptExtenderPresent();
+
+ /// <summary>
+ /// Gets a list of all install plugins.
+ /// </summary>
+ /// <returns>A list of all install plugins.</returns>
+ static array<String^>^ GetAllPlugins();
+
+ /// <summary>
+ /// Retrieves a list of currently active plugins.
+ /// </summary>
+ /// <returns>A list of currently active plugins.</returns>
+ static array<String^>^ GetActivePlugins();
+
+ /// <summary>
+ /// Sets the activated status of a plugin (i.e., and esp or esm file).
+ /// </summary>
+ /// <param name="p_strPluginPath">The path to the plugin to activate or deactivate.</param>
+ /// <param name="p_booActivate">Whether to activate the plugin.</param>
+ static void SetPluginActivation(String^ /* p_strPluginPath */, bool /* p_booActivate */) {
+ // throw gcnew NotImplementedException("SetPluginActivation");
+ }
+
+ /// <summary>
+ /// Sets the load order of the specifid plugin.
+ /// </summary>
+ /// <param name="p_strPlugin">The path to the plugin file whose load order is to be set.</param>
+ /// <param name="p_intNewIndex">The new load order index of the plugin.</param>
+ static void SetPluginOrderIndex(String^ /* p_strPlugin */, int /* p_intNewIndex */) {
+ // throw gcnew NotImplementedException("SetPluginOrderIndex");
+ }
+
+ /// <summary>
+ /// Sets the load order of the plugins.
+ /// </summary>
+ /// <remarks>
+ /// Each plugin will be moved from its current index to its indices' position
+ /// in <paramref name="p_intPlugins"/>.
+ /// </remarks>
+ /// <param name="p_intPlugins">The new load order of the plugins. Each entry in this array
+ /// contains the current index of a plugin. This array must contain all current indices.</param>
+ static void SetLoadOrder(array<int>^ /* p_intPlugins */) {
+ // throw gcnew NotImplementedException("SetLoadOrder");
+ }
+
+ /// <summary>
+ /// Moves the specified plugins to the given position in the load order.
+ /// </summary>
+ /// <remarks>
+ /// Note that the order of the given list of plugins is not maintained. They are re-ordered
+ /// to be in the same order as they are in the before-operation load order. This, I think,
+ /// is somewhat counter-intuitive and may change, though likely not so as to not break
+ /// backwards compatibility.
+ /// </remarks>
+ /// <param name="p_intPlugins">The list of plugins to move to the given position in the
+ /// load order. Each entry in this array contains the current index of a plugin.</param>
+ /// <param name="p_intPosition">The position in the load order to which to move the specified
+ /// plugins.</param>
+ static void SetLoadOrder(array<int>^ /* p_intPlugins */, int /* p_intPosition */) {
+ // throw gcnew NotImplementedException("SetLoadOrder");
+ }
+
+ /// <summary>
+ /// Retrieves the specified settings value as a string.
+ /// </summary>
+ /// <param name="settingsFileName">The name of the settings file from which to retrieve the value.</param>
+ /// <param name="section">The section containing the value to retrieve.</param>
+ /// <param name="key">The key of the value to retrieve.</param>
+ /// <returns>The specified value as a string.</returns>
+ static String^ GetIniString(String^ settingsFileName, String^ section, String^ key);
+
+ /// <summary>
+ /// Retrieves the specified settings value as an integer.
+ /// </summary>
+ /// <param name="settingsFileName">The name of the settings file from which to retrieve the value.</param>
+ /// <param name="section">The section containing the value to retrieve.</param>
+ /// <param name="key">The key of the value to retrieve.</param>
+ /// <returns>The specified value as an integer.</returns>
+ static int GetIniInt(String^ settingsFileName, String^ section, String^ key);
+
+ /// <summary>
+ /// Retrieves the specified Fallout.ini value as a string.
+ /// </summary>
+ /// <param name="section">The section containing the value to retrieve.</param>
+ /// <param name="key">The key of the value to retrieve.</param>
+ /// <returns>The specified value as a string.</returns>
+ /// <seealso cref="GetFalloutIniInt(string, string)"/>
+ static String^ GetFalloutIniString(String^ section, String^ key) {
+ return GetIniString("Fallout.ini", section, key);
+ }
+
+ /// <summary>
+ /// Retrieves the specified Fallout.ini value as an integer.
+ /// </summary>
+ /// <param name="section">The section containing the value to retrieve.</param>
+ /// <param name="key">The key of the value to retrieve.</param>
+ /// <seealso cref="GetFalloutIniString(string, string)"/>
+ static int GetFalloutIniInt(String^ section, String^ key) {
+ return GetIniInt("Fallout.ini", section, key);
+ }
+
+ /// <summary>
+ /// Retrieves the specified FalloutPrefs.ini value as a string.
+ /// </summary>
+ /// <param name="p_strSection">The section containing the value to retrieve.</param>
+ /// <param name="p_strKey">The key of the value to retrieve.</param>
+ /// <returns>The specified value as a string.</returns>
+ /// <seealso cref="GetPrefsIniInt(string, string)"/>
+ static String^ GetPrefsIniString(String^ p_strSection, String^ p_strKey) {
+ // This looks wrong? Yes! But that's what used in other mod managers...
+ return GetIniString("FalloutPrefs.ini", p_strSection, p_strKey);
+ }
+
+ /// <summary>
+ /// Retrieves the specified FalloutPrefs.ini value as an integer.
+ /// </summary>
+ /// <param name="p_strSection">The section containing the value to retrieve.</param>
+ /// <param name="p_strKey">The key of the value to retrieve.</param>
+ /// <returns>The specified value as an integer.</returns>
+ /// <seealso cref="GetPrefsIniString(string, string)"/>
+ static int GetPrefsIniInt(String^ p_strSection, String^ p_strKey) {
+ // This looks wrong? Yes! But that's what used in other mod managers...
+ return GetIniInt("FalloutPrefs.ini", p_strSection, p_strKey);
+ }
+
+ /// <summary>
+ /// Sets the specified value in the specified Ini file to the given value.
+ /// </summary>
+ /// <param name="p_strSettingsFileName">The name of the settings file to edit.</param>
+ /// <param name="p_strSection">The section in the Ini file to edit.</param>
+ /// <param name="p_strKey">The key in the Ini file to edit.</param>
+ /// <param name="p_strValue">The value to which to set the key.</param>
+ /// <returns><c>true</c> if the value was set; <c>false</c>
+ /// if the user chose not to overwrite the existing value.</returns>
+ static bool EditIni(String^ p_strSettingsFileName, String^ p_strSection, String^ p_strKey, String^ p_strValue);
+
+ /// <summary>
+ /// Sets the specified value in the Fallout.ini file to the given value.
+ /// </summary>
+ /// <param name="p_strSection">The section in the Ini file to edit.</param>
+ /// <param name="p_strKey">The key in the Ini file to edit.</param>
+ /// <param name="p_strValue">The value to which to set the key.</param>
+ /// <param name="p_booSaveOld">Not used.</param>
+ /// <returns><c>true</c> if the value was set; <c>false</c>
+ /// if the user chose not to overwrite the existing value.</returns>
+ static bool EditFalloutINI(String^ p_strSection, String^ p_strKey, String^ p_strValue, bool /* p_booSaveOld */) {
+ return EditIni("Fallout.ini", p_strSection, p_strKey, p_strValue);
+ }
+
+ };
+
+ /**
+ * @brief Post-install script.
+ */
+ MOBase::IPluginInstaller::EInstallResult postInstall(std::shared_ptr<MOBase::IFileTree>& tree);
+}
+
+// BaseScript cannot be in a namespace:
+public ref struct SelectOption: public CSharp::SelectOption {
+ SelectOption(System::String^ item, System::String^ preview, System::String^ desc) :
+ CSharp::SelectOption(item, preview, desc) { }
+};
+public ref class BaseScript: public CSharp::BaseScriptImpl { };
+
+#endif
diff --git a/libs/installer_fomod_csharp/src/csharp_interface.cpp b/libs/installer_fomod_csharp/src/csharp_interface.cpp
new file mode 100644
index 0000000..91a4a0d
--- /dev/null
+++ b/libs/installer_fomod_csharp/src/csharp_interface.cpp
@@ -0,0 +1,157 @@
+#include "csharp_interface.h"
+
+#include <fstream>
+#include <regex>
+#include <sstream>
+
+#include <uibase/log.h>
+
+#include "base_script.h"
+#include "csharp_utils.h"
+
+// clang-format off
+
+#using <System.dll>
+
+using namespace MOBase;
+
+/**
+ * This is a assembly resolve handler that does only one thing: returns the assembly
+ * containing BaseScript (usually the DLL) when requested.
+ *
+ * I don't know why this must be done manually... But I did not find any better solution.
+ */
+System::Reflection::Assembly^ currentDomain_AssemblyResolve(System::Object^, System::ResolveEventArgs^ args)
+{
+ using namespace System::Reflection;
+
+ try {
+ Assembly^ baseScriptAssembly = System::Reflection::Assembly::GetAssembly(BaseScript::typeid);
+ if (args->Name->Equals(baseScriptAssembly->FullName)) {
+ return baseScriptAssembly;
+ }
+ }
+ catch (...)
+ {
+ }
+
+ return nullptr;
+}
+
+IPluginInstaller::EInstallResult executeScript(System::String^ script) {
+
+ using namespace System;
+ using namespace System::CodeDom;
+ using namespace System::CodeDom::Compiler;
+ using namespace System::Collections::Generic;
+
+ AppDomain^ currentDomain = AppDomain::CurrentDomain;
+ currentDomain->AssemblyResolve += gcnew ResolveEventHandler(currentDomain_AssemblyResolve);
+
+ // From Nexus-Mods/fomod-installer:
+ Dictionary<String^, String^>^ dicOptions = gcnew Dictionary<String^, String^>(10);
+ dicOptions->Add("CompilerVersion", "v4.0");
+
+ // List of assemblies (including BaseScript) - From Nexus-Mods/fomod-installer:
+ array<String^>^ referenceAssemblies = {
+ "System.dll",
+ "System.Runtime.dll",
+ "System.Drawing.dll",
+ "System.Windows.Forms.dll",
+ "System.Xml.dll",
+ System::Reflection::Assembly::GetAssembly(BaseScript::typeid)->Location
+ };
+
+ CompilerParameters^ cp = gcnew CompilerParameters(referenceAssemblies);
+ cp->GenerateExecutable = false;
+ cp->IncludeDebugInformation = false;
+ cp->GenerateInMemory = true;
+ cp->TreatWarningsAsErrors = false;
+ CodeDomProvider^ provider = CodeDomProvider::CreateProvider("CSharp", dicOptions);
+
+ // Compile the script
+ auto result = provider->CompileAssemblyFromSource(cp, script);
+
+ int errorCount = 0;
+ for each (CompilerError ^ error in result->Errors) {
+ if (error->IsWarning) {
+ log::warn("C# [{}]: {}", error->Line, CSharp::to_string(error->ErrorText));
+ }
+ else {
+ log::error("C# [{}]: {}", error->Line, CSharp::to_string(error->ErrorText));
+ ++errorCount;
+ }
+ }
+
+ if (errorCount > 0) {
+ return IPluginInstaller::EInstallResult::RESULT_FAILED;
+ }
+
+ // Execute the script:
+ try {
+ auto scriptClass = result->CompiledAssembly->GetType("Script");
+ BaseScript^ scriptObject = (BaseScript^)System::Activator::CreateInstance(scriptClass);
+ auto onActivateMethod = scriptObject->GetType()->GetMethod("OnActivate");
+
+ auto success = (bool)(onActivateMethod->IsStatic ? onActivateMethod->Invoke(nullptr, nullptr) : onActivateMethod->Invoke(scriptObject, nullptr));
+ return success ? IPluginInstaller::EInstallResult::RESULT_SUCCESS : IPluginInstaller::EInstallResult::RESULT_CANCELED;
+ }
+ catch (System::Exception^ ex) {
+ log::error("C# ({}): {}\n{}", CSharp::to_string(ex->GetType()->FullName), CSharp::to_string(ex->Message), CSharp::to_string(ex->StackTrace));
+ System::Exception^ innerEx = ex->InnerException;
+ if (innerEx) {
+ log::error("C# ({}): {}\n{}", CSharp::to_string(innerEx->GetType()->FullName), CSharp::to_string(innerEx->Message), CSharp::to_string(innerEx->StackTrace));
+ }
+ return IPluginInstaller::EInstallResult::RESULT_FAILED;
+ }
+
+}
+
+namespace CSharp {
+
+ IPluginInstaller::EInstallResult executeCSharpScript(QString scriptPath, std::shared_ptr<IFileTree>& tree) {
+
+ using namespace System;
+ using namespace System::IO;
+ using namespace System::Text::RegularExpressions;
+
+ // Note: Using C# stuff here to mimicate NMM since there are some encoding issues, and
+ // some regex do not work in C++:
+ array<Byte>^ scriptBytes = File::ReadAllBytes(from_string(scriptPath.toStdWString()));
+
+ // Read the script (using C# to "auto-detect" encoding in a C# way):
+ String^ script;
+ {
+ auto memoryStream = gcnew MemoryStream(scriptBytes);
+ auto reader = gcnew StreamReader(memoryStream, true);
+
+ script = reader->ReadToEnd();
+
+ reader->Close();
+ memoryStream->Close();
+
+ delete reader;
+ delete memoryStream;
+ }
+
+
+ Regex^ regScriptClass = gcnew Regex(R"re((class\s+Script\s*:.*?)(\S*BaseScript))re");
+ Regex^ regFommUsing = gcnew Regex(R"re(\s*using\s*fomm.Scripting\s*;)re");
+
+ String^ strBaseScriptClassName = regScriptClass->Match(script)->Groups[2]->ToString();
+ Regex^ regOtherScriptClasses = gcnew Regex(String::Format(R"re((class\s+\S+\s*:.*?)(?<!\w){0})re", strBaseScriptClassName));
+ String^ strCode = script;
+ strCode = regScriptClass->Replace(strCode, "$1BaseScript");
+ strCode = regOtherScriptClasses->Replace(strCode, "$1BaseScript");
+ strCode = regFommUsing->Replace(strCode, "");
+
+ auto result = executeScript(strCode);
+
+ if (result != IPluginInstaller::EInstallResult::RESULT_SUCCESS) {
+ return result;
+ }
+
+ return postInstall(tree);
+ }
+
+}
diff --git a/libs/installer_fomod_csharp/src/csharp_interface.h b/libs/installer_fomod_csharp/src/csharp_interface.h
new file mode 100644
index 0000000..4f22c20
--- /dev/null
+++ b/libs/installer_fomod_csharp/src/csharp_interface.h
@@ -0,0 +1,40 @@
+#ifndef CSHARP_INTERFACE_H
+#define CSHARP_INTERFACE_H
+
+#include <map>
+
+#include <uibase/ifiletree.h>
+#include <uibase/iplugininstaller.h>
+
+namespace CSharp
+{
+
+void init(MOBase::IOrganizer* moInfo);
+
+/**
+ * @brief Initialize the C# interface before starting an installation.
+ *
+ * @param installer The FOMOD C# installer.
+ * @param manager The installation manager from the installer.
+ * @param parentWidget The parent widget from the installer.
+ * @param tree The archive tree.
+ * @param extractedEntries A map from extracted entries to their extracted path.
+ */
+void beforeInstall(
+ MOBase::IPlugin const* installer, MOBase::IInstallationManager* manager,
+ QWidget* parentWidget, std::shared_ptr<MOBase::IFileTree> tree,
+ std::map<std::shared_ptr<const MOBase::FileTreeEntry>, QString> extractedEntries);
+
+/**
+ * @brief Clear the C# interface after an installation.
+ *
+ * @param scriptPath Path to the script to execute.
+ * @param tree Reference where the final tree will be stored (in case of success.
+ *
+ * @return the installation result after performing post-installation.
+ */
+MOBase::IPluginInstaller::EInstallResult
+executeCSharpScript(QString scriptPath, std::shared_ptr<MOBase::IFileTree>& tree);
+
+} // namespace CSharp
+#endif
diff --git a/libs/installer_fomod_csharp/src/csharp_utils.h b/libs/installer_fomod_csharp/src/csharp_utils.h
new file mode 100644
index 0000000..5ede874
--- /dev/null
+++ b/libs/installer_fomod_csharp/src/csharp_utils.h
@@ -0,0 +1,41 @@
+// clang-format off
+
+#ifndef CSHARP_UTILS_H
+#define CSHARP_UTILS_H
+
+#include <type_traits>
+#include <string>
+
+#include <QString>
+
+#include <msclr\marshal_cppstd.h>
+
+#using <System.dll>
+
+namespace CSharp {
+
+ /**
+ * Handy functions.
+ */
+ inline std::string to_string(System::String^ value) {
+ return msclr::interop::marshal_as<std::string>(value);
+ }
+ inline std::wstring to_wstring(System::String^ value) {
+ return msclr::interop::marshal_as<std::wstring>(value);
+ }
+ inline QString to_qstring(System::String^ value) {
+ msclr::interop::marshal_context ctx;
+ return QString::fromWCharArray(ctx.marshal_as<const wchar_t*>(value));
+ }
+
+ template <class Str>
+ inline System::String^ from_string(Str const& string) {
+ return msclr::interop::marshal_as<System::String^>(string);
+ }
+ inline System::String^ from_string(QString const& string) {
+ return msclr::interop::marshal_as<System::String^>(string.toStdWString().c_str());
+ }
+
+}
+
+#endif
diff --git a/libs/installer_fomod_csharp/src/installer_fomod_csharp.cpp b/libs/installer_fomod_csharp/src/installer_fomod_csharp.cpp
new file mode 100644
index 0000000..02d3a3e
--- /dev/null
+++ b/libs/installer_fomod_csharp/src/installer_fomod_csharp.cpp
@@ -0,0 +1,193 @@
+/*
+Copyright (C) 2020 Holt59. All rights reserved.
+
+Mod Organizer is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+Mod Organizer is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Mod Organizer. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include <uibase/iinstallationmanager.h>
+
+#include "csharp_interface.h"
+#include "installer_fomod_csharp.h"
+#include "installer_fomod_predialog.h"
+#include "xml_info_reader.h"
+
+using namespace MOBase;
+
+bool InstallerFomodCSharp::init(IOrganizer* moInfo)
+{
+ m_MOInfo = moInfo;
+ CSharp::init(moInfo);
+ return true;
+}
+
+std::shared_ptr<const IFileTree>
+InstallerFomodCSharp::findFomodDirectory(std::shared_ptr<const IFileTree> tree) const
+{
+ auto entry = tree->find("fomod", FileTreeEntry::DIRECTORY);
+
+ if (entry != nullptr) {
+ return entry->astree();
+ }
+
+ if (tree->empty()) {
+ return nullptr;
+ }
+
+ // We need at least a directory:
+ if (!tree->at(0)->isDir()) {
+ return nullptr;
+ }
+
+ // But not two:
+ if (tree->size() > 1 && tree->at(1)->isDir()) {
+ return nullptr;
+ }
+
+ return findFomodDirectory(tree->at(0)->astree());
+}
+
+std::shared_ptr<const FileTreeEntry>
+InstallerFomodCSharp::findScriptFile(std::shared_ptr<const IFileTree> tree) const
+{
+ auto fomodDirectory = findFomodDirectory(tree);
+
+ if (fomodDirectory == nullptr) {
+ return nullptr;
+ }
+
+ for (auto e : *fomodDirectory) {
+ if (e->isFile() && e->suffix().compare("cs", Qt::CaseInsensitive) == 0) {
+ return e;
+ }
+ }
+
+ return nullptr;
+}
+
+std::shared_ptr<const FileTreeEntry>
+InstallerFomodCSharp::findInfoFile(std::shared_ptr<const IFileTree> tree) const
+{
+ auto fomodDirectory = findFomodDirectory(tree);
+
+ if (fomodDirectory == nullptr) {
+ return nullptr;
+ }
+
+ for (auto e : *fomodDirectory) {
+ if (e->isFile() && e->compare("info.xml") == 0) {
+ return e;
+ }
+ }
+
+ return nullptr;
+}
+
+bool InstallerFomodCSharp::isArchiveSupported(
+ std::shared_ptr<const MOBase::IFileTree> tree) const
+{
+ return findScriptFile(tree) != nullptr;
+}
+
+InstallerFomodCSharp::EInstallResult
+InstallerFomodCSharp::install(MOBase::GuessedValue<QString>& modName,
+ std::shared_ptr<MOBase::IFileTree>& tree,
+ QString& version, int& modID)
+{
+ static std::set<QString, FileNameComparator> imageSuffixes{"png", "jpg", "jpeg",
+ "gif", "bmp"};
+
+ // Extract the script file:
+ auto scriptFile = findScriptFile(tree);
+ if (scriptFile == nullptr) {
+ return EInstallResult::RESULT_NOTATTEMPTED;
+ }
+
+ // Check if there is a info.xml:
+ auto infoFile = findInfoFile(tree);
+
+ // Set containing everything to extract except the script and the info file:
+ std::set<std::shared_ptr<const FileTreeEntry>> toExtractSet{scriptFile};
+
+ if (infoFile != nullptr) {
+ toExtractSet.insert(infoFile);
+ }
+
+ // Extract all the images:
+ tree->walk([&](const QString&, auto entry) {
+ if (entry->isFile() && imageSuffixes.count(entry->suffix()) > 0) {
+ toExtractSet.insert(entry);
+ }
+ return IFileTree::WalkReturn::CONTINUE;
+ });
+
+ // Extract everything from the fomod/ folder:
+ auto fomodFolder = findFomodDirectory(tree);
+ fomodFolder->walk([&](const QString&, auto entry) {
+ if (entry->isFile()) {
+ toExtractSet.insert(entry);
+ }
+ return IFileTree::WalkReturn::CONTINUE;
+ });
+
+ // Convert to vector:
+ std::vector toExtract(std::begin(toExtractSet), std::end(toExtractSet));
+ QStringList paths(manager()->extractFiles(toExtract));
+
+ // If user cancelled:
+ if (toExtract.size() != static_cast<std::size_t>(paths.size())) {
+ return EInstallResult::RESULT_CANCELED;
+ }
+
+ // Create a map from entry to file path:
+ std::map<std::shared_ptr<const FileTreeEntry>, QString> entryToPath;
+ for (std::size_t i = 0; i < toExtract.size(); ++i) {
+ entryToPath[toExtract[i]] = paths[i];
+ }
+
+ if (infoFile != nullptr) {
+ QFile file(entryToPath[infoFile]);
+ if (file.open(QIODevice::ReadOnly)) {
+ auto info = FomodInfoReader::readXml(file, &FomodInfoReader::parseInfo);
+ if (!std::get<0>(info).isEmpty()) {
+ modName.update(std::get<0>(info), GUESS_META);
+ }
+ if (std::get<1>(info) != -1) {
+ modID = std::get<1>(info);
+ }
+ if (!std::get<2>(info).isEmpty()) {
+ version = std::get<2>(info);
+ }
+ }
+ }
+
+ // Show the dialog:
+ InstallerFomodPredialog dialog(modName, parentWidget());
+ if (dialog.exec() != QDialog::Accepted) {
+ if (dialog.manualRequested()) {
+ modName.update(dialog.getName(), GUESS_USER);
+ return EInstallResult::RESULT_MANUALREQUESTED;
+ } else {
+ return EInstallResult::RESULT_CANCELED;
+ }
+ }
+ modName.update(dialog.getName(), GUESS_USER);
+
+ // Run the C# script:
+ const QString scriptPath = entryToPath[scriptFile];
+ CSharp::beforeInstall(
+ this, manager(), parentWidget(),
+ std::const_pointer_cast<IFileTree>(scriptFile->parent()->parent()),
+ std::move(entryToPath));
+ return CSharp::executeCSharpScript(scriptPath, tree);
+}
diff --git a/libs/installer_fomod_csharp/src/installer_fomod_csharp.h b/libs/installer_fomod_csharp/src/installer_fomod_csharp.h
new file mode 100644
index 0000000..530db37
--- /dev/null
+++ b/libs/installer_fomod_csharp/src/installer_fomod_csharp.h
@@ -0,0 +1,84 @@
+/*
+Copyright (C) 2020 Holt59. All rights reserved.
+
+Mod Organizer is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+Mod Organizer is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Mod Organizer. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef INSTALLER_FOMOD_CSHARP_H
+#define INSTALLER_FOMOD_CSHARP_H
+
+#include <uibase/iplugininstallersimple.h>
+
+class InstallerFomodCSharp : public MOBase::IPluginInstallerSimple
+{
+ Q_OBJECT
+ Q_INTERFACES(MOBase::IPlugin MOBase::IPluginInstaller MOBase::IPluginInstallerSimple)
+ Q_PLUGIN_METADATA(IID "org.holt59.InstallerFomodCSharp")
+
+public:
+ InstallerFomodCSharp() {}
+
+ virtual bool init(MOBase::IOrganizer* moInfo) override;
+
+ virtual QString name() const override { return "Fomod Installer C#"; }
+
+ virtual QString localizedName() const override { return tr("Fomod Installer C#"); }
+
+ virtual QString author() const override { return "Holt59"; }
+
+ virtual QString description() const override
+ {
+ return tr("Installer for C# based FOMOD archives.");
+ }
+
+ virtual MOBase::VersionInfo version() const override
+ {
+ return MOBase::VersionInfo(1, 0, 0, MOBase::VersionInfo::RELEASE_BETA);
+ }
+
+ virtual QList<MOBase::PluginSetting> settings() const override
+ {
+ return {
+ MOBase::PluginSetting("enabled", "check to enable this plugin", QVariant(true)),
+ MOBase::PluginSetting("prefer", "prefer this over the NCC based plugin",
+ QVariant(true))};
+ }
+
+ virtual unsigned int priority() const override
+ {
+ // It's the same priority as the FOMOD installer but those should never conflict:
+ return m_MOInfo->pluginSetting(name(), "prefer").toBool() ? 110 : 90;
+ }
+
+ virtual bool isManualInstaller() const override { return false; }
+
+ virtual bool
+ isArchiveSupported(std::shared_ptr<const MOBase::IFileTree> tree) const override;
+
+ virtual EInstallResult install(MOBase::GuessedValue<QString>& modName,
+ std::shared_ptr<MOBase::IFileTree>& tree,
+ QString& version, int& modID) override;
+
+private:
+ MOBase::IOrganizer* m_MOInfo;
+
+ std::shared_ptr<const MOBase::IFileTree>
+ findFomodDirectory(std::shared_ptr<const MOBase::IFileTree> tree) const;
+ std::shared_ptr<const MOBase::FileTreeEntry>
+ findScriptFile(std::shared_ptr<const MOBase::IFileTree> tree) const;
+ std::shared_ptr<const MOBase::FileTreeEntry>
+ findInfoFile(std::shared_ptr<const MOBase::IFileTree> tree) const;
+};
+
+#endif
diff --git a/libs/installer_fomod_csharp/src/installer_fomod_csharp_en.ts b/libs/installer_fomod_csharp/src/installer_fomod_csharp_en.ts
new file mode 100644
index 0000000..7c13b6c
--- /dev/null
+++ b/libs/installer_fomod_csharp/src/installer_fomod_csharp_en.ts
@@ -0,0 +1,125 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!DOCTYPE TS>
+<TS version="2.1" language="en_US">
+<context>
+ <name>FomodCSharpPostDialog</name>
+ <message>
+ <location filename="installer_fomod_csharp_postdialog.ui" line="14"/>
+ <source>Settings modification required</source>
+ <translation type="unfinished"></translation>
+ </message>
+ <message>
+ <location filename="installer_fomod_csharp_postdialog.ui" line="20"/>
+ <source>The installer needs to edit the following settings. You can either apply them, discard them or move them to the mod installation folder (under INI Tweaks).</source>
+ <translation type="unfinished"></translation>
+ </message>
+ <message>
+ <location filename="installer_fomod_csharp_postdialog.ui" line="56"/>
+ <source>Apply the settings to the INI files corresponding to the current profile.</source>
+ <translation type="unfinished"></translation>
+ </message>
+ <message>
+ <location filename="installer_fomod_csharp_postdialog.ui" line="59"/>
+ <source>Apply</source>
+ <translation type="unfinished"></translation>
+ </message>
+ <message>
+ <location filename="installer_fomod_csharp_postdialog.ui" line="66"/>
+ <source>Discard the settings.</source>
+ <translation type="unfinished"></translation>
+ </message>
+ <message>
+ <location filename="installer_fomod_csharp_postdialog.ui" line="69"/>
+ <source>Discard</source>
+ <translation type="unfinished"></translation>
+ </message>
+ <message>
+ <location filename="installer_fomod_csharp_postdialog.ui" line="76"/>
+ <source>Create files under &quot;INI Tweaks&quot; in the mod folder with these settings.</source>
+ <translation type="unfinished"></translation>
+ </message>
+ <message>
+ <location filename="installer_fomod_csharp_postdialog.ui" line="79"/>
+ <source>INI Tweaks</source>
+ <translation type="unfinished"></translation>
+ </message>
+ <message>
+ <location filename="installer_fomod_csharp_postdialog.ui" line="86"/>
+ <source>Cancel the installation.</source>
+ <translation type="unfinished"></translation>
+ </message>
+ <message>
+ <location filename="installer_fomod_csharp_postdialog.ui" line="89"/>
+ <source>Cancel</source>
+ <translation type="unfinished"></translation>
+ </message>
+</context>
+<context>
+ <name>FomodCSharpPredialog</name>
+ <message>
+ <location filename="installer_fomod_csharp_predialog.ui" line="14"/>
+ <source>FOMOD C# Installer</source>
+ <translation type="unfinished"></translation>
+ </message>
+ <message>
+ <location filename="installer_fomod_csharp_predialog.ui" line="22"/>
+ <source>Name</source>
+ <translation type="unfinished"></translation>
+ </message>
+ <message>
+ <location filename="installer_fomod_csharp_predialog.ui" line="40"/>
+ <location filename="installer_fomod_csharp_predialog.ui" line="43"/>
+ <source>Opens a Dialog that allows custom modifications.</source>
+ <translation type="unfinished"></translation>
+ </message>
+ <message>
+ <location filename="installer_fomod_csharp_predialog.ui" line="46"/>
+ <source>Manual</source>
+ <translation type="unfinished"></translation>
+ </message>
+ <message>
+ <location filename="installer_fomod_csharp_predialog.ui" line="69"/>
+ <source>Start</source>
+ <translation type="unfinished"></translation>
+ </message>
+ <message>
+ <location filename="installer_fomod_csharp_predialog.ui" line="79"/>
+ <source>Cancel</source>
+ <translation type="unfinished"></translation>
+ </message>
+</context>
+<context>
+ <name>FomodInfoReader</name>
+ <message>
+ <location filename="xml_info_reader.h" line="109"/>
+ <source>Failed to parse %1. See console for details.</source>
+ <translation type="unfinished"></translation>
+ </message>
+</context>
+<context>
+ <name>InstallerFomodCSharp</name>
+ <message>
+ <location filename="installer_fomod_csharp.h" line="36"/>
+ <source>Fomod Installer C#</source>
+ <translation type="unfinished"></translation>
+ </message>
+ <message>
+ <location filename="installer_fomod_csharp.h" line="42"/>
+ <source>Installer for C# based FOMOD archives.</source>
+ <translation type="unfinished"></translation>
+ </message>
+</context>
+<context>
+ <name>QObject</name>
+ <message>
+ <location filename="base_script.cpp" line="516"/>
+ <source>Choose any:</source>
+ <translation type="unfinished"></translation>
+ </message>
+ <message>
+ <location filename="base_script.cpp" line="519"/>
+ <source>Choose one:</source>
+ <translation type="unfinished"></translation>
+ </message>
+</context>
+</TS>
diff --git a/libs/installer_fomod_csharp/src/installer_fomod_csharp_postdialog.ui b/libs/installer_fomod_csharp/src/installer_fomod_csharp_postdialog.ui
new file mode 100644
index 0000000..89a6106
--- /dev/null
+++ b/libs/installer_fomod_csharp/src/installer_fomod_csharp_postdialog.ui
@@ -0,0 +1,99 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>FomodCSharpPostDialog</class>
+ <widget class="QDialog" name="FomodCSharpPostDialog">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>589</width>
+ <height>399</height>
+ </rect>
+ </property>
+ <property name="windowTitle">
+ <string>Settings modification required</string>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout">
+ <item>
+ <widget class="QLabel" name="label">
+ <property name="text">
+ <string>The installer needs to edit the following settings. You can either apply them, discard them or move them to the mod installation folder (under INI Tweaks).</string>
+ </property>
+ <property name="wordWrap">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <layout class="QHBoxLayout" name="horizontalLayout">
+ <item>
+ <widget class="QTabWidget" name="tabWidget">
+ <property name="currentIndex">
+ <number>-1</number>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <layout class="QHBoxLayout" name="horizontalLayout_2" stretch="0,0,0,0,0">
+ <item>
+ <spacer name="horizontalSpacer">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>40</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item>
+ <widget class="QPushButton" name="applyBtn">
+ <property name="toolTip">
+ <string>Apply the settings to the INI files corresponding to the current profile.</string>
+ </property>
+ <property name="text">
+ <string>Apply</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="discardBtn">
+ <property name="toolTip">
+ <string>Discard the settings.</string>
+ </property>
+ <property name="text">
+ <string>Discard</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="moveBtn">
+ <property name="toolTip">
+ <string>Create files under &quot;INI Tweaks&quot; in the mod folder with these settings.</string>
+ </property>
+ <property name="text">
+ <string>INI Tweaks</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="cancelBtn">
+ <property name="toolTip">
+ <string>Cancel the installation.</string>
+ </property>
+ <property name="text">
+ <string>Cancel</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/libs/installer_fomod_csharp/src/installer_fomod_csharp_predialog.ui b/libs/installer_fomod_csharp/src/installer_fomod_csharp_predialog.ui
new file mode 100644
index 0000000..0aa08c3
--- /dev/null
+++ b/libs/installer_fomod_csharp/src/installer_fomod_csharp_predialog.ui
@@ -0,0 +1,89 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>FomodCSharpPredialog</class>
+ <widget class="QDialog" name="FomodCSharpPredialog">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>400</width>
+ <height>83</height>
+ </rect>
+ </property>
+ <property name="windowTitle">
+ <string>FOMOD C# Installer</string>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout">
+ <item>
+ <layout class="QHBoxLayout" name="horizontalLayout" stretch="0,1">
+ <item>
+ <widget class="QLabel" name="label">
+ <property name="text">
+ <string>Name</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QComboBox" name="nameCombo">
+ <property name="editable">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <layout class="QHBoxLayout" name="horizontalLayout_2">
+ <item>
+ <widget class="QPushButton" name="manualBtn">
+ <property name="toolTip">
+ <string>Opens a Dialog that allows custom modifications.</string>
+ </property>
+ <property name="whatsThis">
+ <string>Opens a Dialog that allows custom modifications.</string>
+ </property>
+ <property name="text">
+ <string>Manual</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <spacer name="horizontalSpacer">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeType">
+ <enum>QSizePolicy::MinimumExpanding</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>20</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item>
+ <widget class="QPushButton" name="okBtn">
+ <property name="text">
+ <string>Start</string>
+ </property>
+ <property name="default">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="cancelBtn">
+ <property name="text">
+ <string>Cancel</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/libs/installer_fomod_csharp/src/installer_fomod_postdialog.h b/libs/installer_fomod_csharp/src/installer_fomod_postdialog.h
new file mode 100644
index 0000000..9804610
--- /dev/null
+++ b/libs/installer_fomod_csharp/src/installer_fomod_postdialog.h
@@ -0,0 +1,87 @@
+#ifndef INSTALLER_FOMOD_POSTDIALOG_H
+#define INSTALLER_FOMOD_POSTDIALOG_H
+
+#include "ui_installer_fomod_csharp_postdialog.h"
+
+#include <QTextEdit>
+
+#include "psettings.h"
+
+/**
+ * @brief Dialog for the installation of a simple archive
+ * a simple archive is one that doesn't require any manual changes to work correctly
+ **/
+class InstallerFomodPostDialog : public QDialog
+{
+ Q_OBJECT
+
+public:
+ enum class Result
+ {
+ APPLY,
+ DISCARD,
+ MOVE,
+ };
+
+ /**
+ * @brief constructor
+ *
+ * @param preset suggested name for the mod
+ * @param parent parent widget
+ **/
+ explicit InstallerFomodPostDialog(QWidget* parent = 0)
+ : QDialog(parent), ui(new Ui::FomodCSharpPostDialog)
+ {
+ ui->setupUi(this);
+ setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint));
+ }
+
+ ~InstallerFomodPostDialog() {}
+
+ /**
+ * @return the result of this dialog if the user did not cancel.
+ */
+ Result result() const { return m_Result; }
+
+ /**
+ *
+ */
+ void setIniSettings(std::map<QString, PSettings> const& settings)
+ {
+ for (auto p : settings) {
+ QTextEdit* widget = new QTextEdit(this);
+ widget->append(p.second.toString());
+ widget->setReadOnly(true);
+ ui->tabWidget->addTab(widget, p.first);
+ }
+ }
+
+private slots:
+
+ void on_discardBtn_clicked()
+ {
+ m_Result = Result::DISCARD;
+ this->accept();
+ }
+
+ void on_applyBtn_clicked()
+ {
+ m_Result = Result::APPLY;
+ this->accept();
+ }
+
+ void on_moveBtn_clicked()
+ {
+ m_Result = Result::MOVE;
+ this->accept();
+ }
+
+ void on_cancelBtn_clicked() { this->reject(); }
+
+private:
+ std::unique_ptr<Ui::FomodCSharpPostDialog> ui;
+
+ Result m_Result{Result::APPLY};
+};
+
+#endif
diff --git a/libs/installer_fomod_csharp/src/installer_fomod_predialog.h b/libs/installer_fomod_csharp/src/installer_fomod_predialog.h
new file mode 100644
index 0000000..5c57fdf
--- /dev/null
+++ b/libs/installer_fomod_csharp/src/installer_fomod_predialog.h
@@ -0,0 +1,72 @@
+#ifndef INSTALLER_FOMOD_PREDIALOG_H
+#define INSTALLER_FOMOD_PREDIALOG_H
+
+#include "ui_installer_fomod_csharp_predialog.h"
+
+#include <uibase/guessedvalue.h>
+
+#include <QCompleter>
+
+/**
+ * @brief Dialog for the installation of a simple archive
+ * a simple archive is one that doesn't require any manual changes to work correctly
+ **/
+class InstallerFomodPredialog : public QDialog
+{
+ Q_OBJECT
+
+public:
+ /**
+ * @brief constructor
+ *
+ * @param preset suggested name for the mod
+ * @param parent parent widget
+ **/
+ explicit InstallerFomodPredialog(const MOBase::GuessedValue<QString>& preset,
+ QWidget* parent = 0)
+ : QDialog(parent), ui(new Ui::FomodCSharpPredialog), m_Manual(false)
+ {
+
+ ui->setupUi(this);
+ setWindowTitle(preset + " - " + windowTitle());
+
+ for (auto iter = preset.variants().begin(); iter != preset.variants().end();
+ ++iter) {
+ ui->nameCombo->addItem(*iter);
+ }
+
+ ui->nameCombo->setCurrentIndex(ui->nameCombo->findText(preset));
+ setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint));
+ ui->nameCombo->completer()->setCaseSensitivity(Qt::CaseSensitive);
+ }
+
+ ~InstallerFomodPredialog() {}
+
+ /**
+ * @return true if the user requested a manual installation.
+ **/
+ bool manualRequested() const { return m_Manual; }
+
+ /**
+ * @return the (user-modified) mod name
+ **/
+ QString getName() const { return ui->nameCombo->currentText(); }
+
+private slots:
+
+ void on_okBtn_clicked() { this->accept(); }
+
+ void on_cancelBtn_clicked() { this->reject(); }
+
+ void on_manualBtn_clicked()
+ {
+ m_Manual = true;
+ this->reject();
+ }
+
+private:
+ std::unique_ptr<Ui::FomodCSharpPredialog> ui;
+ bool m_Manual;
+};
+
+#endif
diff --git a/libs/installer_fomod_csharp/src/psettings.h b/libs/installer_fomod_csharp/src/psettings.h
new file mode 100644
index 0000000..649c7da
--- /dev/null
+++ b/libs/installer_fomod_csharp/src/psettings.h
@@ -0,0 +1,108 @@
+#ifndef PSETTINGS_H
+#define PSETTINGS_H
+
+#include <QSettings>
+#include <QString>
+#include <map>
+
+/**
+ * This is a small class that can be used to store INI settings in memory since
+ * QSettings is a pain to use without an actual file.
+ *
+ * It is a much simpler structure since it stores everything as string.
+ */
+struct PSettings
+{
+
+ /**
+ *
+ */
+ PSettings() = default;
+
+public: // Value read/write.
+ /**
+ * @brief Set the value of the given section/key.
+ *
+ * @param section The section of the value.
+ * @param key The key of the value.
+ * @param value The value to set.
+ */
+ void setValue(QString section, QString key, QString value)
+ {
+ m_Values[std::make_pair(section, key)] = value;
+ }
+
+ /**
+ * @brief Return the value at the given section/key.
+ *
+ * @param section The section of the value.
+ * @param key The key of the value.
+ *
+ * @return the corresponding value, or an empty string if the section/key does not
+ * exist.
+ */
+ QString value(QString section, QString key) const
+ {
+ auto it = m_Values.find(std::make_pair(section, key));
+ return it == m_Values.end() ? QString() : it->second;
+ }
+
+ /**
+ * @brief Check if the given section/key exists in these settings.
+ *
+ * @param section The section of the value.
+ * @param key The key of the value.
+ *
+ * @return true if the section/key exist.
+ */
+ bool hasValue(QString section, QString key) const
+ {
+ return m_Values.find(std::make_pair(section, key)) != m_Values.end();
+ }
+
+public: // Output:
+ /**
+ * @brief Convert this PSettings to a string.
+ *
+ * @return a string representing the content of a valid INI file corresponding
+ * to this PSettings.
+ */
+ QString toString() const
+ {
+ QString result = "";
+ QString cSection;
+ for (auto& p : m_Values) {
+ if (cSection != p.first.first) {
+ if (!cSection.isEmpty()) {
+ result += '\n';
+ }
+ cSection = p.first.first;
+ result += "[" + cSection + "]\n";
+ }
+ result += p.first.second + "=" + p.second + "\n";
+ }
+ return result;
+ }
+
+ /**
+ * @brief Update the given QSettings with all the value in this.
+ *
+ * @param settings The settings to update.
+ */
+ void update(QSettings& settings) const
+ {
+ for (auto& p : m_Values) {
+ if (p.first.first == "General") {
+ settings.setValue(p.first.second, p.second);
+ } else {
+ settings.setValue(p.first.first + "/" + p.first.second, p.second);
+ }
+ }
+ }
+
+private:
+ // Map from <section, key> to value:
+ std::map<std::pair<QString, QString>, QString> m_Values;
+};
+
+#endif // !PSETTINGS_H
diff --git a/libs/installer_fomod_csharp/src/xml_info_reader.h b/libs/installer_fomod_csharp/src/xml_info_reader.h
new file mode 100644
index 0000000..91d6d9a
--- /dev/null
+++ b/libs/installer_fomod_csharp/src/xml_info_reader.h
@@ -0,0 +1,140 @@
+#ifndef XML_INFO_READER_H
+#define XML_INFO_READER_H
+
+#include <QFile>
+#include <QIODevice>
+#include <QString>
+#include <QStringEncoder>
+#include <QTextStream>
+#include <QXmlStreamReader>
+
+#include <uibase/log.h>
+#include <uibase/utility.h>
+
+// This is from installer_fomod, but should probably not be duplicated here.
+
+struct FomodInfoReader : QObject
+{
+
+ Q_OBJECT
+
+public:
+ struct XmlParseError : MOBase::Exception
+ {
+ XmlParseError(const QString& message) : MOBase::Exception(message) {}
+ };
+
+ static QByteArray skipXmlHeader(QIODevice& file)
+ {
+ static const unsigned char UTF16LE_BOM[] = {0xFF, 0xFE};
+ static const unsigned char UTF16BE_BOM[] = {0xFE, 0xFF};
+ static const unsigned char UTF8_BOM[] = {0xEF, 0xBB, 0xBF};
+ static const unsigned char UTF16LE[] = {0x3C, 0x00, 0x3F, 0x00};
+ static const unsigned char UTF16BE[] = {0x00, 0x3C, 0x00, 0x3F};
+ static const unsigned char UTF8[] = {0x3C, 0x3F, 0x78, 0x6D};
+
+ file.seek(0);
+ QByteArray rawBytes = file.read(4);
+ QTextStream stream(&file);
+ int bom = 0;
+ if (rawBytes.startsWith((const char*)UTF16LE_BOM)) {
+ stream.setEncoding(QStringEncoder::Encoding::Utf16LE);
+ bom = 2;
+ } else if (rawBytes.startsWith((const char*)UTF16BE_BOM)) {
+ stream.setEncoding(QStringEncoder::Encoding::Utf16BE);
+ bom = 2;
+ } else if (rawBytes.startsWith((const char*)UTF8_BOM)) {
+ stream.setEncoding(QStringEncoder::Encoding::Utf8);
+ bom = 3;
+ } else if (rawBytes.startsWith(QByteArray((const char*)UTF16LE, 4))) {
+ stream.setEncoding(QStringEncoder::Encoding::Utf16LE);
+ } else if (rawBytes.startsWith(QByteArray((const char*)UTF16BE, 4))) {
+ stream.setEncoding(QStringEncoder::Encoding::Utf16BE);
+ } else if (rawBytes.startsWith(QByteArray((const char*)UTF8, 4))) {
+ stream.setEncoding(QStringEncoder::Encoding::Utf8);
+ } // otherwise maybe the textstream knows the encoding?
+
+ stream.seek(bom);
+ QString header = stream.readLine();
+ if (!header.startsWith("<?")) {
+ // it was all for nothing, there is no header here...
+ stream.seek(bom);
+ }
+ // this seems to be necessary due to buffering in QTextStream
+ file.seek(stream.pos());
+ return file.readAll();
+ }
+
+ template <class Fn>
+ static auto readXml(QFile& file, Fn&& fn)
+ {
+ // List of encodings to try:
+ static const std::vector<QStringConverter::Encoding> encodings{
+ QStringConverter::Utf16, QStringConverter::Utf8, QStringConverter::Latin1};
+
+ std::string errorMessage;
+ try {
+ QXmlStreamReader reader(&file);
+ return fn(reader);
+ } catch (const XmlParseError& e) {
+ MOBase::log::warn(
+ "The {} in this file is incorrectly encoded ({}). Applying heuristics...",
+ file.fileName(), e.what());
+ }
+
+ // nmm's xml parser is less strict than the one from qt and allows files with
+ // wrong encoding in the header. Being strict here would be bad user experience
+ // this works around bad headers.
+ QByteArray headerlessData = skipXmlHeader(file);
+
+ // try parsing the file with several encodings to support broken files
+ for (auto encoding : encodings) {
+ MOBase::log::debug("Trying encoding {} for {}... ",
+ QStringConverter::nameForEncoding(encoding), file.fileName());
+ try {
+ QStringEncoder encoder(encoding);
+ QXmlStreamReader reader(
+ encoder.encode(QString("<?xml version=\"1.0\" encoding=\"%1\" ?>")
+ .arg(encoder.name())) +
+ headerlessData);
+ MOBase::log::debug("Interpreting {} as {}.", file.fileName(), encoder.name());
+ return fn(reader);
+ } catch (const XmlParseError& e) {
+ MOBase::log::debug("Not {}: {}.", QStringConverter::nameForEncoding(encoding),
+ e.what());
+ }
+ }
+
+ throw XmlParseError(
+ tr("Failed to parse %1. See console for details.").arg(file.fileName()));
+ }
+
+ static std::tuple<QString, int, QString> parseInfo(QXmlStreamReader& reader)
+ {
+ std::tuple<QString, int, QString> info{"", -1, ""};
+ while (!reader.atEnd()) {
+ switch (reader.readNext()) {
+ case QXmlStreamReader::StartElement: {
+ if (reader.name().toString() == "Name") {
+ std::get<0>(info) = reader.readElementText();
+ } else if (reader.name().toString() == "Author") {
+ } else if (reader.name().toString() == "Version") {
+ std::get<2>(info) = reader.readElementText();
+ } else if (reader.name().toString() == "Id") {
+ std::get<1>(info) = reader.readElementText().toInt();
+ } else if (reader.name().toString() == "Website") {
+ }
+ } break;
+ default: {
+ } break;
+ }
+ }
+ if (reader.hasError()) {
+ throw XmlParseError(
+ QString("%1 in line %2").arg(reader.errorString()).arg(reader.lineNumber()));
+ }
+ return info;
+ }
+};
+
+#endif