From 57178f898838afed6e7a50413899d6082aad9989 Mon Sep 17 00:00:00 2001 From: Project579 Date: Mon, 20 Aug 2018 12:55:02 -0500 Subject: Added button to disable Archives in Data Tree and entirely. --- src/settings.cpp | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) (limited to 'src/settings.cpp') diff --git a/src/settings.cpp b/src/settings.cpp index 18e893cb..eb5b372f 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -474,6 +474,11 @@ uint Settings::getMotDHash() const return m_Settings.value("motd_hash", 0).toUInt(); } +bool Settings::archiveParsing() const +{ + return m_Settings.value("Settings/archive_parsing", true).toBool(); +} + QVariant Settings::pluginSetting(const QString &pluginName, const QString &key) const { auto iterPlugin = m_PluginSettings.find(pluginName); @@ -1085,6 +1090,7 @@ Settings::WorkaroundsTab::WorkaroundsTab(Settings *m_parent, , m_forceEnableBox(m_dialog.findChild("forceEnableBox")) , m_displayForeignBox(m_dialog.findChild("displayForeignBox")) , m_lockGUIBox(m_dialog.findChild("lockGUIBox")) + , m_enableArchiveParsingBox(m_dialog.findChild("enableArchiveParsingBox")) { m_appIDEdit->setText(m_parent->getSteamAppID()); @@ -1119,7 +1125,8 @@ Settings::WorkaroundsTab::WorkaroundsTab(Settings *m_parent, m_forceEnableBox->setChecked(m_parent->forceEnableCoreFiles()); m_displayForeignBox->setChecked(m_parent->displayForeign()); m_lockGUIBox->setChecked(m_parent->lockGUI()); - + m_enableArchiveParsingBox->setChecked(m_parent->archiveParsing()); + m_dialog.setExecutableBlacklist(m_parent->executablesBlacklist()); } @@ -1137,6 +1144,7 @@ void Settings::WorkaroundsTab::update() m_Settings.setValue("Settings/force_enable_core_files", m_forceEnableBox->isChecked()); m_Settings.setValue("Settings/display_foreign", m_displayForeignBox->isChecked()); m_Settings.setValue("Settings/lock_gui", m_lockGUIBox->isChecked()); + m_Settings.setValue("Settings/archive_parsing", m_enableArchiveParsingBox->isChecked()); m_Settings.setValue("Settings/executable_blacklist", m_dialog.getExecutableBlacklist()); -- cgit v1.3.1 From 4436d376a8d426867f217b03838570a424b09c5f Mon Sep 17 00:00:00 2001 From: LostDragonist Date: Wed, 12 Dec 2018 20:26:35 -0600 Subject: Clean up and fix merge issues --- src/directoryrefresher.cpp | 3 +- src/mainwindow.cpp | 77 ++- src/mainwindow.ui | 15 +- src/modflagicondelegate.cpp | 3 - src/modinfo.h | 10 - src/modinfodialog.h | 3 +- src/modinfowithconflictinfo.cpp | 2 +- src/modlist.cpp | 18 +- src/modlist.h | 2 - src/organizer_en.ts | 1124 ++++++++++++++++++++------------------- src/organizercore.cpp | 18 +- src/settings.cpp | 4 +- 12 files changed, 652 insertions(+), 627 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/directoryrefresher.cpp b/src/directoryrefresher.cpp index 82eb093b..e6e6a8e0 100644 --- a/src/directoryrefresher.cpp +++ b/src/directoryrefresher.cpp @@ -85,7 +85,6 @@ void DirectoryRefresher::addModBSAToStructure(DirectoryEntry *directoryStructure int priority, const QString &directory, const QStringList &archives) { std::wstring directoryW = ToWString(QDir::toNativeSeparators(directory)); - //QStringList loadOrder = QStringList(); IPluginGame *game = qApp->property("managed_game").value(); GamePlugins *gamePlugins = game->feature(); @@ -95,7 +94,7 @@ void DirectoryRefresher::addModBSAToStructure(DirectoryEntry *directoryStructure for (const QString &archive : archives) { QFileInfo fileInfo(archive); if (m_EnabledArchives.find(fileInfo.fileName()) != m_EnabledArchives.end()) { - + int order = -1; for (auto plugin : loadOrder) diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index cdd53dc9..73a40f46 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -313,8 +313,7 @@ MainWindow::MainWindow(QSettings &initSettings ui->espList->setItemDelegateForColumn(PluginList::COL_FLAGS, new GenericIconDelegate(ui->espList)); ui->espList->installEventFilter(m_OrganizerCore.pluginList()); - //bsaList converted to normal QTreeWidget since we can't sort BSAs anymore. - //ui->bsaList->setLocalMoveOnly(true); + ui->bsaList->setLocalMoveOnly(true); bool pluginListAdjusted = registerWidgetState(ui->espList->objectName(), ui->espList->header(), "plugin_list_state"); registerWidgetState(ui->dataTree->objectName(), ui->dataTree->header()); @@ -451,15 +450,15 @@ MainWindow::MainWindow(QSettings &initSettings if (m_OrganizerCore.getArchiveParsing()) { - ui->showArchiveDataCheckBox->setCheckState(Qt::Checked); - ui->showArchiveDataCheckBox->setEnabled(true); - m_showArchiveData = true; + ui->showArchiveDataCheckBox->setCheckState(Qt::Checked); + ui->showArchiveDataCheckBox->setEnabled(true); + m_showArchiveData = true; } else { - ui->showArchiveDataCheckBox->setCheckState(Qt::Unchecked); - ui->showArchiveDataCheckBox->setEnabled(false); - m_showArchiveData = false; + ui->showArchiveDataCheckBox->setCheckState(Qt::Unchecked); + ui->showArchiveDataCheckBox->setEnabled(false); + m_showArchiveData = false; } refreshExecutablesList(); @@ -1230,7 +1229,7 @@ void MainWindow::updateTo(QTreeWidgetItem *subTree, const std::wstring &director directoryChild->setData(0, Qt::DecorationRole, (new QFileIconProvider())->icon(QFileIconProvider::Folder)); directoryChild->setData(0, Qt::UserRole + 3, isDirectory); - if (conflictsOnly) { + if (conflictsOnly || !m_showArchiveData) { updateTo(directoryChild, temp.str(), **current, conflictsOnly); if (directoryChild->childCount() != 0) { subTree->addChild(directoryChild); @@ -1264,9 +1263,9 @@ void MainWindow::updateTo(QTreeWidgetItem *subTree, const std::wstring &director if (conflictsOnly && (current->getAlternatives().size() == 0)) { continue; } - + bool isArchive = false; - int originID = current->getOrigin(isArchive); + int originID = current->getOrigin(isArchive); if (!m_showArchiveData && isArchive) { continue; } @@ -2304,10 +2303,10 @@ void MainWindow::fileMoved(const QString &filePath, const QString &oldOriginName QString fullNewPath = ToQString(newOrigin.getPath()) + "\\" + filePath; WIN32_FIND_DATAW findData; - HANDLE hFind; - hFind = ::FindFirstFileW(ToWString(fullNewPath).c_str(), &findData); + HANDLE hFind; + hFind = ::FindFirstFileW(ToWString(fullNewPath).c_str(), &findData); filePtr->addOrigin(newOrigin.getID(), findData.ftCreationTime, L"", -1); - FindClose(hFind); + FindClose(hFind); } if (m_OrganizerCore.directoryStructure()->originExists(ToWString(oldOriginName))) { FilesOrigin &oldOrigin = m_OrganizerCore.directoryStructure()->getOriginByName(ToWString(oldOriginName)); @@ -4372,22 +4371,22 @@ void MainWindow::on_actionSettings_triggered() const auto state = settings.archiveParsing(); if (state != m_OrganizerCore.getArchiveParsing()) { - m_OrganizerCore.setArchiveParsing(state); - if (!state) - { - ui->showArchiveDataCheckBox->setCheckState(Qt::Unchecked); - ui->showArchiveDataCheckBox->setEnabled(false); - m_showArchiveData = false; - } - else - { - ui->showArchiveDataCheckBox->setCheckState(Qt::Checked); - ui->showArchiveDataCheckBox->setEnabled(true); - m_showArchiveData = true; - } - m_OrganizerCore.refreshModList(); - m_OrganizerCore.refreshDirectoryStructure(); - m_OrganizerCore.refreshLists(); + m_OrganizerCore.setArchiveParsing(state); + if (!state) + { + ui->showArchiveDataCheckBox->setCheckState(Qt::Unchecked); + ui->showArchiveDataCheckBox->setEnabled(false); + m_showArchiveData = false; + } + else + { + ui->showArchiveDataCheckBox->setCheckState(Qt::Checked); + ui->showArchiveDataCheckBox->setEnabled(true); + m_showArchiveData = true; + } + m_OrganizerCore.refreshModList(); + m_OrganizerCore.refreshDirectoryStructure(); + m_OrganizerCore.refreshLists(); } if (settings.getCacheDirectory() != oldCacheDirectory) { @@ -6027,14 +6026,14 @@ void MainWindow::sendSelectedModsToSeparator_clicked() void MainWindow::on_showArchiveDataCheckBox_toggled(const bool checked) { - if (m_OrganizerCore.getArchiveParsing() && checked) - { - m_showArchiveData = checked; - } - else - { - m_showArchiveData = false; - } - refreshDataTree(); + if (m_OrganizerCore.getArchiveParsing() && checked) + { + m_showArchiveData = checked; + } + else + { + m_showArchiveData = false; + } + refreshDataTree(); } diff --git a/src/mainwindow.ui b/src/mainwindow.ui index eb88a855..c6b43be0 100644 --- a/src/mainwindow.ui +++ b/src/mainwindow.ui @@ -831,6 +831,9 @@ p, li { white-space: pre-wrap; } + + true + Sort @@ -1045,7 +1048,7 @@ p, li { white-space: pre-wrap; } - + Qt::CustomContextMenu @@ -1061,19 +1064,19 @@ p, li { white-space: pre-wrap; } false - + false - + false - + 20 - + true - + 1 diff --git a/src/modflagicondelegate.cpp b/src/modflagicondelegate.cpp index 48d71313..eb6945c4 100644 --- a/src/modflagicondelegate.cpp +++ b/src/modflagicondelegate.cpp @@ -89,11 +89,8 @@ QString ModFlagIconDelegate::getFlagIcon(ModInfo::EFlag flag) const case ModInfo::FLAG_NOTES: return ":/MO/gui/emblem_notes"; case ModInfo::FLAG_CONFLICT_MIXED: return ":/MO/gui/emblem_conflict_mixed"; case ModInfo::FLAG_CONFLICT_OVERWRITE: return ":/MO/gui/emblem_conflict_overwrite"; - case ModInfo::FLAG_CONFLICT_LOOSE_OVERWRITE_ARCHIVE: return ":/MO/gui/emblem_conflict_loose_overwrite_archive"; case ModInfo::FLAG_CONFLICT_OVERWRITTEN: return ":/MO/gui/emblem_conflict_overwritten"; - case ModInfo::FLAG_CONFLICT_MIXED: return ":/MO/gui/emblem_conflict_mixed"; case ModInfo::FLAG_CONFLICT_REDUNDANT: return ":MO/gui/emblem_conflict_redundant"; - case ModInfo::FLAG_ARCHIVE_LOOSE_CONFLICT_MIXED: return ":/MO/gui/archive_loose_conflict_mixed"; case ModInfo::FLAG_ARCHIVE_LOOSE_CONFLICT_OVERWRITE: return ":/MO/gui/archive_loose_conflict_overwrite"; case ModInfo::FLAG_ARCHIVE_LOOSE_CONFLICT_OVERWRITTEN: return ":/MO/gui/archive_loose_conflict_overwritten"; case ModInfo::FLAG_ARCHIVE_CONFLICT_MIXED: return ":/MO/gui/archive_conflict_mixed"; diff --git a/src/modinfo.h b/src/modinfo.h index 00859209..350b3a0d 100644 --- a/src/modinfo.h +++ b/src/modinfo.h @@ -639,16 +639,6 @@ public: */ virtual std::set getModArchiveOverwritten() { return std::set(); } - /** - * @return retrieve list of mods (as mod index) with archives that are overwritten by this one. Updates may be delayed - */ - virtual std::set getModArchiveOverwrite() { return std::set(); } - - /** - * @return list of mods (as mod index) with archives that overwrite this one. Updates may be delayed - */ - virtual std::set getModArchiveOverwritten() { return std::set(); } - /** * @return retrieve list of mods (as mod index) with archives that are overwritten by thos mod's loose files. Updates may be delayed */ diff --git a/src/modinfodialog.h b/src/modinfodialog.h index 6a315a93..52768649 100644 --- a/src/modinfodialog.h +++ b/src/modinfodialog.h @@ -78,7 +78,8 @@ public: * @param modInfo info structure about the mod to display * @param parent parend widget **/ - explicit ModInfoDialog(ModInfo::Ptr modInfo, const MOShared::DirectoryEntry *directory, bool unmanaged, OrganizerCore *organizerCore, PluginContainer *pluginContainer, QWidget *parent = 0); + explicit ModInfoDialog(ModInfo::Ptr modInfo, const MOShared::DirectoryEntry *directory, bool unmanaged, OrganizerCore *organizerCore, PluginContainer *pluginContainer, QWidget *parent = 0); + ~ModInfoDialog(); /** diff --git a/src/modinfowithconflictinfo.cpp b/src/modinfowithconflictinfo.cpp index 79896cc3..12cbf416 100644 --- a/src/modinfowithconflictinfo.cpp +++ b/src/modinfowithconflictinfo.cpp @@ -35,7 +35,7 @@ std::vector ModInfoWithConflictInfo::getFlags() const switch (isLooseArchiveConflicted()) { case CONFLICT_MIXED: { result.push_back(ModInfo::FLAG_ARCHIVE_LOOSE_CONFLICT_OVERWRITE); - result.push_back(ModInfo::FLAG_ARCHIVE_LOOSE_CONFLICT_OVERWRITTEN); + result.push_back(ModInfo::FLAG_ARCHIVE_LOOSE_CONFLICT_OVERWRITTEN); } break; case CONFLICT_OVERWRITE: { result.push_back(ModInfo::FLAG_ARCHIVE_LOOSE_CONFLICT_OVERWRITE); diff --git a/src/modlist.cpp b/src/modlist.cpp index 8c070667..757fedb2 100644 --- a/src/modlist.cpp +++ b/src/modlist.cpp @@ -159,7 +159,6 @@ QString ModList::getFlagText(ModInfo::EFlag flag, ModInfo::Ptr modInfo) const return output.join("
"); } case ModInfo::FLAG_CONFLICT_OVERWRITE: return tr("Overwrites loose files"); - case ModInfo::FLAG_CONFLICT_LOOSE_OVERWRITE_ARCHIVE: return tr("Loose files overwrite another archive"); case ModInfo::FLAG_CONFLICT_OVERWRITTEN: return tr("Overwritten loose files"); case ModInfo::FLAG_CONFLICT_MIXED: return tr("Loose files Overwrites & Overwritten"); case ModInfo::FLAG_CONFLICT_REDUNDANT: return tr("Redundant"); @@ -420,13 +419,13 @@ QVariant ModList::data(const QModelIndex &modelIndex, int role) const (archiveLooseOverwrite && (overwritten || archiveOverwritten)) || (archiveLooseOverwritten && (overwrite || archiveLooseOverwrite)) ) { - return QColor(255, 0, 255, 32); //TODO: Make configurable - } else if (overwrite || archiveOverwrite || archiveLooseOverwrite) { return Settings::instance().modlistOverwrittenLooseColor(); } - } else if (overwritten || archiveOverwritten || archiveLooseOverwritten) { + else if (overwrite || archiveOverwrite || archiveLooseOverwrite) { return Settings::instance().modlistOverwritingLooseColor(); - } else if (modInfo->hasFlag(ModInfo::FLAG_SEPARATOR) + } else if (overwritten || archiveOverwritten || archiveLooseOverwritten) { + return QColor(255, 0, 0, 64); //TODO: Make configurable + } else if (modInfo->hasFlag(ModInfo::FLAG_SEPARATOR) && modInfo->getColor().isValid() && ((role != ViewMarkingScrollBar::DEFAULT_ROLE) || Settings::instance().colorSeparatorScrollbar())) { @@ -789,14 +788,7 @@ void ModList::setArchiveLooseOverwriteMarkers(const std::set &over void ModList::setPluginContainer(PluginContainer *pluginContianer) { - m_PluginContainer = pluginContianer; -} - -void ModList::setArchiveOverwriteMarkers(const std::set &overwrite, const std::set &overwritten) -{ - m_ArchiveOverwrite = overwrite; - m_ArchiveOverwritten = overwritten; - notifyChange(0, rowCount() - 1); + m_PluginContainer = pluginContianer; } bool ModList::modInfoAboutToChange(ModInfo::Ptr info) diff --git a/src/modlist.h b/src/modlist.h index a8263a76..49627d68 100644 --- a/src/modlist.h +++ b/src/modlist.h @@ -115,8 +115,6 @@ public: void setArchiveOverwriteMarkers(const std::set &overwrite, const std::set &overwritten); void setArchiveLooseOverwriteMarkers(const std::set &overwrite, const std::set &overwritten); - void setArchiveOverwriteMarkers(const std::set &overwrite, const std::set &overwritten); - bool modInfoAboutToChange(ModInfo::Ptr info); void modInfoChanged(ModInfo::Ptr info); diff --git a/src/organizer_en.ts b/src/organizer_en.ts index 44a386d6..550f7d5c 100644 --- a/src/organizer_en.ts +++ b/src/organizer_en.ts @@ -279,12 +279,12 @@ p, li { white-space: pre-wrap; } DirectoryRefresher - + failed to parse bsa %1: %2 - + failed to read mod (%1): %2 @@ -1620,7 +1620,7 @@ p, li { white-space: pre-wrap; } - + Create Backup @@ -1657,7 +1657,7 @@ p, li { white-space: pre-wrap; } - + Namefilter @@ -1783,9 +1783,9 @@ p, li { white-space: pre-wrap; } - - - + + + Refresh @@ -1805,23 +1805,34 @@ p, li { white-space: pre-wrap; } - - - Filter the above list so that only conflicts are displayed. + + + Filters the above list so that only conflicts are displayed. - + Show only conflicts - + + + Filters the above list so that files from archives are not shown + + + + + Show files from Archives + + + + Saves - + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } @@ -1832,160 +1843,160 @@ p, li { white-space: pre-wrap; } - + Downloads - + Refresh downloads view - + This is a list of mods you downloaded from Nexus. Double click one to install it. You can also drag an archive into here. - + Show Hidden - + Tool Bar - + Install Mod - + Install &Mod - + Install a new mod from an archive - + Ctrl+M - + Profiles - + &Profiles - + Configure Profiles - + Ctrl+P - + Executables - + &Executables - + Configure the executables that can be started through Mod Organizer - + Ctrl+E - - + + Tools - + &Tools - + Ctrl+I - + Settings - + &Settings - + Configure settings and workarounds - + Ctrl+S - + Nexus - + Search nexus network for more mods - + Ctrl+N - - + + Update - + Mod Organizer is up-to-date - - + + No Problems - + This button will be highlighted if MO discovered potential problems in your setup and provide tips on how to fix them. !Work in progress! @@ -1993,830 +2004,830 @@ Right now this has very limited functionality - - + + Help - + Ctrl+H - + Endorse MO - - + + Endorse Mod Organizer - + Copy Log to Clipboard - + Change Game - + Open the Instance selection dialog to manage a different Game - + Toolbar - + Desktop - + Start Menu - + There is no supported sort mechanism for this game. You will probably have to use a third-party tool. - + Problems - + There are potential problems with your setup - + Everything seems to be in order - + Help on UI - + Documentation Wiki - + Report Issue - + Tutorials - + About - + About Qt - + Name - + Please enter a name for the new profile - + failed to create profile: %1 - + Show tutorial? - + You are starting Mod Organizer for the first time. Do you want to show a tutorial of its basic features? If you choose no you can always start the tutorial from the "Help"-menu. - + Downloads in progress - + There are still downloads in progress, do you really want to quit? - + Plugin "%1" failed: %2 - + Plugin "%1" failed - + Browse Mod Page - + Also in: <br> - + No conflict - + <Edit...> - + This bsa is enabled in the ini file so it may be required! - + Activating Network Proxy - + Notice: Your current MO version (%1) is lower than the previous version (%2).<br>The GUI may not downgrade gracefully, so you may experience oddities.<br>However, there should be no serious issues. - + Choose Mod - + Mod Archive - + Start Tutorial? - + You're about to start a tutorial. For technical reasons it's not possible to end the tutorial early. Continue? - + failed to spawn notepad.exe: %1 - + failed to change origin name: %1 - + failed to move "%1" from mod "%2" to "%3": %4 - + <Contains %1> - + <Checked> - + <Unchecked> - + <Update> - + <Mod Backup> - + <Managed by MO> - + <Managed outside MO> - + <No category> - + <Conflicted> - + <Not Endorsed> - + failed to rename mod: %1 - + Overwrite? - + This will replace the existing mod "%1". Continue? - + failed to remove mod "%1" - - - + + + failed to rename "%1" to "%2" - - - - + + + + Confirm - + Remove the following mods?<br><ul>%1</ul> - + failed to remove mod: %1 - - - + + + Failed - + Installation file no longer exists - + Mods installed with old versions of MO can't be reinstalled in this way. - + Failed to create backup. - + You need to be logged in with Nexus to resume a download - - + + You need to be logged in with Nexus to endorse - + Failed to display overwrite dialog: %1 - + Nexus ID for this Mod is unknown - + Web page for this mod is unknown - - - + + + Create Mod... - + This will create an empty mod. Please enter a name: - - + + A mod with this name already exists - + Create Separator... - + This will create a new separator. Please enter a name: - + A separator with this name already exists - + This will move all files from overwrite into a new, regular mod. Please enter a name: - - + + Are you sure? - + About to recursively delete: - + Not logged in, endorsement information will be wrong - + Continue? - + The versioning scheme decides which version is considered newer than another. This function will guess the versioning scheme under the assumption that the installed version is outdated. - - + + Sorry - + I don't know a versioning scheme where %1 is newer than %2. - + Really enable all visible mods? - + Really disable all visible mods? - + Export to csv - + CSV (Comma Separated Values) is a format that can be imported in programs like Excel to create a spreadsheet. You can also use online editors and converters instead. - + Select what mods you want export: - + All installed mods - + Only active (checked) mods from your current profile - + All currently visible mods in the mod list - + Choose what Columns to export: - + Mod_Priority - + Mod_Name - + Mod_Status - + Primary_Category - + Nexus_ID - + Mod_Nexus_URL - + Mod_Version - + Install_Date - + Download_File_Name - + export failed: %1 - + Open Game folder - + Open MyGames folder - + Open Instance folder - + Open Mods folder - + Open Profile folder - + Open Downloads folder - + Open MO2 Install folder - + Open MO2 Plugins folder - + Open MO2 Logs folder - + Install Mod... - + Create empty mod - + Create Separator - + Enable all visible - + Disable all visible - + Check all for update - + Export to csv... - - + + Send to - - + + Top - - + + Bottom - - + + Priority... - + Separator... - + All Mods - + Sync to Mods... - + Clear Overwrite... - - + + Open in Explorer - + Restore Backup - + Remove Backup... - - + + Change Categories - - + + Primary Category - + Rename Separator... - + Remove Separator... - + Select Color... - + Reset Color - + Change versioning scheme - + Un-ignore update - + Ignore update - - + + Enable selected - - + + Disable selected - + Rename Mod... - + Reinstall Mod - + Remove Mod... - + Un-Endorse - - + + Endorse - + Won't endorse - + Endorsement state unknown - + Ignore missing data - + Mark as converted/working - + Visit on Nexus - + Visit web page - + Information... - - + + Exception: - - + + Unknown exception - + <All> - + <Multiple> - + %1 more - + Are you sure you want to remove the following %n save(s)?<br><ul>%1</ul><br>Removed saves will be sent to the Recycle Bin. @@ -2824,12 +2835,12 @@ You can also use online editors and converters instead. - + Enable Mods... - + Delete %n save(s) @@ -2837,22 +2848,22 @@ You can also use online editors and converters instead. - + failed to remove %1 - + failed to create %1 - + Restarting MO - + Changing the managed game directory requires restarting MO. Any pending downloads will be paused. @@ -2860,335 +2871,335 @@ Click OK to restart MO now. - + Can't change download directory while downloads are in progress! - + failed to write to file %1 - + %1 written - + Select binary - + Binary - + Enter Name - + Please enter a name for the executable - + Not an executable - + This is not a recognized executable. - - + + Replace file? - + There already is a hidden version of this file. Replace it? - - + + File operation failed - - + + Failed to remove "%1". Maybe you lack the required file permissions? - + There already is a visible version of this file. Replace it? - - + + Set Priority - + Set the priority of the selected plugins - + file not found: %1 - + failed to generate preview for %1 - + Sorry, can't preview anything. This function currently does not support extracting from bsas. - + Update available - + Open/Execute - + Add as Executable - + Preview - + Un-Hide - + Hide - + Write To File... - + Do you want to endorse Mod Organizer on %1 now? - + Thank you! - + Thank you for your endorsement! - + Request to Nexus failed: %1 - - + + failed to read %1: %2 - - + + Error - + failed to extract %1 (errorcode %2) - + Extract BSA - + This archive contains invalid hashes. Some files may be broken. - + Extract... - + This will restart MO, continue? - + Edit Categories... - + Deselect filter - + Remove - + Enable all - + Disable all - + Unlock load order - + Lock load order - + Open Origin in Explorer - + Open Origin Info... - + depends on missing "%1" - + incompatible with "%1" - + Please wait while LOOT is running - + loot failed. Exit code was: %1 - + failed to start loot - + failed to run loot: %1 - + Errors occured - + Backup of load order created - + Choose backup to restore - + No Backups - + There are no backups to restore - - + + Restore failed - - + + Failed to restore the backup. Errorcode: %1 - + Backup of modlist created - + A file with the same name has already been downloaded. What would you like to do? - + Overwrite - + Rename new file - + Ignore file - + Set the priority of the selected mods @@ -3649,243 +3660,243 @@ p, li { white-space: pre-wrap; } - - + + Save changes? - - + + Save changes to "%1"? - + File Exists - + A file with that name exists, please enter a new one - + failed to move file - + failed to create directory "optional" - - + + Info requested, please wait - + Main - + Update - + Optional - + Old - + Misc - + Unknown - + Current Version: %1 - + No update available - + (description incomplete, please visit nexus) - + <a href="%1">Visit on Nexus</a> - + Failed to delete %1 - - - - + + + + Confirm - - + + Are sure you want to delete "%1"? - - + + Are sure you want to delete the selected files? - - + + New Folder - + Failed to create "%1" - - + + Replace file? - + There already is a hidden version of this file. Replace it? - - + + File operation failed - - + + Failed to remove "%1". Maybe you lack the required file permissions? - - + + failed to rename %1 to %2 - + There already is a visible version of this file. Replace it? - + Select binary - + Binary - + file not found: %1 - + failed to generate preview for %1 - + Sorry - + Sorry, can't preview anything. This function currently does not support extracting from bsas. - + Un-Hide - + Hide - - + + Open/Execute - - + + Preview - + Name - + Please enter a name - - + + Error - + Invalid name. Must be a valid file name - + A tweak by that name exists - + Create Tweak @@ -4037,182 +4048,197 @@ p, li { white-space: pre-wrap; } - Overwrites files + Overwrites loose files - Overwritten files + Loose files overwrite another archive - Overwrites & Overwritten + Overwritten loose files - Redundant + Loose files Overwrites & Overwritten - Alternate game source + Redundant - - Non-MO + + Overwrites an archive with loose files - - invalid + + Archive is overwritten by loose files - - installed version: "%1", newest version: "%2" + + Overwrites another archive file - - The newest version on Nexus seems to be older than the one you have installed. This could either mean the version you have has been withdrawn (i.e. due to a bug) or the author uses a non-standard versioning scheme and that newest version is actually newer. Either way you may want to "upgrade". + + Overwritten by another archive file - - Categories: <br> + + Archive files overwrites & overwritten + + + + + Alternate game source + + + + + Non-MO - + + invalid + + + + Invalid name - + Name is already in use by another mod - + drag&drop failed: %1 - + Confirm - + Are you sure you want to remove "%1"? - + Flags - + Content - + Mod Name - + Version - + Priority - + Category - + Source Game - + Nexus ID - + Installation - + Notes - - + + unknown - + Name of your mods - + Version of the mod (if available) - + Installation priority of your mod. The higher, the more "important" it is and thus overwrites files from mods with lower priority. - + Category of the mod. - + The source game which was the origin of this mod. - + Id of the mod as used on Nexus. - + Emblemes to highlight things that might require attention. - + Depicts the content of the mod:<br><table cellspacing=7><tr><td><img src=":/MO/gui/content/plugin" width=32/></td><td>Game plugins (esp/esm/esl)</td></tr><tr><td><img src=":/MO/gui/content/interface" width=32/></td><td>Interface</td></tr><tr><td><img src=":/MO/gui/content/mesh" width=32/></td><td>Meshes</td></tr><tr><td><img src=":/MO/gui/content/bsa" width=32/></td><td>BSA</td></tr><tr><td><img src=":/MO/gui/content/texture" width=32/></td><td>Textures</td></tr><tr><td><img src=":/MO/gui/content/sound" width=32/></td><td>Sounds</td></tr><tr><td><img src=":/MO/gui/content/music" width=32/></td><td>Music</td></tr><tr><td><img src=":/MO/gui/content/string" width=32/></td><td>Strings</td></tr><tr><td><img src=":/MO/gui/content/script" width=32/></td><td>Scripts (Papyrus)</td></tr><tr><td><img src=":/MO/gui/content/skse" width=32/></td><td>Script Extender plugins</td></tr><tr><td><img src=":/MO/gui/content/skyproc" width=32/></td><td>SkyProc Patcher</td></tr><tr><td><img src=":/MO/gui/content/menu" width=32/></td><td>Mod Configuration Menu</td></tr><tr><td><img src=":/MO/gui/content/inifile" width=32/></td><td>INI files</td></tr><tr><td><img src=":/MO/gui/content/modgroup" width=32/></td><td>ModGroup files</td></tr></table> - + Time this mod was installed - + User notes about the mod @@ -4220,7 +4246,7 @@ p, li { white-space: pre-wrap; } ModListSortProxy - + Drag&Drop is only supported when sorting by priority @@ -4350,171 +4376,171 @@ p, li { white-space: pre-wrap; } - - + + Installation successful - - + + Configure Mod - - + + This mod contains ini tweaks. Do you want to configure them now? - - + + mod "%1" not found - - + + Installation cancelled - - + + The mod was not installed completely. - + Executable "%1" not found - + Start Steam? - + Steam is required to be running already to correctly start the game. Should MO try to start steam now? - + Error - + Windows Event Log Error - + The Windows Event Log service is disabled and/or not running. This prevents USVFS from running properly. Your mods may not be working in the executable that you are launching. Note that you may have to restart MO and/or your PC after the service is fixed. Continue launching %1? - + Blacklisted Executable - + The executable you are attempted to launch is blacklisted in the virtual file system. This will likely prevent the executable, and any executables that are launched by this one, from seeing any mods. This could extend to INI files, save games and any other virtualized files. Continue launching %1? - + No profile set - + Failed to refresh list of esps: %1 - + Multiple esps/esls activated, please check that they don't conflict. - + Download? - + A download has been started but no installed page plugin recognizes it. If you download anyway no information (i.e. version) will be associated with the download. Continue? - + failed to update mod list: %1 - - + + login successful - + Login failed - + Login failed, try again? - + login failed: %1. Download will not be associated with an account - + login failed: %1 - + login failed: %1. You need to log-in with Nexus to update MO. - + MO1 "Script Extender" load mechanism has left hook.dll in your game folder - - + + Description missing - + <a href="%1">hook.dll</a> has been found in your game folder (right click to copy the full path). This is most likely a leftover of setting the ModOrganizer 1 load mechanism to "Script Extender", in which case you must remove this file either by changing the load mechanism in ModOrganizer 1 or manually removing the file, otherwise the game is likely to crash and burn. - + failed to save load order: %1 - + The designated write target "%1" is not enabled. @@ -4661,94 +4687,94 @@ Continue? - + failed to update esp info for file %1 (source id: %2), error: %3 - + esp not found: %1 - - + + Confirm - + Really enable all plugins? - + Really disable all plugins? - + The file containing locked plugin indices is broken - - + + <b>Origin</b>: %1 - + <br><b><i>This plugin can't be disabled (enforced by the game).</i></b> - + Author - + Description - + Missing Masters - + Enabled Masters - + Loads Archives - + There are Archives connected to this plugin. Their assets will be added to your game, overwriting in case of conflicts following the plugin order. Loose files will always overwrite assets from Archives. (This flag only checks for Archives from the same mod as the plugin) - + Loads INI settings - + There is an ini file connected to this plugin. Its settings will be added to your game settings, overwriting in case of conflicts. - + This ESP is flagged as an ESL. It will adhere to the ESP load order but the records will be loaded in ESL space. - + failed to restore load order for %1 @@ -5490,7 +5516,7 @@ If the folder was still in use, restart MO and try again. - + Mod Organizer @@ -5505,18 +5531,18 @@ If the folder was still in use, restart MO and try again. - + Please use "Help" from the toolbar to get usage instructions to all elements - - + + <Manage...> - + failed to parse profile %1: %2 @@ -5552,12 +5578,12 @@ If the folder was still in use, restart MO and try again. - + failed to access %1 - + failed to set file time %1 @@ -5567,12 +5593,12 @@ If the folder was still in use, restart MO and try again. - + Script Extender - + Proxy DLL @@ -5763,12 +5789,12 @@ Select Show Details option to see the full change-log. - + Failed to start %1: %2 - + Error @@ -5786,28 +5812,28 @@ Select Show Details option to see the full change-log. - - + + attempt to store setting for unknown plugin "%1" - + Error - + Failed to create "%1", you may not have the necessary permission. path remains unchanged. - + Restart Mod Organizer? - + In order to reset the window geometries, MO must be restarted. Restart it now? @@ -6351,75 +6377,90 @@ programs you are intentionally running. + Enable parsing of Archives Archives, has effects on perfromance. + + + - Resets the window geometries for all windows. This can be useful if a window becomes too small or too large, if a column becomes too thin or too wide, and in similar situations. + + By default Mod Organizer will parse Archive files to calculate conflicts between themselves and loose files, this process has a noticeable cost in performance. + This feature should not be confused from the one offered by ModOrganizer 1, ModOrganizer 2 will only show conflicts with archives NOT load them into the game or program. + + If you disable this feature, MO will only display conflicts with Loose files. + - - Reset Window Geometries + + Enable parsing of Archives - - These are workarounds for problems with Mod Organizer. Please make sure you read the help text before changing anything here. + + + Resets the window geometries for all windows. This can be useful if a window becomes too small or too large, if a column becomes too thin or too wide, and in similar situations. - - Diagnostics + + Reset Window Geometries - - Log Level + + These are workarounds for problems with Mod Organizer. Please make sure you read the help text before changing anything here. - - Decides the amount of data printed to "ModOrganizer.log" + + Diagnostics - - - Decides the amount of data printed to "ModOrganizer.log". - "Debug" produces very useful information for finding problems. There is usually no noteworthy performance impact but the file may become rather large. If this is a problem you may prefer the "Info" level for regluar use. On the "Error" level the log file usually remains empty. - + + Max Dumps To Keep - - Debug + + Maximum number of crash dumps to keep on disk. Use 0 for unlimited. - - Info (recommended) + + + Maximum number of crash dumps to keep on disk. Use 0 for unlimited. + Set "Crash Dumps" above to None to disable crash dump collection. + - - Warning + + Hint: right click link and copy link location - - Error + + + Logs and crash dumps are stored under your current instance in the <a href="LOGS_FULL_PATH">LOGS_DIR</a> + and <a href="DUMPS_FULL_PATH">DUMPS_DIR</a> folders. + Sending logs and/or crash dumps to the developers can help investigate issues. + It is recommended to compress large log and dmp files before sending. + - + Crash Dumps - + Decides which type of crash dumps are collected when injected processes crash. - + Decides which type of crash dumps are collected when injected processes crash. "None" Disables the generation of crash dumps by MO. @@ -6430,56 +6471,61 @@ programs you are intentionally running. - + None - + Mini (recommended) - + Data - + Full - - Max Dumps To Keep + + Log Level - - Maximum number of crash dumps to keep on disk. Use 0 for unlimited. + + Decides the amount of data printed to "ModOrganizer.log" - + - Maximum number of crash dumps to keep on disk. Use 0 for unlimited. - Set "Crash Dumps" above to None to disable crash dump collection. + Decides the amount of data printed to "ModOrganizer.log". + "Debug" produces very useful information for finding problems. There is usually no noteworthy performance impact but the file may become rather large. If this is a problem you may prefer the "Info" level for regluar use. On the "Error" level the log file usually remains empty. - - Hint: right click link and copy link location + + Debug - - - Logs and crash dumps are stored under your current instance in the <a href="LOGS_FULL_PATH">LOGS_DIR</a> - and <a href="DUMPS_FULL_PATH">DUMPS_DIR</a> folders. - Sending logs and/or crash dumps to the developers can help investigate issues. - It is recommended to compress large log and dmp files before sending. - + + Info (recommended) + + + + + Warning + + + + + Error diff --git a/src/organizercore.cpp b/src/organizercore.cpp index d21fa844..acce25dc 100644 --- a/src/organizercore.cpp +++ b/src/organizercore.cpp @@ -788,12 +788,12 @@ std::wstring OrganizerCore::crashDumpsPath() { bool OrganizerCore::getArchiveParsing() const { - return m_ArchiveParsing; + return m_ArchiveParsing; } void OrganizerCore::setArchiveParsing(const bool archiveParsing) { - m_ArchiveParsing = archiveParsing; + m_ArchiveParsing = archiveParsing; } void OrganizerCore::setCurrentProfile(const QString &profileName) @@ -1936,13 +1936,13 @@ std::vector OrganizerCore::enabledArchives() { std::vector result; if (m_ArchiveParsing) { - QFile archiveFile(m_CurrentProfile->getArchivesFileName()); - if (archiveFile.open(QIODevice::ReadOnly)) { - while (!archiveFile.atEnd()) { - result.push_back(QString::fromUtf8(archiveFile.readLine()).trimmed()); - } - archiveFile.close(); - } + QFile archiveFile(m_CurrentProfile->getArchivesFileName()); + if (archiveFile.open(QIODevice::ReadOnly)) { + while (!archiveFile.atEnd()) { + result.push_back(QString::fromUtf8(archiveFile.readLine()).trimmed()); + } + archiveFile.close(); + } } return result; } diff --git a/src/settings.cpp b/src/settings.cpp index eb5b372f..74c95ebf 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -476,7 +476,7 @@ uint Settings::getMotDHash() const bool Settings::archiveParsing() const { - return m_Settings.value("Settings/archive_parsing", true).toBool(); + return m_Settings.value("Settings/archive_parsing", true).toBool(); } QVariant Settings::pluginSetting(const QString &pluginName, const QString &key) const @@ -1126,7 +1126,7 @@ Settings::WorkaroundsTab::WorkaroundsTab(Settings *m_parent, m_displayForeignBox->setChecked(m_parent->displayForeign()); m_lockGUIBox->setChecked(m_parent->lockGUI()); m_enableArchiveParsingBox->setChecked(m_parent->archiveParsing()); - + m_dialog.setExecutableBlacklist(m_parent->executablesBlacklist()); } -- cgit v1.3.1 From 40a3e93c4698f31494df6483ff964a535342e177 Mon Sep 17 00:00:00 2001 From: LostDragonist Date: Mon, 24 Dec 2018 21:43:57 -0600 Subject: Add an option to disable endorsements --- src/mainwindow.cpp | 7 +++--- src/modinfodialog.cpp | 2 +- src/modinforegular.cpp | 5 +++- src/settings.cpp | 8 +++++++ src/settings.h | 6 +++++ src/settingsdialog.ui | 64 ++++++++++++++++++++++++++++++-------------------- 6 files changed, 61 insertions(+), 31 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 47fe4308..10b91c7c 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -4270,7 +4270,7 @@ void MainWindow::on_modList_customContextMenuRequested(const QPoint &pos) menu->addSeparator(); - if (info->getNexusID() > 0) { + if (info->getNexusID() > 0 && Settings::instance().endorsementIntegration()) { switch (info->endorsedState()) { case ModInfo::ENDORSED_TRUE: { menu->addAction(tr("Un-Endorse"), this, SLOT(unendorse_clicked())); @@ -5143,7 +5143,7 @@ void MainWindow::nxmUpdatesAvailable(const std::vector &modIDs, QVariant us if (game && result["id"].toInt() == game->nexusModOrganizerID() && result["game_id"].toInt() == game->nexusGameID()) { - if (!result["voted_by_user"].toBool()) { + if (!result["voted_by_user"].toBool() && Settings::instance().endorsementIntegration()) { ui->actionEndorseMO->setVisible(true); } } else { @@ -5167,7 +5167,8 @@ void MainWindow::nxmUpdatesAvailable(const std::vector &modIDs, QVariant us (*iter)->setNewestVersion(result["version"].toString()); (*iter)->setNexusDescription(result["description"].toString()); if (NexusInterface::instance(&m_PluginContainer)->getAccessManager()->loggedIn() && - result.contains("voted_by_user")) { + result.contains("voted_by_user") && + Settings::instance().endorsementIntegration()) { // don't use endorsement info if we're not logged in or if the response doesn't contain it (*iter)->setIsEndorsed(result["voted_by_user"].toBool()); } diff --git a/src/modinfodialog.cpp b/src/modinfodialog.cpp index 6d894237..c8e0fb9e 100644 --- a/src/modinfodialog.cpp +++ b/src/modinfodialog.cpp @@ -171,8 +171,8 @@ ModInfoDialog::ModInfoDialog(ModInfo::Ptr modInfo, const DirectoryEntry *directo ui->tabWidget->setTabEnabled(TAB_CONFLICTS, m_Origin != nullptr); - + ui->endorseBtn->setVisible(Settings::instance().endorsementIntegration()); ui->endorseBtn->setEnabled((m_ModInfo->endorsedState() == ModInfo::ENDORSED_FALSE) || (m_ModInfo->endorsedState() == ModInfo::ENDORSED_NEVER)); diff --git a/src/modinforegular.cpp b/src/modinforegular.cpp index 6a52d3df..548e3178 100644 --- a/src/modinforegular.cpp +++ b/src/modinforegular.cpp @@ -4,6 +4,7 @@ #include "messagedialog.h" #include "report.h" #include "scriptextender.h" +#include "settings.h" #include #include @@ -466,7 +467,9 @@ void ModInfoRegular::ignoreUpdate(bool ignore) std::vector ModInfoRegular::getFlags() const { std::vector result = ModInfoWithConflictInfo::getFlags(); - if ((m_NexusID > 0) && (endorsedState() == ENDORSED_FALSE)) { + if ((m_NexusID > 0) && + (endorsedState() == ENDORSED_FALSE) && + Settings::instance().endorsementIntegration()) { result.push_back(ModInfo::FLAG_NOTENDORSED); } if (!isValid() && !m_Validated) { diff --git a/src/settings.cpp b/src/settings.cpp index 18e893cb..42bf1357 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -459,6 +459,11 @@ bool Settings::useProxy() const return m_Settings.value("Settings/use_proxy", false).toBool(); } +bool Settings::endorsementIntegration() const +{ + return m_Settings.value("Settings/endorsement_integration", true).toBool(); +} + bool Settings::displayForeign() const { return m_Settings.value("Settings/display_foreign", true).toBool(); @@ -941,6 +946,7 @@ Settings::NexusTab::NexusTab(Settings *parent, SettingsDialog &dialog) , m_knownServersList(dialog.findChild("knownServersList")) , m_preferredServersList( dialog.findChild("preferredServersList")) + , m_endorsementBox(dialog.findChild("endorsementBox")) { if (parent->automaticLoginEnabled()) { m_loginCheckBox->setChecked(true); @@ -950,6 +956,7 @@ Settings::NexusTab::NexusTab(Settings *parent, SettingsDialog &dialog) m_offlineBox->setChecked(parent->offlineMode()); m_proxyBox->setChecked(parent->useProxy()); + m_endorsementBox->setChecked(parent->endorsementIntegration()); // display server preferences m_Settings.beginGroup("Servers"); @@ -991,6 +998,7 @@ void Settings::NexusTab::update() } m_Settings.setValue("Settings/offline_mode", m_offlineBox->isChecked()); m_Settings.setValue("Settings/use_proxy", m_proxyBox->isChecked()); + m_Settings.setValue("Settings/endorsement_integration", m_endorsementBox->isChecked()); // store server preference m_Settings.beginGroup("Servers"); diff --git a/src/settings.h b/src/settings.h index 912864e2..25f22911 100644 --- a/src/settings.h +++ b/src/settings.h @@ -270,6 +270,11 @@ public: */ bool useProxy() const; + /** + * @return true if endorsement integration is enabled + */ + bool endorsementIntegration() const; + /** * @return true if the user wants to see non-official plugins installed outside MO in his mod list */ @@ -470,6 +475,7 @@ private: QCheckBox *m_proxyBox; QListWidget *m_knownServersList; QListWidget *m_preferredServersList; + QCheckBox *m_endorsementBox; }; /** Display/store the configuration in the 'steam' tab of the settings dialogue */ diff --git a/src/settingsdialog.ui b/src/settingsdialog.ui index 0412fc10..d9fa92d8 100644 --- a/src/settingsdialog.ui +++ b/src/settingsdialog.ui @@ -537,30 +537,44 @@ p, li { white-space: pre-wrap; }
- - - Disable automatic internet features - - - Disable automatic internet features. This does not affect features that are explicitly invoked by the user (like checking mods for updates, endorsing, opening the web browser) - - - Offline Mode - - - - - - - Use a proxy for network connections. - - - Use a proxy for network connections. This uses the system-wide settings which can be configured in Internet Explorer. Please note that MO will start up a few seconds slower on some systems when using a proxy. - - - Use HTTP Proxy (Uses System Settings) - - + + + + + Disable automatic internet features + + + Disable automatic internet features. This does not affect features that are explicitly invoked by the user (like checking mods for updates, endorsing, opening the web browser) + + + Offline Mode + + + + + + + Use a proxy for network connections. + + + Use a proxy for network connections. This uses the system-wide settings which can be configured in Internet Explorer. Please note that MO will start up a few seconds slower on some systems when using a proxy. + + + Use HTTP Proxy (Uses System Settings) + + + + + + + Endorsement Integration + + + true + + + + @@ -1347,8 +1361,6 @@ programs you are intentionally running. usernameEdit passwordEdit clearCacheButton - offlineBox - proxyBox associateButton knownServersList preferredServersList -- cgit v1.3.1 From 580f45429fca07a4d3cd8daae83b6963ce5de54a Mon Sep 17 00:00:00 2001 From: LostDragonist Date: Sun, 30 Dec 2018 18:52:15 -0600 Subject: Fix conflict colors and make archive conflict colors configurable --- src/modlist.cpp | 29 +++++++++------- src/settings.cpp | 22 ++++++++++++ src/settings.h | 6 ++++ src/settingsdialog.cpp | 56 +++++++++++++++++------------- src/settingsdialog.h | 10 ++++++ src/settingsdialog.ui | 92 +++++++++++++++++++++++++++++--------------------- 6 files changed, 141 insertions(+), 74 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/modlist.cpp b/src/modlist.cpp index 0b66a663..44ca6eaf 100644 --- a/src/modlist.cpp +++ b/src/modlist.cpp @@ -411,21 +411,26 @@ QVariant ModList::data(const QModelIndex &modelIndex, int role) const bool archiveOverwritten = m_ArchiveOverwritten.find(modIndex) != m_ArchiveOverwritten.end(); bool archiveLooseOverwritten = m_ArchiveLooseOverwritten.find(modIndex) != m_ArchiveLooseOverwritten.end(); if (modInfo->getHighlight() & ModInfo::HIGHLIGHT_PLUGIN) { + return Settings::instance().modlistContainsPluginColor(); - } else if ((overwrite && (archiveOverwritten || archiveLooseOverwritten)) || - (overwritten && (archiveOverwrite || archiveLooseOverwrite)) || - (archiveOverwrite && (overwritten || archiveLooseOverwritten)) || - (archiveOverwritten && (overwrite || archiveLooseOverwrite)) || - (archiveLooseOverwrite && (overwritten || archiveOverwritten)) || - (archiveLooseOverwritten && (overwrite || archiveLooseOverwrite)) - ) { + + } else if (overwritten || archiveLooseOverwritten) { + return Settings::instance().modlistOverwrittenLooseColor(); - } - else if (overwrite || archiveOverwrite || archiveLooseOverwrite) { + + } else if (overwrite || archiveLooseOverwrite) { + return Settings::instance().modlistOverwritingLooseColor(); - } else if (overwritten || archiveOverwritten || archiveLooseOverwritten) { - return QColor(255, 0, 0, 64); //TODO: Make configurable - } else if (modInfo->hasFlag(ModInfo::FLAG_SEPARATOR) + + } else if (archiveOverwritten) { + + return Settings::instance().modlistOverwrittenArchiveColor(); + + } else if (archiveOverwrite) { + + return Settings::instance().modlistOverwritingArchiveColor(); + + } else if (modInfo->hasFlag(ModInfo::FLAG_SEPARATOR) && modInfo->getColor().isValid() && ((role != ViewMarkingScrollBar::DEFAULT_ROLE) || Settings::instance().colorSeparatorScrollbar())) { diff --git a/src/settings.cpp b/src/settings.cpp index 2bad749f..3202dffe 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -391,6 +391,16 @@ QColor Settings::modlistOverwritingLooseColor() const return m_Settings.value("Settings/overwritingLooseFilesColor", QColor(255, 0, 0, 64)).value(); } +QColor Settings::modlistOverwrittenArchiveColor() const +{ + return m_Settings.value("Settings/overwrittenArchiveFilesColor", QColor(0, 255, 255, 64)).value(); +} + +QColor Settings::modlistOverwritingArchiveColor() const +{ + return m_Settings.value("Settings/overwritingArchiveFilesColor", QColor(255, 0, 255, 64)).value(); +} + QColor Settings::modlistContainsPluginColor() const { return m_Settings.value("Settings/containsPluginColor", QColor(0, 0, 255, 64)).value(); @@ -729,6 +739,8 @@ Settings::GeneralTab::GeneralTab(Settings *m_parent, SettingsDialog &m_dialog) , m_usePrereleaseBox(m_dialog.findChild("usePrereleaseBox")) , m_overwritingBtn(m_dialog.findChild("overwritingBtn")) , m_overwrittenBtn(m_dialog.findChild("overwrittenBtn")) + , m_overwritingArchiveBtn(m_dialog.findChild("overwritingArchiveBtn")) + , m_overwrittenArchiveBtn(m_dialog.findChild("overwrittenArchiveBtn")) , m_containsBtn(m_dialog.findChild("containsBtn")) , m_containedBtn(m_dialog.findChild("containedBtn")) , m_colorSeparatorsBox(m_dialog.findChild("colorSeparatorsBox")) @@ -789,6 +801,12 @@ Settings::GeneralTab::GeneralTab(Settings *m_parent, SettingsDialog &m_dialog) m_overwrittenBtn->setStyleSheet(m_dialog.getColoredButtonStyleSheet().arg( m_parent->modlistOverwrittenLooseColor().name()).arg(getIdealTextColor( m_parent->modlistOverwrittenLooseColor()).name())); + m_overwritingArchiveBtn->setStyleSheet(m_dialog.getColoredButtonStyleSheet().arg( + m_parent->modlistOverwritingArchiveColor().name()).arg(getIdealTextColor( + m_parent->modlistOverwritingArchiveColor()).name())); + m_overwrittenArchiveBtn->setStyleSheet(m_dialog.getColoredButtonStyleSheet().arg( + m_parent->modlistOverwrittenArchiveColor().name()).arg(getIdealTextColor( + m_parent->modlistOverwrittenArchiveColor()).name())); m_containsBtn->setStyleSheet(m_dialog.getColoredButtonStyleSheet().arg( m_parent->modlistContainsPluginColor().name()).arg(getIdealTextColor( m_parent->modlistContainsPluginColor()).name())); @@ -798,6 +816,8 @@ Settings::GeneralTab::GeneralTab(Settings *m_parent, SettingsDialog &m_dialog) m_dialog.setOverwritingColor(m_parent->modlistOverwritingLooseColor()); m_dialog.setOverwrittenColor(m_parent->modlistOverwrittenLooseColor()); + m_dialog.setOverwritingArchiveColor(m_parent->modlistOverwritingArchiveColor()); + m_dialog.setOverwrittenArchiveColor(m_parent->modlistOverwrittenArchiveColor()); m_dialog.setContainsColor(m_parent->modlistContainsPluginColor()); m_dialog.setContainedColor(m_parent->pluginListContainedColor()); @@ -825,6 +845,8 @@ void Settings::GeneralTab::update() m_Settings.setValue("Settings/overwritingLooseFilesColor", m_dialog.getOverwritingColor()); m_Settings.setValue("Settings/overwrittenLooseFilesColor", m_dialog.getOverwrittenColor()); + m_Settings.setValue("Settings/overwritingArchiveFilesColor", m_dialog.getOverwritingArchiveColor()); + m_Settings.setValue("Settings/overwrittenArchiveFilesColor", m_dialog.getOverwrittenArchiveColor()); m_Settings.setValue("Settings/containsPluginColor", m_dialog.getContainsColor()); m_Settings.setValue("Settings/containedColor", m_dialog.getContainedColor()); m_Settings.setValue("Settings/compact_downloads", m_compactBox->isChecked()); diff --git a/src/settings.h b/src/settings.h index 4a932da7..f88f9652 100644 --- a/src/settings.h +++ b/src/settings.h @@ -233,6 +233,10 @@ public: QColor modlistOverwritingLooseColor() const; + QColor modlistOverwrittenArchiveColor() const; + + QColor modlistOverwritingArchiveColor() const; + QColor modlistContainsPluginColor() const; QColor pluginListContainedColor() const; @@ -428,6 +432,8 @@ private: QCheckBox *m_usePrereleaseBox; QPushButton *m_overwritingBtn; QPushButton *m_overwrittenBtn; + QPushButton *m_overwritingArchiveBtn; + QPushButton *m_overwrittenArchiveBtn; QPushButton *m_containsBtn; QPushButton *m_containedBtn; QCheckBox *m_colorSeparatorsBox; diff --git a/src/settingsdialog.cpp b/src/settingsdialog.cpp index 0d96e63a..75e08afd 100644 --- a/src/settingsdialog.cpp +++ b/src/settingsdialog.cpp @@ -239,12 +239,6 @@ void SettingsDialog::on_containsBtn_clicked() ui->containsBtn->setStyleSheet(getColoredButtonStyleSheet().arg( result.name()).arg(Settings::getIdealTextColor( result).name())); - - /*ui->containsBtn->setAutoFillBackground(true); - ui->containsBtn->setPalette(QPalette(result)); - QPalette palette = ui->containsBtn->palette(); - palette.setColor(QPalette::Background, result); - ui->containsBtn->setPalette(palette);*/ } } @@ -257,12 +251,6 @@ void SettingsDialog::on_containedBtn_clicked() ui->containedBtn->setStyleSheet(getColoredButtonStyleSheet().arg( result.name()).arg(Settings::getIdealTextColor( result).name())); - - /*ui->containedBtn->setAutoFillBackground(true); - ui->containedBtn->setPalette(QPalette(result)); - QPalette palette = ui->containedBtn->palette(); - palette.setColor(QPalette::Background, result); - ui->containedBtn->setPalette(palette);*/ } } @@ -275,12 +263,6 @@ void SettingsDialog::on_overwrittenBtn_clicked() ui->overwrittenBtn->setStyleSheet(getColoredButtonStyleSheet().arg( result.name()).arg(Settings::getIdealTextColor( result).name())); - - /*ui->overwrittenBtn->setAutoFillBackground(true); - ui->overwrittenBtn->setPalette(QPalette(result)); - QPalette palette = ui->overwrittenBtn->palette(); - palette.setColor(QPalette::Background, result); - ui->overwrittenBtn->setPalette(palette);*/ } } @@ -293,12 +275,30 @@ void SettingsDialog::on_overwritingBtn_clicked() ui->overwritingBtn->setStyleSheet(getColoredButtonStyleSheet().arg( result.name()).arg(Settings::getIdealTextColor( result).name())); + } +} + +void SettingsDialog::on_overwrittenArchiveBtn_clicked() +{ + QColor result = QColorDialog::getColor(m_OverwrittenArchiveColor, this); + if (result.isValid()) { + m_OverwrittenArchiveColor = result; + + ui->overwrittenArchiveBtn->setStyleSheet(getColoredButtonStyleSheet().arg( + result.name()).arg(Settings::getIdealTextColor( + result).name())); + } +} + +void SettingsDialog::on_overwritingArchiveBtn_clicked() +{ + QColor result = QColorDialog::getColor(m_OverwritingArchiveColor, this); + if (result.isValid()) { + m_OverwritingArchiveColor = result; - /*ui->overwritingBtn->setAutoFillBackground(true); - ui->overwritingBtn->setPalette(QPalette(result)); - QPalette palette = ui->overwritingBtn->palette(); - palette.setColor(QPalette::Background, result); - ui->overwritingBtn->setPalette(palette);*/ + ui->overwritingArchiveBtn->setStyleSheet(getColoredButtonStyleSheet().arg( + result.name()).arg(Settings::getIdealTextColor( + result).name())); } } @@ -306,6 +306,8 @@ void SettingsDialog::on_resetColorsBtn_clicked() { m_OverwritingColor = QColor(255, 0, 0, 64); m_OverwrittenColor = QColor(0, 255, 0, 64); + m_OverwritingArchiveColor = QColor(255, 0, 255, 64); + m_OverwrittenArchiveColor = QColor(0, 255, 255, 64); m_ContainsColor = QColor(0, 0, 255, 64); m_ContainedColor = QColor(0, 0, 255, 64); @@ -317,6 +319,14 @@ void SettingsDialog::on_resetColorsBtn_clicked() QColor(0, 255, 0, 64).name()).arg(Settings::getIdealTextColor( QColor(0, 255, 0, 64)).name())); + ui->overwritingArchiveBtn->setStyleSheet(getColoredButtonStyleSheet().arg( + QColor(255, 0, 255, 64).name()).arg(Settings::getIdealTextColor( + QColor(255, 0, 255, 64)).name())); + + ui->overwrittenArchiveBtn->setStyleSheet(getColoredButtonStyleSheet().arg( + QColor(0, 255, 255, 64).name()).arg(Settings::getIdealTextColor( + QColor(0, 255, 255, 64)).name())); + ui->containsBtn->setStyleSheet(getColoredButtonStyleSheet().arg( QColor(0, 0, 255, 64).name()).arg(Settings::getIdealTextColor( QColor(0, 0, 255, 64)).name())); diff --git a/src/settingsdialog.h b/src/settingsdialog.h index f0567d87..e3c7d413 100644 --- a/src/settingsdialog.h +++ b/src/settingsdialog.h @@ -67,6 +67,8 @@ public: QColor getOverwritingColor() { return m_OverwritingColor; } QColor getOverwrittenColor() { return m_OverwrittenColor; } + QColor getOverwritingArchiveColor() { return m_OverwritingArchiveColor; } + QColor getOverwrittenArchiveColor() { return m_OverwrittenArchiveColor; } QColor getContainsColor() { return m_ContainsColor; } QColor getContainedColor() { return m_ContainedColor; } QString getExecutableBlacklist() { return m_ExecutableBlacklist; } @@ -74,6 +76,8 @@ public: void setOverwritingColor(QColor col) { m_OverwritingColor = col; } void setOverwrittenColor(QColor col) { m_OverwrittenColor = col; } + void setOverwritingArchiveColor(QColor col) { m_OverwritingArchiveColor = col; } + void setOverwrittenArchiveColor(QColor col) { m_OverwrittenArchiveColor = col; } void setContainsColor(QColor col) { m_ContainsColor = col; } void setContainedColor(QColor col) { m_ContainedColor = col; } void setExecutableBlacklist(QString blacklist) { m_ExecutableBlacklist = blacklist; } @@ -116,6 +120,10 @@ private slots: void on_overwrittenBtn_clicked(); + void on_overwritingArchiveBtn_clicked(); + + void on_overwrittenArchiveBtn_clicked(); + void on_containsBtn_clicked(); void on_containedBtn_clicked(); @@ -140,6 +148,8 @@ private: QColor m_OverwritingColor; QColor m_OverwrittenColor; + QColor m_OverwritingArchiveColor; + QColor m_OverwrittenArchiveColor; QColor m_ContainsColor; QColor m_ContainedColor; diff --git a/src/settingsdialog.ui b/src/settingsdialog.ui index 832fa71a..58b2b48f 100644 --- a/src/settingsdialog.ui +++ b/src/settingsdialog.ui @@ -7,7 +7,7 @@ 0 0 586 - 462 + 486 @@ -99,10 +99,26 @@ If you use pre-releases, never contact me directly by e-mail or via private mess Colors + + + + When this is enabled, the color defined for a separator will be shown on the mod list scrollbar at the location of the separator. This can be useful for quick navigation between separator sections or to a specific separator section. + + + When this is enabled, the color defined for a separator will be shown on the mod list scrollbar at the location of the separator. This can be useful for quick navigation between separator sections or to a specific separator section. + + + Show mod list separator colors on the scrollbar + + + true + + + - + - Reset Colors + Plugin is Contained in selected Mod @@ -113,40 +129,38 @@ If you use pre-releases, never contact me directly by e-mail or via private mess - - + + - Mod Contains selected Plugin + Is overwriting (loose files) - - + + - Plugin is Contained in selected Mod + Reset Colors - - + + - Is overwriting (loose files) + Mod Contains selected Plugin - - - - When this is enabled, the color defined for a separator will be shown on the mod list scrollbar at the location of the separator. This can be useful for quick navigation between separator sections or to a specific separator section. - - - When this is enabled, the color defined for a separator will be shown on the mod list scrollbar at the location of the separator. This can be useful for quick navigation between separator sections or to a specific separator section. - + + - Show mod list separator colors on the scrollbar + Is overwritten (archive files) - - true + + + + + + Is overwriting (archive files) @@ -1114,27 +1128,27 @@ programs you are intentionally running. - - - - Enable parsing of Archives Archives, has effects on perfromance. - - - + + + + Enable parsing of Archives Archives, has effects on perfromance. + + + By default Mod Organizer will parse Archive files to calculate conflicts between themselves and loose files, this process has a noticeable cost in performance. This feature should not be confused from the one offered by ModOrganizer 1, ModOrganizer 2 will only show conflicts with archives NOT load them into the game or program. If you disable this feature, MO will only display conflicts with Loose files. - - - Enable parsing of Archives - - - true - - - + + + Enable parsing of Archives + + + true + + + -- cgit v1.3.1 From 4809c301324b5ebcdad4146325023f53d20d05d8 Mon Sep 17 00:00:00 2001 From: LostDragonist Date: Sun, 30 Dec 2018 20:19:23 -0600 Subject: Apply alpha color settings to the settings dialog --- src/settings.cpp | 23 ++++++-------- src/settingsdialog.cpp | 82 +++++++++++++++----------------------------------- src/settingsdialog.h | 2 ++ 3 files changed, 36 insertions(+), 71 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/settings.cpp b/src/settings.cpp index 42bf1357..8f768fd2 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -197,9 +197,12 @@ QString Settings::deObfuscate(const QString &password) return QString::fromUtf8(buffer.constData()); } -QColor Settings::getIdealTextColor(const QColor& rBackgroundColor) +QColor Settings::getIdealTextColor(const QColor& rBackgroundColor) { - const int THRESHOLD = 106; + if (rBackgroundColor.alpha() == 0) + return QColor(Qt::black); + + const int THRESHOLD = 106 * 255.0f / rBackgroundColor.alpha(); int BackgroundDelta = (rBackgroundColor.red() * 0.299) + (rBackgroundColor.green() * 0.587) + (rBackgroundColor.blue() * 0.114); return QColor((255 - BackgroundDelta <= THRESHOLD) ? Qt::black : Qt::white); } @@ -778,18 +781,10 @@ Settings::GeneralTab::GeneralTab(Settings *m_parent, SettingsDialog &m_dialog) */ //version with stylesheet - m_overwritingBtn->setStyleSheet(m_dialog.getColoredButtonStyleSheet().arg( - m_parent->modlistOverwritingLooseColor().name()).arg(getIdealTextColor( - m_parent->modlistOverwritingLooseColor()).name())); - m_overwrittenBtn->setStyleSheet(m_dialog.getColoredButtonStyleSheet().arg( - m_parent->modlistOverwrittenLooseColor().name()).arg(getIdealTextColor( - m_parent->modlistOverwrittenLooseColor()).name())); - m_containsBtn->setStyleSheet(m_dialog.getColoredButtonStyleSheet().arg( - m_parent->modlistContainsPluginColor().name()).arg(getIdealTextColor( - m_parent->modlistContainsPluginColor()).name())); - m_containedBtn->setStyleSheet(m_dialog.getColoredButtonStyleSheet().arg( - m_parent->pluginListContainedColor().name()).arg(getIdealTextColor( - m_parent->pluginListContainedColor()).name())); + m_dialog.setButtonColor(m_overwritingBtn, m_parent->modlistOverwritingLooseColor()); + m_dialog.setButtonColor(m_overwrittenBtn, m_parent->modlistOverwrittenLooseColor()); + m_dialog.setButtonColor(m_containsBtn, m_parent->modlistContainsPluginColor()); + m_dialog.setButtonColor(m_containedBtn, m_parent->pluginListContainedColor()); m_dialog.setOverwritingColor(m_parent->modlistOverwritingLooseColor()); m_dialog.setOverwrittenColor(m_parent->modlistOverwrittenLooseColor()); diff --git a/src/settingsdialog.cpp b/src/settingsdialog.cpp index beed5dba..b975fa75 100644 --- a/src/settingsdialog.cpp +++ b/src/settingsdialog.cpp @@ -42,7 +42,6 @@ along with Mod Organizer. If not, see . using namespace MOBase; - SettingsDialog::SettingsDialog(PluginContainer *pluginContainer, QWidget *parent) : TutorableDialog("SettingsDialog", parent) , ui(new Ui::SettingsDialog) @@ -71,6 +70,23 @@ QString SettingsDialog::getColoredButtonStyleSheet() const "}"); } +void SettingsDialog::setButtonColor(QPushButton *button, QColor &color) +{ + button->setStyleSheet( + QString("QPushButton {" + "background-color: rgba(%1, %2, %3, %4);" + "color: %5;" + "border: 1px solid;" + "padding: 3px;" + "}") + .arg(color.red()) + .arg(color.green()) + .arg(color.blue()) + .arg(color.alpha()) + .arg(Settings::getIdealTextColor(color).name()) + ); +}; + void SettingsDialog::accept() { QString newModPath = ui->modDirEdit->text(); @@ -235,16 +251,7 @@ void SettingsDialog::on_containsBtn_clicked() QColor result = QColorDialog::getColor(m_ContainsColor, this, "Color Picker: Mod contains selected plugin", QColorDialog::ShowAlphaChannel); if (result.isValid()) { m_ContainsColor = result; - - ui->containsBtn->setStyleSheet(getColoredButtonStyleSheet().arg( - result.name()).arg(Settings::getIdealTextColor( - result).name())); - - /*ui->containsBtn->setAutoFillBackground(true); - ui->containsBtn->setPalette(QPalette(result)); - QPalette palette = ui->containsBtn->palette(); - palette.setColor(QPalette::Background, result); - ui->containsBtn->setPalette(palette);*/ + setButtonColor(ui->containsBtn, result); } } @@ -253,16 +260,7 @@ void SettingsDialog::on_containedBtn_clicked() QColor result = QColorDialog::getColor(m_ContainedColor, this, "ColorPicker: Plugin is Contained in selected Mod", QColorDialog::ShowAlphaChannel); if (result.isValid()) { m_ContainedColor = result; - - ui->containedBtn->setStyleSheet(getColoredButtonStyleSheet().arg( - result.name()).arg(Settings::getIdealTextColor( - result).name())); - - /*ui->containedBtn->setAutoFillBackground(true); - ui->containedBtn->setPalette(QPalette(result)); - QPalette palette = ui->containedBtn->palette(); - palette.setColor(QPalette::Background, result); - ui->containedBtn->setPalette(palette);*/ + setButtonColor(ui->containedBtn, result); } } @@ -271,16 +269,7 @@ void SettingsDialog::on_overwrittenBtn_clicked() QColor result = QColorDialog::getColor(m_OverwrittenColor, this, "ColorPicker: Is overwritten", QColorDialog::ShowAlphaChannel); if (result.isValid()) { m_OverwrittenColor = result; - - ui->overwrittenBtn->setStyleSheet(getColoredButtonStyleSheet().arg( - result.name()).arg(Settings::getIdealTextColor( - result).name())); - - /*ui->overwrittenBtn->setAutoFillBackground(true); - ui->overwrittenBtn->setPalette(QPalette(result)); - QPalette palette = ui->overwrittenBtn->palette(); - palette.setColor(QPalette::Background, result); - ui->overwrittenBtn->setPalette(palette);*/ + setButtonColor(ui->overwrittenBtn, result); } } @@ -289,16 +278,7 @@ void SettingsDialog::on_overwritingBtn_clicked() QColor result = QColorDialog::getColor(m_OverwritingColor, this, "ColorPicker: Is overwriting", QColorDialog::ShowAlphaChannel); if (result.isValid()) { m_OverwritingColor = result; - - ui->overwritingBtn->setStyleSheet(getColoredButtonStyleSheet().arg( - result.name()).arg(Settings::getIdealTextColor( - result).name())); - - /*ui->overwritingBtn->setAutoFillBackground(true); - ui->overwritingBtn->setPalette(QPalette(result)); - QPalette palette = ui->overwritingBtn->palette(); - palette.setColor(QPalette::Background, result); - ui->overwritingBtn->setPalette(palette);*/ + setButtonColor(ui->overwritingBtn, result); } } @@ -309,22 +289,10 @@ void SettingsDialog::on_resetColorsBtn_clicked() m_ContainsColor = QColor(0, 0, 255, 64); m_ContainedColor = QColor(0, 0, 255, 64); - ui->overwritingBtn->setStyleSheet(getColoredButtonStyleSheet().arg( - QColor(255, 0, 0, 64).name()).arg(Settings::getIdealTextColor( - QColor(255, 0, 0, 64)).name())); - - ui->overwrittenBtn->setStyleSheet(getColoredButtonStyleSheet().arg( - QColor(0, 255, 0, 64).name()).arg(Settings::getIdealTextColor( - QColor(0, 255, 0, 64)).name())); - - ui->containsBtn->setStyleSheet(getColoredButtonStyleSheet().arg( - QColor(0, 0, 255, 64).name()).arg(Settings::getIdealTextColor( - QColor(0, 0, 255, 64)).name())); - - ui->containedBtn->setStyleSheet(getColoredButtonStyleSheet().arg( - QColor(0, 0, 255, 64).name()).arg(Settings::getIdealTextColor( - QColor(0, 0, 255, 64)).name())); - + setButtonColor(ui->overwritingBtn, m_OverwritingColor); + setButtonColor(ui->overwrittenBtn, m_OverwrittenColor); + setButtonColor(ui->containsBtn, m_ContainsColor); + setButtonColor(ui->containedBtn, m_ContainedColor); } void SettingsDialog::on_resetDialogsButton_clicked() diff --git a/src/settingsdialog.h b/src/settingsdialog.h index f0567d87..b005f928 100644 --- a/src/settingsdialog.h +++ b/src/settingsdialog.h @@ -50,6 +50,8 @@ public: */ QString getColoredButtonStyleSheet() const; + void setButtonColor(QPushButton *button, QColor &color); + public slots: virtual void accept(); -- cgit v1.3.1 From f2c145b2fc9d6ffce838398e06f7aa583d05887d Mon Sep 17 00:00:00 2001 From: LostDragonist Date: Sat, 5 Jan 2019 16:34:10 -0600 Subject: Change qPrintable to qUtf8Printable to better support non-ASCII text --- src/bbcode.cpp | 2 +- src/directoryrefresher.cpp | 2 +- src/downloadmanager.cpp | 18 +++++++++--------- src/editexecutablesdialog.cpp | 2 +- src/icondelegate.cpp | 2 +- src/installationmanager.cpp | 8 ++++---- src/instancemanager.cpp | 2 +- src/logbuffer.cpp | 14 +++++++------- src/main.cpp | 24 ++++++++++++------------ src/mainwindow.cpp | 20 ++++++++++---------- src/messagedialog.cpp | 2 +- src/moapplication.cpp | 2 +- src/modinforegular.cpp | 2 +- src/modlist.cpp | 2 +- src/nexusinterface.cpp | 8 ++++---- src/nxmaccessmanager.cpp | 6 +++--- src/organizercore.cpp | 24 ++++++++++++------------ src/persistentcookiejar.cpp | 6 +++--- src/plugincontainer.cpp | 14 +++++++------- src/pluginlist.cpp | 12 ++++++------ src/profile.cpp | 18 +++++++++--------- src/profilesdialog.cpp | 2 +- src/selfupdater.cpp | 10 +++++----- src/settings.cpp | 4 ++-- src/usvfsconnector.cpp | 2 +- 25 files changed, 104 insertions(+), 104 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/bbcode.cpp b/src/bbcode.cpp index 56369538..84d7a7c0 100644 --- a/src/bbcode.cpp +++ b/src/bbcode.cpp @@ -88,7 +88,7 @@ public: return temp.replace(tagIter->second.first, QString("%2").arg(color, content)); } } else { - qWarning("don't know how to deal with tag %s", qPrintable(tagName)); + qWarning("don't know how to deal with tag %s", qUtf8Printable(tagName)); } } else { if (tagName == "*") { diff --git a/src/directoryrefresher.cpp b/src/directoryrefresher.cpp index 272b0596..cc745cc8 100644 --- a/src/directoryrefresher.cpp +++ b/src/directoryrefresher.cpp @@ -117,7 +117,7 @@ void DirectoryRefresher::addModFilesToStructure(DirectoryEntry *directoryStructu origin.addFile(file->getIndex()); file->addOrigin(origin.getID(), file->getFileTime(), L""); } else { - qWarning("%s not found", qPrintable(fileInfo.fileName())); + qWarning("%s not found", qUtf8Printable(fileInfo.fileName())); } } } else { diff --git a/src/downloadmanager.cpp b/src/downloadmanager.cpp index b408f1a6..15831126 100644 --- a/src/downloadmanager.cpp +++ b/src/downloadmanager.cpp @@ -400,7 +400,7 @@ bool DownloadManager::addDownload(const QStringList &URLs, QString gameName, } QUrl preferredUrl = QUrl::fromEncoded(URLs.first().toLocal8Bit()); - qDebug("selected download url: %s", qPrintable(preferredUrl.toString())); + qDebug("selected download url: %s", qUtf8Printable(preferredUrl.toString())); QNetworkRequest request(preferredUrl); request.setHeader(QNetworkRequest::UserAgentHeader, m_NexusInterface->getAccessManager()->userAgent()); return addDownload(m_NexusInterface->getAccessManager()->get(request), URLs, fileName, gameName, modID, fileID, fileInfo); @@ -540,9 +540,9 @@ void DownloadManager::addNXMDownload(const QString &url) QStringList validGames; validGames.append(m_ManagedGame->gameShortName()); validGames.append(m_ManagedGame->validShortNames()); - qDebug("add nxm download: %s", qPrintable(url)); + qDebug("add nxm download: %s", qUtf8Printable(url)); if (!validGames.contains(nxmInfo.game(), Qt::CaseInsensitive)) { - qDebug("download requested for wrong game (game: %s, url: %s)", qPrintable(m_ManagedGame->gameShortName()), qPrintable(nxmInfo.game())); + qDebug("download requested for wrong game (game: %s, url: %s)", qUtf8Printable(m_ManagedGame->gameShortName()), qUtf8Printable(nxmInfo.game())); QMessageBox::information(nullptr, tr("Wrong Game"), tr("The download link is for a mod for \"%1\" but this instance of MO " "has been set up for \"%2\".").arg(nxmInfo.game()).arg(m_ManagedGame->gameShortName()), QMessageBox::Ok); return; @@ -550,7 +550,7 @@ void DownloadManager::addNXMDownload(const QString &url) for (auto tuple : m_PendingDownloads) { if (std::get<0>(tuple).compare(nxmInfo.game(), Qt::CaseInsensitive) == 0, std::get<1>(tuple) == nxmInfo.modId() && std::get<2>(tuple) == nxmInfo.fileId()) { - qDebug("download requested is already started (mod id: %s, file id: %s)", qPrintable(QString(nxmInfo.modId())), qPrintable(QString(nxmInfo.fileId()))); + qDebug("download requested is already started (mod id: %s, file id: %s)", qUtf8Printable(QString(nxmInfo.modId())), qUtf8Printable(QString(nxmInfo.fileId()))); QMessageBox::information(nullptr, tr("Already Started"), tr("A download for this mod file has already been queued."), QMessageBox::Ok); return; } @@ -559,8 +559,8 @@ void DownloadManager::addNXMDownload(const QString &url) for (DownloadInfo *download : m_ActiveDownloads) { if (download->m_FileInfo->modID == nxmInfo.modId() && download->m_FileInfo->fileID == nxmInfo.fileId()) { if (download->m_State == STATE_DOWNLOADING || download->m_State == STATE_PAUSED || download->m_State == STATE_STARTED) { - qDebug("download requested is already started (mod: %s, file: %s)", qPrintable(QString(download->m_FileInfo->modID)), - qPrintable(download->m_FileInfo->fileName)); + qDebug("download requested is already started (mod: %s, file: %s)", qUtf8Printable(QString(download->m_FileInfo->modID)), + qUtf8Printable(download->m_FileInfo->fileName)); QMessageBox::information(nullptr, tr("Already Started"), tr("There is already a download started for this file (mod: %1, file: %2).") .arg(download->m_FileInfo->modName).arg(download->m_FileInfo->fileName), QMessageBox::Ok); @@ -814,7 +814,7 @@ void DownloadManager::resumeDownloadInt(int index) if (info->m_State == STATE_ERROR) { info->m_CurrentUrl = (info->m_CurrentUrl + 1) % info->m_Urls.count(); } - qDebug("request resume from url %s", qPrintable(info->currentURL())); + qDebug("request resume from url %s", qUtf8Printable(info->currentURL())); QNetworkRequest request(QUrl::fromEncoded(info->currentURL().toLocal8Bit())); request.setHeader(QNetworkRequest::UserAgentHeader, m_NexusInterface->getAccessManager()->userAgent()); if (info->m_State != STATE_ERROR) { @@ -1434,7 +1434,7 @@ QDateTime DownloadManager::matchDate(const QString &timeString) if (m_DateExpression.exactMatch(timeString)) { return QDateTime::fromMSecsSinceEpoch(m_DateExpression.cap(1).toLongLong()); } else { - qWarning("date not matched: %s", qPrintable(timeString)); + qWarning("date not matched: %s", qUtf8Printable(timeString)); return QDateTime::currentDateTime(); } } @@ -1783,7 +1783,7 @@ void DownloadManager::downloadError(QNetworkReply::NetworkError error) { if (error != QNetworkReply::OperationCanceledError) { QNetworkReply *reply = qobject_cast(sender()); - qWarning("%s (%d)", reply != nullptr ? qPrintable(reply->errorString()) + qWarning("%s (%d)", reply != nullptr ? qUtf8Printable(reply->errorString()) : "Download error occured", error); } diff --git a/src/editexecutablesdialog.cpp b/src/editexecutablesdialog.cpp index fde6b397..be2ee127 100644 --- a/src/editexecutablesdialog.cpp +++ b/src/editexecutablesdialog.cpp @@ -324,7 +324,7 @@ void EditExecutablesDialog::on_executablesListBox_clicked(const QModelIndex &cur QString customOverwrite = m_Profile->setting("custom_overwrites", selectedExecutable.m_Title).toString(); if (!customOverwrite.isEmpty()) { index = ui->newFilesModBox->findText(customOverwrite); - qDebug("find %s -> %d", qPrintable(customOverwrite), index); + qDebug("find %s -> %d", qUtf8Printable(customOverwrite), index); } ui->newFilesModCheckBox->setChecked(index != -1); diff --git a/src/icondelegate.cpp b/src/icondelegate.cpp index e502dc69..249dae6f 100644 --- a/src/icondelegate.cpp +++ b/src/icondelegate.cpp @@ -54,7 +54,7 @@ void IconDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, if (!QPixmapCache::find(fullIconId, &icon)) { icon = QIcon(iconId).pixmap(iconWidth, iconWidth); if (icon.isNull()) { - qWarning("failed to load icon %s", qPrintable(iconId)); + qWarning("failed to load icon %s", qUtf8Printable(iconId)); } QPixmapCache::insert(fullIconId, icon); } diff --git a/src/installationmanager.cpp b/src/installationmanager.cpp index 76b1e086..57c5e861 100644 --- a/src/installationmanager.cpp +++ b/src/installationmanager.cpp @@ -758,7 +758,7 @@ bool InstallationManager::install(const QString &fileName, if (fileInfo.dir() == QDir(m_DownloadsDirectory)) { m_CurrentFile = fileInfo.fileName(); } - qDebug("using mod name \"%s\" (id %d) -> %s", modName->toUtf8().constData(), modID, qPrintable(m_CurrentFile)); + qDebug("using mod name \"%s\" (id %d) -> %s", modName->toUtf8().constData(), modID, qUtf8Printable(m_CurrentFile)); //If there's an archive already open, close it. This happens with the bundle //installer when it uncompresses a split archive, then finds it has a real archive @@ -770,8 +770,8 @@ bool InstallationManager::install(const QString &fileName, new MethodCallback(this, &InstallationManager::queryPassword)); if (!archiveOpen) { qDebug("integrated archiver can't open %s: %s (%d)", - qPrintable(fileName), - qPrintable(getErrorString(m_ArchiveHandler->getLastError())), + qUtf8Printable(fileName), + qUtf8Printable(getErrorString(m_ArchiveHandler->getLastError())), m_ArchiveHandler->getLastError()); } ON_BLOCK_EXIT(std::bind(&InstallationManager::postInstallCleanup, this)); @@ -841,7 +841,7 @@ bool InstallationManager::install(const QString &fileName, } } catch (const IncompatibilityException &e) { qCritical("plugin \"%s\" incompatible: %s", - qPrintable(installer->name()), e.what()); + qUtf8Printable(installer->name()), e.what()); } // act upon the installation result. at this point the files have already been diff --git a/src/instancemanager.cpp b/src/instancemanager.cpp index 9066741d..a5a52d63 100644 --- a/src/instancemanager.cpp +++ b/src/instancemanager.cpp @@ -86,7 +86,7 @@ bool InstanceManager::deleteLocalInstance(const QString &instanceId) const if (!MOBase::shellDelete(QStringList(instancePath),true)) { - qWarning("Failed to shell-delete \"%s\" (errorcode %lu), trying regular delete", qPrintable(instancePath), ::GetLastError()); + qWarning("Failed to shell-delete \"%s\" (errorcode %lu), trying regular delete", qUtf8Printable(instancePath), ::GetLastError()); if (!MOBase::removeDir(instancePath)) { qWarning("regular delete failed too"); diff --git a/src/logbuffer.cpp b/src/logbuffer.cpp index 522ce3c8..485e27db 100644 --- a/src/logbuffer.cpp +++ b/src/logbuffer.cpp @@ -127,7 +127,7 @@ void LogBuffer::log(QtMsgType type, const QMessageLogContext &context, { // QMutexLocker doesn't support timeout... if (!s_Mutex.tryLock(100)) { - fprintf(stderr, "failed to log: %s", qPrintable(message)); + fprintf(stderr, "failed to log: %s", qUtf8Printable(message)); return; } ON_BLOCK_EXIT([]() { s_Mutex.unlock(); }); @@ -137,17 +137,17 @@ void LogBuffer::log(QtMsgType type, const QMessageLogContext &context, } if (type == QtDebugMsg) { - fprintf(stdout, "%s [%c] %s\n", qPrintable(QTime::currentTime().toString()), - msgTypeID(type), qPrintable(message)); + fprintf(stdout, "%s [%c] %s\n", qUtf8Printable(QTime::currentTime().toString()), + msgTypeID(type), qUtf8Printable(message)); } else { if (context.line != 0) { fprintf(stdout, "%s [%c] (%s:%u) %s\n", - qPrintable(QTime::currentTime().toString()), msgTypeID(type), - context.file, context.line, qPrintable(message)); + qUtf8Printable(QTime::currentTime().toString()), msgTypeID(type), + context.file, context.line, qUtf8Printable(message)); } else { fprintf(stdout, "%s [%c] %s\n", - qPrintable(QTime::currentTime().toString()), msgTypeID(type), - qPrintable(message)); + qUtf8Printable(QTime::currentTime().toString()), msgTypeID(type), + qUtf8Printable(message)); } } fflush(stdout); diff --git a/src/main.cpp b/src/main.cpp index 4d2bb7ed..190a8f4b 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -262,7 +262,7 @@ QString determineProfile(QStringList &arguments, const QSettings &settings) qDebug("no configured profile"); selectedProfileName = "Default"; } else { - qDebug("configured profile: %s", qPrintable(selectedProfileName)); + qDebug("configured profile: %s", qUtf8Printable(selectedProfileName)); } return selectedProfileName; @@ -401,7 +401,7 @@ void setupPath() { static const int BUFSIZE = 4096; - qDebug("MO at: %s", qPrintable(QDir::toNativeSeparators( + qDebug("MO at: %s", qUtf8Printable(QDir::toNativeSeparators( QCoreApplication::applicationDirPath()))); QCoreApplication::setLibraryPaths(QStringList(QCoreApplication::applicationDirPath() + "/dlls") + QCoreApplication::libraryPaths()); @@ -429,18 +429,18 @@ static void preloadSsl() else { QString libeay32 = appPath + "\\libeay32.dll"; if (!QFile::exists(libeay32)) - qWarning("libeay32.dll not found: %s", qPrintable(libeay32)); + qWarning("libeay32.dll not found: %s", qUtf8Printable(libeay32)); else if (!LoadLibraryW(libeay32.toStdWString().c_str())) - qWarning("failed to load: %s, %d", qPrintable(libeay32), GetLastError()); + qWarning("failed to load: %s, %d", qUtf8Printable(libeay32), GetLastError()); } if (GetModuleHandleA("ssleay32.dll")) qWarning("ssleay32.dll already loaded?!"); else { QString ssleay32 = appPath + "\\ssleay32.dll"; if (!QFile::exists(ssleay32)) - qWarning("ssleay32.dll not found: %s", qPrintable(ssleay32)); + qWarning("ssleay32.dll not found: %s", qUtf8Printable(ssleay32)); else if (!LoadLibraryW(ssleay32.toStdWString().c_str())) - qWarning("failed to load: %s, %d", qPrintable(ssleay32), GetLastError()); + qWarning("failed to load: %s, %d", qUtf8Printable(ssleay32), GetLastError()); } } @@ -453,7 +453,7 @@ int runApplication(MOApplication &application, SingleInstance &instance, const QString &splashPath) { - qDebug("Starting Mod Organizer version %s revision %s", qPrintable(getVersionDisplayString()), + qDebug("Starting Mod Organizer version %s revision %s", qUtf8Printable(getVersionDisplayString()), #if defined(HGID) HGID #elif defined(GITID) @@ -471,7 +471,7 @@ int runApplication(MOApplication &application, SingleInstance &instance, #endif QString dataPath = application.property("dataPath").toString(); - qDebug("data path: %s", qPrintable(dataPath)); + qDebug("data path: %s", qUtf8Printable(dataPath)); if (!bootstrap()) { reportError("failed to set up data paths"); @@ -483,7 +483,7 @@ int runApplication(MOApplication &application, SingleInstance &instance, QStringList arguments = application.arguments(); try { - qDebug("Working directory: %s", qPrintable(QDir::toNativeSeparators(QDir::currentPath()))); + qDebug("Working directory: %s", qUtf8Printable(QDir::toNativeSeparators(QDir::currentPath()))); QSettings settings(dataPath + "/" + QString::fromStdWString(AppConfig::iniFileName()), @@ -552,7 +552,7 @@ int runApplication(MOApplication &application, SingleInstance &instance, } game->setGameVariant(settings.value("game_edition").toString()); - qDebug("managing game at %s", qPrintable(QDir::toNativeSeparators( + qDebug("managing game at %s", qUtf8Printable(QDir::toNativeSeparators( game->gameDirectory().absolutePath()))); organizer.updateExecutablesList(settings); @@ -578,12 +578,12 @@ int runApplication(MOApplication &application, SingleInstance &instance, } else if (OrganizerCore::isNxmLink(arguments.at(1))) { qDebug("starting download from command line: %s", - qPrintable(arguments.at(1))); + qUtf8Printable(arguments.at(1))); organizer.externalMessage(arguments.at(1)); } else { QString exeName = arguments.at(1); - qDebug("starting %s from command line", qPrintable(exeName)); + qDebug("starting %s from command line", qUtf8Printable(exeName)); arguments.removeFirst(); // remove application name (ModOrganizer.exe) arguments.removeFirst(); // remove binary name // pass the remaining parameters to the binary diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 83205ac4..ae37968c 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -1558,7 +1558,7 @@ void MainWindow::refreshSaveList() QDir savesDir = currentSavesDir(); savesDir.setNameFilters(filters); - qDebug("reading save games from %s", qPrintable(savesDir.absolutePath())); + qDebug("reading save games from %s", qUtf8Printable(savesDir.absolutePath())); QFileInfoList files = savesDir.entryInfoList(QDir::Files, QDir::Time); for (const QFileInfo &file : files) { @@ -1763,7 +1763,7 @@ void MainWindow::setupNetworkProxy(bool activate) query.setProtocolTag("http"); QList proxies = QNetworkProxyFactory::systemProxyForQuery(query); if ((proxies.size() > 0) && (proxies.at(0).type() != QNetworkProxy::NoProxy)) { - qDebug("Using proxy: %s", qPrintable(proxies.at(0).hostName())); + qDebug("Using proxy: %s", qUtf8Printable(proxies.at(0).hostName())); QNetworkProxy::setApplicationProxy(proxies[0]); } else { qDebug("Not using proxy"); @@ -2418,7 +2418,7 @@ void MainWindow::refreshFilters() while (currentID != 0) { categoriesUsed.insert(currentID); if (!cycleTest.insert(currentID).second) { - qWarning("cycle in categories: %s", qPrintable(SetJoin(cycleTest, ", "))); + qWarning("cycle in categories: %s", qUtf8Printable(SetJoin(cycleTest, ", "))); break; } currentID = m_CategoryFactory.getParentID(m_CategoryFactory.getCategoryIndex(currentID)); @@ -2732,7 +2732,7 @@ void MainWindow::unendorse_clicked() void MainWindow::loginFailed(const QString &error) { - qDebug("login failed: %s", qPrintable(error)); + qDebug("login failed: %s", qUtf8Printable(error)); statusBar()->hide(); } @@ -3711,7 +3711,7 @@ void MainWindow::addRemoveCategories_MenuHandler() { int maxRow = -1; for (const QPersistentModelIndex &idx : selected) { - qDebug("change categories on: %s", qPrintable(idx.data().toString())); + qDebug("change categories on: %s", qUtf8Printable(idx.data().toString())); QModelIndex modIdx = mapToModel(m_OrganizerCore.modList(), idx); if (modIdx.row() != m_ContextIdx.row()) { addRemoveCategoriesFromMenu(menu, modIdx.row(), m_ContextIdx.row()); @@ -3793,7 +3793,7 @@ void MainWindow::saveArchiveList() } } if (archiveFile.commitIfDifferent(m_ArchiveListHash)) { - qDebug("%s saved", qPrintable(QDir::toNativeSeparators(m_OrganizerCore.currentProfile()->getArchivesFileName()))); + qDebug("%s saved", qUtf8Printable(QDir::toNativeSeparators(m_OrganizerCore.currentProfile()->getArchivesFileName()))); } } else { qWarning("archive list not initialised"); @@ -4693,7 +4693,7 @@ void MainWindow::installTranslator(const QString &name) QString fileName = name + "_" + m_CurrentLanguage; if (!translator->load(fileName, qApp->applicationDirPath() + "/translations")) { if (m_CurrentLanguage.compare("en", Qt::CaseInsensitive)) { - qDebug("localization file %s not found", qPrintable(fileName)); + qDebug("localization file %s not found", qUtf8Printable(fileName)); } // we don't actually expect localization files for English } @@ -4718,7 +4718,7 @@ void MainWindow::languageChange(const QString &newLanguage) installTranslator(QFileInfo(fileName).baseName()); } ui->retranslateUi(this); - qDebug("loaded language %s", qPrintable(newLanguage)); + qDebug("loaded language %s", qUtf8Printable(newLanguage)); ui->profileBox->setItemText(0, QObject::tr("")); @@ -6134,7 +6134,7 @@ void MainWindow::dropLocalFile(const QUrl &url, const QString &outputDir, bool m { QFileInfo file(url.toLocalFile()); if (!file.exists()) { - qWarning("invalid source file %s", qPrintable(file.absoluteFilePath())); + qWarning("invalid source file %s", qUtf8Printable(file.absoluteFilePath())); return; } QString target = outputDir + "/" + file.fileName(); @@ -6167,7 +6167,7 @@ void MainWindow::dropLocalFile(const QUrl &url, const QString &outputDir, bool m success = shellCopy(file.absoluteFilePath(), target, true, this); } if (!success) { - qCritical("file operation failed: %s", qPrintable(windowsErrorString(::GetLastError()))); + qCritical("file operation failed: %s", qUtf8Printable(windowsErrorString(::GetLastError()))); } } diff --git a/src/messagedialog.cpp b/src/messagedialog.cpp index 90b0a9d3..6c6de3e7 100644 --- a/src/messagedialog.cpp +++ b/src/messagedialog.cpp @@ -81,7 +81,7 @@ void MessageDialog::resizeEvent(QResizeEvent *event) void MessageDialog::showMessage(const QString &text, QWidget *reference, bool bringToFront) { - qDebug("%s", qPrintable(text)); + qDebug("%s", qUtf8Printable(text)); if (reference != nullptr) { if (bringToFront || (qApp->activeWindow() != nullptr)) { MessageDialog *dialog = new MessageDialog(text, reference); diff --git a/src/moapplication.cpp b/src/moapplication.cpp index 9ddd9e54..3a791827 100644 --- a/src/moapplication.cpp +++ b/src/moapplication.cpp @@ -137,7 +137,7 @@ void MOApplication::updateStyle(const QString &fileName) if (QFile::exists(fileName)) { setStyleSheet(QString("file:///%1").arg(fileName)); } else { - qWarning("invalid stylesheet: %s", qPrintable(fileName)); + qWarning("invalid stylesheet: %s", qUtf8Printable(fileName)); } } } diff --git a/src/modinforegular.cpp b/src/modinforegular.cpp index 548e3178..45c3985b 100644 --- a/src/modinforegular.cpp +++ b/src/modinforegular.cpp @@ -302,7 +302,7 @@ bool ModInfoRegular::setName(const QString &name) } else { if (!shellRename(modDir.absoluteFilePath(m_Name), modDir.absoluteFilePath(name))) { qCritical("failed to rename mod %s (errorcode %d)", - qPrintable(name), ::GetLastError()); + qUtf8Printable(name), ::GetLastError()); return false; } } diff --git a/src/modlist.cpp b/src/modlist.cpp index 2cb74d50..c1954b39 100644 --- a/src/modlist.cpp +++ b/src/modlist.cpp @@ -960,7 +960,7 @@ bool ModList::dropURLs(const QMimeData *mimeData, int row, const QModelIndex &pa QString overwriteName = ModInfo::getByIndex(overwriteIndex)->name(); for (const QUrl &url : mimeData->urls()) { - qDebug("URL drop requested: %s", qPrintable(url.toLocalFile())); + qDebug("URL drop requested: %s", qUtf8Printable(url.toLocalFile())); if (!url.isLocalFile()) { qDebug("URL drop ignored: Not a local file."); continue; diff --git a/src/nexusinterface.cpp b/src/nexusinterface.cpp index e97e9800..c6f05405 100644 --- a/src/nexusinterface.cpp +++ b/src/nexusinterface.cpp @@ -226,7 +226,7 @@ void NexusInterface::interpretNexusFileName(const QString &fileName, QString &mo } else { modID = strtol(candidate.c_str(), nullptr, 10); } - qDebug("mod id guessed: %s -> %d", qPrintable(fileName), modID); + qDebug("mod id guessed: %s -> %d", qUtf8Printable(fileName), modID); } else if (std::regex_search(fileNameUTF8.constData(), result, simpleexp)) { qDebug("simple expression matched, using name only"); modName = QString::fromUtf8(result[1].str().c_str()); @@ -542,7 +542,7 @@ void NexusInterface::requestFinished(std::list::iterator iter) if (nexusError.length() == 0) { nexusError = tr("empty response"); } - qDebug("nexus error: %s", qPrintable(nexusError)); + qDebug("nexus error: %s", qUtf8Printable(nexusError)); emit nxmRequestFailed(iter->m_GameName, iter->m_ModID, iter->m_FileID, iter->m_UserData, iter->m_ID, nexusError); } else { bool ok; @@ -602,8 +602,8 @@ void NexusInterface::requestError(QNetworkReply::NetworkError) } qCritical("request (%s) error: %s (%d)", - qPrintable(reply->url().toString()), - qPrintable(reply->errorString()), + qUtf8Printable(reply->url().toString()), + qUtf8Printable(reply->errorString()), reply->error()); } diff --git a/src/nxmaccessmanager.cpp b/src/nxmaccessmanager.cpp index 426c8b9c..912eab30 100644 --- a/src/nxmaccessmanager.cpp +++ b/src/nxmaccessmanager.cpp @@ -106,7 +106,7 @@ void NXMAccessManager::showCookies() const for (const QNetworkCookie &cookie : cookieJar()->cookiesForUrl(url)) { qDebug("%s - %s (expires: %s)", cookie.name().constData(), cookie.value().constData(), - qPrintable(cookie.expirationDate().toString())); + qUtf8Printable(cookie.expirationDate().toString())); } } @@ -164,7 +164,7 @@ void NXMAccessManager::retrieveCredentials() connect(reply, static_cast(&QNetworkReply::error), [=] (QNetworkReply::NetworkError) { - qDebug("failed to retrieve account credentials: %s", qPrintable(reply->errorString())); + qDebug("failed to retrieve account credentials: %s", qUtf8Printable(reply->errorString())); reply->deleteLater(); }); } @@ -235,7 +235,7 @@ QString NXMAccessManager::userAgent(const QString &subModule) const void NXMAccessManager::pageLogin() { - qDebug("logging %s in on Nexus", qPrintable(m_Username)); + qDebug("logging %s in on Nexus", qUtf8Printable(m_Username)); QString requestString = (Nexus_Management_URL + "/Sessions/?Login&uri=%1") .arg(QString(QUrl::toPercentEncoding(Nexus_Management_URL))); diff --git a/src/organizercore.cpp b/src/organizercore.cpp index 9ebe9f47..c4029a6d 100644 --- a/src/organizercore.cpp +++ b/src/organizercore.cpp @@ -47,7 +47,7 @@ #include #include -#include // for qPrintable, etc +#include // for qUtf8Printable, etc #include #include @@ -89,8 +89,8 @@ static bool isOnline() continue; } qDebug("interface %s seems to be up (address: %s)", - qPrintable(iter->humanReadableName()), - qPrintable(addresses[0].ip().toString())); + qUtf8Printable(iter->humanReadableName()), + qUtf8Printable(addresses[0].ip().toString())); connected = true; } } @@ -640,7 +640,7 @@ bool OrganizerCore::nexusLogin(bool retry) if ((!retry && m_Settings.getNexusLogin(username, password)) || (m_AskForNexusPW && queryLogin(username, password))) { // credentials stored or user entered them manually - qDebug("attempt login with username %s", qPrintable(username)); + qDebug("attempt login with username %s", qUtf8Printable(username)); accessManager->login(username, password); return true; } else { @@ -681,7 +681,7 @@ void OrganizerCore::startMOUpdate() void OrganizerCore::downloadRequestedNXM(const QString &url) { - qDebug("download requested: %s", qPrintable(url)); + qDebug("download requested: %s", qUtf8Printable(url)); if (nexusLogin()) { m_PendingDownloads.append(url); } else { @@ -1116,7 +1116,7 @@ QStringList OrganizerCore::findFiles( } } } else { - qWarning("directory %s not found", qPrintable(path)); + qWarning("directory %s not found", qUtf8Printable(path)); } return result; } @@ -1135,7 +1135,7 @@ QStringList OrganizerCore::getFileOrigins(const QString &fileName) const ToQString(m_DirectoryStructure->getOriginByID(i.first).getName())); } } else { - qDebug("%s not found", qPrintable(fileName)); + qDebug("%s not found", qUtf8Printable(fileName)); } return result; } @@ -1402,7 +1402,7 @@ HANDLE OrganizerCore::spawnBinaryProcess(const QFileInfo &binary, } } else { qDebug("start of \"%s\" canceled by plugin", - qPrintable(binary.absoluteFilePath())); + qUtf8Printable(binary.absoluteFilePath())); return INVALID_HANDLE_VALUE; } } @@ -1781,7 +1781,7 @@ void OrganizerCore::updateModActiveState(int index, bool active) dir.entryList(QStringList() << "*.esm", QDir::Files)) { const FileEntry::Ptr file = m_DirectoryStructure->findFile(ToWString(esm)); if (file.get() == nullptr) { - qWarning("failed to activate %s", qPrintable(esm)); + qWarning("failed to activate %s", qUtf8Printable(esm)); continue; } @@ -1797,7 +1797,7 @@ void OrganizerCore::updateModActiveState(int index, bool active) dir.entryList(QStringList() << "*.esl", QDir::Files)) { const FileEntry::Ptr file = m_DirectoryStructure->findFile(ToWString(esl)); if (file.get() == nullptr) { - qWarning("failed to activate %s", qPrintable(esl)); + qWarning("failed to activate %s", qUtf8Printable(esl)); continue; } @@ -1813,7 +1813,7 @@ void OrganizerCore::updateModActiveState(int index, bool active) for (const QString &esp : esps) { const FileEntry::Ptr file = m_DirectoryStructure->findFile(ToWString(esp)); if (file.get() == nullptr) { - qWarning("failed to activate %s", qPrintable(esp)); + qWarning("failed to activate %s", qUtf8Printable(esp)); continue; } @@ -2140,7 +2140,7 @@ std::vector OrganizerCore::activeProblems() const // of a "log spam". But since this is a sevre error which will most likely make the // game crash/freeze/etc. and is very hard to diagnose, this "log spam" will make it // easier for the user to notice the warning. - qWarning("hook.dll found in game folder: %s", qPrintable(hookdll)); + qWarning("hook.dll found in game folder: %s", qUtf8Printable(hookdll)); problems.push_back(PROBLEM_MO1SCRIPTEXTENDERWORKAROUND); } return problems; diff --git a/src/persistentcookiejar.cpp b/src/persistentcookiejar.cpp index a6eb78fa..1ed463c6 100644 --- a/src/persistentcookiejar.cpp +++ b/src/persistentcookiejar.cpp @@ -11,7 +11,7 @@ PersistentCookieJar::PersistentCookieJar(const QString &fileName, QObject *paren } PersistentCookieJar::~PersistentCookieJar() { - qDebug("save %s", qPrintable(m_FileName)); + qDebug("save %s", qUtf8Printable(m_FileName)); save(); } @@ -40,14 +40,14 @@ void PersistentCookieJar::save() { QFile oldCookies(m_FileName); if (oldCookies.exists()) { if (!oldCookies.remove()) { - qCritical("failed to save cookies: failed to remove %s", qPrintable(m_FileName)); + qCritical("failed to save cookies: failed to remove %s", qUtf8Printable(m_FileName)); return; } } // if it doesn't exists that's fine } if (!file.copy(m_FileName)) { - qCritical("failed to save cookies: failed to write %s", qPrintable(m_FileName)); + qCritical("failed to save cookies: failed to write %s", qUtf8Printable(m_FileName)); } } diff --git a/src/plugincontainer.cpp b/src/plugincontainer.cpp index 8935c472..46a95f0c 100644 --- a/src/plugincontainer.cpp +++ b/src/plugincontainer.cpp @@ -160,12 +160,12 @@ bool PluginContainer::registerPlugin(QObject *plugin, const QString &fileName) for (QObject *proxiedPlugin : matchingPlugins) { if (proxiedPlugin != nullptr) { if (registerPlugin(proxiedPlugin, pluginName)) { - qDebug("loaded plugin \"%s\"", qPrintable(QFileInfo(pluginName).fileName())); + qDebug("loaded plugin \"%s\"", qUtf8Printable(QFileInfo(pluginName).fileName())); } else { qWarning("plugin \"%s\" failed to load. If this plugin is for an older version of MO " "you have to update it or delete it if no update exists.", - qPrintable(pluginName)); + qUtf8Printable(pluginName)); } } } @@ -220,7 +220,7 @@ void PluginContainer::unloadPlugins() QPluginLoader *loader = m_PluginLoaders.back(); m_PluginLoaders.pop_back(); if ((loader != nullptr) && !loader->unload()) { - qDebug("failed to unload %s: %s", qPrintable(loader->fileName()), qPrintable(loader->errorString())); + qDebug("failed to unload %s: %s", qUtf8Printable(loader->fileName()), qUtf8Printable(loader->errorString())); } delete loader; } @@ -275,7 +275,7 @@ void PluginContainer::loadPlugins() while (iter.hasNext()) { iter.next(); if (m_Organizer->settings().pluginBlacklisted(iter.fileName())) { - qDebug("plugin \"%s\" blacklisted", qPrintable(iter.fileName())); + qDebug("plugin \"%s\" blacklisted", qUtf8Printable(iter.fileName())); continue; } loadCheck.write(iter.fileName().toUtf8()); @@ -287,14 +287,14 @@ void PluginContainer::loadPlugins() if (pluginLoader->instance() == nullptr) { m_FailedPlugins.push_back(pluginName); qCritical("failed to load plugin %s: %s", - qPrintable(pluginName), qPrintable(pluginLoader->errorString())); + qUtf8Printable(pluginName), qUtf8Printable(pluginLoader->errorString())); } else { if (registerPlugin(pluginLoader->instance(), pluginName)) { - qDebug("loaded plugin \"%s\"", qPrintable(QFileInfo(pluginName).fileName())); + qDebug("loaded plugin \"%s\"", qUtf8Printable(QFileInfo(pluginName).fileName())); m_PluginLoaders.push_back(pluginLoader.release()); } else { m_FailedPlugins.push_back(pluginName); - qWarning("plugin \"%s\" failed to load (may be outdated)", qPrintable(pluginName)); + qWarning("plugin \"%s\" failed to load (may be outdated)", qUtf8Printable(pluginName)); } } } diff --git a/src/pluginlist.cpp b/src/pluginlist.cpp index 5171bf19..6f417331 100644 --- a/src/pluginlist.cpp +++ b/src/pluginlist.cpp @@ -182,7 +182,7 @@ void PluginList::refresh(const QString &profileName ba2Reg.setPatternSyntax(QRegExp::Wildcard); ba2Reg.setCaseSensitivity(Qt::CaseInsensitive); - //TODO: try QRegularExpression when we move to Qt5.12 + //TODO: try QRegularExpression when we move to Qt5.12 /*QRegularExpression bsaReg = QRegularExpression(); QRegularExpression ba2Reg = QRegularExpression(); bsaReg.setPatternOptions(QRegularExpression::CaseInsensitiveOption); @@ -435,7 +435,7 @@ void PluginList::addInformation(const QString &name, const QString &message) if (iter != m_ESPsByName.end()) { m_AdditionalInfo[name.toLower()].m_Messages.append(message); } else { - qWarning("failed to associate message for \"%s\"", qPrintable(name)); + qWarning("failed to associate message for \"%s\"", qUtf8Printable(name)); } } @@ -499,7 +499,7 @@ void PluginList::writeLockedOrder(const QString &fileName) const file->write(QString("%1|%2\r\n").arg(iter->first).arg(iter->second).toUtf8()); } file.commit(); - qDebug("%s saved", QDir::toNativeSeparators(fileName).toUtf8().constData()); + qDebug("%s saved", qUtf8Printable(QDir::toNativeSeparators(fileName))); } @@ -524,7 +524,7 @@ void PluginList::saveTo(const QString &lockedOrderFileName } } if (deleterFile.commitIfDifferent(m_LastSaveHash[deleterFileName])) { - qDebug("%s saved", qPrintable(QDir::toNativeSeparators(deleterFileName))); + qDebug("%s saved", qUtf8Printable(QDir::toNativeSeparators(deleterFileName))); } } else if (QFile::exists(deleterFileName)) { shellDelete(QStringList() << deleterFileName); @@ -712,7 +712,7 @@ void PluginList::setState(const QString &name, PluginStates state) { m_ESPs[iter->second].m_Enabled = (state == IPluginList::STATE_ACTIVE) || m_ESPs[iter->second].m_ForceEnabled; } else { - qWarning("plugin %s not found", qPrintable(name)); + qWarning("plugin %s not found", qUtf8Printable(name)); } } @@ -1386,7 +1386,7 @@ PluginList::ESPInfo::ESPInfo(const QString &name, bool enabled, m_Masters.insert(QString(iter->c_str())); } } catch (const std::exception &e) { - qCritical("failed to parse plugin file %s: %s", qPrintable(fullPath), e.what()); + qCritical("failed to parse plugin file %s: %s", qUtf8Printable(fullPath), e.what()); m_IsMaster = false; m_IsLight = false; m_IsLightFlagged = false; diff --git a/src/profile.cpp b/src/profile.cpp index 9da1a698..e8ead8e8 100644 --- a/src/profile.cpp +++ b/src/profile.cpp @@ -40,7 +40,7 @@ along with Mod Organizer. If not, see . #include #include // for QStringList #include // for qDebug, qWarning, etc -#include // for qPrintable +#include // for qUtf8Printable #include #include @@ -124,7 +124,7 @@ Profile::Profile(const QDir &directory, IPluginGame const *gamePlugin) findProfileSettings(); if (!QFile::exists(m_Directory.filePath("modlist.txt"))) { - qWarning("missing modlist.txt in %s", qPrintable(directory.path())); + qWarning("missing modlist.txt in %s", qUtf8Printable(directory.path())); touchFile(m_Directory.filePath("modlist.txt")); } @@ -252,7 +252,7 @@ void Profile::doWriteModlist() } if (file.commitIfDifferent(m_LastModlistHash)) { - qDebug("%s saved", QDir::toNativeSeparators(fileName).toUtf8().constData()); + qDebug("%s saved", qUtf8Printable(QDir::toNativeSeparators(fileName))); } } catch (const std::exception &e) { reportError(tr("failed to write mod list: %1").arg(e.what())); @@ -288,7 +288,7 @@ void Profile::createTweakedIniFile() if (error) { reportError(tr("failed to create tweaked ini: %1").arg(getCurrentErrorString().c_str())); } - qDebug("%s saved", qPrintable(QDir::toNativeSeparators(tweakedIni))); + qDebug("%s saved", qUtf8Printable(QDir::toNativeSeparators(tweakedIni))); } // static @@ -303,7 +303,7 @@ void Profile::renameModInAllProfiles(const QString& oldName, const QString& newN if (modList.exists()) renameModInList(modList, oldName, newName); else - qWarning("Profile has no modlist.txt : %s", qPrintable(profileIter.filePath())); + qWarning("Profile has no modlist.txt : %s", qUtf8Printable(profileIter.filePath())); } } @@ -361,7 +361,7 @@ void Profile::renameModInList(QFile &modList, const QString &oldName, const QStr if (renamed) qDebug("Renamed %d \"%s\" mod to \"%s\" in %s", - renamed, qPrintable(oldName), qPrintable(newName), qPrintable(modList.fileName())); + renamed, qUtf8Printable(oldName), qUtf8Printable(newName), qUtf8Printable(modList.fileName())); } void Profile::refreshModStatus() @@ -421,13 +421,13 @@ void Profile::refreshModStatus() } } else { qWarning("no mod state for \"%s\" (profile \"%s\")", - qPrintable(modName), m_Directory.path().toUtf8().constData()); + qUtf8Printable(modName), m_Directory.path().toUtf8().constData()); // need to rewrite the modlist to fix this modStatusModified = true; } } else { qDebug("mod \"%s\" (profile \"%s\") not found", - qPrintable(modName), m_Directory.path().toUtf8().constData()); + qUtf8Printable(modName), m_Directory.path().toUtf8().constData()); // need to rewrite the modlist to fix this modStatusModified = true; } @@ -775,7 +775,7 @@ bool Profile::localSettingsEnabled() const QStringList missingFiles; for (QString file : m_GamePlugin->iniFiles()) { if (!QFile::exists(m_Directory.filePath(file))) { - qWarning("missing %s in %s", qPrintable(file), qPrintable(m_Directory.path())); + qWarning("missing %s in %s", qUtf8Printable(file), qUtf8Printable(m_Directory.path())); missingFiles << file; } } diff --git a/src/profilesdialog.cpp b/src/profilesdialog.cpp index 17844357..f9ea655f 100644 --- a/src/profilesdialog.cpp +++ b/src/profilesdialog.cpp @@ -214,7 +214,7 @@ void ProfilesDialog::on_removeProfileButton_clicked() delete item; } if (!shellDelete(QStringList(profilePath))) { - qWarning("Failed to shell-delete \"%s\" (errorcode %lu), trying regular delete", qPrintable(profilePath), ::GetLastError()); + qWarning("Failed to shell-delete \"%s\" (errorcode %lu), trying regular delete", qUtf8Printable(profilePath), ::GetLastError()); if (!removeDir(profilePath)) { qWarning("regular delete failed too"); } diff --git a/src/selfupdater.cpp b/src/selfupdater.cpp index d26ca96c..cdcbc2f4 100644 --- a/src/selfupdater.cpp +++ b/src/selfupdater.cpp @@ -145,15 +145,15 @@ void SelfUpdater::testForUpdate() if (newestVer > this->m_MOVersion) { m_UpdateCandidate = newest; qDebug("update available: %s -> %s", - qPrintable(this->m_MOVersion.displayString()), - qPrintable(newestVer.displayString())); + qUtf8Printable(this->m_MOVersion.displayString()), + qUtf8Printable(newestVer.displayString())); emit updateAvailable(); } else if (newestVer < this->m_MOVersion) { // this could happen if the user switches from using prereleases to // stable builds. Should we downgrade? qDebug("this version is newer than the newest installed one: %s -> %s", - qPrintable(this->m_MOVersion.displayString()), - qPrintable(newestVer.displayString())); + qUtf8Printable(this->m_MOVersion.displayString()), + qUtf8Printable(newestVer.displayString())); } } }); @@ -224,7 +224,7 @@ void SelfUpdater::closeProgress() void SelfUpdater::openOutputFile(const QString &fileName) { QString outputPath = QDir::fromNativeSeparators(qApp->property("dataPath").toString()) + "/" + fileName; - qDebug("downloading to %s", qPrintable(outputPath)); + qDebug("downloading to %s", qUtf8Printable(outputPath)); m_UpdateFile.setFileName(outputPath); m_UpdateFile.open(QIODevice::WriteOnly); } diff --git a/src/settings.cpp b/src/settings.cpp index 8f768fd2..5cfe427b 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -167,7 +167,7 @@ void Settings::registerPlugin(IPlugin *plugin) QVariant temp = m_Settings.value("Plugins/" + plugin->name() + "/" + setting.key, setting.defaultValue); if (!temp.convert(setting.defaultValue.type())) { qWarning("failed to interpret \"%s\" as correct type for \"%s\" in plugin \"%s\", using default", - qPrintable(temp.toString()), qPrintable(setting.key), qPrintable(plugin->name())); + qUtf8Printable(temp.toString()), qUtf8Printable(setting.key), qUtf8Printable(plugin->name())); temp = setting.defaultValue; } m_PluginSettings[plugin->name()][setting.key] = temp; @@ -574,7 +574,7 @@ void Settings::updateServers(const QList &servers) QVariantMap val = m_Settings.value(key).toMap(); QDate lastSeen = val["lastSeen"].toDate(); if (lastSeen.daysTo(now) > 30) { - qDebug("removing server %s since it hasn't been available for downloads in over a month", qPrintable(key)); + qDebug("removing server %s since it hasn't been available for downloads in over a month", qUtf8Printable(key)); m_Settings.remove(key); } } diff --git a/src/usvfsconnector.cpp b/src/usvfsconnector.cpp index 9c81d0d9..ef7314c0 100644 --- a/src/usvfsconnector.cpp +++ b/src/usvfsconnector.cpp @@ -61,7 +61,7 @@ LogWorker::LogWorker() { m_LogFile.open(QIODevice::WriteOnly); qDebug("usvfs log messages are written to %s", - qPrintable(m_LogFile.fileName())); + qUtf8Printable(m_LogFile.fileName())); } LogWorker::~LogWorker() -- cgit v1.3.1 From 347ac2b8b5f34a2583ae7844e0dfd79773657270 Mon Sep 17 00:00:00 2001 From: LostDragonist Date: Fri, 11 Jan 2019 01:39:05 -0600 Subject: Support for force loading libraries --- src/CMakeLists.txt | 6 + src/aboutdialog.ui | 8 +- src/editexecutablesdialog.cpp | 47 ++- src/editexecutablesdialog.h | 6 + src/editexecutablesdialog.ui | 37 ++ src/forcedloaddialog.cpp | 76 ++++ src/forcedloaddialog.h | 32 ++ src/forcedloaddialog.ui | 117 ++++++ src/forcedloaddialogwidget.cpp | 87 ++++ src/forcedloaddialogwidget.h | 38 ++ src/forcedloaddialogwidget.ui | 104 +++++ src/mainwindow.cpp | 21 +- src/organizer.pro | 12 +- src/organizer_en.ts | 893 +++++++++++++++++++++++------------------ src/organizercore.cpp | 34 +- src/organizercore.h | 8 +- src/profile.cpp | 118 +++++- src/profile.h | 13 + src/settings.cpp | 4 +- src/settings.h | 4 +- src/settingsdialog.cpp | 6 +- src/usvfsconnector.cpp | 18 +- src/usvfsconnector.h | 3 + 23 files changed, 1260 insertions(+), 432 deletions(-) create mode 100644 src/forcedloaddialog.cpp create mode 100644 src/forcedloaddialog.h create mode 100644 src/forcedloaddialog.ui create mode 100644 src/forcedloaddialogwidget.cpp create mode 100644 src/forcedloaddialogwidget.h create mode 100644 src/forcedloaddialogwidget.ui (limited to 'src/settings.cpp') diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 4c883cf5..5cbd5aa9 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -92,6 +92,8 @@ SET(organizer_SRCS moshortcut.cpp listdialog.cpp lcdnumber.cpp + forcedloaddialog.cpp + forcedloaddialogwidget.cpp shared/windows_error.cpp shared/error_report.cpp @@ -187,6 +189,8 @@ SET(organizer_HDRS moshortcut.h listdialog.h lcdnumber.h + forcedloaddialog.h + forcedloaddialogwidget.h shared/windows_error.h shared/error_report.h @@ -226,6 +230,8 @@ SET(organizer_UIS browserdialog.ui aboutdialog.ui listdialog.ui + forcedloaddialog.ui + forcedloaddialogwidget.ui ) SET(organizer_QRCS diff --git a/src/aboutdialog.ui b/src/aboutdialog.ui index 98a76061..ac7db1fc 100644 --- a/src/aboutdialog.ui +++ b/src/aboutdialog.ui @@ -161,7 +161,7 @@ - + QAbstractItemView::NoSelection @@ -202,7 +202,7 @@ - + QAbstractItemView::NoSelection @@ -231,7 +231,7 @@ Translators - + @@ -363,7 +363,7 @@ Other Supporters && Contributors - + diff --git a/src/editexecutablesdialog.cpp b/src/editexecutablesdialog.cpp index be2ee127..212993f1 100644 --- a/src/editexecutablesdialog.cpp +++ b/src/editexecutablesdialog.cpp @@ -25,7 +25,8 @@ along with Mod Organizer. If not, see . #include #include #include - +#include "forcedloaddialog.h" +#include using namespace MOBase; using namespace MOShared; @@ -44,6 +45,8 @@ EditExecutablesDialog::EditExecutablesDialog( refreshExecutablesWidget(); ui->newFilesModBox->addItems(modList.allMods()); + + m_ForcedLibraries = m_Profile->determineForcedLibraries(ui->titleEdit->text()); } EditExecutablesDialog::~EditExecutablesDialog() @@ -93,6 +96,7 @@ void EditExecutablesDialog::resetInput() ui->overwriteAppIDBox->setChecked(false); ui->useAppIconCheckBox->setChecked(false); ui->newFilesModCheckBox->setChecked(false); + ui->forceLoadCheckBox->setChecked(false); m_CurrentItem = nullptr; } @@ -118,6 +122,9 @@ void EditExecutablesDialog::saveExecutable() else { m_Profile->removeSetting("custom_overwrites", ui->titleEdit->text()); } + + m_Profile->saveForcedLibraries(ui->titleEdit->text(), m_ForcedLibraries); + m_Profile->setForcedLibrariesEnabled(ui->titleEdit->text(), ui->forceLoadCheckBox->isChecked()); } @@ -130,6 +137,21 @@ void EditExecutablesDialog::delayedRefresh() } +void EditExecutablesDialog::on_forceLoadButton_clicked() +{ + ForcedLoadDialog dialog(this); + dialog.setValues(m_ForcedLibraries); + if (dialog.exec() == QDialog::Accepted) { + m_ForcedLibraries = dialog.values(); + } +} + +void EditExecutablesDialog::on_forceLoadCheckBox_toggled() +{ + ui->forceLoadButton->setEnabled(ui->forceLoadCheckBox->isChecked()); +} + + void EditExecutablesDialog::on_addButton_clicked() { if (executableChanged()) { @@ -231,6 +253,20 @@ bool EditExecutablesDialog::executableChanged() QString storedCustomOverwrite = m_Profile->setting("custom_overwrites", selectedExecutable.m_Title).toString(); + bool forcedLibrariesDirty = false; + auto forcedLibaries = m_Profile->determineForcedLibraries(selectedExecutable.m_Title); + forcedLibrariesDirty |= !std::equal(forcedLibaries.begin(), forcedLibaries.end(), + m_ForcedLibraries.begin(), m_ForcedLibraries.end(), + [](const ExecutableForcedLoadSetting &lhs, const ExecutableForcedLoadSetting &rhs) + { + return lhs.enabled() == rhs.enabled() && + lhs.forced() == rhs.forced() && + lhs.library() == rhs.library() && + lhs.process() == rhs.process(); + }); + forcedLibrariesDirty |= m_Profile->setting("forced_libraries", ui->titleEdit->text() + "/enabled", false).toBool() != + ui->forceLoadCheckBox->isChecked(); + return selectedExecutable.m_Title != ui->titleEdit->text() || selectedExecutable.m_Arguments != ui->argumentsEdit->text() || selectedExecutable.m_SteamAppID != ui->appIDOverwriteEdit->text() @@ -238,7 +274,9 @@ bool EditExecutablesDialog::executableChanged() || !storedCustomOverwrite.isEmpty() && (storedCustomOverwrite != ui->newFilesModBox->currentText()) || selectedExecutable.m_WorkingDirectory != QDir::fromNativeSeparators(ui->workingDirEdit->text()) || selectedExecutable.m_BinaryInfo.absoluteFilePath() != QDir::fromNativeSeparators(ui->binaryEdit->text()) - || selectedExecutable.usesOwnIcon() != ui->useAppIconCheckBox->isChecked(); + || selectedExecutable.usesOwnIcon() != ui->useAppIconCheckBox->isChecked() + || forcedLibrariesDirty + ; } else { QFileInfo fileInfo(ui->binaryEdit->text()); return !ui->binaryEdit->text().isEmpty() @@ -331,6 +369,11 @@ void EditExecutablesDialog::on_executablesListBox_clicked(const QModelIndex &cur if (index != -1) { ui->newFilesModBox->setCurrentIndex(index); } + + m_ForcedLibraries = m_Profile->determineForcedLibraries(ui->titleEdit->text()); + bool forcedLibraries = m_Profile->forcedLibrariesEnabled(ui->titleEdit->text()); + ui->forceLoadButton->setEnabled(forcedLibraries); + ui->forceLoadCheckBox->setChecked(forcedLibraries); } } diff --git a/src/editexecutablesdialog.h b/src/editexecutablesdialog.h index 0f3dbaff..82e63e15 100644 --- a/src/editexecutablesdialog.h +++ b/src/editexecutablesdialog.h @@ -92,6 +92,10 @@ private slots: void on_executablesListBox_clicked(const QModelIndex &index); + void on_forceLoadButton_clicked(); + + void on_forceLoadCheckBox_toggled(); + private: void resetInput(); @@ -108,6 +112,8 @@ private: ExecutablesList m_ExecutablesList; Profile *m_Profile; + + QList m_ForcedLibraries; }; #endif // EDITEXECUTABLESDIALOG_H diff --git a/src/editexecutablesdialog.ui b/src/editexecutablesdialog.ui index bdbb8bd1..4f9223d5 100644 --- a/src/editexecutablesdialog.ui +++ b/src/editexecutablesdialog.ui @@ -191,6 +191,43 @@ Right now the only case I know of where this needs to be overwritten is for the + + + + + + If this is enabled, the configured libraries will be automatically loaded when this executable is launched. + + + Force Load Libraries (*) + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + false + + + Configure Libraries + + + + + diff --git a/src/forcedloaddialog.cpp b/src/forcedloaddialog.cpp new file mode 100644 index 00000000..ad30a58c --- /dev/null +++ b/src/forcedloaddialog.cpp @@ -0,0 +1,76 @@ +#include "forcedloaddialog.h" +#include "ui_forcedloaddialog.h" + +#include "forcedloaddialogwidget.h" + +#include +#include + +using namespace MOBase; + +ForcedLoadDialog::ForcedLoadDialog(QWidget *parent) : + QDialog(parent), + ui(new Ui::ForcedLoadDialog) +{ + ui->setupUi(this); +} + +ForcedLoadDialog::~ForcedLoadDialog() +{ + delete ui; +} + +void ForcedLoadDialog::setValues(QList &values) +{ + ui->tableWidget->clearContents(); + + for (int i = 0; i < values.count(); i++) { + ForcedLoadDialogWidget *item = new ForcedLoadDialogWidget(this); + item->setEnabled(values[i].enabled()); + item->setProcess(values[i].process()); + item->setLibraryPath(values[i].library()); + item->setForced(values[i].forced()); + + ui->tableWidget->insertRow(i); + ui->tableWidget->setCellWidget(i, 0, item); + } + + ui->tableWidget->resizeRowsToContents(); +} + +QList ForcedLoadDialog::values() +{ + QList results; + for (int row = 0; row < ui->tableWidget->rowCount(); row++) { + auto widget = (ForcedLoadDialogWidget*)ui->tableWidget->cellWidget(row, 0); + results.append( + ExecutableForcedLoadSetting( + widget->getProcess(), + widget->getLibraryPath() + ).withEnabled(widget->getEnabled()) + .withForced(widget->getForced()) + ); + } + return results; +} + + +void ForcedLoadDialog::on_addRowButton_clicked() +{ + int row = ui->tableWidget->rowCount(); + ui->tableWidget->insertRow(row); + ForcedLoadDialogWidget *item = new ForcedLoadDialogWidget(this); + ui->tableWidget->setCellWidget(row, 0, item); + ui->tableWidget->resizeRowsToContents(); +} + +void ForcedLoadDialog::on_deleteRowButton_clicked() +{ + for (auto rowIndex: ui->tableWidget->selectionModel()->selectedRows()) { + int row = rowIndex.row(); + auto widget = (ForcedLoadDialogWidget*)ui->tableWidget->cellWidget(row, 0); + if (!widget->getForced()){ + ui->tableWidget->removeRow(row); + } + } +} diff --git a/src/forcedloaddialog.h b/src/forcedloaddialog.h new file mode 100644 index 00000000..68460d91 --- /dev/null +++ b/src/forcedloaddialog.h @@ -0,0 +1,32 @@ +#ifndef FORCEDLOADDIALOG_H +#define FORCEDLOADDIALOG_H + +#include +#include + +#include "executableinfo.h" + +namespace Ui { +class ForcedLoadDialog; +} + +class ForcedLoadDialog : public QDialog +{ + Q_OBJECT + +public: + explicit ForcedLoadDialog(QWidget *parent = nullptr); + ~ForcedLoadDialog(); + + void setValues(QList &values); + QList values(); + +private slots: + void on_addRowButton_clicked(); + void on_deleteRowButton_clicked(); + +private: + Ui::ForcedLoadDialog *ui; +}; + +#endif // FORCEDLOADDIALOG_H diff --git a/src/forcedloaddialog.ui b/src/forcedloaddialog.ui new file mode 100644 index 00000000..9c5b2d10 --- /dev/null +++ b/src/forcedloaddialog.ui @@ -0,0 +1,117 @@ + + + ForcedLoadDialog + + + + 0 + 0 + 700 + 400 + + + + Forced Load Settings + + + + + + QAbstractItemView::NoEditTriggers + + + QAbstractItemView::SingleSelection + + + QAbstractItemView::SelectRows + + + 1 + + + false + + + true + + + + + + + + + + Adds a row to the table. + + + Adds a row to the table. + + + Add Row + + + + + + + Deletes the selected row from the table. + + + Deletes the selected row from the table. + + + Delete Row + + + + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + + + + + buttonBox + accepted() + ForcedLoadDialog + accept() + + + 248 + 254 + + + 157 + 274 + + + + + buttonBox + rejected() + ForcedLoadDialog + reject() + + + 316 + 260 + + + 286 + 274 + + + + + diff --git a/src/forcedloaddialogwidget.cpp b/src/forcedloaddialogwidget.cpp new file mode 100644 index 00000000..61805068 --- /dev/null +++ b/src/forcedloaddialogwidget.cpp @@ -0,0 +1,87 @@ +#include "forcedloaddialogwidget.h" +#include "ui_forcedloaddialogwidget.h" + +#include + +#include "executableinfo.h" + +ForcedLoadDialogWidget::ForcedLoadDialogWidget(QWidget *parent) : + QWidget(parent), + ui(new Ui::ForcedLoadDialogWidget) +{ + ui->setupUi(this); +} + +ForcedLoadDialogWidget::~ForcedLoadDialogWidget() +{ + delete ui; +} + +bool ForcedLoadDialogWidget::getEnabled() +{ + return ui->enabledBox->isChecked(); +} + +bool ForcedLoadDialogWidget::getForced() +{ + return m_Forced; +} + +QString ForcedLoadDialogWidget::getLibraryPath() +{ + return ui->libraryPathEdit->text(); +} + +QString ForcedLoadDialogWidget::getProcess() +{ + return ui->processEdit->text(); +} + +void ForcedLoadDialogWidget::setEnabled(bool enabled) +{ + ui->enabledBox->setChecked(enabled); +} + +void ForcedLoadDialogWidget::setForced(bool forced) +{ + m_Forced = forced; + ui->libraryPathBrowseButton->setEnabled(!forced); + ui->libraryPathEdit->setEnabled(!forced); + ui->processBrowseButton->setEnabled(!forced); + ui->processEdit->setEnabled(!forced); +} + +void ForcedLoadDialogWidget::setLibraryPath(QString &path) +{ + ui->libraryPathEdit->setText(path); +} + +void ForcedLoadDialogWidget::setProcess(QString &name) +{ + ui->processEdit->setText(name); +} + +void ForcedLoadDialogWidget::on_enabledBox_toggled() +{ + // anything to do? +} + +void ForcedLoadDialogWidget::on_libraryPathBrowseButton_clicked() +{ + QDir gameDir("D:/Games/Steam Library/steamapps/common/Fallout 4"); + QString startPath = gameDir.absolutePath(); + QString result = QFileDialog::getOpenFileName(nullptr, "Select a library...", startPath, "Dynamic link library (*.dll)", nullptr, QFileDialog::ReadOnly); + if (!result.isEmpty()) { + ui->libraryPathEdit->setText(result); + } +} + +void ForcedLoadDialogWidget::on_processBrowseButton_clicked() +{ + QDir gameDir("D:/Games/Steam Library/steamapps/common/Fallout 4"); + QString startPath = gameDir.absolutePath(); + QString result = QFileDialog::getOpenFileName(nullptr, "Select a process...", startPath, "Executable (*.exe)", nullptr, QFileDialog::ReadOnly); + if (!result.isEmpty()) { + ui->processEdit->setText(QFile(result).fileName()); + } +} diff --git a/src/forcedloaddialogwidget.h b/src/forcedloaddialogwidget.h new file mode 100644 index 00000000..06ad0009 --- /dev/null +++ b/src/forcedloaddialogwidget.h @@ -0,0 +1,38 @@ +#ifndef FORCEDLOADDIALOGWIDGET_H +#define FORCEDLOADDIALOGWIDGET_H + +#include + +namespace Ui { +class ForcedLoadDialogWidget; +} + +class ForcedLoadDialogWidget : public QWidget +{ + Q_OBJECT + +public: + explicit ForcedLoadDialogWidget(QWidget *parent = nullptr); + ~ForcedLoadDialogWidget(); + + bool getEnabled(); + bool getForced(); + QString getLibraryPath(); + QString getProcess(); + + void setEnabled(bool enabled); + void setForced(bool forced); + void setLibraryPath(QString &path); + void setProcess(QString &name); + +private slots: + void on_enabledBox_toggled(); + void on_libraryPathBrowseButton_clicked(); + void on_processBrowseButton_clicked(); + +private: + Ui::ForcedLoadDialogWidget *ui; + bool m_Forced; +}; + +#endif // FORCEDLOADDIALOGWIDGET_H diff --git a/src/forcedloaddialogwidget.ui b/src/forcedloaddialogwidget.ui new file mode 100644 index 00000000..4df78beb --- /dev/null +++ b/src/forcedloaddialogwidget.ui @@ -0,0 +1,104 @@ + + + ForcedLoadDialogWidget + + + + 0 + 0 + 400 + 41 + + + + + 0 + 0 + + + + Form + + + + + + + + + + + + + The name of the process that should be forced to load a library. + + + The name of the process that should be forced to load a library. + + + Process name + + + + + + + + 0 + 0 + + + + + 32 + 0 + + + + + 32 + 16777215 + + + + Browse for a process. + + + Browse for a process. + + + ... + + + + + + + Library to load + + + + + + + + 32 + 16777215 + + + + Browse for a library. + + + Browse for a library. + + + ... + + + + + + + + diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index c6dc145d..0ebad6ae 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -1162,15 +1162,20 @@ void MainWindow::startExeAction() { QAction *action = qobject_cast(sender()); if (action != nullptr) { - const Executable &selectedExecutable( - m_OrganizerCore.executablesList()->find(action->text())); - QString customOverwrite= m_OrganizerCore.currentProfile()->setting("custom_overwrites", selectedExecutable.m_Title).toString(); + const Executable &selectedExecutable(m_OrganizerCore.executablesList()->find(action->text())); + QString customOverwrite = m_OrganizerCore.currentProfile()->setting("custom_overwrites", selectedExecutable.m_Title).toString(); + auto forcedLibraries = m_OrganizerCore.currentProfile()->determineForcedLibraries(selectedExecutable.m_Title); + if (!m_OrganizerCore.currentProfile()->forcedLibrariesEnabled(selectedExecutable.m_Title)) { + forcedLibraries.clear(); + } m_OrganizerCore.spawnBinary( selectedExecutable.m_BinaryInfo, selectedExecutable.m_Arguments, selectedExecutable.m_WorkingDirectory.length() != 0 ? selectedExecutable.m_WorkingDirectory : selectedExecutable.m_BinaryInfo.absolutePath(), - selectedExecutable.m_SteamAppID, customOverwrite); + selectedExecutable.m_SteamAppID, + customOverwrite, + forcedLibraries); } else { qCritical("not an action?"); } @@ -1957,12 +1962,18 @@ void MainWindow::on_startButton_clicked() { try { const Executable &selectedExecutable(getSelectedExecutable()); QString customOverwrite = m_OrganizerCore.currentProfile()->setting("custom_overwrites", selectedExecutable.m_Title).toString(); + auto forcedLibraries = m_OrganizerCore.currentProfile()->determineForcedLibraries(selectedExecutable.m_Title); + if (!m_OrganizerCore.currentProfile()->forcedLibrariesEnabled(selectedExecutable.m_Title)) { + forcedLibraries.clear(); + } m_OrganizerCore.spawnBinary( selectedExecutable.m_BinaryInfo, selectedExecutable.m_Arguments, selectedExecutable.m_WorkingDirectory.length() != 0 ? selectedExecutable.m_WorkingDirectory : selectedExecutable.m_BinaryInfo.absolutePath(), - selectedExecutable.m_SteamAppID, customOverwrite); + selectedExecutable.m_SteamAppID, + customOverwrite, + forcedLibraries); } catch (...) { ui->startButton->setEnabled(true); throw; diff --git a/src/organizer.pro b/src/organizer.pro index b8e79e0c..ddf676f2 100644 --- a/src/organizer.pro +++ b/src/organizer.pro @@ -92,7 +92,9 @@ SOURCES += \ modinfooverwrite.cpp \ modinfoforeign.cpp \ listdialog.cpp \ - lcdnumber.cpp + lcdnumber.cpp \ + forcedloaddialog.cpp \ + forcedloaddialogwidget.cpp HEADERS += \ @@ -169,7 +171,9 @@ HEADERS += \ modinfooverwrite.h \ modinfoforeign.h \ listdialog.h \ - lcdnumber.h + lcdnumber.h \ + forcedloaddialog.h \ + forcedloaddialogwidget.h FORMS += \ transfersavesdialog.ui \ @@ -197,7 +201,9 @@ FORMS += \ previewdialog.ui \ browserdialog.ui \ aboutdialog.ui \ - listdialog.ui + listdialog.ui \ + forcedloaddialog.ui \ + forcedloaddialogwidget.ui RESOURCES += \ resources.qrc \ diff --git a/src/organizer_en.ts b/src/organizer_en.ts index 299ffe6a..4291f3ae 100644 --- a/src/organizer_en.ts +++ b/src/organizer_en.ts @@ -27,7 +27,6 @@ Lead Developers/ Maintainers - Current Maintainers @@ -116,7 +115,12 @@ - + + Tannin (Original Creator) + + + + Close @@ -980,92 +984,107 @@ Right now the only case I know of where this needs to be overwritten is for the - + + If this is enabled, the configured libraries will be automatically loaded when this executable is launched. + + + + + Force Load Libraries (*) + + + + + Configure Libraries + + + + Use Application's Icon for shortcuts - + (*) This setting is profile-specific - - + + Add an executable - - + + Add - - + + Remove the selected executable - + Remove - + Close - + Select a binary - + Executable (%1) - + Java (32-bit) required - + MO requires 32-bit java to run this application. If you already have it installed, select javaw.exe from that installation as the binary. - + Select a directory - + Confirm - + Really remove "%1" from executables? - + Modify - - + + Save Changes? - - + + You made changes to the current executable, do you want to save them? @@ -1117,6 +1136,78 @@ Right now the only case I know of where this needs to be overwritten is for the + + ForcedLoadDialog + + + Forced Load Settings + + + + + + Adds a row to the table. + + + + + Add Row + + + + + + Deletes the selected row from the table. + + + + + Delete Row + + + + + ForcedLoadDialogWidget + + + Form + + + + + + The name of the process that should be forced to load a library. + + + + + Process name + + + + + + Browse for a process. + + + + + + ... + + + + + Library to load + + + + + + Browse for a library. + + + InstallDialog @@ -1457,7 +1548,7 @@ p, li { white-space: pre-wrap; } - + Create Backup @@ -1486,7 +1577,7 @@ p, li { white-space: pre-wrap; } - + Filter @@ -1633,8 +1724,8 @@ p, li { white-space: pre-wrap; } - - + + Refresh @@ -1696,145 +1787,145 @@ p, li { white-space: pre-wrap; } - + Show Hidden - + Tool Bar - + Install Mod - + Install &Mod - + Install a new mod from an archive - + Ctrl+M - + Profiles - + &Profiles - + Configure Profiles - + Ctrl+P - + Executables - + &Executables - + Configure the executables that can be started through Mod Organizer - + Ctrl+E - + Tools - + &Tools - + Ctrl+I - + Settings - + &Settings - + Configure settings and workarounds - + Ctrl+S - + Nexus - + Search nexus network for more mods - + Ctrl+N - - + + Update - + Mod Organizer is up-to-date - + No Problems - + This button will be highlighted if MO discovered potential problems in your setup and provide tips on how to fix them. !Work in progress! @@ -1842,39 +1933,39 @@ Right now this has very limited functionality - - + + Help - + Ctrl+H - + Endorse MO - - + + Endorse Mod Organizer - + Copy Log to Clipboard - + Change Game - + Open the Instance selection dialog to manage a different Game @@ -1927,8 +2018,8 @@ Error: %1 - - + + Endorse @@ -2044,7 +2135,7 @@ Error: %1 - Notice: Your current MO version (%1) is lower than the previous version (%2).<br>The GUI may not downgrade gracefully, so you may experience oddities.<br>However, there should be no serious issues. + Notice: Your current MO version (%1) is lower than the previously used one (%2). The GUI may not downgrade gracefully, so you may experience oddities. However, there should be no serious issues. @@ -2058,676 +2149,676 @@ Error: %1 - + Start Tutorial? - + You're about to start a tutorial. For technical reasons it's not possible to end the tutorial early. Continue? - + failed to spawn notepad.exe: %1 - + failed to change origin name: %1 - + failed to move "%1" from mod "%2" to "%3": %4 - + <Contains %1> - + <Checked> - + <Unchecked> - + <Update> - + <Mod Backup> - + <Managed by MO> - + <Managed outside MO> - + <No category> - + <Conflicted> - + <Not Endorsed> - + failed to rename mod: %1 - + Overwrite? - + This will replace the existing mod "%1". Continue? - + failed to remove mod "%1" - - - + + + failed to rename "%1" to "%2" - - - - + + + + Confirm - + Remove the following mods?<br><ul>%1</ul> - + failed to remove mod: %1 - - + + Failed - + Installation file no longer exists - + Mods installed with old versions of MO can't be reinstalled in this way. - + Failed to create backup. - + You need to be logged in with Nexus to resume a download - - - - + + + + You need to be logged in with Nexus to endorse - - + + Endorsing multiple mods will take a while. Please wait... - - + + Unendorsing multiple mods will take a while. Please wait... - + Failed to display overwrite dialog: %1 - + Opening Nexus Links - + You are trying to open %1 links to Nexus Mods. Are you sure you want to do this? - + Nexus ID for this Mod is unknown - + Web page for this mod is unknown - + <table cellspacing="5"><tr><th>Type</th><th>All</th><th>Visible</th><tr><td>Enabled mods:&emsp;</td><td align=right>%1 / %2</td><td align=right>%3 / %4</td></tr><tr><td>Unmanaged/DLCs:&emsp;</td><td align=right>%5</td><td align=right>%6</td></tr><tr><td>Mod backups:&emsp;</td><td align=right>%7</td><td align=right>%8</td></tr><tr><td>Separators:&emsp;</td><td align=right>%9</td><td align=right>%10</td></tr></table> - - <table cellspacing="4"><tr><th>Type</th><th>Active</th><th>Total</th></tr><tr><td>Active plugins:</td><td align=right>%1</td><td align=right>%2</td></tr><tr><td>Active ESMs:</td><td align=right>%3</td><td align=right>%4</td></tr><tr><td>Active ESPs:</td><td align=right>%7</td><td align=right>%8</td></tr><tr><td>Active ESMs+ESPs:</td><td align=right>%9</td><td align=right>%10</td></tr><tr><td>Active ESLs:</td><td align=right>%5</td><td align=right>%6</td></tr></table> + + <table cellspacing="6"><tr><th>Type</th><th>Active </th><th>Total</th></tr><tr><td>All plugins:</td><td align=right>%1 </td><td align=right>%2</td></tr><tr><td>ESMs:</td><td align=right>%3 </td><td align=right>%4</td></tr><tr><td>ESPs:</td><td align=right>%7 </td><td align=right>%8</td></tr><tr><td>ESMs+ESPs:</td><td align=right>%9 </td><td align=right>%10</td></tr><tr><td>ESLs:</td><td align=right>%5 </td><td align=right>%6</td></tr></table> - - - + + + Create Mod... - + This will create an empty mod. Please enter a name: - - + + A mod with this name already exists - + Create Separator... - + This will create a new separator. Please enter a name: - + A separator with this name already exists - + This will move all files from overwrite into a new, regular mod. Please enter a name: - - + + Are you sure? - + About to recursively delete: - + Not logged in, endorsement information will be wrong - + Continue? - + The versioning scheme decides which version is considered newer than another. This function will guess the versioning scheme under the assumption that the installed version is outdated. - - + + Sorry - + I don't know a versioning scheme where %1 is newer than %2. - + Really enable all visible mods? - + Really disable all visible mods? - + Export to csv - + CSV (Comma Separated Values) is a format that can be imported in programs like Excel to create a spreadsheet. You can also use online editors and converters instead. - + Select what mods you want export: - + All installed mods - + Only active (checked) mods from your current profile - + All currently visible mods in the mod list - + Choose what Columns to export: - + Mod_Priority - + Mod_Name - + Notes_column - + Mod_Status - + Primary_Category - + Nexus_ID - + Mod_Nexus_URL - + Mod_Version - + Install_Date - + Download_File_Name - + export failed: %1 - + Open Game folder - + Open MyGames folder - + Open INIs folder - + Open Instance folder - + Open Mods folder - + Open Profile folder - + Open Downloads folder - + Open MO2 Install folder - + Open MO2 Plugins folder - + Open MO2 Logs folder - + Install Mod... - + Create empty mod - + Create Separator - + Enable all visible - + Disable all visible - + Check all for update - + Export to csv... - - + + Send to - - + + Top - - + + Bottom - - + + Priority... - + Separator... - + All Mods - + Sync to Mods... - + Clear Overwrite... - - + + Open in Explorer - + Restore Backup - + Remove Backup... - - + + Change Categories - - + + Primary Category - + Rename Separator... - + Remove Separator... - + Select Color... - + Reset Color - + Change versioning scheme - + Un-ignore update - + Ignore update - - + + Enable selected - - + + Disable selected - + Rename Mod... - + Reinstall Mod - + Remove Mod... - + Un-Endorse - + Won't endorse - + Endorsement state unknown - + Ignore missing data - + Mark as converted/working - + Visit on Nexus - + Visit web page - + Information... - - + + Exception: - - + + Unknown exception - + <All> - + <Multiple> - + %1 more - + Are you sure you want to remove the following %n save(s)?<br><ul>%1</ul><br>Removed saves will be sent to the Recycle Bin. @@ -2735,12 +2826,12 @@ You can also use online editors and converters instead. - + Enable Mods... - + Delete %n save(s) @@ -2748,22 +2839,22 @@ You can also use online editors and converters instead. - + failed to remove %1 - + failed to create %1 - + Restarting MO - + Changing the managed game directory requires restarting MO. Any pending downloads will be paused. @@ -2771,335 +2862,335 @@ Click OK to restart MO now. - + Can't change download directory while downloads are in progress! - + failed to write to file %1 - + %1 written - + Select binary - + Binary - + Enter Name - + Please enter a name for the executable - + Not an executable - + This is not a recognized executable. - - + + Replace file? - + There already is a hidden version of this file. Replace it? - - + + File operation failed - - + + Failed to remove "%1". Maybe you lack the required file permissions? - + There already is a visible version of this file. Replace it? - - + + Set Priority - + Set the priority of the selected plugins - + file not found: %1 - + failed to generate preview for %1 - + Sorry, can't preview anything. This function currently does not support extracting from bsas. - + Update available - + Open/Execute - + Add as Executable - + Preview - + Un-Hide - + Hide - + Write To File... - + Do you want to endorse Mod Organizer on %1 now? - + Thank you! - + Thank you for your endorsement! - + Request to Nexus failed: %1 - - + + failed to read %1: %2 - - + + Error - + failed to extract %1 (errorcode %2) - + Extract BSA - + This archive contains invalid hashes. Some files may be broken. - + Extract... - + This will restart MO, continue? - + Edit Categories... - + Deselect filter - + Remove - + Enable all - + Disable all - + Unlock load order - + Lock load order - + Open Origin in Explorer - + Open Origin Info... - + depends on missing "%1" - + incompatible with "%1" - + Please wait while LOOT is running - + loot failed. Exit code was: %1 - + failed to start loot - + failed to run loot: %1 - + Errors occured - + Backup of load order created - + Choose backup to restore - + No Backups - + There are no backups to restore - - + + Restore failed - - + + Failed to restore the backup. Errorcode: %1 - + Backup of modlist created - + A file with the same name has already been downloaded. What would you like to do? - + Overwrite - + Rename new file - + Ignore file - + Set the priority of the selected mods @@ -4007,123 +4098,123 @@ p, li { white-space: pre-wrap; } - + drag&drop failed: %1 - + Confirm - + Are you sure you want to remove "%1"? - + Flags - + Content - + Mod Name - + Version - + Priority - + Category - + Source Game - + Nexus ID - + Installation - + Notes - - + + unknown - + Name of your mods - + Version of the mod (if available) - + Installation priority of your mod. The higher, the more "important" it is and thus overwrites files from mods with lower priority. - + Category of the mod. - + The source game which was the origin of this mod. - + Id of the mod as used on Nexus. - + Emblemes to highlight things that might require attention. - + Depicts the content of the mod:<br><table cellspacing=7><tr><td><img src=":/MO/gui/content/plugin" width=32/></td><td>Game plugins (esp/esm/esl)</td></tr><tr><td><img src=":/MO/gui/content/interface" width=32/></td><td>Interface</td></tr><tr><td><img src=":/MO/gui/content/mesh" width=32/></td><td>Meshes</td></tr><tr><td><img src=":/MO/gui/content/bsa" width=32/></td><td>BSA</td></tr><tr><td><img src=":/MO/gui/content/texture" width=32/></td><td>Textures</td></tr><tr><td><img src=":/MO/gui/content/sound" width=32/></td><td>Sounds</td></tr><tr><td><img src=":/MO/gui/content/music" width=32/></td><td>Music</td></tr><tr><td><img src=":/MO/gui/content/string" width=32/></td><td>Strings</td></tr><tr><td><img src=":/MO/gui/content/script" width=32/></td><td>Scripts (Papyrus)</td></tr><tr><td><img src=":/MO/gui/content/skse" width=32/></td><td>Script Extender plugins</td></tr><tr><td><img src=":/MO/gui/content/skyproc" width=32/></td><td>SkyProc Patcher</td></tr><tr><td><img src=":/MO/gui/content/menu" width=32/></td><td>Mod Configuration Menu</td></tr><tr><td><img src=":/MO/gui/content/inifile" width=32/></td><td>INI files</td></tr><tr><td><img src=":/MO/gui/content/modgroup" width=32/></td><td>ModGroup files</td></tr></table> - + Time this mod was installed - + User notes about the mod @@ -4131,7 +4222,7 @@ p, li { white-space: pre-wrap; } ModListSortProxy - + Drag&Drop is only supported when sorting by priority @@ -4351,81 +4442,81 @@ Continue launching %1? - + Multiple esps/esls activated, please check that they don't conflict. - + Download? - + A download has been started but no installed page plugin recognizes it. If you download anyway no information (i.e. version) will be associated with the download. Continue? - + failed to update mod list: %1 - - + + login successful - + Login failed - + Login failed, try again? - + login failed: %1. Download will not be associated with an account - + login failed: %1 - + login failed: %1. You need to log-in with Nexus to update MO. - + MO1 "Script Extender" load mechanism has left hook.dll in your game folder - - + + Description missing - + <a href="%1">hook.dll</a> has been found in your game folder (right click to copy the full path). This is most likely a leftover of setting the ModOrganizer 1 load mechanism to "Script Extender", in which case you must remove this file either by changing the load mechanism in ModOrganizer 1 or manually removing the file, otherwise the game is likely to crash and burn. - + failed to save load order: %1 - + The designated write target "%1" is not enabled. @@ -4531,135 +4622,135 @@ Continue? PluginList - + Name - + Priority - + Mod Index - + Flags - - + + unknown - + Name of your mods - + Load priority of your mod. The higher, the more "important" it is and thus overwrites data from plugins with lower priority. - + The modindex determines the formids of objects originating from this mods. - + failed to update esp info for file %1 (source id: %2), error: %3 - + esp not found: %1 - - + + Confirm - + Really enable all plugins? - + Really disable all plugins? - + The file containing locked plugin indices is broken - - + + <b>Origin</b>: %1 - + <br><b><i>This plugin can't be disabled (enforced by the game).</i></b> - + Author - + Description - + Missing Masters - + Enabled Masters - + Loads Archives - + There are Archives connected to this plugin. Their assets will be added to your game, overwriting in case of conflicts following the plugin order. Loose files will always overwrite assets from Archives. (This flag only checks for Archives from the same mod as the plugin) - + Loads INI settings - + There is an ini file connected to this plugin. Its settings will be added to your game settings, overwriting in case of conflicts. - + This ESP is flagged as an ESL. It will adhere to the ESP load order but the records will be loaded in ESL space. - + failed to restore load order for %1 @@ -4721,76 +4812,76 @@ p, li { white-space: pre-wrap; } Profile - + invalid profile name %1 - + failed to create %1 - + failed to write mod list: %1 - + failed to update tweaked ini file, wrong settings may be used: %1 - + failed to create tweaked ini: %1 - + failed to open %1 - + "%1" is missing or inaccessible - - - - - + + + + + invalid index %1 - + Overwrite directory couldn't be parsed - + invalid priority %1 - + Delete profile-specific save games? - + Do you want to delete the profile-specific save games? (If you select "No", the save games will show up again if you re-enable profile-specific save games) - + Missing profile-specific game INI files! - + Some of your profile-specific game INI files were missing. They will now be copied from the vanilla game folder. You might want double-check your settings. Missing files: @@ -4798,12 +4889,12 @@ Missing files: - + Delete profile-specific game INI files? - + Do you want to delete the profile-specific game INI files? (If you select "No", the INI files will be used again if you re-enable profile-specific game INI files.) @@ -5322,7 +5413,7 @@ If the folder was still in use, restart MO and try again. - + failed to create %1 @@ -5465,7 +5556,7 @@ If the folder was still in use, restart MO and try again. - + <Manage...> @@ -5506,12 +5597,12 @@ If the folder was still in use, restart MO and try again. - + failed to access %1 - + failed to set file time %1 @@ -6714,7 +6805,7 @@ On Windows XP: UsvfsConnector - + Preparing vfs diff --git a/src/organizercore.cpp b/src/organizercore.cpp index c4029a6d..39cb4d13 100644 --- a/src/organizercore.cpp +++ b/src/organizercore.cpp @@ -1199,10 +1199,15 @@ QStringList OrganizerCore::modsSortedByProfilePriority() const return res; } -void OrganizerCore::spawnBinary(const QFileInfo &binary, const QString &arguments, const QDir ¤tDirectory, const QString &steamAppID, const QString &customOverwrite) +void OrganizerCore::spawnBinary(const QFileInfo &binary, + const QString &arguments, + const QDir ¤tDirectory, + const QString &steamAppID, + const QString &customOverwrite, + const QList &forcedLibraries) { DWORD processExitCode = 0; - HANDLE processHandle = spawnBinaryDirect(binary, arguments, m_CurrentProfile->name(), currentDirectory, steamAppID, customOverwrite, &processExitCode); + HANDLE processHandle = spawnBinaryDirect(binary, arguments, m_CurrentProfile->name(), currentDirectory, steamAppID, customOverwrite, forcedLibraries, &processExitCode); if (processHandle != INVALID_HANDLE_VALUE) { refreshDirectoryStructure(); // need to remove our stored load order because it may be outdated if a foreign tool changed the @@ -1227,9 +1232,10 @@ HANDLE OrganizerCore::spawnBinaryDirect(const QFileInfo &binary, const QDir ¤tDirectory, const QString &steamAppID, const QString &customOverwrite, + const QList &forcedLibraries, LPDWORD exitCode) { - HANDLE processHandle = spawnBinaryProcess(binary, arguments, profileName, currentDirectory, steamAppID, customOverwrite); + HANDLE processHandle = spawnBinaryProcess(binary, arguments, profileName, currentDirectory, steamAppID, customOverwrite, forcedLibraries); if (Settings::instance().lockGUI() && processHandle != INVALID_HANDLE_VALUE) { std::unique_ptr dlg; ILockedWaitingForProcess* uilock = nullptr; @@ -1264,7 +1270,8 @@ HANDLE OrganizerCore::spawnBinaryProcess(const QFileInfo &binary, const QString &profileName, const QDir ¤tDirectory, const QString &steamAppID, - const QString &customOverwrite) + const QString &customOverwrite, + const QList &forcedLibraries) { prepareStart(); @@ -1324,6 +1331,8 @@ HANDLE OrganizerCore::spawnBinaryProcess(const QFileInfo &binary, if (m_AboutToRun(binary.absoluteFilePath())) { try { m_USVFS.updateMapping(fileMapping(profileName, customOverwrite)); + m_USVFS.updateForcedLibraries(forcedLibraries); + } catch (const UsvfsConnectorException &e) { qDebug(e.what()); return INVALID_HANDLE_VALUE; @@ -1416,6 +1425,10 @@ HANDLE OrganizerCore::runShortcut(const MOShortcut& shortcut) .toLocal8Bit().constData()); Executable& exe = m_ExecutablesList.find(shortcut.executable()); + auto forcedLibaries = m_CurrentProfile->determineForcedLibraries(shortcut.executable()); + if (!m_CurrentProfile->forcedLibrariesEnabled(exe.m_BinaryInfo.fileName())) { + forcedLibaries.clear(); + } return spawnBinaryDirect( exe.m_BinaryInfo, exe.m_Arguments, @@ -1423,7 +1436,9 @@ HANDLE OrganizerCore::runShortcut(const MOShortcut& shortcut) exe.m_WorkingDirectory.length() != 0 ? exe.m_WorkingDirectory : exe.m_BinaryInfo.absolutePath(), - exe.m_SteamAppID, ""); + exe.m_SteamAppID, + "", + forcedLibaries); } HANDLE OrganizerCore::startApplication(const QString &executable, @@ -1444,6 +1459,7 @@ HANDLE OrganizerCore::startApplication(const QString &executable, } QString steamAppID; QString customOverwrite; + QList forcedLibraries; if (executable.contains('\\') || executable.contains('/')) { // file path @@ -1462,6 +1478,9 @@ HANDLE OrganizerCore::startApplication(const QString &executable, customOverwrite = m_CurrentProfile->setting("custom_overwrites", exe.m_Title) .toString(); + if (m_CurrentProfile->forcedLibrariesEnabled(exe.m_Title)) { + forcedLibraries = m_CurrentProfile->determineForcedLibraries(exe.m_Title); + } } catch (const std::runtime_error &) { // nop } @@ -1473,6 +1492,9 @@ HANDLE OrganizerCore::startApplication(const QString &executable, customOverwrite = m_CurrentProfile->setting("custom_overwrites", exe.m_Title) .toString(); + if (m_CurrentProfile->forcedLibrariesEnabled(exe.m_Title)) { + forcedLibraries = m_CurrentProfile->determineForcedLibraries(exe.m_Title); + } if (arguments == "") { arguments = exe.m_Arguments; } @@ -1487,7 +1509,7 @@ HANDLE OrganizerCore::startApplication(const QString &executable, } } - return spawnBinaryDirect(binary, arguments, profileName, currentDirectory, steamAppID, customOverwrite); + return spawnBinaryDirect(binary, arguments, profileName, currentDirectory, steamAppID, customOverwrite, forcedLibraries); } bool OrganizerCore::waitForApplication(HANDLE handle, LPDWORD exitCode) diff --git a/src/organizercore.h b/src/organizercore.h index 086fa11d..61020acd 100644 --- a/src/organizercore.h +++ b/src/organizercore.h @@ -20,6 +20,7 @@ #include #include #include +#include "executableinfo.h" class ModListSortProxy; class PluginListSortProxy; @@ -141,20 +142,23 @@ public: void spawnBinary(const QFileInfo &binary, const QString &arguments = "", const QDir ¤tDirectory = QDir(), const QString &steamAppID = "", - const QString &customOverwrite = ""); + const QString &customOverwrite = "", + const QList &forcedLibraries = QList()); HANDLE spawnBinaryDirect(const QFileInfo &binary, const QString &arguments, const QString &profileName, const QDir ¤tDirectory, const QString &steamAppID, const QString &customOverwrite, + const QList &forcedLibraries = QList(), LPDWORD exitCode = nullptr); HANDLE spawnBinaryProcess(const QFileInfo &binary, const QString &arguments, const QString &profileName, const QDir ¤tDirectory, const QString &steamAppID, - const QString &customOverwrite); + const QString &customOverwrite, + const QList &forcedLibraries = QList()); void loginSuccessfulUpdate(bool necessary); void loginFailedUpdate(const QString &message); diff --git a/src/profile.cpp b/src/profile.cpp index 09c2a5f5..02257de9 100644 --- a/src/profile.cpp +++ b/src/profile.cpp @@ -884,7 +884,6 @@ QVariant Profile::setting(const QString §ion, const QString &name, return m_Settings->value(section + "/" + name, fallback); } - void Profile::storeSetting(const QString §ion, const QString &name, const QVariant &value) { @@ -906,7 +905,124 @@ void Profile::removeSetting(const QString &name) removeSetting("", name); } +QVariantMap Profile::settingsByGroup(const QString §ion) const +{ + QVariantMap results; + m_Settings->beginGroup(section); + for (auto key : m_Settings->childKeys()) { + results[key] = m_Settings->value(key); + } + m_Settings->endGroup(); + return results; +} + +void Profile::storeSettingsByGroup(const QString §ion, const QVariantMap &values) +{ + m_Settings->beginGroup(section); + for (auto key : values.keys()) { + m_Settings->setValue(key, values[key]); + } + m_Settings->endGroup(); +} + +QList Profile::settingsByArray(const QString &prefix) const +{ + QList results; + int size = m_Settings->beginReadArray(prefix); + for (int i = 0; i < size; i++) { + m_Settings->setArrayIndex(i); + QVariantMap item; + for (auto key : m_Settings->childKeys()) { + item[key] = m_Settings->value(key); + } + results.append(item); + } + m_Settings->endArray(); + return results; +} + +void Profile::storeSettingsByArray(const QString &prefix, const QList &values) +{ + m_Settings->beginWriteArray(prefix); + for (int i = 0; i < values.length(); i++) { + m_Settings->setArrayIndex(i); + for (auto key : values.at(i).keys()) { + m_Settings->setValue(key, values.at(i)[key]); + } + } + m_Settings->endArray(); +} + int Profile::getPriorityMinimum() const { return m_ModIndexByPriority.begin()->first; } + +bool Profile::forcedLibrariesEnabled(const QString &executable) +{ + return setting("forced_libraries", executable + "/enabled", false).toBool(); +} + +void Profile::setForcedLibrariesEnabled(const QString &executable, bool enabled) +{ + storeSetting("forced_libraries", executable + "/enabled", enabled); +} + +QList Profile::determineForcedLibraries(const QString &executable) +{ + QList results; + + auto rawSettings = settingsByArray("forced_libraries/" + executable); + auto forcedLoads = m_GamePlugin->executableForcedLoads(); + + // look for enabled status on forced loads and add those + for (auto forcedLoad : forcedLoads) { + bool found = false; + for (auto rawSetting : rawSettings) { + if ((rawSetting.value("process").toString().compare(forcedLoad.process(), Qt::CaseInsensitive) == 0) + && (rawSetting.value("library").toString().compare(forcedLoad.library(), Qt::CaseInsensitive) == 0)) + { + results.append(forcedLoad.withEnabled(rawSetting.value("enabled", false).toBool())); + found = true; + } + } + if (!found) { + results.append(forcedLoad); + } + } + + // add everything else + for (auto rawSetting : rawSettings) { + bool add = true; + for (auto forcedLoad : forcedLoads) { + if ((rawSetting.value("process").toString().compare(forcedLoad.process(), Qt::CaseInsensitive) == 0) + && (rawSetting.value("library").toString().compare(forcedLoad.library(), Qt::CaseInsensitive) == 0)) + { + add = false; + } + } + if (add) { + results.append( + ExecutableForcedLoadSetting( + rawSetting.value("process").toString(), + rawSetting.value("library").toString() + ).withEnabled(rawSetting.value("enabled", false).toBool()) + ); + } + } + + return results; +} + +void Profile::saveForcedLibraries(const QString &executable, const QList &values) +{ + QList rawSettings; + for (auto setting : values) { + QVariantMap rawSetting; + rawSetting["enabled"] = setting.enabled(); + rawSetting["process"] = setting.process(); + rawSetting["library"] = setting.library(); + rawSettings.append(rawSetting); + } + storeSettingsByArray("forced_libraries/" + executable, rawSettings); +} diff --git a/src/profile.h b/src/profile.h index 95a5c59d..d7fb7785 100644 --- a/src/profile.h +++ b/src/profile.h @@ -24,12 +24,14 @@ along with Mod Organizer. If not, see . #include "modinfo.h" #include #include +#include "executableinfo.h" #include #include #include #include #include +#include #include @@ -310,8 +312,19 @@ public: void removeSetting(const QString §ion, const QString &name = QString()); void removeSetting(const QString &name); + QVariantMap settingsByGroup(const QString §ion) const; + void storeSettingsByGroup(const QString §ion, const QVariantMap &values); + + QList settingsByArray(const QString &prefix) const; + void storeSettingsByArray(const QString &prefix, const QList &values); + int getPriorityMinimum() const; + bool forcedLibrariesEnabled(const QString &executable); + void setForcedLibrariesEnabled(const QString &executable, bool enabled); + QList determineForcedLibraries(const QString &executable); + void saveForcedLibraries(const QString &executable, const QList &values); + signals: /** diff --git a/src/settings.cpp b/src/settings.cpp index 5cfe427b..f981f811 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -161,8 +161,8 @@ void Settings::managedGameChanged(IPluginGame const *gamePlugin) void Settings::registerPlugin(IPlugin *plugin) { m_Plugins.push_back(plugin); - m_PluginSettings.insert(plugin->name(), QMap()); - m_PluginDescriptions.insert(plugin->name(), QMap()); + m_PluginSettings.insert(plugin->name(), QVariantMap()); + m_PluginDescriptions.insert(plugin->name(), QVariantMap()); for (const PluginSetting &setting : plugin->settings()) { QVariant temp = m_Settings.value("Plugins/" + plugin->name() + "/" + setting.key, setting.defaultValue); if (!temp.convert(setting.defaultValue.type())) { diff --git a/src/settings.h b/src/settings.h index 25f22911..a47c255c 100644 --- a/src/settings.h +++ b/src/settings.h @@ -543,8 +543,8 @@ private: std::vector m_Plugins; - QMap> m_PluginSettings; - QMap> m_PluginDescriptions; + QMap m_PluginSettings; + QMap m_PluginDescriptions; QSet m_PluginBlacklist; diff --git a/src/settingsdialog.cpp b/src/settingsdialog.cpp index b975fa75..3032a6c6 100644 --- a/src/settingsdialog.cpp +++ b/src/settingsdialog.cpp @@ -307,7 +307,7 @@ void SettingsDialog::on_resetDialogsButton_clicked() void SettingsDialog::storeSettings(QListWidgetItem *pluginItem) { if (pluginItem != nullptr) { - QMap settings = pluginItem->data(Qt::UserRole + 1).toMap(); + QVariantMap settings = pluginItem->data(Qt::UserRole + 1).toMap(); for (int i = 0; i < ui->pluginSettingsList->topLevelItemCount(); ++i) { const QTreeWidgetItem *item = ui->pluginSettingsList->topLevelItem(i); @@ -328,8 +328,8 @@ void SettingsDialog::on_pluginsList_currentItemChanged(QListWidgetItem *current, ui->versionLabel->setText(plugin->version().canonicalString()); ui->descriptionLabel->setText(plugin->description()); - QMap settings = current->data(Qt::UserRole + 1).toMap(); - QMap descriptions = current->data(Qt::UserRole + 2).toMap(); + QVariantMap settings = current->data(Qt::UserRole + 1).toMap(); + QVariantMap descriptions = current->data(Qt::UserRole + 2).toMap(); ui->pluginSettingsList->setEnabled(settings.count() != 0); for (auto iter = settings.begin(); iter != settings.end(); ++iter) { QTreeWidgetItem *newItem = new QTreeWidgetItem(QStringList(iter.key())); diff --git a/src/usvfsconnector.cpp b/src/usvfsconnector.cpp index ef7314c0..5ad19fb0 100644 --- a/src/usvfsconnector.cpp +++ b/src/usvfsconnector.cpp @@ -138,6 +138,8 @@ UsvfsConnector::UsvfsConnector() BlacklistExecutable(buf.data()); } + ClearLibraryForceLoads(); + m_LogWorker.moveToThread(&m_WorkerThread); connect(&m_WorkerThread, SIGNAL(started()), &m_LogWorker, SLOT(process())); @@ -203,7 +205,8 @@ void UsvfsConnector::updateMapping(const MappingType &mapping) */ } -void UsvfsConnector::updateParams(int logLevel, int crashDumpsType, QString executableBlacklist) { +void UsvfsConnector::updateParams(int logLevel, int crashDumpsType, QString executableBlacklist) +{ USVFSUpdateParams(::logLevel(logLevel), ::crashDumpsType(crashDumpsType)); ClearExecutableBlacklist(); for (auto exec : executableBlacklist.split(";")) { @@ -211,3 +214,16 @@ void UsvfsConnector::updateParams(int logLevel, int crashDumpsType, QString exec BlacklistExecutable(buf.data()); } } + +void UsvfsConnector::updateForcedLibraries(const QList &forcedLibraries) +{ + ClearLibraryForceLoads(); + for (auto setting : forcedLibraries) { + if (setting.enabled()) { + ForceLoadLibrary( + setting.process().toStdWString().data(), + setting.library().toStdWString().data() + ); + } + } +} diff --git a/src/usvfsconnector.h b/src/usvfsconnector.h index 3aefb703..8a88bde5 100644 --- a/src/usvfsconnector.h +++ b/src/usvfsconnector.h @@ -27,7 +27,9 @@ along with Mod Organizer. If not, see . #include #include #include +#include #include +#include "executableinfo.h" class LogWorker : public QThread { @@ -83,6 +85,7 @@ public: void updateMapping(const MappingType &mapping); void updateParams(int logLevel, int crashDumpsType, QString executableBlacklist); + void updateForcedLibraries(const QList &forcedLibraries); private: -- cgit v1.3.1 From cc7c3adcad973949ac976c3dc71bb8cf2677056c Mon Sep 17 00:00:00 2001 From: Al Date: Fri, 11 Jan 2019 13:50:51 +0100 Subject: Fix or ignore a number of compiler warnings. --- src/aboutdialog.ui | 10 +++++----- src/overwriteinfodialog.cpp | 2 +- src/pluginlist.cpp | 2 +- src/selfupdater.cpp | 3 +-- src/settings.cpp | 2 +- src/shared/leaktrace.cpp | 13 ++++++++++++- src/spawn.cpp | 2 +- 7 files changed, 22 insertions(+), 12 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/aboutdialog.ui b/src/aboutdialog.ui index ac7db1fc..86b95c83 100644 --- a/src/aboutdialog.ui +++ b/src/aboutdialog.ui @@ -161,7 +161,7 @@ - + QAbstractItemView::NoSelection @@ -202,7 +202,7 @@ - + QAbstractItemView::NoSelection @@ -231,9 +231,9 @@ Translators - + - + QAbstractItemView::NoSelection @@ -363,7 +363,7 @@ Other Supporters && Contributors - + diff --git a/src/overwriteinfodialog.cpp b/src/overwriteinfodialog.cpp index 1fe3f645..4d35a2c3 100644 --- a/src/overwriteinfodialog.cpp +++ b/src/overwriteinfodialog.cpp @@ -220,7 +220,7 @@ void OverwriteInfoDialog::openFile(const QModelIndex &index) QString fileName = m_FileSystemModel->filePath(index); HINSTANCE res = ::ShellExecuteW(nullptr, L"open", ToWString(fileName).c_str(), nullptr, nullptr, SW_SHOW); - if ((int)res <= 32) { + if ((INT_PTR)res <= 32) { qCritical("failed to invoke %s: %d", fileName.toUtf8().constData(), res); } } diff --git a/src/pluginlist.cpp b/src/pluginlist.cpp index 6f417331..25f9c545 100644 --- a/src/pluginlist.cpp +++ b/src/pluginlist.cpp @@ -153,7 +153,7 @@ void PluginList::highlightPlugins(const QItemSelectionModel *selection, const MO } } } - emit dataChanged(this->index(0, 0), this->index(m_ESPs.size() - 1, this->columnCount() - 1)); + emit dataChanged(this->index(0, 0), this->index(static_cast(m_ESPs.size()) - 1, this->columnCount() - 1)); } void PluginList::refresh(const QString &profileName diff --git a/src/selfupdater.cpp b/src/selfupdater.cpp index c913af6a..b5e7684c 100644 --- a/src/selfupdater.cpp +++ b/src/selfupdater.cpp @@ -338,9 +338,8 @@ void SelfUpdater::installUpdate() } else { reportError(tr("Failed to start %1: %2") .arg(m_UpdateFile.fileName()) - .arg((int)res)); + .arg((INT_PTR)res)); } - m_UpdateFile.remove(); } diff --git a/src/settings.cpp b/src/settings.cpp index f981f811..9267cccf 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -142,7 +142,7 @@ void Settings::registerAsNXMHandler(bool force) } parameters += L" \"" + executable + L"\""; HINSTANCE res = ::ShellExecuteW(nullptr, L"open", nxmPath.c_str(), parameters.c_str(), nullptr, SW_SHOWNORMAL); - if ((int)res <= 32) { + if ((INT_PTR)res <= 32) { QMessageBox::critical(nullptr, tr("Failed"), tr("Sorry, failed to start the helper application")); } diff --git a/src/shared/leaktrace.cpp b/src/shared/leaktrace.cpp index 1ff1fa9d..466162a4 100644 --- a/src/shared/leaktrace.cpp +++ b/src/shared/leaktrace.cpp @@ -1,3 +1,8 @@ +//disable warning messages 4302 , 4311 and 4312 +#pragma warning( disable : 4302 ) +#pragma warning( disable : 4311 ) +#pragma warning( disable : 4312 ) + #include "leaktrace.h" #include "stackdata.h" #include @@ -31,7 +36,7 @@ static struct __TraceData { for (auto iter = result.begin(); iter != result.end(); ++iter) { printf("-----------------------------------\n" "%d objects not freed, allocated at:\n%s", - iter->second.size(), iter->first.toString().c_str()); + static_cast(iter->second.size()), iter->first.toString().c_str()); printf("Addresses: "); for (int i = 0; i < (std::min)(5, static_cast(iter->second.size())); ++i) { @@ -55,3 +60,9 @@ void LeakTrace::TraceDealloc(void *ptr) { __trace.deregTrace(ptr); } + +//re-enable warning messages 4302 , 4311 and 4312 +#pragma warning( default : 4302 ) +#pragma warning( default : 4311 ) +#pragma warning( default : 4312 ) + diff --git a/src/spawn.cpp b/src/spawn.cpp index f8a7bb5f..e1de5c0f 100644 --- a/src/spawn.cpp +++ b/src/spawn.cpp @@ -94,7 +94,7 @@ static bool spawn(LPCWSTR binary, LPCWSTR arguments, LPCWSTR currentDirectory, PROCESS_INFORMATION pi; BOOL success = FALSE; if (hooked) { - qDebug() << "Creating process hooked: <" << QString::fromWCharArray(commandLine, length) <<">"; + qDebug() << "Creating process hooked: <" << QString::fromWCharArray(commandLine, static_cast(length)) <<">"; success = ::CreateProcessHooked(nullptr, commandLine, nullptr, nullptr, // no special process or thread attributes -- cgit v1.3.1 From d24519501fdba4fb5418da3f99e2b36ccef07826 Mon Sep 17 00:00:00 2001 From: LostDragonist Date: Fri, 11 Jan 2019 17:51:09 -0600 Subject: Delete the settings array before writing a new one --- src/editexecutablesdialog.cpp | 1 + src/modinfodialog.cpp | 1 + src/modinforegular.cpp | 1 + src/organizercore.cpp | 1 + src/settings.cpp | 1 + 5 files changed, 5 insertions(+) (limited to 'src/settings.cpp') diff --git a/src/editexecutablesdialog.cpp b/src/editexecutablesdialog.cpp index bea497ef..78e1accb 100644 --- a/src/editexecutablesdialog.cpp +++ b/src/editexecutablesdialog.cpp @@ -124,6 +124,7 @@ void EditExecutablesDialog::saveExecutable() m_Profile->removeSetting("custom_overwrites", ui->titleEdit->text()); } + m_Profile->removeForcedLibraries(ui->titleEdit->text()); m_Profile->storeForcedLibraries(ui->titleEdit->text(), m_ForcedLibraries); m_Profile->setForcedLibrariesEnabled(ui->titleEdit->text(), ui->forceLoadCheckBox->isChecked()); } diff --git a/src/modinfodialog.cpp b/src/modinfodialog.cpp index ed77f596..40fae0e4 100644 --- a/src/modinfodialog.cpp +++ b/src/modinfodialog.cpp @@ -562,6 +562,7 @@ void ModInfoDialog::openIniFile(const QString &fileName) void ModInfoDialog::saveIniTweaks() { + m_Settings->remove("INI Tweaks"); m_Settings->beginWriteArray("INI Tweaks"); int countEnabled = 0; diff --git a/src/modinforegular.cpp b/src/modinforegular.cpp index 45c3985b..185f0495 100644 --- a/src/modinforegular.cpp +++ b/src/modinforegular.cpp @@ -162,6 +162,7 @@ void ModInfoRegular::saveMeta() metaFile.setValue("endorsed", m_EndorsedState); } + metaFile.remove("installedFiles"); metaFile.beginWriteArray("installedFiles"); int idx = 0; for (auto iter = m_InstalledFileIDs.begin(); iter != m_InstalledFileIDs.end(); ++iter) { diff --git a/src/organizercore.cpp b/src/organizercore.cpp index 4e399ac7..e72b9a50 100644 --- a/src/organizercore.cpp +++ b/src/organizercore.cpp @@ -907,6 +907,7 @@ MOBase::IModInterface *OrganizerCore::createMod(GuessedValue &name) settingsFile.setValue("category", 0); settingsFile.setValue("installationFile", ""); + settingsFile.remove("installedFiles"); settingsFile.beginWriteArray("installedFiles", 0); settingsFile.endArray(); } diff --git a/src/settings.cpp b/src/settings.cpp index 9267cccf..c4228f65 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -592,6 +592,7 @@ void Settings::addBlacklistPlugin(const QString &fileName) void Settings::writePluginBlacklist() { + m_Settings.remove("pluginBlacklist"); m_Settings.beginWriteArray("pluginBlacklist"); int idx = 0; for (const QString &plugin : m_PluginBlacklist) { -- cgit v1.3.1 From a853b07953b1bfa79ea7885fd4183bfc6f8091e0 Mon Sep 17 00:00:00 2001 From: LostDragonist Date: Fri, 25 Jan 2019 10:35:58 -0600 Subject: Change archive parsing to experimental and default to disabled --- src/settings.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/settings.cpp b/src/settings.cpp index 95d7af49..40d6d010 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -494,7 +494,7 @@ uint Settings::getMotDHash() const bool Settings::archiveParsing() const { - return m_Settings.value("Settings/archive_parsing", true).toBool(); + return m_Settings.value("Settings/archive_parsing_experimental", false).toBool(); } QVariant Settings::pluginSetting(const QString &pluginName, const QString &key) const @@ -1166,7 +1166,7 @@ void Settings::WorkaroundsTab::update() m_Settings.setValue("Settings/force_enable_core_files", m_forceEnableBox->isChecked()); m_Settings.setValue("Settings/display_foreign", m_displayForeignBox->isChecked()); m_Settings.setValue("Settings/lock_gui", m_lockGUIBox->isChecked()); - m_Settings.setValue("Settings/archive_parsing", m_enableArchiveParsingBox->isChecked()); + m_Settings.setValue("Settings/archive_parsing_experimental", m_enableArchiveParsingBox->isChecked()); m_Settings.setValue("Settings/executable_blacklist", m_dialog.getExecutableBlacklist()); -- cgit v1.3.1 From 10336caf9edca2204a64955903f865de6e2b6cb2 Mon Sep 17 00:00:00 2001 From: LostDragonist Date: Tue, 5 Feb 2019 19:39:10 -0600 Subject: Add Discord, GOG Galaxy, and Spotify to default blacklist --- src/settings.cpp | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src/settings.cpp') diff --git a/src/settings.cpp b/src/settings.cpp index 40d6d010..0ce647fd 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -424,6 +424,9 @@ QString Settings::executablesBlacklist() const << "TGitCache.exe" << "Steam.exe" << "GameOverlayUI.exe" + << "Discord.exe" + << "GalaxyClient.exe" + << "Spotify.exe" ).join(";") ).toString(); } -- cgit v1.3.1 From 9fe2f6126dc7b9396d188b57ccb097f0035f57b7 Mon Sep 17 00:00:00 2001 From: Silarn Date: Mon, 20 Aug 2018 18:34:31 -0500 Subject: Initial Nexus API changes: - Switch to SSO with WebSocket - Update endpoints (all but version checking) --- src/CMakeLists.txt | 7 +- src/credentialsdialog.cpp | 10 - src/credentialsdialog.h | 3 - src/downloadmanager.cpp | 19 +- src/main.cpp | 5 +- src/mainwindow.cpp | 13112 ++++++++++++++++++++++---------------------- src/modinforegular.cpp | 23 +- src/nexusinterface.cpp | 101 +- src/nexusinterface.h | 10 +- src/nxmaccessmanager.cpp | 615 +-- src/nxmaccessmanager.h | 61 +- src/organizer_en.ts | 2936 +++++----- src/organizercore.cpp | 4946 +++++++++-------- src/organizercore.h | 5 +- src/settings.cpp | 48 +- src/settings.h | 12 +- src/settingsdialog.cpp | 42 + src/settingsdialog.h | 340 +- src/settingsdialog.ui | 44 +- 19 files changed, 10893 insertions(+), 11446 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 5cbd5aa9..a518ccd4 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -267,6 +267,7 @@ FIND_PACKAGE(Qt5Quick REQUIRED) FIND_PACKAGE(Qt5Network REQUIRED) FIND_PACKAGE(Qt5WinExtras REQUIRED) FIND_PACKAGE(Qt5WebEngineWidgets REQUIRED) +FIND_PACKAGE(Qt5WebSockets REQUIRED) FIND_PACKAGE(Qt5Qml REQUIRED) FIND_PACKAGE(Qt5LinguistTools) QT5_WRAP_UI(organizer_UIHDRS ${organizer_UIS}) @@ -325,7 +326,7 @@ ENDIF() ADD_EXECUTABLE(ModOrganizer WIN32 ${organizer_HDRS} ${organizer_SRCS} ${organizer_UIHDRS} ${organizer_RCS} ${organizer_RCCPPS} ${organizer_translations_qm}) TARGET_LINK_LIBRARIES(ModOrganizer Qt5::Widgets Qt5::WinExtras Qt5::WebEngineWidgets Qt5::Quick - Qt5::Qml Qt5::QuickWidgets Qt5::Network + Qt5::Qml Qt5::QuickWidgets Qt5::Network Qt5::WebSockets ${Boost_LIBRARIES} zlibstatic uibase esptk bsatk githubpp @@ -368,12 +369,12 @@ SET(windeploy_parameters "--no-translations --plugindir qtplugins --libdir dlls INSTALL( CODE "EXECUTE_PROCESS(COMMAND - ${qt5bin}/windeployqt.exe ModOrganizer.exe --webenginewidgets ${windeploy_parameters} + ${qt5bin}/windeployqt.exe ModOrganizer.exe --webenginewidgets --websockets ${windeploy_parameters} WORKING_DIRECTORY ${CMAKE_INSTALL_PREFIX}/bin ) # run it a second time because on the first run it misses some files EXECUTE_PROCESS(COMMAND - ${qt5bin}/windeployqt.exe ModOrganizer.exe --webenginewidgets ${windeploy_parameters} + ${qt5bin}/windeployqt.exe ModOrganizer.exe --webenginewidgets --websockets ${windeploy_parameters} WORKING_DIRECTORY ${CMAKE_INSTALL_PREFIX}/bin ) EXECUTE_PROCESS(COMMAND diff --git a/src/credentialsdialog.cpp b/src/credentialsdialog.cpp index 04774548..73e75387 100644 --- a/src/credentialsdialog.cpp +++ b/src/credentialsdialog.cpp @@ -32,16 +32,6 @@ CredentialsDialog::~CredentialsDialog() delete ui; } -QString CredentialsDialog::username() const -{ - return ui->usernameEdit->text(); -} - -QString CredentialsDialog::password() const -{ - return ui->passwordEdit->text(); -} - bool CredentialsDialog::store() const { return ui->rememberCheck->isChecked(); diff --git a/src/credentialsdialog.h b/src/credentialsdialog.h index 8a68c7d8..2f3bcbb7 100644 --- a/src/credentialsdialog.h +++ b/src/credentialsdialog.h @@ -34,9 +34,6 @@ public: explicit CredentialsDialog(QWidget *parent = 0); ~CredentialsDialog(); - QString username() const; - QString password() const; - bool store() const; bool neverAsk() const; diff --git a/src/downloadmanager.cpp b/src/downloadmanager.cpp index ab8da7b8..c927695e 100644 --- a/src/downloadmanager.cpp +++ b/src/downloadmanager.cpp @@ -1536,10 +1536,10 @@ void DownloadManager::nxmFileInfoAvailable(QString gameName, int modID, int file if (!info->version.isValid()) { info->version = info->newestVersion; } - info->fileName = result["uri"].toString(); + info->fileName = result["file_name"].toString(); info->fileCategory = result["category_id"].toInt(); - info->fileTime = matchDate(result["date"].toString()); - info->description = BBCode::convertToHTML(result["description"].toString()); + info->fileTime = matchDate(result["uploaded_timestamp"].toString()); + info->description = BBCode::convertToHTML(result["changelog_html"].toString()); info->repository = "Nexus"; info->gameName = gameName; @@ -1554,23 +1554,12 @@ static int evaluateFileInfoMap(const QVariantMap &map, const std::mapsecond * 20; } - if (map["IsPremium"].toBool()) result += 5; - return result; } diff --git a/src/main.cpp b/src/main.cpp index 275845e2..631ec5b5 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -621,7 +621,10 @@ int runApplication(MOApplication &application, SingleInstance &instance, splash.show(); splash.activateWindow(); - NexusInterface::instance(&pluginContainer)->getAccessManager()->startLoginCheck(); + QString apiKey; + if (organizer.settings().getNexusApiKey(apiKey)) { + NexusInterface::instance(&pluginContainer)->getAccessManager()->apiCheck(apiKey); + } qDebug("initializing tutorials"); TutorialManager::init( diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index a30fdaac..add1ef7f 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -1,6554 +1,6558 @@ -/* -Copyright (C) 2012 Sebastian Herbord. All rights reserved. - -This file is part of Mod Organizer. - -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 . -*/ - -#include "mainwindow.h" -#include "ui_mainwindow.h" - -#include "directoryentry.h" -#include "directoryrefresher.h" -#include "executableinfo.h" -#include "executableslist.h" -#include "guessedvalue.h" -#include "imodinterface.h" -#include "iplugingame.h" -#include "iplugindiagnose.h" -#include "isavegame.h" -#include "isavegameinfowidget.h" -#include "nexusinterface.h" -#include "organizercore.h" -#include "pluginlistsortproxy.h" -#include "previewgenerator.h" -#include "serverinfo.h" -#include "savegameinfo.h" -#include "spawn.h" -#include "versioninfo.h" -#include "instancemanager.h" - -#include "report.h" -#include "modlist.h" -#include "modlistsortproxy.h" -#include "qtgroupingproxy.h" -#include "profile.h" -#include "pluginlist.h" -#include "profilesdialog.h" -#include "editexecutablesdialog.h" -#include "categories.h" -#include "categoriesdialog.h" -#include "modinfodialog.h" -#include "overwriteinfodialog.h" -#include "activatemodsdialog.h" -#include "downloadlist.h" -#include "downloadlistwidget.h" -#include "messagedialog.h" -#include "installationmanager.h" -#include "lockeddialog.h" -#include "waitingonclosedialog.h" -#include "logbuffer.h" -#include "downloadlistsortproxy.h" -#include "motddialog.h" -#include "filedialogmemory.h" -#include "tutorialmanager.h" -#include "modflagicondelegate.h" -#include "genericicondelegate.h" -#include "selectiondialog.h" -#include "csvbuilder.h" -#include "savetextasdialog.h" -#include "problemsdialog.h" -#include "previewdialog.h" -#include "browserdialog.h" -#include "aboutdialog.h" -#include -#include "nxmaccessmanager.h" -#include "appconfig.h" -#include "eventfilter.h" -#include -#include -#include -#include -#include -#include -#include "localsavegames.h" -#include "listdialog.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#ifndef Q_MOC_RUN -#include -#include -#include -#include -#include -#endif - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef TEST_MODELS -#include "modeltest.h" -#endif // TEST_MODELS - -#pragma warning( disable : 4428 ) - -using namespace MOBase; -using namespace MOShared; - - -MainWindow::MainWindow(QSettings &initSettings - , OrganizerCore &organizerCore - , PluginContainer &pluginContainer - , QWidget *parent) - : QMainWindow(parent) - , ui(new Ui::MainWindow) - , m_WasVisible(false) - , m_Tutorial(this, "MainWindow") - , m_OldProfileIndex(-1) - , m_ModListGroupingProxy(nullptr) - , m_ModListSortProxy(nullptr) - , m_OldExecutableIndex(-1) - , m_CategoryFactory(CategoryFactory::instance()) - , m_ContextItem(nullptr) - , m_ContextAction(nullptr) - , m_ContextRow(-1) - , m_CurrentSaveView(nullptr) - , m_OrganizerCore(organizerCore) - , m_PluginContainer(pluginContainer) - , m_DidUpdateMasterList(false) - , m_ArchiveListWriter(std::bind(&MainWindow::saveArchiveList, this)) -{ - QWebEngineProfile::defaultProfile()->setPersistentCookiesPolicy(QWebEngineProfile::NoPersistentCookies); - QWebEngineProfile::defaultProfile()->setHttpCacheMaximumSize(52428800); - QWebEngineProfile::defaultProfile()->setCachePath(m_OrganizerCore.settings().getCacheDirectory()); - QWebEngineProfile::defaultProfile()->setPersistentStoragePath(m_OrganizerCore.settings().getCacheDirectory()); - ui->setupUi(this); - updateWindowTitle(QString(), false); - - languageChange(m_OrganizerCore.settings().language()); - - m_CategoryFactory.loadCategories(); - - ui->logList->setModel(LogBuffer::instance()); - ui->logList->setColumnWidth(0, 100); - ui->logList->setAutoScroll(true); - ui->logList->scrollToBottom(); - ui->logList->addAction(ui->actionCopy_Log_to_Clipboard); - int splitterSize = this->size().height(); // actually total window size, but the splitter doesn't seem to return the true value - ui->topLevelSplitter->setSizes(QList() << splitterSize - 100 << 100); - connect(ui->logList->model(), SIGNAL(rowsInserted(const QModelIndex &, int, int)), - ui->logList, SLOT(scrollToBottom())); - connect(ui->logList->model(), SIGNAL(dataChanged(QModelIndex,QModelIndex)), - ui->logList, SLOT(scrollToBottom())); - - m_RefreshProgress = new QProgressBar(statusBar()); - m_RefreshProgress->setTextVisible(true); - m_RefreshProgress->setRange(0, 100); - m_RefreshProgress->setValue(0); - m_RefreshProgress->setVisible(false); - statusBar()->addWidget(m_RefreshProgress, 1000); - statusBar()->clearMessage(); - statusBar()->hide(); - - updateProblemsButton(); - - // Setup toolbar - QWidget *spacer = new QWidget(ui->toolBar); - spacer->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred); - QWidget *widget = ui->toolBar->widgetForAction(ui->actionTool); - QToolButton *toolBtn = qobject_cast(widget); - - if (toolBtn->menu() == nullptr) { - actionToToolButton(ui->actionTool); - } - - actionToToolButton(ui->actionHelp); - createHelpWidget(); - - actionToToolButton(ui->actionEndorseMO); - createEndorseWidget(); - ui->actionEndorseMO->setVisible(false); - - for (QAction *action : ui->toolBar->actions()) { - if (action->isSeparator()) { - // insert spacers - ui->toolBar->insertWidget(action, spacer); - m_Sep = action; - // m_Sep would only use the last separator anyway, and we only have the one anyway? - break; - } - } - - TaskProgressManager::instance().tryCreateTaskbar(); - - // set up mod list - m_ModListSortProxy = m_OrganizerCore.createModListProxyModel(); - - ui->modList->setModel(m_ModListSortProxy); - - GenericIconDelegate *contentDelegate = new GenericIconDelegate(ui->modList, Qt::UserRole + 3, ModList::COL_CONTENT, 150); - connect(ui->modList->header(), SIGNAL(sectionResized(int,int,int)), contentDelegate, SLOT(columnResized(int,int,int))); - ui->modList->sortByColumn(ModList::COL_PRIORITY, Qt::AscendingOrder); - ModFlagIconDelegate *flagDelegate = new ModFlagIconDelegate(ui->modList, ModList::COL_FLAGS, 120); - connect(ui->modList->header(), SIGNAL(sectionResized(int,int,int)), flagDelegate, SLOT(columnResized(int,int,int))); - ui->modList->setItemDelegateForColumn(ModList::COL_FLAGS, flagDelegate); - ui->modList->setItemDelegateForColumn(ModList::COL_CONTENT, contentDelegate); - ui->modList->header()->installEventFilter(m_OrganizerCore.modList()); - connect(ui->modList->header(), SIGNAL(sectionResized(int, int, int)), this, SLOT(modListSectionResized(int, int, int))); - - bool modListAdjusted = registerWidgetState(ui->modList->objectName(), ui->modList->header(), "mod_list_state"); - - if (modListAdjusted) { - // hack: force the resize-signal to be triggered because restoreState doesn't seem to do that - for (int column = 0; column <= ModList::COL_LASTCOLUMN; ++column) { - int sectionSize = ui->modList->header()->sectionSize(column); - ui->modList->header()->resizeSection(column, sectionSize + 1); - ui->modList->header()->resizeSection(column, sectionSize); - } - } else { - // hide these columns by default - ui->modList->header()->setSectionHidden(ModList::COL_CONTENT, true); - ui->modList->header()->setSectionHidden(ModList::COL_MODID, true); - ui->modList->header()->setSectionHidden(ModList::COL_GAME, true); - ui->modList->header()->setSectionHidden(ModList::COL_INSTALLTIME, true); - ui->modList->header()->setSectionHidden(ModList::COL_NOTES, true); - } - - ui->modList->header()->setSectionHidden(ModList::COL_NAME, false); // prevent the name-column from being hidden - ui->modList->installEventFilter(m_OrganizerCore.modList()); - - // set up plugin list - m_PluginListSortProxy = m_OrganizerCore.createPluginListProxyModel(); - - ui->espList->setModel(m_PluginListSortProxy); - ui->espList->sortByColumn(PluginList::COL_PRIORITY, Qt::AscendingOrder); - ui->espList->setItemDelegateForColumn(PluginList::COL_FLAGS, new GenericIconDelegate(ui->espList)); - ui->espList->installEventFilter(m_OrganizerCore.pluginList()); - - ui->bsaList->setLocalMoveOnly(true); - - initDownloadView(); - bool pluginListAdjusted = registerWidgetState(ui->espList->objectName(), ui->espList->header(), "plugin_list_state"); - registerWidgetState(ui->dataTree->objectName(), ui->dataTree->header()); - registerWidgetState(ui->downloadView->objectName(), - ui->downloadView->header()); - - ui->splitter->setStretchFactor(0, 3); - ui->splitter->setStretchFactor(1, 2); - - resizeLists(modListAdjusted, pluginListAdjusted); - - QMenu *linkMenu = new QMenu(this); - linkMenu->addAction(QIcon(":/MO/gui/link"), tr("Toolbar"), this, SLOT(linkToolbar())); - linkMenu->addAction(QIcon(":/MO/gui/link"), tr("Desktop"), this, SLOT(linkDesktop())); - linkMenu->addAction(QIcon(":/MO/gui/link"), tr("Start Menu"), this, SLOT(linkMenu())); - ui->linkButton->setMenu(linkMenu); - - QMenu *listOptionsMenu = new QMenu(ui->listOptionsBtn); - initModListContextMenu(listOptionsMenu); - ui->listOptionsBtn->setMenu(listOptionsMenu); - connect(ui->listOptionsBtn, SIGNAL(pressed()), this, SLOT(on_listOptionsBtn_pressed())); - - ui->openFolderMenu->setMenu(openFolderMenu()); - - ui->savegameList->installEventFilter(this); - ui->savegameList->setMouseTracking(true); - - // don't allow mouse wheel to switch grouping, too many people accidentally - // turn on grouping and then don't understand what happened - EventFilter *noWheel - = new EventFilter(this, [](QObject *, QEvent *event) -> bool { - return event->type() == QEvent::Wheel; - }); - - ui->groupCombo->installEventFilter(noWheel); - ui->profileBox->installEventFilter(noWheel); - - if (organizerCore.managedGame()->sortMechanism() == MOBase::IPluginGame::SortMechanism::NONE) { - ui->bossButton->setDisabled(true); - ui->bossButton->setToolTip(tr("There is no supported sort mechanism for this game. You will probably have to use a third-party tool.")); - } - - connect(ui->savegameList, SIGNAL(itemEntered(QListWidgetItem*)), this, SLOT(saveSelectionChanged(QListWidgetItem*))); - - connect(ui->modList, SIGNAL(dropModeUpdate(bool)), m_OrganizerCore.modList(), SLOT(dropModeUpdate(bool))); - - connect(ui->modList->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)), this, SLOT(modlistSelectionChanged(QModelIndex,QModelIndex))); - connect(m_ModListSortProxy, SIGNAL(filterActive(bool)), this, SLOT(modFilterActive(bool))); - connect(m_ModListSortProxy, SIGNAL(layoutChanged()), this, SLOT(updateModCount())); - connect(ui->modFilterEdit, SIGNAL(textChanged(QString)), m_ModListSortProxy, SLOT(updateFilter(QString))); - - connect(ui->espFilterEdit, SIGNAL(textChanged(QString)), m_PluginListSortProxy, SLOT(updateFilter(QString))); - connect(ui->espFilterEdit, SIGNAL(textChanged(QString)), this, SLOT(espFilterChanged(QString))); - - connect(ui->dataTree, SIGNAL(itemExpanded(QTreeWidgetItem*)), this, SLOT(expandDataTreeItem(QTreeWidgetItem*))); - - connect(m_OrganizerCore.directoryRefresher(), SIGNAL(refreshed()), this, SLOT(directory_refreshed())); - connect(m_OrganizerCore.directoryRefresher(), SIGNAL(progress(int)), this, SLOT(refresher_progress(int))); - connect(m_OrganizerCore.directoryRefresher(), SIGNAL(error(QString)), this, SLOT(showError(QString))); - - connect(&m_SavesWatcher, SIGNAL(directoryChanged(QString)), this, SLOT(refreshSavesIfOpen())); - - connect(&m_OrganizerCore.settings(), SIGNAL(languageChanged(QString)), this, SLOT(languageChange(QString))); - connect(&m_OrganizerCore.settings(), SIGNAL(styleChanged(QString)), this, SIGNAL(styleChanged(QString))); - - connect(m_OrganizerCore.updater(), SIGNAL(restart()), this, SLOT(close())); - connect(m_OrganizerCore.updater(), SIGNAL(updateAvailable()), this, SLOT(updateAvailable())); - connect(m_OrganizerCore.updater(), SIGNAL(motdAvailable(QString)), this, SLOT(motdReceived(QString))); - - connect(NexusInterface::instance(&pluginContainer), SIGNAL(requestNXMDownload(QString)), &m_OrganizerCore, SLOT(downloadRequestedNXM(QString))); - connect(NexusInterface::instance(&pluginContainer), SIGNAL(nxmDownloadURLsAvailable(QString,int,int,QVariant,QVariant,int)), this, SLOT(nxmDownloadURLs(QString,int,int,QVariant,QVariant,int))); - connect(NexusInterface::instance(&pluginContainer), SIGNAL(needLogin()), &m_OrganizerCore, SLOT(nexusLogin())); - connect(NexusInterface::instance(&pluginContainer)->getAccessManager(), SIGNAL(loginFailed(QString)), this, SLOT(loginFailed(QString))); - connect(NexusInterface::instance(&pluginContainer)->getAccessManager(), SIGNAL(credentialsReceived(const QString&, bool)), - this, SLOT(updateWindowTitle(const QString&, bool))); - - connect(&TutorialManager::instance(), SIGNAL(windowTutorialFinished(QString)), this, SLOT(windowTutorialFinished(QString))); - connect(ui->tabWidget, SIGNAL(currentChanged(int)), &TutorialManager::instance(), SIGNAL(tabChanged(int))); - connect(ui->modList->header(), SIGNAL(sortIndicatorChanged(int,Qt::SortOrder)), this, SLOT(modListSortIndicatorChanged(int,Qt::SortOrder))); - connect(ui->toolBar, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(toolBar_customContextMenuRequested(QPoint))); - - connect(&m_OrganizerCore, &OrganizerCore::modInstalled, this, &MainWindow::modInstalled); - connect(&m_OrganizerCore, &OrganizerCore::close, this, &QMainWindow::close); - - connect(&m_IntegratedBrowser, SIGNAL(requestDownload(QUrl,QNetworkReply*)), &m_OrganizerCore, SLOT(requestDownload(QUrl,QNetworkReply*))); - - connect(this, SIGNAL(styleChanged(QString)), this, SLOT(updateStyle(QString))); - - m_CheckBSATimer.setSingleShot(true); - connect(&m_CheckBSATimer, SIGNAL(timeout()), this, SLOT(checkBSAList())); - - connect(ui->espList->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this, SLOT(esplistSelectionsChanged(QItemSelection))); - connect(ui->modList->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this, SLOT(modlistSelectionsChanged(QItemSelection))); - - new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Enter), this, SLOT(openExplorer_activated())); - new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Return), this, SLOT(openExplorer_activated())); - - new QShortcut(QKeySequence::Refresh, this, SLOT(refreshProfile_activated())); - - new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_F), this, SLOT(search_activated())); - new QShortcut(QKeySequence(Qt::Key_Escape), this, SLOT(searchClear_activated())); - - m_UpdateProblemsTimer.setSingleShot(true); - connect(&m_UpdateProblemsTimer, SIGNAL(timeout()), this, SLOT(updateProblemsButton())); - - m_SaveMetaTimer.setSingleShot(false); - connect(&m_SaveMetaTimer, SIGNAL(timeout()), this, SLOT(saveModMetas())); - m_SaveMetaTimer.start(5000); - - setCategoryListVisible(initSettings.value("categorylist_visible", true).toBool()); - FileDialogMemory::restore(initSettings); - - fixCategories(); - - m_StartTime = QTime::currentTime(); - - m_Tutorial.expose("modList", m_OrganizerCore.modList()); - m_Tutorial.expose("espList", m_OrganizerCore.pluginList()); - - m_OrganizerCore.setUserInterface(this, this); - for (const QString &fileName : m_PluginContainer.pluginFileNames()) { - installTranslator(QFileInfo(fileName).baseName()); - } - - registerPluginTools(m_PluginContainer.plugins()); - - for (IPluginModPage *modPagePlugin : m_PluginContainer.plugins()) { - registerModPage(modPagePlugin); - } - - // refresh profiles so the current profile can be activated - refreshProfiles(false); - - ui->profileBox->setCurrentText(m_OrganizerCore.currentProfile()->name()); - - if (m_OrganizerCore.getArchiveParsing()) - { - ui->showArchiveDataCheckBox->setCheckState(Qt::Checked); - ui->showArchiveDataCheckBox->setEnabled(true); - m_showArchiveData = true; - } - else - { - ui->showArchiveDataCheckBox->setCheckState(Qt::Unchecked); - ui->showArchiveDataCheckBox->setEnabled(false); - m_showArchiveData = false; - } - - refreshExecutablesList(); - updateToolBar(); - - for (QAction *action : ui->toolBar->actions()) { - // set the name of the widget to the name of the action to allow styling - QWidget *actionWidget = ui->toolBar->widgetForAction(action); - actionWidget->setObjectName(action->objectName()); - actionWidget->style()->unpolish(actionWidget); - actionWidget->style()->polish(actionWidget); - } - - updatePluginCount(); - updateModCount(); -} - - -MainWindow::~MainWindow() -{ - try { - cleanup(); - - m_PluginContainer.setUserInterface(nullptr, nullptr); - m_OrganizerCore.setUserInterface(nullptr, nullptr); - m_IntegratedBrowser.close(); - delete ui; - } catch (std::exception &e) { - QMessageBox::critical(nullptr, tr("Crash on exit"), - tr("MO crashed while exiting. Some settings may not be saved.\n\nError: %1").arg(e.what()), - QMessageBox::Ok); - } -} - - -void MainWindow::updateWindowTitle(const QString &accountName, bool premium) -{ - QString title = QString("%1 Mod Organizer v%2").arg( - m_OrganizerCore.managedGame()->gameName(), - m_OrganizerCore.getVersion().displayString(3)); - - if (!accountName.isEmpty()) { - title.append(QString(" (%1%2)").arg(accountName, premium ? "*" : "")); - } - - this->setWindowTitle(title); -} - - -void MainWindow::disconnectPlugins() -{ - if (ui->actionTool->menu() != nullptr) { - ui->actionTool->menu()->clear(); - } -} - - -void MainWindow::resizeLists(bool modListCustom, bool pluginListCustom) -{ - if (!modListCustom) { - // resize mod list to fit content - for (int i = 0; i < ui->modList->header()->count(); ++i) { - ui->modList->header()->setSectionResizeMode(i, QHeaderView::ResizeToContents); - } - ui->modList->header()->setSectionResizeMode(ModList::COL_NAME, QHeaderView::Stretch); - } - - // ensure the columns aren't so small you can't see them any more - for (int i = 0; i < ui->modList->header()->count(); ++i) { - if (ui->modList->header()->sectionSize(i) < 10) { - ui->modList->header()->resizeSection(i, 10); - } - } - - if (!pluginListCustom) { - // resize plugin list to fit content - for (int i = 0; i < ui->espList->header()->count(); ++i) { - ui->espList->header()->setSectionResizeMode(i, QHeaderView::ResizeToContents); - } - ui->espList->header()->setSectionResizeMode(0, QHeaderView::Stretch); - } -} - - -void MainWindow::allowListResize() -{ - // allow resize on mod list - for (int i = 0; i < ui->modList->header()->count(); ++i) { - ui->modList->header()->setSectionResizeMode(i, QHeaderView::Interactive); - } - //ui->modList->header()->setSectionResizeMode(ui->modList->header()->count() - 1, QHeaderView::Stretch); - ui->modList->header()->setStretchLastSection(true); - - - // allow resize on plugin list - for (int i = 0; i < ui->espList->header()->count(); ++i) { - ui->espList->header()->setSectionResizeMode(i, QHeaderView::Interactive); - } - //ui->espList->header()->setSectionResizeMode(ui->espList->header()->count() - 1, QHeaderView::Stretch); - ui->espList->header()->setStretchLastSection(true); -} - -void MainWindow::updateStyle(const QString&) -{ - // no effect? - ensurePolished(); -} - -void MainWindow::resizeEvent(QResizeEvent *event) -{ - m_Tutorial.resize(event->size()); - QMainWindow::resizeEvent(event); -} - - -static QModelIndex mapToModel(const QAbstractItemModel *targetModel, QModelIndex idx) -{ - QModelIndex result = idx; - const QAbstractItemModel *model = idx.model(); - while (model != targetModel) { - if (model == nullptr) { - return QModelIndex(); - } - const QAbstractProxyModel *proxyModel = qobject_cast(model); - if (proxyModel == nullptr) { - return QModelIndex(); - } - result = proxyModel->mapToSource(result); - model = proxyModel->sourceModel(); - } - return result; -} - - -void MainWindow::actionToToolButton(QAction *&sourceAction) -{ - QToolButton *button = new QToolButton(ui->toolBar); - button->setObjectName(sourceAction->objectName()); - button->setIcon(sourceAction->icon()); - button->setText(sourceAction->text()); - button->setPopupMode(QToolButton::InstantPopup); - button->setToolButtonStyle(ui->toolBar->toolButtonStyle()); - button->setToolTip(sourceAction->toolTip()); - button->setShortcut(sourceAction->shortcut()); - QMenu *buttonMenu = new QMenu(sourceAction->text(), button); - button->setMenu(buttonMenu); - QAction *newAction = ui->toolBar->insertWidget(sourceAction, button); - newAction->setObjectName(sourceAction->objectName()); - newAction->setIcon(sourceAction->icon()); - newAction->setText(sourceAction->text()); - newAction->setToolTip(sourceAction->toolTip()); - newAction->setShortcut(sourceAction->shortcut()); - ui->toolBar->removeAction(sourceAction); - sourceAction->deleteLater(); - sourceAction = newAction; -} - -void MainWindow::updateToolBar() -{ - for (QAction *action : ui->toolBar->actions()) { - if (action->objectName().startsWith("custom__")) { - ui->toolBar->removeAction(action); - action->deleteLater(); - } - } - - std::vector::iterator begin, end; - m_OrganizerCore.executablesList()->getExecutables(begin, end); - for (auto iter = begin; iter != end; ++iter) { - if (iter->isShownOnToolbar()) { - QAction *exeAction = new QAction(iconForExecutable(iter->m_BinaryInfo.filePath()), - iter->m_Title, - ui->toolBar); - exeAction->setObjectName(QString("custom__") + iter->m_Title); - if (!connect(exeAction, SIGNAL(triggered()), this, SLOT(startExeAction()))) { - qDebug("failed to connect trigger?"); - } - ui->toolBar->insertAction(m_Sep, exeAction); - } - } -} - - -void MainWindow::scheduleUpdateButton() -{ - if (!m_UpdateProblemsTimer.isActive()) { - m_UpdateProblemsTimer.start(1000); - } -} - - -void MainWindow::updateProblemsButton() -{ - size_t numProblems = checkForProblems(); - if (numProblems > 0) { - ui->actionNotifications->setEnabled(true); - ui->actionNotifications->setIconText(tr("Notifications")); - ui->actionNotifications->setToolTip(tr("There are notifications to read")); - - QPixmap mergedIcon = QPixmap(":/MO/gui/warning").scaled(64, 64); - { - QPainter painter(&mergedIcon); - std::string badgeName = std::string(":/MO/gui/badge_") + (numProblems < 10 ? std::to_string(static_cast(numProblems)) : "more"); - painter.drawPixmap(32, 32, 32, 32, QPixmap(badgeName.c_str())); - } - ui->actionNotifications->setIcon(QIcon(mergedIcon)); - } else { - ui->actionNotifications->setEnabled(false); - ui->actionNotifications->setIconText(tr("No Notifications")); - ui->actionNotifications->setToolTip(tr("There are no notifications")); - ui->actionNotifications->setIcon(QIcon(":/MO/gui/warning")); - } -} - - -bool MainWindow::errorReported(QString &logFile) -{ - QDir dir(qApp->property("dataPath").toString() + "/" + QString::fromStdWString(AppConfig::logPath())); - QFileInfoList files = dir.entryInfoList(QStringList("ModOrganizer_??_??_??_??_??.log"), - QDir::Files, QDir::Name | QDir::Reversed); - - if (files.count() > 0) { - logFile = files.at(0).absoluteFilePath(); - QFile file(logFile); - if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { - char buffer[1024]; - int line = 0; - while (!file.atEnd()) { - file.readLine(buffer, 1024); - if (strncmp(buffer, "ERROR", 5) == 0) { - return true; - } - - // prevent this function from taking forever - if (line++ >= 50000) { - break; - } - } - } - } - - return false; -} - - -size_t MainWindow::checkForProblems() -{ - size_t numProblems = 0; - for (IPluginDiagnose *diagnose : m_PluginContainer.plugins()) { - numProblems += diagnose->activeProblems().size(); - } - return numProblems; -} - -void MainWindow::about() -{ - AboutDialog dialog(m_OrganizerCore.getVersion().displayString(3), this); - connect(&dialog, SIGNAL(linkClicked(QString)), this, SLOT(linkClicked(QString))); - dialog.exec(); -} - - -void MainWindow::createEndorseWidget() -{ - QToolButton *toolBtn = qobject_cast(ui->toolBar->widgetForAction(ui->actionEndorseMO)); - QMenu *buttonMenu = toolBtn->menu(); - if (buttonMenu == nullptr) { - return; - } - buttonMenu->clear(); - - QAction *endorseAction = new QAction(tr("Endorse"), buttonMenu); - connect(endorseAction, SIGNAL(triggered()), this, SLOT(on_actionEndorseMO_triggered())); - buttonMenu->addAction(endorseAction); - - QAction *wontEndorseAction = new QAction(tr("Won't Endorse"), buttonMenu); - connect(wontEndorseAction, SIGNAL(triggered()), this, SLOT(wontEndorse())); - buttonMenu->addAction(wontEndorseAction); -} - - -void MainWindow::createHelpWidget() -{ - QToolButton *toolBtn = qobject_cast(ui->toolBar->widgetForAction(ui->actionHelp)); - QMenu *buttonMenu = toolBtn->menu(); - if (buttonMenu == nullptr) { - return; - } - buttonMenu->clear(); - - QAction *helpAction = new QAction(tr("Help on UI"), buttonMenu); - connect(helpAction, SIGNAL(triggered()), this, SLOT(helpTriggered())); - buttonMenu->addAction(helpAction); - - QAction *wikiAction = new QAction(tr("Documentation"), buttonMenu); - connect(wikiAction, SIGNAL(triggered()), this, SLOT(wikiTriggered())); - buttonMenu->addAction(wikiAction); - - QAction *discordAction = new QAction(tr("Chat on Discord"), buttonMenu); - connect(discordAction, SIGNAL(triggered()), this, SLOT(discordTriggered())); - buttonMenu->addAction(discordAction); - - QAction *issueAction = new QAction(tr("Report Issue"), buttonMenu); - connect(issueAction, SIGNAL(triggered()), this, SLOT(issueTriggered())); - buttonMenu->addAction(issueAction); - - QMenu *tutorialMenu = new QMenu(tr("Tutorials"), buttonMenu); - - typedef std::vector > ActionList; - - ActionList tutorials; - - QDirIterator dirIter(QApplication::applicationDirPath() + "/tutorials", QStringList("*.js"), QDir::Files); - while (dirIter.hasNext()) { - dirIter.next(); - QString fileName = dirIter.fileName(); - - QFile file(dirIter.filePath()); - if (!file.open(QIODevice::ReadOnly)) { - qCritical() << "Failed to open " << fileName; - continue; - } - QString firstLine = QString::fromUtf8(file.readLine()); - if (firstLine.startsWith("//TL")) { - QStringList params = firstLine.mid(4).trimmed().split('#'); - if (params.size() != 2) { - qCritical() << "invalid header line for tutorial " << fileName << " expected 2 parameters"; - continue; - } - QAction *tutAction = new QAction(params.at(0), tutorialMenu); - tutAction->setData(fileName); - tutorials.push_back(std::make_pair(params.at(1).toInt(), tutAction)); - } - } - - std::sort(tutorials.begin(), tutorials.end(), - [] (const ActionList::value_type &LHS, const ActionList::value_type &RHS) { - return LHS.first < RHS.first; } ); - - for (auto iter = tutorials.begin(); iter != tutorials.end(); ++iter) { - connect(iter->second, SIGNAL(triggered()), this, SLOT(tutorialTriggered())); - tutorialMenu->addAction(iter->second); - } - - buttonMenu->addMenu(tutorialMenu); - buttonMenu->addAction(tr("About"), this, SLOT(about())); - buttonMenu->addAction(tr("About Qt"), qApp, SLOT(aboutQt())); -} - -void MainWindow::modFilterActive(bool filterActive) -{ - ui->clearFiltersButton->setVisible(filterActive); - if (filterActive) { -// m_OrganizerCore.modList()->setOverwriteMarkers(std::set(), std::set()); - ui->modList->setStyleSheet("QTreeView { border: 2px ridge #f00; }"); - ui->activeModsCounter->setStyleSheet("QLCDNumber { border: 2px ridge #f00; }"); - } else if (ui->groupCombo->currentIndex() != 0) { - ui->modList->setStyleSheet("QTreeView { border: 2px ridge #337733; }"); - ui->activeModsCounter->setStyleSheet(""); - } else { - ui->modList->setStyleSheet(""); - ui->activeModsCounter->setStyleSheet(""); - } -} - -void MainWindow::espFilterChanged(const QString &filter) -{ - if (!filter.isEmpty()) { - ui->espList->setStyleSheet("QTreeView { border: 2px ridge #f00; }"); - ui->activePluginsCounter->setStyleSheet("QLCDNumber { border: 2px ridge #f00; }"); - } else { - ui->espList->setStyleSheet(""); - ui->activePluginsCounter->setStyleSheet(""); - } - updatePluginCount(); -} - -void MainWindow::downloadFilterChanged(const QString &filter) -{ - if (!filter.isEmpty()) { - ui->downloadView->setStyleSheet("QTreeView { border: 2px ridge #f00; }"); - } else { - ui->downloadView->setStyleSheet(""); - } -} - -void MainWindow::expandModList(const QModelIndex &index) -{ - QAbstractItemModel *model = ui->modList->model(); -#pragma message("why is this so complicated? mapping the index doesn't work, probably a bug in QtGroupingProxy?") - for (int i = 0; i < model->rowCount(); ++i) { - QModelIndex targetIdx = model->index(i, 0); - if (model->data(targetIdx).toString() == index.data().toString()) { - ui->modList->expand(targetIdx); - break; - } - } -} - - -bool MainWindow::addProfile() -{ - QComboBox *profileBox = findChild("profileBox"); - bool okClicked = false; - - QString name = QInputDialog::getText(this, tr("Name"), - tr("Please enter a name for the new profile"), - QLineEdit::Normal, QString(), &okClicked); - if (okClicked && (name.size() > 0)) { - try { - profileBox->addItem(name); - profileBox->setCurrentIndex(profileBox->count() - 1); - return true; - } catch (const std::exception& e) { - reportError(tr("failed to create profile: %1").arg(e.what())); - return false; - } - } else { - return false; - } -} - -void MainWindow::hookUpWindowTutorials() -{ - QDirIterator dirIter(QApplication::applicationDirPath() + "/tutorials", QStringList("*.js"), QDir::Files); - while (dirIter.hasNext()) { - dirIter.next(); - QString fileName = dirIter.fileName(); - QFile file(dirIter.filePath()); - if (!file.open(QIODevice::ReadOnly)) { - qCritical() << "Failed to open " << fileName; - continue; - } - QString firstLine = QString::fromUtf8(file.readLine()); - if (firstLine.startsWith("//WIN")) { - QString windowName = firstLine.mid(6).trimmed(); - if (!m_OrganizerCore.settings().directInterface().value("CompletedWindowTutorials/" + windowName, false).toBool()) { - TutorialManager::instance().activateTutorial(windowName, fileName); - } - } - } -} - -void MainWindow::showEvent(QShowEvent *event) -{ - refreshFilters(); - - QMainWindow::showEvent(event); - - if (!m_WasVisible) { - // only the first time the window becomes visible - m_Tutorial.registerControl(); - - hookUpWindowTutorials(); - - if (m_OrganizerCore.settings().directInterface().value("first_start", true).toBool()) { - QString firstStepsTutorial = ToQString(AppConfig::firstStepsTutorial()); - if (TutorialManager::instance().hasTutorial(firstStepsTutorial)) { - if (QMessageBox::question(this, tr("Show tutorial?"), - tr("You are starting Mod Organizer for the first time. " - "Do you want to show a tutorial of its basic features? If you choose " - "no you can always start the tutorial from the \"Help\"-menu."), - QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { - TutorialManager::instance().activateTutorial("MainWindow", firstStepsTutorial); - } - } else { - qCritical() << firstStepsTutorial << " missing"; - QPoint pos = ui->toolBar->mapToGlobal(QPoint()); - pos.rx() += ui->toolBar->width() / 2; - pos.ry() += ui->toolBar->height(); - QWhatsThis::showText(pos, - QObject::tr("Please use \"Help\" from the toolbar to get usage instructions to all elements")); - } - - m_OrganizerCore.settings().directInterface().setValue("first_start", false); - } - - // this has no visible impact when called before the ui is visible - int grouping = m_OrganizerCore.settings().directInterface().value("group_state").toInt(); - ui->groupCombo->setCurrentIndex(grouping); - - allowListResize(); - - m_OrganizerCore.settings().registerAsNXMHandler(false); - m_WasVisible = true; - updateProblemsButton(); - } -} - - -void MainWindow::closeEvent(QCloseEvent* event) -{ - m_closing = true; - - if (m_OrganizerCore.downloadManager()->downloadsInProgressNoPause()) { - if (QMessageBox::question(this, tr("Downloads in progress"), - tr("There are still downloads in progress, do you really want to quit?"), - QMessageBox::Yes | QMessageBox::Cancel) == QMessageBox::Cancel) { - event->ignore(); - return; - } else { - m_OrganizerCore.downloadManager()->pauseAll(); - } - } - - std::vector hiddenList; - hiddenList.push_back(QFileInfo(QCoreApplication::applicationFilePath()).fileName()); - HANDLE injected_process_still_running = m_OrganizerCore.findAndOpenAUSVFSProcess(hiddenList, GetCurrentProcessId()); - if (injected_process_still_running != INVALID_HANDLE_VALUE) - { - m_OrganizerCore.waitForApplication(injected_process_still_running); - if (!m_closing) { // if operation cancelled - event->ignore(); - return; - } - } - - setCursor(Qt::WaitCursor); -} - -void MainWindow::cleanup() -{ - if (ui->logList->model() != nullptr) { - disconnect(ui->logList->model(), nullptr, nullptr, nullptr); - ui->logList->setModel(nullptr); - } - - QWebEngineProfile::defaultProfile()->clearAllVisitedLinks(); - m_IntegratedBrowser.close(); - m_SaveMetaTimer.stop(); - m_MetaSave.waitForFinished(); -} - - -void MainWindow::setBrowserGeometry(const QByteArray &geometry) -{ - m_IntegratedBrowser.restoreGeometry(geometry); -} - -void MainWindow::displaySaveGameInfo(QListWidgetItem *newItem) -{ - QString const &save = newItem->data(Qt::UserRole).toString(); - if (m_CurrentSaveView == nullptr) { - IPluginGame const *game = m_OrganizerCore.managedGame(); - SaveGameInfo const *info = game->feature(); - if (info != nullptr) { - m_CurrentSaveView = info->getSaveGameWidget(this); - } - if (m_CurrentSaveView == nullptr) { - return; - } - } - m_CurrentSaveView->setSave(save); - - QRect screenRect = QApplication::desktop()->availableGeometry(m_CurrentSaveView); - - QPoint pos = QCursor::pos(); - if (pos.x() + m_CurrentSaveView->width() > screenRect.right()) { - pos.rx() -= (m_CurrentSaveView->width() + 2); - } else { - pos.rx() += 5; - } - - if (pos.y() + m_CurrentSaveView->height() > screenRect.bottom()) { - pos.ry() -= (m_CurrentSaveView->height() + 10); - } else { - pos.ry() += 20; - } - m_CurrentSaveView->move(pos); - - m_CurrentSaveView->show(); - m_CurrentSaveView->setProperty("displayItem", qVariantFromValue(static_cast(newItem))); - - ui->savegameList->activateWindow(); -} - - -void MainWindow::saveSelectionChanged(QListWidgetItem *newItem) -{ - if (newItem == nullptr) { - hideSaveGameInfo(); - } else if (m_CurrentSaveView == nullptr || newItem != m_CurrentSaveView->property("displayItem").value()) { - displaySaveGameInfo(newItem); - } -} - - -void MainWindow::hideSaveGameInfo() -{ - if (m_CurrentSaveView != nullptr) { - m_CurrentSaveView->deleteLater(); - m_CurrentSaveView = nullptr; - } -} - -bool MainWindow::eventFilter(QObject *object, QEvent *event) -{ - if ((object == ui->savegameList) && - ((event->type() == QEvent::Leave) || (event->type() == QEvent::WindowDeactivate))) { - hideSaveGameInfo(); - } - return false; -} - - -void MainWindow::toolPluginInvoke() -{ - QAction *triggeredAction = qobject_cast(sender()); - IPluginTool *plugin = qobject_cast(triggeredAction->data().value()); - if (plugin != nullptr) { - try { - plugin->display(); - } catch (const std::exception &e) { - reportError(tr("Plugin \"%1\" failed: %2").arg(plugin->name()).arg(e.what())); - } catch (...) { - reportError(tr("Plugin \"%1\" failed").arg(plugin->name())); - } - } -} - -void MainWindow::modPagePluginInvoke() -{ - QAction *triggeredAction = qobject_cast(sender()); - IPluginModPage *plugin = qobject_cast(triggeredAction->data().value()); - if (plugin != nullptr) { - if (plugin->useIntegratedBrowser()) { - m_IntegratedBrowser.setWindowTitle(plugin->displayName()); - m_IntegratedBrowser.openUrl(plugin->pageURL()); - } else { - QDesktopServices::openUrl(QUrl(plugin->pageURL())); - } - } -} - -void MainWindow::registerPluginTool(IPluginTool *tool, QString name, QMenu *menu) -{ - if (name.isEmpty()) - name = tool->displayName(); - - QAction *action = new QAction(tool->icon(), name, ui->toolBar); - action->setToolTip(tool->tooltip()); - tool->setParentWidget(this); - action->setData(qVariantFromValue((QObject*)tool)); - connect(action, SIGNAL(triggered()), this, SLOT(toolPluginInvoke()), Qt::QueuedConnection); - - if (menu == nullptr) { - QToolButton *toolBtn = qobject_cast(ui->toolBar->widgetForAction(ui->actionTool)); - toolBtn->menu()->addAction(action); - } else { - menu->addAction(action); - } -} - -void MainWindow::registerPluginTools(std::vector toolPlugins) -{ - // Sort the plugins by display name - std::sort(toolPlugins.begin(), toolPlugins.end(), - [](IPluginTool *left, IPluginTool *right) { - return left->displayName().toLower() < right->displayName().toLower(); - } - ); - - // Group the plugins into submenus - QMap>> submenuMap; - for (auto toolPlugin : toolPlugins) { - QStringList toolName = toolPlugin->displayName().split("/"); - QString submenu = toolName[0]; - toolName.pop_front(); - submenuMap[submenu].append(QPair(toolName.join("/"), toolPlugin)); - } - - // Start registering plugins - for (auto submenuKey : submenuMap.keys()) { - if (submenuMap[submenuKey].length() > 1) { - QMenu *submenu = new QMenu(submenuKey, this); - for (auto info : submenuMap[submenuKey]) { - registerPluginTool(info.second, info.first, submenu); - } - QToolButton *toolBtn = qobject_cast(ui->toolBar->widgetForAction(ui->actionTool)); - toolBtn->menu()->addMenu(submenu); - } - else { - registerPluginTool(submenuMap[submenuKey].front().second); - } - } -} - -void MainWindow::registerModPage(IPluginModPage *modPage) -{ - // turn the browser action into a drop-down menu if necessary - if (ui->actionNexus->menu() == nullptr) { - QAction *nexusAction = ui->actionNexus; - // TODO: use a different icon for nexus! - ui->actionNexus = new QAction(nexusAction->icon(), tr("Browse Mod Page"), ui->toolBar); - ui->toolBar->insertAction(nexusAction, ui->actionNexus); - ui->toolBar->removeAction(nexusAction); - actionToToolButton(ui->actionNexus); - - QToolButton *browserBtn = qobject_cast(ui->toolBar->widgetForAction(ui->actionNexus)); - browserBtn->menu()->addAction(nexusAction); - } - - QAction *action = new QAction(modPage->icon(), modPage->displayName(), ui->toolBar); - modPage->setParentWidget(this); - action->setData(qVariantFromValue(reinterpret_cast(modPage))); - - connect(action, SIGNAL(triggered()), this, SLOT(modPagePluginInvoke()), Qt::QueuedConnection); - QToolButton *toolBtn = qobject_cast(ui->toolBar->widgetForAction(ui->actionNexus)); - toolBtn->menu()->addAction(action); -} - - -void MainWindow::startExeAction() -{ - QAction *action = qobject_cast(sender()); - if (action != nullptr) { - const Executable &selectedExecutable(m_OrganizerCore.executablesList()->find(action->text())); - QString customOverwrite = m_OrganizerCore.currentProfile()->setting("custom_overwrites", selectedExecutable.m_Title).toString(); - auto forcedLibraries = m_OrganizerCore.currentProfile()->determineForcedLibraries(selectedExecutable.m_Title); - if (!m_OrganizerCore.currentProfile()->forcedLibrariesEnabled(selectedExecutable.m_Title)) { - forcedLibraries.clear(); - } - m_OrganizerCore.spawnBinary( - selectedExecutable.m_BinaryInfo, selectedExecutable.m_Arguments, - selectedExecutable.m_WorkingDirectory.length() != 0 - ? selectedExecutable.m_WorkingDirectory - : selectedExecutable.m_BinaryInfo.absolutePath(), - selectedExecutable.m_SteamAppID, - customOverwrite, - forcedLibraries); - } else { - qCritical("not an action?"); - } -} - - -void MainWindow::setExecutableIndex(int index) -{ - QComboBox *executableBox = findChild("executablesListBox"); - - if ((index != 0) && (executableBox->count() > index)) { - executableBox->setCurrentIndex(index); - } else { - executableBox->setCurrentIndex(1); - } -} - -void MainWindow::activateSelectedProfile() -{ - m_OrganizerCore.setCurrentProfile(ui->profileBox->currentText()); - - m_ModListSortProxy->setProfile(m_OrganizerCore.currentProfile()); - - refreshSaveList(); - m_OrganizerCore.refreshModList(); - updateModCount(); - updatePluginCount(); -} - -void MainWindow::on_profileBox_currentIndexChanged(int index) -{ - if (ui->profileBox->isEnabled()) { - int previousIndex = m_OldProfileIndex; - m_OldProfileIndex = index; - - if ((previousIndex != -1) && - (m_OrganizerCore.currentProfile() != nullptr) && - m_OrganizerCore.currentProfile()->exists()) { - m_OrganizerCore.saveCurrentLists(); - } - - // ensure the new index is valid - if (index < 0 || index >= ui->profileBox->count()) { - qDebug("invalid profile index, using last profile"); - ui->profileBox->setCurrentIndex(ui->profileBox->count() - 1); - } - - if (ui->profileBox->currentIndex() == 0) { - ui->profileBox->setCurrentIndex(previousIndex); - ProfilesDialog(ui->profileBox->currentText(), m_OrganizerCore.managedGame(), this).exec(); - while (!refreshProfiles()) { - ProfilesDialog(ui->profileBox->currentText(), m_OrganizerCore.managedGame(), this).exec(); - } - } else { - activateSelectedProfile(); - } - - LocalSavegames *saveGames = m_OrganizerCore.managedGame()->feature(); - if (saveGames != nullptr) { - if (saveGames->prepareProfile(m_OrganizerCore.currentProfile())) - refreshSaveList(); - } - - BSAInvalidation *invalidation = m_OrganizerCore.managedGame()->feature(); - if (invalidation != nullptr) { - if (invalidation->prepareProfile(m_OrganizerCore.currentProfile())) - QTimer::singleShot(5, &m_OrganizerCore, SLOT(profileRefresh())); - } - } -} - -void MainWindow::updateTo(QTreeWidgetItem *subTree, const std::wstring &directorySoFar, const DirectoryEntry &directoryEntry, bool conflictsOnly, QIcon *fileIcon, QIcon *folderIcon) -{ - bool isDirectory = true; - //QIcon folderIcon = (new QFileIconProvider())->icon(QFileIconProvider::Folder); - //QIcon fileIcon = (new QFileIconProvider())->icon(QFileIconProvider::File); - - std::wostringstream temp; - temp << directorySoFar << "\\" << directoryEntry.getName(); - { - std::vector::const_iterator current, end; - directoryEntry.getSubDirectories(current, end); - for (; current != end; ++current) { - QString pathName = ToQString((*current)->getName()); - QStringList columns(pathName); - columns.append(""); - if (!(*current)->isEmpty()) { - QTreeWidgetItem *directoryChild = new QTreeWidgetItem(columns); - directoryChild->setData(0, Qt::DecorationRole, *folderIcon); - directoryChild->setData(0, Qt::UserRole + 3, isDirectory); - - if (conflictsOnly || !m_showArchiveData) { - updateTo(directoryChild, temp.str(), **current, conflictsOnly, fileIcon, folderIcon); - if (directoryChild->childCount() != 0) { - subTree->addChild(directoryChild); - } - else { - delete directoryChild; - } - } - else { - QTreeWidgetItem *onDemandLoad = new QTreeWidgetItem(QStringList()); - onDemandLoad->setData(0, Qt::UserRole + 0, "__loaded_on_demand__"); - onDemandLoad->setData(0, Qt::UserRole + 1, ToQString(temp.str())); - onDemandLoad->setData(0, Qt::UserRole + 2, conflictsOnly); - directoryChild->addChild(onDemandLoad); - subTree->addChild(directoryChild); - } - } - else { - QTreeWidgetItem *directoryChild = new QTreeWidgetItem(columns); - directoryChild->setData(0, Qt::DecorationRole, *folderIcon); - directoryChild->setData(0, Qt::UserRole + 3, isDirectory); - subTree->addChild(directoryChild); - } - } - } - - - isDirectory = false; - { - for (const FileEntry::Ptr current : directoryEntry.getFiles()) { - if (conflictsOnly && (current->getAlternatives().size() == 0)) { - continue; - } - - bool isArchive = false; - int originID = current->getOrigin(isArchive); - if (!m_showArchiveData && isArchive) { - continue; - } - - QString fileName = ToQString(current->getName()); - QStringList columns(fileName); - FilesOrigin origin = m_OrganizerCore.directoryStructure()->getOriginByID(originID); - QString source("data"); - unsigned int modIndex = ModInfo::getIndex(ToQString(origin.getName())); - if (modIndex != UINT_MAX) { - ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); - source = modInfo->name(); - } - - std::pair archive = current->getArchive(); - if (archive.first.length() != 0) { - source.append(" (").append(ToQString(archive.first)).append(")"); - } - columns.append(source); - QTreeWidgetItem *fileChild = new QTreeWidgetItem(columns); - if (isArchive) { - QFont font = fileChild->font(0); - font.setItalic(true); - fileChild->setFont(0, font); - fileChild->setFont(1, font); - } else if (fileName.endsWith(ModInfo::s_HiddenExt)) { - QFont font = fileChild->font(0); - font.setStrikeOut(true); - fileChild->setFont(0, font); - fileChild->setFont(1, font); - } - fileChild->setData(0, Qt::UserRole, ToQString(current->getFullPath())); - fileChild->setData(0, Qt::DecorationRole, *fileIcon); - fileChild->setData(0, Qt::UserRole + 3, isDirectory); - fileChild->setData(0, Qt::UserRole + 1, isArchive); - fileChild->setData(1, Qt::UserRole, source); - fileChild->setData(1, Qt::UserRole + 1, originID); - - std::vector>> alternatives = current->getAlternatives(); - - if (!alternatives.empty()) { - std::wostringstream altString; - altString << ToWString(tr("Also in:
")); - for (std::vector>>::iterator altIter = alternatives.begin(); - altIter != alternatives.end(); ++altIter) { - if (altIter != alternatives.begin()) { - altString << " , "; - } - altString << "" << m_OrganizerCore.directoryStructure()->getOriginByID(altIter->first).getName() << ""; - } - fileChild->setToolTip(1, QString("%1").arg(ToQString(altString.str()))); - fileChild->setForeground(1, QBrush(Qt::red)); - } else { - fileChild->setToolTip(1, tr("No conflict")); - } - subTree->addChild(fileChild); - } - } - - - //subTree->sortChildren(0, Qt::AscendingOrder); -} - -void MainWindow::delayedRemove() -{ - for (QTreeWidgetItem *item : m_RemoveWidget) { - item->removeChild(item->child(0)); - } - m_RemoveWidget.clear(); -} - -void MainWindow::expandDataTreeItem(QTreeWidgetItem *item) -{ - if ((item->childCount() == 1) && (item->child(0)->data(0, Qt::UserRole).toString() == "__loaded_on_demand__")) { - // read the data we need from the sub-item, then dispose of it - QTreeWidgetItem *onDemandDataItem = item->child(0); - std::wstring path = ToWString(onDemandDataItem->data(0, Qt::UserRole + 1).toString()); - bool conflictsOnly = onDemandDataItem->data(0, Qt::UserRole + 2).toBool(); - - std::wstring virtualPath = (path + L"\\").substr(6) + ToWString(item->text(0)); - DirectoryEntry *dir = m_OrganizerCore.directoryStructure()->findSubDirectoryRecursive(virtualPath); - if (dir != nullptr) { - QIcon folderIcon = (new QFileIconProvider())->icon(QFileIconProvider::Folder); - QIcon fileIcon = (new QFileIconProvider())->icon(QFileIconProvider::File); - updateTo(item, path, *dir, conflictsOnly, &fileIcon, &folderIcon); - } else { - qWarning("failed to update view of %ls", path.c_str()); - } - m_RemoveWidget.push_back(item); - QTimer::singleShot(5, this, SLOT(delayedRemove())); - } -} - - -bool MainWindow::refreshProfiles(bool selectProfile) -{ - QComboBox* profileBox = findChild("profileBox"); - - QString currentProfileName = profileBox->currentText(); - - profileBox->blockSignals(true); - profileBox->clear(); - profileBox->addItem(QObject::tr("")); - - QDir profilesDir(Settings::instance().getProfileDirectory()); - profilesDir.setFilter(QDir::AllDirs | QDir::NoDotAndDotDot); - - QDirIterator profileIter(profilesDir); - - while (profileIter.hasNext()) { - profileIter.next(); - try { - profileBox->addItem(profileIter.fileName()); - } catch (const std::runtime_error& error) { - reportError(QObject::tr("failed to parse profile %1: %2").arg(profileIter.fileName()).arg(error.what())); - } - } - - // now select one of the profiles, preferably the one that was selected before - profileBox->blockSignals(false); - - if (selectProfile) { - if (profileBox->count() > 1) { - profileBox->setCurrentText(currentProfileName); - if (profileBox->currentIndex() == 0) { - profileBox->setCurrentIndex(1); - } - } - } - return profileBox->count() > 1; -} - - -void MainWindow::refreshExecutablesList() -{ - QComboBox* executablesList = findChild("executablesListBox"); - executablesList->setEnabled(false); - executablesList->clear(); - executablesList->addItem(tr("")); - - QAbstractItemModel *model = executablesList->model(); - - std::vector::const_iterator current, end; - m_OrganizerCore.executablesList()->getExecutables(current, end); - for(int i = 0; current != end; ++current, ++i) { - QIcon icon = iconForExecutable(current->m_BinaryInfo.filePath()); - executablesList->addItem(icon, current->m_Title); - model->setData(model->index(i, 0), QSize(0, executablesList->iconSize().height() + 4), Qt::SizeHintRole); - } - - setExecutableIndex(1); - executablesList->setEnabled(true); -} - - -void MainWindow::refreshDataTree() -{ - QCheckBox *conflictsBox = findChild("conflictsCheckBox"); - QTreeWidget *tree = findChild("dataTree"); - QIcon folderIcon = (new QFileIconProvider())->icon(QFileIconProvider::Folder); - QIcon fileIcon = (new QFileIconProvider())->icon(QFileIconProvider::File); - tree->clear(); - QStringList columns("data"); - columns.append(""); - QTreeWidgetItem *subTree = new QTreeWidgetItem(columns); - subTree->setData(0, Qt::DecorationRole, (new QFileIconProvider())->icon(QFileIconProvider::Folder)); - updateTo(subTree, L"", *m_OrganizerCore.directoryStructure(), conflictsBox->isChecked(), &fileIcon, &folderIcon); - tree->insertTopLevelItem(0, subTree); - subTree->setExpanded(true); -} - -void MainWindow::refreshDataTreeKeepExpandedNodes() -{ - QCheckBox *conflictsBox = findChild("conflictsCheckBox"); - QTreeWidget *tree = findChild("dataTree"); - QIcon folderIcon = (new QFileIconProvider())->icon(QFileIconProvider::Folder); - QIcon fileIcon = (new QFileIconProvider())->icon(QFileIconProvider::File); - QStringList expandedNodes; - QTreeWidgetItemIterator it1(tree, QTreeWidgetItemIterator::NotHidden | QTreeWidgetItemIterator::HasChildren); - while (*it1) { - QTreeWidgetItem *current = (*it1); - if (current->isExpanded() && !(current->text(0)=="data")) { - expandedNodes.append(current->text(0)+"/"+current->parent()->text(0)); - } - ++it1; - } - - tree->clear(); - QStringList columns("data"); - columns.append(""); - QTreeWidgetItem *subTree = new QTreeWidgetItem(columns); - subTree->setData(0, Qt::DecorationRole, (new QFileIconProvider())->icon(QFileIconProvider::Folder)); - updateTo(subTree, L"", *m_OrganizerCore.directoryStructure(), conflictsBox->isChecked(), &fileIcon, &folderIcon); - tree->insertTopLevelItem(0, subTree); - subTree->setExpanded(true); - QTreeWidgetItemIterator it2(tree, QTreeWidgetItemIterator::HasChildren); - while (*it2) { - QTreeWidgetItem *current = (*it2); - if (!(current->text(0)=="data") && expandedNodes.contains(current->text(0)+"/"+current->parent()->text(0))) { - current->setExpanded(true); - } - ++it2; - } -} - - -void MainWindow::refreshSavesIfOpen() -{ - if (ui->tabWidget->currentIndex() == 3) { - refreshSaveList(); - } -} - -QDir MainWindow::currentSavesDir() const -{ - QDir savesDir; - if (m_OrganizerCore.currentProfile()->localSavesEnabled()) { - savesDir.setPath(m_OrganizerCore.currentProfile()->savePath()); - } else { - QString iniPath = m_OrganizerCore.currentProfile()->localSettingsEnabled() - ? m_OrganizerCore.currentProfile()->absolutePath() - : m_OrganizerCore.managedGame()->documentsDirectory().absolutePath(); - iniPath += "/" + m_OrganizerCore.managedGame()->iniFiles()[0]; - - wchar_t path[MAX_PATH]; - ::GetPrivateProfileStringW( - L"General", L"SLocalSavePath", L"Saves", - path, MAX_PATH, - iniPath.toStdWString().c_str() - ); - savesDir.setPath(m_OrganizerCore.managedGame()->documentsDirectory().absoluteFilePath(QString::fromWCharArray(path))); - } - - return savesDir; -} - -void MainWindow::startMonitorSaves() -{ - stopMonitorSaves(); - - QDir savesDir = currentSavesDir(); - - m_SavesWatcher.addPath(savesDir.absolutePath()); -} - -void MainWindow::stopMonitorSaves() -{ - if (m_SavesWatcher.directories().length() > 0) { - m_SavesWatcher.removePaths(m_SavesWatcher.directories()); - } -} - -void MainWindow::refreshSaveList() -{ - ui->savegameList->clear(); - - startMonitorSaves(); // re-starts monitoring - - QStringList filters; - filters << QString("*.") + m_OrganizerCore.managedGame()->savegameExtension(); - - QDir savesDir = currentSavesDir(); - savesDir.setNameFilters(filters); - qDebug("reading save games from %s", qUtf8Printable(savesDir.absolutePath())); - - QFileInfoList files = savesDir.entryInfoList(QDir::Files, QDir::Time); - for (const QFileInfo &file : files) { - QListWidgetItem *item = new QListWidgetItem(file.fileName()); - item->setData(Qt::UserRole, file.absoluteFilePath()); - ui->savegameList->addItem(item); - } -} - - -static bool BySortValue(const std::pair &LHS, const std::pair &RHS) -{ - return LHS.first < RHS.first; -} - -template -static QStringList toStringList(InputIterator current, InputIterator end) -{ - QStringList result; - for (; current != end; ++current) { - result.append(*current); - } - return result; -} - -void MainWindow::updateBSAList(const QStringList &defaultArchives, const QStringList &activeArchives) -{ - m_DefaultArchives = defaultArchives; - ui->bsaList->clear(); - ui->bsaList->header()->setSectionResizeMode(QHeaderView::ResizeToContents); - std::vector> items; - - BSAInvalidation * invalidation = m_OrganizerCore.managedGame()->feature(); - std::vector files = m_OrganizerCore.directoryStructure()->getFiles(); - - QStringList plugins = m_OrganizerCore.findFiles("", [](const QString &fileName) -> bool { - return fileName.endsWith(".esp", Qt::CaseInsensitive) - || fileName.endsWith(".esm", Qt::CaseInsensitive) - || fileName.endsWith(".esl", Qt::CaseInsensitive); - }); - - auto hasAssociatedPlugin = [&](const QString &bsaName) -> bool { - for (const QString &pluginName : plugins) { - QFileInfo pluginInfo(pluginName); - if (bsaName.startsWith(QFileInfo(pluginName).baseName(), Qt::CaseInsensitive) - && (m_OrganizerCore.pluginList()->state(pluginInfo.fileName()) == IPluginList::STATE_ACTIVE)) { - return true; - } - } - return false; - }; - - for (FileEntry::Ptr current : files) { - QFileInfo fileInfo(ToQString(current->getName().c_str())); - - if (fileInfo.suffix().toLower() == "bsa" || fileInfo.suffix().toLower() == "ba2") { - int index = activeArchives.indexOf(fileInfo.fileName()); - if (index == -1) { - index = 0xFFFF; - } - else { - index += 2; - } - - if ((invalidation != nullptr) && invalidation->isInvalidationBSA(fileInfo.fileName())) { - index = 1; - } - - int originId = current->getOrigin(); - FilesOrigin & origin = m_OrganizerCore.directoryStructure()->getOriginByID(originId); - - QTreeWidgetItem * newItem = new QTreeWidgetItem(QStringList() - << fileInfo.fileName() - << ToQString(origin.getName())); - newItem->setData(0, Qt::UserRole, index); - newItem->setData(1, Qt::UserRole, originId); - newItem->setFlags(newItem->flags() & ~(Qt::ItemIsDropEnabled | Qt::ItemIsUserCheckable)); - newItem->setCheckState(0, (index != -1) ? Qt::Checked : Qt::Unchecked); - newItem->setData(0, Qt::UserRole, false); - if (m_OrganizerCore.settings().forceEnableCoreFiles() - && defaultArchives.contains(fileInfo.fileName())) { - newItem->setCheckState(0, Qt::Checked); - newItem->setDisabled(true); - newItem->setData(0, Qt::UserRole, true); - } else if (fileInfo.fileName().compare("update.bsa", Qt::CaseInsensitive) == 0) { - newItem->setCheckState(0, Qt::Checked); - newItem->setDisabled(true); - } else if (hasAssociatedPlugin(fileInfo.fileName())) { - newItem->setCheckState(0, Qt::Checked); - newItem->setDisabled(true); - } else { - newItem->setCheckState(0, Qt::Unchecked); - newItem->setDisabled(true); - } - if (index < 0) index = 0; - - UINT32 sortValue = ((origin.getPriority() & 0xFFFF) << 16) | (index & 0xFFFF); - items.push_back(std::make_pair(sortValue, newItem)); - } - } - std::sort(items.begin(), items.end(), BySortValue); - - for (auto iter = items.begin(); iter != items.end(); ++iter) { - int originID = iter->second->data(1, Qt::UserRole).toInt(); - - FilesOrigin origin = m_OrganizerCore.directoryStructure()->getOriginByID(originID); - QString modName("data"); - unsigned int modIndex = ModInfo::getIndex(ToQString(origin.getName())); - if (modIndex != UINT_MAX) { - ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); - modName = modInfo->name(); - } - QList items = ui->bsaList->findItems(modName, Qt::MatchFixedString); - QTreeWidgetItem * subItem = nullptr; - if (items.length() > 0) { - subItem = items.at(0); - } - else { - subItem = new QTreeWidgetItem(QStringList(modName)); - subItem->setFlags(subItem->flags() & ~Qt::ItemIsDragEnabled); - ui->bsaList->addTopLevelItem(subItem); - } - subItem->addChild(iter->second); - subItem->setExpanded(true); - } - checkBSAList(); -} - -void MainWindow::checkBSAList() -{ - DataArchives * archives = m_OrganizerCore.managedGame()->feature(); - - if (archives != nullptr) { - ui->bsaList->blockSignals(true); - ON_BLOCK_EXIT([&]() { ui->bsaList->blockSignals(false); }); - - QStringList defaultArchives = archives->archives(m_OrganizerCore.currentProfile()); - - bool warning = false; - - for (int i = 0; i < ui->bsaList->topLevelItemCount(); ++i) { - bool modWarning = false; - QTreeWidgetItem * tlItem = ui->bsaList->topLevelItem(i); - for (int j = 0; j < tlItem->childCount(); ++j) { - QTreeWidgetItem * item = tlItem->child(j); - QString filename = item->text(0); - item->setIcon(0, QIcon()); - item->setToolTip(0, QString()); - - if (item->checkState(0) == Qt::Unchecked) { - if (defaultArchives.contains(filename)) { - item->setIcon(0, QIcon(":/MO/gui/warning")); - item->setToolTip(0, tr("This bsa is enabled in the ini file so it may be required!")); - modWarning = true; - } - } - } - if (modWarning) { - ui->bsaList->expandItem(ui->bsaList->topLevelItem(i)); - warning = true; - } - } - if (warning) { - ui->tabWidget->setTabIcon(1, QIcon(":/MO/gui/warning")); - } else { - ui->tabWidget->setTabIcon(1, QIcon()); - } - } -} - -void MainWindow::saveModMetas() -{ - if (m_MetaSave.isFinished()) { - m_MetaSave = QtConcurrent::run([this]() { - for (unsigned int i = 0; i < ModInfo::getNumMods(); ++i) { - ModInfo::Ptr modInfo = ModInfo::getByIndex(i); - modInfo->saveMeta(); - } - }); - } -} - -void MainWindow::fixCategories() -{ - for (unsigned int i = 0; i < ModInfo::getNumMods(); ++i) { - ModInfo::Ptr modInfo = ModInfo::getByIndex(i); - std::set categories = modInfo->getCategories(); - for (std::set::iterator iter = categories.begin(); - iter != categories.end(); ++iter) { - if (!m_CategoryFactory.categoryExists(*iter)) { - modInfo->setCategory(*iter, false); - } - } - } -} - - -void MainWindow::setupNetworkProxy(bool activate) -{ - QNetworkProxyFactory::setUseSystemConfiguration(activate); -/* QNetworkProxyQuery query(QUrl("http://www.google.com"), QNetworkProxyQuery::UrlRequest); - query.setProtocolTag("http"); - QList proxies = QNetworkProxyFactory::systemProxyForQuery(query); - if ((proxies.size() > 0) && (proxies.at(0).type() != QNetworkProxy::NoProxy)) { - qDebug("Using proxy: %s", qUtf8Printable(proxies.at(0).hostName())); - QNetworkProxy::setApplicationProxy(proxies[0]); - } else { - qDebug("Not using proxy"); - }*/ -} - - -void MainWindow::activateProxy(bool activate) -{ - QProgressDialog busyDialog(tr("Activating Network Proxy"), QString(), 0, 0, parentWidget()); - busyDialog.setWindowFlags(busyDialog.windowFlags() & ~Qt::WindowContextHelpButtonHint); - busyDialog.setWindowModality(Qt::WindowModal); - busyDialog.show(); - QFuture future = QtConcurrent::run(MainWindow::setupNetworkProxy, activate); - while (!future.isFinished()) { - QCoreApplication::processEvents(); - ::Sleep(100); - } - busyDialog.hide(); -} - -void MainWindow::readSettings() -{ - QSettings settings(qApp->property("dataPath").toString() + "/" + QString::fromStdWString(AppConfig::iniFileName()), QSettings::IniFormat); - - if (settings.contains("window_geometry")) { - restoreGeometry(settings.value("window_geometry").toByteArray()); - } - - if (settings.contains("window_split")) { - ui->splitter->restoreState(settings.value("window_split").toByteArray()); - } - - if (settings.contains("log_split")) { - ui->topLevelSplitter->restoreState(settings.value("log_split").toByteArray()); - } - - bool filtersVisible = settings.value("filters_visible", false).toBool(); - setCategoryListVisible(filtersVisible); - ui->displayCategoriesBtn->setChecked(filtersVisible); - - int selectedExecutable = settings.value("selected_executable").toInt(); - setExecutableIndex(selectedExecutable); - - if (settings.value("Settings/use_proxy", false).toBool()) { - activateProxy(true); - } -} - -void MainWindow::processUpdates() { - QSettings settings(qApp->property("dataPath").toString() + "/" + QString::fromStdWString(AppConfig::iniFileName()), QSettings::IniFormat); - QVersionNumber lastVersion = QVersionNumber::fromString(settings.value("version", "2.1.2").toString()).normalized(); - QVersionNumber currentVersion = QVersionNumber::fromString(m_OrganizerCore.getVersion().displayString()).normalized(); - if (!m_OrganizerCore.settings().directInterface().value("first_start", true).toBool()) { - if (lastVersion < QVersionNumber(2, 1, 3)) { - bool lastHidden = true; - for (int i = ModList::COL_GAME; i < ui->modList->model()->columnCount(); ++i) { - bool hidden = ui->modList->header()->isSectionHidden(i); - ui->modList->header()->setSectionHidden(i, lastHidden); - lastHidden = hidden; - } - } - if (lastVersion < QVersionNumber(2,1,6)) { - ui->modList->header()->setSectionHidden(ModList::COL_NOTES, true); - } - } - - if (currentVersion > lastVersion) { - //NOP - } else if (currentVersion < lastVersion) - qWarning() << tr("Notice: Your current MO version (%1) is lower than the previously used one (%2). " - "The GUI may not downgrade gracefully, so you may experience oddities. " - "However, there should be no serious issues.").arg(currentVersion.toString()).arg(lastVersion.toString()).toStdWString(); - //save version in all case - settings.setValue("version", currentVersion.toString()); -} - -void MainWindow::storeSettings(QSettings &settings) { - settings.setValue("group_state", ui->groupCombo->currentIndex()); - settings.setValue("selected_executable", - ui->executablesListBox->currentIndex()); - - if (settings.value("reset_geometry", false).toBool()) { - settings.remove("window_geometry"); - settings.remove("window_split"); - settings.remove("log_split"); - settings.remove("filters_visible"); - settings.remove("browser_geometry"); - settings.remove("geometry"); - settings.remove("reset_geometry"); - } else { - settings.setValue("window_geometry", saveGeometry()); - settings.setValue("window_split", ui->splitter->saveState()); - settings.setValue("log_split", ui->topLevelSplitter->saveState()); - settings.setValue("browser_geometry", m_IntegratedBrowser.saveGeometry()); - settings.setValue("filters_visible", ui->displayCategoriesBtn->isChecked()); - for (const std::pair kv : m_PersistedGeometry) { - QString key = QString("geometry/") + kv.first; - settings.setValue(key, kv.second->saveState()); - } - } -} - -ILockedWaitingForProcess* MainWindow::lock() -{ - if (m_LockDialog != nullptr) { - ++m_LockCount; - return m_LockDialog; - } - if (m_closing) - m_LockDialog = new WaitingOnCloseDialog(this); - else - m_LockDialog = new LockedDialog(this, true); - m_LockDialog->setModal(true); - m_LockDialog->show(); - setEnabled(false); - m_LockDialog->setEnabled(true); //What's the point otherwise? - ++m_LockCount; - return m_LockDialog; -} - -void MainWindow::unlock() -{ - //If you come through here with a null lock pointer, it's a bug! - if (m_LockDialog == nullptr) { - qDebug("Unlocking main window when already unlocked"); - return; - } - --m_LockCount; - if (m_LockCount == 0) { - if (m_closing && m_LockDialog->canceled()) - m_closing = false; - m_LockDialog->hide(); - m_LockDialog->deleteLater(); - m_LockDialog = nullptr; - setEnabled(true); - } -} - -void MainWindow::on_btnRefreshData_clicked() -{ - m_OrganizerCore.refreshDirectoryStructure(); -} - -void MainWindow::on_btnRefreshDownloads_clicked() -{ - m_OrganizerCore.downloadManager()->refreshList(); -} - -void MainWindow::on_tabWidget_currentChanged(int index) -{ - if (index == 0) { - m_OrganizerCore.refreshESPList(); - } else if (index == 1) { - m_OrganizerCore.refreshBSAList(); - } else if (index == 2) { - refreshDataTreeKeepExpandedNodes(); - } else if (index == 3) { - refreshSaveList(); - } -} - - -void MainWindow::installMod(QString fileName) -{ - try { - if (fileName.isEmpty()) { - QStringList extensions = m_OrganizerCore.installationManager()->getSupportedExtensions(); - for (auto iter = extensions.begin(); iter != extensions.end(); ++iter) { - *iter = "*." + *iter; - } - - fileName = FileDialogMemory::getOpenFileName("installMod", this, tr("Choose Mod"), QString(), - tr("Mod Archive").append(QString(" (%1)").arg(extensions.join(" ")))); - } - - if (fileName.isEmpty()) { - return; - } else { - m_OrganizerCore.installMod(fileName, QString()); - } - } catch (const std::exception &e) { - reportError(e.what()); - } -} - -void MainWindow::on_startButton_clicked() { - ui->startButton->setEnabled(false); - try { - const Executable &selectedExecutable(getSelectedExecutable()); - QString customOverwrite = m_OrganizerCore.currentProfile()->setting("custom_overwrites", selectedExecutable.m_Title).toString(); - auto forcedLibraries = m_OrganizerCore.currentProfile()->determineForcedLibraries(selectedExecutable.m_Title); - if (!m_OrganizerCore.currentProfile()->forcedLibrariesEnabled(selectedExecutable.m_Title)) { - forcedLibraries.clear(); - } - m_OrganizerCore.spawnBinary( - selectedExecutable.m_BinaryInfo, selectedExecutable.m_Arguments, - selectedExecutable.m_WorkingDirectory.length() != 0 - ? selectedExecutable.m_WorkingDirectory - : selectedExecutable.m_BinaryInfo.absolutePath(), - selectedExecutable.m_SteamAppID, - customOverwrite, - forcedLibraries); - } catch (...) { - ui->startButton->setEnabled(true); - throw; - } - ui->startButton->setEnabled(true); -} - -static HRESULT CreateShortcut(LPCWSTR targetFileName, LPCWSTR arguments, - LPCSTR linkFileName, LPCWSTR description, - LPCTSTR iconFileName, int iconNumber, - LPCWSTR currentDirectory) -{ - HRESULT result = E_INVALIDARG; - if ((targetFileName != nullptr) && (wcslen(targetFileName) > 0) && - (arguments != nullptr) && - (linkFileName != nullptr) && (strlen(linkFileName) > 0) && - (description != nullptr) && - (currentDirectory != nullptr)) { - - IShellLink* shellLink; - result = CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, - IID_IShellLink, (LPVOID*)&shellLink); - - if (!SUCCEEDED(result)) { - qCritical("failed to create IShellLink instance"); - return result; - } - - result = shellLink->SetPath(targetFileName); - if (!SUCCEEDED(result)) { - qCritical("failed to set target path %ls", targetFileName); - shellLink->Release(); - return result; - } - - result = shellLink->SetArguments(arguments); - if (!SUCCEEDED(result)) { - qCritical("failed to set arguments: %ls", arguments); - shellLink->Release(); - return result; - } - - if (wcslen(description) > 0) { - result = shellLink->SetDescription(description); - if (!SUCCEEDED(result)) { - qCritical("failed to set description: %ls", description); - shellLink->Release(); - return result; - } - } - - if (wcslen(currentDirectory) > 0) { - result = shellLink->SetWorkingDirectory(currentDirectory); - if (!SUCCEEDED(result)) { - qCritical("failed to set working directory: %ls", currentDirectory); - shellLink->Release(); - return result; - } - } - - if (iconFileName != nullptr) { - result = shellLink->SetIconLocation(iconFileName, iconNumber); - if (!SUCCEEDED(result)) { - qCritical("failed to load program icon: %ls %d", iconFileName, iconNumber); - shellLink->Release(); - return result; - } - } - - IPersistFile *persistFile; - result = shellLink->QueryInterface(IID_IPersistFile, (LPVOID*)&persistFile); - if (SUCCEEDED(result)) { - wchar_t linkFileNameW[MAX_PATH]; - if (MultiByteToWideChar(CP_ACP, 0, linkFileName, -1, linkFileNameW, MAX_PATH) > 0) { - result = persistFile->Save(linkFileNameW, TRUE); - } else { - qCritical("failed to create link: %s", linkFileName); - } - persistFile->Release(); - } else { - qCritical("failed to create IPersistFile instance"); - } - - shellLink->Release(); - } - return result; -} - - -bool MainWindow::modifyExecutablesDialog() -{ - bool result = false; - try { - EditExecutablesDialog dialog(*m_OrganizerCore.executablesList(), - *m_OrganizerCore.modList(), - m_OrganizerCore.currentProfile(), - m_OrganizerCore.managedGame()); - QSettings &settings = m_OrganizerCore.settings().directInterface(); - QString key = QString("geometry/%1").arg(dialog.objectName()); - if (settings.contains(key)) { - dialog.restoreGeometry(settings.value(key).toByteArray()); - } - if (dialog.exec() == QDialog::Accepted) { - m_OrganizerCore.setExecutablesList(dialog.getExecutablesList()); - result = true; - } - settings.setValue(key, dialog.saveGeometry()); - refreshExecutablesList(); - } catch (const std::exception &e) { - reportError(e.what()); - } - return result; -} - -void MainWindow::on_executablesListBox_currentIndexChanged(int index) -{ - QComboBox* executablesList = findChild("executablesListBox"); - - int previousIndex = m_OldExecutableIndex; - m_OldExecutableIndex = index; - - if (executablesList->isEnabled()) { - //I think the 2nd test is impossible - if ((index == 0) || (index > static_cast(m_OrganizerCore.executablesList()->size()))) { - if (modifyExecutablesDialog()) { - setExecutableIndex(previousIndex); - } - } else { - setExecutableIndex(index); - } - } -} - -void MainWindow::helpTriggered() -{ - QWhatsThis::enterWhatsThisMode(); -} - -void MainWindow::wikiTriggered() -{ - QDesktopServices::openUrl(QUrl("https://modorganizer2.github.io/")); -} - -void MainWindow::discordTriggered() -{ - QDesktopServices::openUrl(QUrl("https://discord.gg/cYwdcxj")); -} - -void MainWindow::issueTriggered() -{ - QDesktopServices::openUrl(QUrl("https://github.com/Modorganizer2/modorganizer/issues")); -} - -void MainWindow::tutorialTriggered() -{ - QAction *tutorialAction = qobject_cast(sender()); - if (tutorialAction != nullptr) { - if (QMessageBox::question(this, tr("Start Tutorial?"), - tr("You're about to start a tutorial. For technical reasons it's not possible to end " - "the tutorial early. Continue?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { - TutorialManager::instance().activateTutorial("MainWindow", tutorialAction->data().toString()); - } - } -} - - -void MainWindow::on_actionInstallMod_triggered() -{ - installMod(); -} - -void MainWindow::on_actionAdd_Profile_triggered() -{ - for (;;) { - ProfilesDialog profilesDialog(m_OrganizerCore.currentProfile()->name(), - m_OrganizerCore.managedGame(), - this); - QSettings &settings = m_OrganizerCore.settings().directInterface(); - QString key = QString("geometry/%1").arg(profilesDialog.objectName()); - if (settings.contains(key)) { - profilesDialog.restoreGeometry(settings.value(key).toByteArray()); - } - // workaround: need to disable monitoring of the saves directory, otherwise the active - // profile directory is locked - stopMonitorSaves(); - profilesDialog.exec(); - settings.setValue(key, profilesDialog.saveGeometry()); - refreshSaveList(); // since the save list may now be outdated we have to refresh it completely - if (refreshProfiles() && !profilesDialog.failed()) { - break; - } - } - - LocalSavegames *saveGames = m_OrganizerCore.managedGame()->feature(); - if (saveGames != nullptr) { - if (saveGames->prepareProfile(m_OrganizerCore.currentProfile())) - refreshSaveList(); - } - - BSAInvalidation *invalidation = m_OrganizerCore.managedGame()->feature(); - if (invalidation != nullptr) { - if (invalidation->prepareProfile(m_OrganizerCore.currentProfile())) - QTimer::singleShot(5, &m_OrganizerCore, SLOT(profileRefresh())); - } -} - -void MainWindow::on_actionModify_Executables_triggered() -{ - if (modifyExecutablesDialog()) { - setExecutableIndex(m_OldExecutableIndex); - } -} - - -void MainWindow::setModListSorting(int index) -{ - Qt::SortOrder order = ((index & 0x01) != 0) ? Qt::DescendingOrder : Qt::AscendingOrder; - int column = index >> 1; - ui->modList->header()->setSortIndicator(column, order); -} - - -void MainWindow::setESPListSorting(int index) -{ - switch (index) { - case 0: { - ui->espList->header()->setSortIndicator(1, Qt::AscendingOrder); - } break; - case 1: { - ui->espList->header()->setSortIndicator(1, Qt::DescendingOrder); - } break; - case 2: { - ui->espList->header()->setSortIndicator(0, Qt::AscendingOrder); - } break; - case 3: { - ui->espList->header()->setSortIndicator(0, Qt::DescendingOrder); - } break; - } -} - -void MainWindow::refresher_progress(int percent) -{ - if (percent == 100) { - m_RefreshProgress->setVisible(false); - statusBar()->hide(); - this->setEnabled(true); - } else if (!m_RefreshProgress->isVisible()) { - this->setEnabled(false); - statusBar()->show(); - m_RefreshProgress->setVisible(true); - m_RefreshProgress->setRange(0, 100); - m_RefreshProgress->setValue(percent); - } -} - -void MainWindow::directory_refreshed() -{ - // some problem-reports may rely on the virtual directory tree so they need to be updated - // now - refreshDataTreeKeepExpandedNodes(); - updateProblemsButton(); - statusBar()->hide(); -} - -void MainWindow::esplist_changed() -{ - updatePluginCount(); -} - -void MainWindow::modorder_changed() -{ - for (unsigned int i = 0; i < m_OrganizerCore.currentProfile()->numMods(); ++i) { - int priority = m_OrganizerCore.currentProfile()->getModPriority(i); - if (m_OrganizerCore.currentProfile()->modEnabled(i)) { - ModInfo::Ptr modInfo = ModInfo::getByIndex(i); - // priorities in the directory structure are one higher because data is 0 - m_OrganizerCore.directoryStructure()->getOriginByName(ToWString(modInfo->internalName())).setPriority(priority + 1); - } - } - m_OrganizerCore.refreshBSAList(); - m_OrganizerCore.currentProfile()->writeModlist(); - m_ArchiveListWriter.write(); - m_OrganizerCore.directoryStructure()->getFileRegister()->sortOrigins(); - - { // refresh selection - QModelIndex current = ui->modList->currentIndex(); - if (current.isValid()) { - ModInfo::Ptr modInfo = ModInfo::getByIndex(current.data(Qt::UserRole + 1).toInt()); - // clear caches on all mods conflicting with the moved mod - for (int i : modInfo->getModOverwrite()) { - ModInfo::getByIndex(i)->clearCaches(); - } - for (int i : modInfo->getModOverwritten()) { - ModInfo::getByIndex(i)->clearCaches(); - } - for (int i : modInfo->getModArchiveOverwrite()) { - ModInfo::getByIndex(i)->clearCaches(); - } - for (int i : modInfo->getModArchiveOverwritten()) { - ModInfo::getByIndex(i)->clearCaches(); - } - for (int i : modInfo->getModArchiveLooseOverwrite()) { - ModInfo::getByIndex(i)->clearCaches(); - } - for (int i : modInfo->getModArchiveLooseOverwritten()) { - ModInfo::getByIndex(i)->clearCaches(); - } - // update conflict check on the moved mod - modInfo->doConflictCheck(); - m_OrganizerCore.modList()->setOverwriteMarkers(modInfo->getModOverwrite(), modInfo->getModOverwritten()); - m_OrganizerCore.modList()->setArchiveOverwriteMarkers(modInfo->getModArchiveOverwrite(), modInfo->getModArchiveOverwritten()); - m_OrganizerCore.modList()->setArchiveLooseOverwriteMarkers(modInfo->getModArchiveLooseOverwrite(), modInfo->getModArchiveLooseOverwritten()); - if (m_ModListSortProxy != nullptr) { - m_ModListSortProxy->invalidate(); - } - ui->modList->verticalScrollBar()->repaint(); - } - } -} - -void MainWindow::modInstalled(const QString &modName) -{ - QModelIndexList posList = - m_OrganizerCore.modList()->match(m_OrganizerCore.modList()->index(0, 0), Qt::DisplayRole, modName); - if (posList.count() == 1) { - ui->modList->scrollTo(posList.at(0)); - } -} - -void MainWindow::procError(QProcess::ProcessError error) -{ - reportError(tr("failed to spawn notepad.exe: %1").arg(error)); - this->sender()->deleteLater(); -} - -void MainWindow::procFinished(int, QProcess::ExitStatus) -{ - this->sender()->deleteLater(); -} - -void MainWindow::showMessage(const QString &message) -{ - MessageDialog::showMessage(message, this); -} - -void MainWindow::showError(const QString &message) -{ - reportError(message); -} - -void MainWindow::installMod_clicked() -{ - installMod(); -} - -void MainWindow::modRenamed(const QString &oldName, const QString &newName) -{ - Profile::renameModInAllProfiles(oldName, newName); - - // immediately refresh the active profile because the data in memory is invalid - m_OrganizerCore.currentProfile()->refreshModStatus(); - - // also fix the directory structure - try { - if (m_OrganizerCore.directoryStructure()->originExists(ToWString(oldName))) { - FilesOrigin &origin = m_OrganizerCore.directoryStructure()->getOriginByName(ToWString(oldName)); - origin.setName(ToWString(newName)); - } else { - - } - } catch (const std::exception &e) { - reportError(tr("failed to change origin name: %1").arg(e.what())); - } -} - -void MainWindow::fileMoved(const QString &filePath, const QString &oldOriginName, const QString &newOriginName) -{ - const FileEntry::Ptr filePtr = m_OrganizerCore.directoryStructure()->findFile(ToWString(filePath)); - if (filePtr.get() != nullptr) { - try { - if (m_OrganizerCore.directoryStructure()->originExists(ToWString(newOriginName))) { - FilesOrigin &newOrigin = m_OrganizerCore.directoryStructure()->getOriginByName(ToWString(newOriginName)); - - QString fullNewPath = ToQString(newOrigin.getPath()) + "\\" + filePath; - WIN32_FIND_DATAW findData; - HANDLE hFind; - hFind = ::FindFirstFileW(ToWString(fullNewPath).c_str(), &findData); - filePtr->addOrigin(newOrigin.getID(), findData.ftCreationTime, L"", -1); - FindClose(hFind); - } - if (m_OrganizerCore.directoryStructure()->originExists(ToWString(oldOriginName))) { - FilesOrigin &oldOrigin = m_OrganizerCore.directoryStructure()->getOriginByName(ToWString(oldOriginName)); - filePtr->removeOrigin(oldOrigin.getID()); - } - } catch (const std::exception &e) { - reportError(tr("failed to move \"%1\" from mod \"%2\" to \"%3\": %4").arg(filePath).arg(oldOriginName).arg(newOriginName).arg(e.what())); - } - } else { - // this is probably not an error, the specified path is likely a directory - } -} - -QTreeWidgetItem *MainWindow::addFilterItem(QTreeWidgetItem *root, const QString &name, int categoryID, ModListSortProxy::FilterType type) -{ - QTreeWidgetItem *item = new QTreeWidgetItem(QStringList(name)); - item->setData(0, Qt::ToolTipRole, name); - item->setData(0, Qt::UserRole, categoryID); - item->setData(0, Qt::UserRole + 1, type); - if (root != nullptr) { - root->addChild(item); - } else { - ui->categoriesList->addTopLevelItem(item); - } - return item; -} - -void MainWindow::addContentFilters() -{ - for (unsigned i = 0; i < ModInfo::NUM_CONTENT_TYPES; ++i) { - addFilterItem(nullptr, tr("").arg(ModInfo::getContentTypeName(i)), i, ModListSortProxy::TYPE_CONTENT); - } -} - -void MainWindow::addCategoryFilters(QTreeWidgetItem *root, const std::set &categoriesUsed, int targetID) -{ - for (unsigned int i = 1; - i < static_cast(m_CategoryFactory.numCategories()); ++i) { - if ((m_CategoryFactory.getParentID(i) == targetID)) { - int categoryID = m_CategoryFactory.getCategoryID(i); - if (categoriesUsed.find(categoryID) != categoriesUsed.end()) { - QTreeWidgetItem *item = - addFilterItem(root, m_CategoryFactory.getCategoryName(i), - categoryID, ModListSortProxy::TYPE_CATEGORY); - if (m_CategoryFactory.hasChildren(i)) { - addCategoryFilters(item, categoriesUsed, categoryID); - } - } - } - } -} - -void MainWindow::refreshFilters() -{ - QItemSelection currentSelection = ui->modList->selectionModel()->selection(); - - QVariant currentIndexName = ui->modList->currentIndex().data(); - ui->modList->setCurrentIndex(QModelIndex()); - - QStringList selectedItems; - for (QTreeWidgetItem *item : ui->categoriesList->selectedItems()) { - selectedItems.append(item->text(0)); - } - - ui->categoriesList->clear(); - addFilterItem(nullptr, tr(""), CategoryFactory::CATEGORY_SPECIAL_CHECKED, ModListSortProxy::TYPE_SPECIAL); - addFilterItem(nullptr, tr(""), CategoryFactory::CATEGORY_SPECIAL_UNCHECKED, ModListSortProxy::TYPE_SPECIAL); - addFilterItem(nullptr, tr(""), CategoryFactory::CATEGORY_SPECIAL_UPDATEAVAILABLE, ModListSortProxy::TYPE_SPECIAL); - addFilterItem(nullptr, tr(""), CategoryFactory::CATEGORY_SPECIAL_BACKUP, ModListSortProxy::TYPE_SPECIAL); - addFilterItem(nullptr, tr(""), CategoryFactory::CATEGORY_SPECIAL_MANAGED, ModListSortProxy::TYPE_SPECIAL); - addFilterItem(nullptr, tr(""), CategoryFactory::CATEGORY_SPECIAL_UNMANAGED, ModListSortProxy::TYPE_SPECIAL); - addFilterItem(nullptr, tr(""), CategoryFactory::CATEGORY_SPECIAL_NOCATEGORY, ModListSortProxy::TYPE_SPECIAL); - addFilterItem(nullptr, tr(""), CategoryFactory::CATEGORY_SPECIAL_CONFLICT, ModListSortProxy::TYPE_SPECIAL); - addFilterItem(nullptr, tr(""), CategoryFactory::CATEGORY_SPECIAL_NOTENDORSED, ModListSortProxy::TYPE_SPECIAL); - - addContentFilters(); - std::set categoriesUsed; - for (unsigned int modIdx = 0; modIdx < ModInfo::getNumMods(); ++modIdx) { - ModInfo::Ptr modInfo = ModInfo::getByIndex(modIdx); - for (int categoryID : modInfo->getCategories()) { - int currentID = categoryID; - std::set cycleTest; - // also add parents so they show up in the tree - while (currentID != 0) { - categoriesUsed.insert(currentID); - if (!cycleTest.insert(currentID).second) { - qWarning("cycle in categories: %s", qUtf8Printable(SetJoin(cycleTest, ", "))); - break; - } - currentID = m_CategoryFactory.getParentID(m_CategoryFactory.getCategoryIndex(currentID)); - } - } - } - - addCategoryFilters(nullptr, categoriesUsed, 0); - - for (const QString &item : selectedItems) { - QList matches = ui->categoriesList->findItems(item, Qt::MatchFixedString | Qt::MatchRecursive); - if (matches.size() > 0) { - matches.at(0)->setSelected(true); - } - } - ui->modList->selectionModel()->select(currentSelection, QItemSelectionModel::Select); - QModelIndexList matchList; - if (currentIndexName.isValid()) { - matchList = ui->modList->model()->match(ui->modList->model()->index(0, 0), Qt::DisplayRole, currentIndexName); - } - - if (matchList.size() > 0) { - ui->modList->setCurrentIndex(matchList.at(0)); - } -} - - -void MainWindow::renameMod_clicked() -{ - try { - ui->modList->edit(ui->modList->currentIndex()); - } catch (const std::exception &e) { - reportError(tr("failed to rename mod: %1").arg(e.what())); - } -} - - -void MainWindow::restoreBackup_clicked() -{ - QRegExp backupRegEx("(.*)_backup[0-9]*$"); - ModInfo::Ptr modInfo = ModInfo::getByIndex(m_ContextRow); - if (backupRegEx.indexIn(modInfo->name()) != -1) { - QString regName = backupRegEx.cap(1); - QDir modDir(QDir::fromNativeSeparators(m_OrganizerCore.settings().getModDirectory())); - if (!modDir.exists(regName) || - (QMessageBox::question(this, tr("Overwrite?"), - tr("This will replace the existing mod \"%1\". Continue?").arg(regName), - QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes)) { - if (modDir.exists(regName) && !shellDelete(QStringList(modDir.absoluteFilePath(regName)))) { - reportError(tr("failed to remove mod \"%1\"").arg(regName)); - } else { - QString destinationPath = QDir::fromNativeSeparators(m_OrganizerCore.settings().getModDirectory()) + "/" + regName; - if (!modDir.rename(modInfo->absolutePath(), destinationPath)) { - reportError(tr("failed to rename \"%1\" to \"%2\"").arg(modInfo->absolutePath()).arg(destinationPath)); - } - m_OrganizerCore.refreshModList(); - } - } - } -} - -void MainWindow::modlistChanged(const QModelIndex&, int) -{ - m_OrganizerCore.currentProfile()->writeModlist(); - updateModCount(); -} - -void MainWindow::modlistChanged(const QModelIndexList&, int) -{ - m_OrganizerCore.currentProfile()->writeModlist(); - updateModCount(); -} - -void MainWindow::modlistSelectionChanged(const QModelIndex ¤t, const QModelIndex&) -{ - if (current.isValid()) { - ModInfo::Ptr selectedMod = ModInfo::getByIndex(current.data(Qt::UserRole + 1).toInt()); - m_OrganizerCore.modList()->setOverwriteMarkers(selectedMod->getModOverwrite(), selectedMod->getModOverwritten()); - m_OrganizerCore.modList()->setArchiveOverwriteMarkers(selectedMod->getModArchiveOverwrite(), selectedMod->getModArchiveOverwritten()); - m_OrganizerCore.modList()->setArchiveLooseOverwriteMarkers(selectedMod->getModArchiveLooseOverwrite(), selectedMod->getModArchiveLooseOverwritten()); - } else { - m_OrganizerCore.modList()->setOverwriteMarkers(std::set(), std::set()); - m_OrganizerCore.modList()->setArchiveOverwriteMarkers(std::set(), std::set()); - m_OrganizerCore.modList()->setArchiveLooseOverwriteMarkers(std::set(), std::set()); - } -/* if ((m_ModListSortProxy != nullptr) - && !m_ModListSortProxy->beingInvalidated()) { - m_ModListSortProxy->invalidate(); - }*/ - ui->modList->verticalScrollBar()->repaint(); -} - -void MainWindow::modlistSelectionsChanged(const QItemSelection &selected) -{ - m_OrganizerCore.pluginList()->highlightPlugins(ui->modList->selectionModel(), *m_OrganizerCore.directoryStructure(), *m_OrganizerCore.currentProfile()); - ui->espList->verticalScrollBar()->repaint(); -} - -void MainWindow::esplistSelectionsChanged(const QItemSelection &selected) -{ - m_OrganizerCore.modList()->highlightMods(ui->espList->selectionModel(), *m_OrganizerCore.directoryStructure()); - ui->modList->verticalScrollBar()->repaint(); -} - -void MainWindow::modListSortIndicatorChanged(int, Qt::SortOrder) -{ - ui->modList->verticalScrollBar()->repaint(); -} - -void MainWindow::modListSectionResized(int logicalIndex, int oldSize, int newSize) -{ - bool enabled = (newSize != 0); - qobject_cast(ui->modList->model())->setColumnVisible(logicalIndex, enabled); -} - -void MainWindow::removeMod_clicked() -{ - try { - QItemSelectionModel *selection = ui->modList->selectionModel(); - if (selection->hasSelection() && selection->selectedRows().count() > 1) { - QString mods; - QStringList modNames; - for (QModelIndex idx : selection->selectedRows()) { - QString name = idx.data().toString(); - if (!ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt())->isRegular()) { - continue; - } - mods += "
  • " + name + "
  • "; - modNames.append(ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt())->name()); - } - if (QMessageBox::question(this, tr("Confirm"), - tr("Remove the following mods?
      %1
    ").arg(mods), - QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { - // use mod names instead of indexes because those become invalid during the removal - DownloadManager::startDisableDirWatcher(); - for (QString name : modNames) { - m_OrganizerCore.modList()->removeRowForce(ModInfo::getIndex(name), QModelIndex()); - } - DownloadManager::endDisableDirWatcher(); - } - } else { - m_OrganizerCore.modList()->removeRow(m_ContextRow, QModelIndex()); - } - updateModCount(); - updatePluginCount(); - } catch (const std::exception &e) { - reportError(tr("failed to remove mod: %1").arg(e.what())); - } -} - - -void MainWindow::modRemoved(const QString &fileName) -{ - if (!fileName.isEmpty() && !QFileInfo(fileName).isAbsolute()) { - m_OrganizerCore.downloadManager()->markUninstalled(fileName); - } -} - - -void MainWindow::reinstallMod_clicked() -{ - ModInfo::Ptr modInfo = ModInfo::getByIndex(m_ContextRow); - QString installationFile = modInfo->getInstallationFile(); - if (installationFile.length() != 0) { - QString fullInstallationFile; - QFileInfo fileInfo(installationFile); - if (fileInfo.isAbsolute()) { - if (fileInfo.exists()) { - fullInstallationFile = installationFile; - } else { - fullInstallationFile = m_OrganizerCore.downloadManager()->getOutputDirectory() + "/" + fileInfo.fileName(); - } - } else { - fullInstallationFile = m_OrganizerCore.downloadManager()->getOutputDirectory() + "/" + installationFile; - } - if (QFile::exists(fullInstallationFile)) { - m_OrganizerCore.installMod(fullInstallationFile, modInfo->name()); - } else { - QMessageBox::information(this, tr("Failed"), tr("Installation file no longer exists")); - } - } else { - QMessageBox::information(this, tr("Failed"), - tr("Mods installed with old versions of MO can't be reinstalled in this way.")); - } -} - -void MainWindow::backupMod_clicked() -{ - ModInfo::Ptr modInfo = ModInfo::getByIndex(m_ContextRow); - QString backupDirectory = m_OrganizerCore.installationManager()->generateBackupName(modInfo->absolutePath()); - if (!copyDir(modInfo->absolutePath(), backupDirectory, false)) { - QMessageBox::information(this, tr("Failed"), - tr("Failed to create backup.")); - } - m_OrganizerCore.refreshModList(); -} - -void MainWindow::resumeDownload(int downloadIndex) -{ - if (NexusInterface::instance(&m_PluginContainer)->getAccessManager()->loggedIn()) { - m_OrganizerCore.downloadManager()->resumeDownload(downloadIndex); - } else { - QString username, password; - if (m_OrganizerCore.settings().getNexusLogin(username, password)) { - m_OrganizerCore.doAfterLogin([this, downloadIndex] () { - this->resumeDownload(downloadIndex); - }); - NexusInterface::instance(&m_PluginContainer)->getAccessManager()->login(username, password); - } else { - MessageDialog::showMessage(tr("You need to be logged in with Nexus to resume a download"), this); - } - } -} - - -void MainWindow::endorseMod(ModInfo::Ptr mod) -{ - if (NexusInterface::instance(&m_PluginContainer)->getAccessManager()->loggedIn()) { - mod->endorse(true); - } else { - QString username, password; - if (m_OrganizerCore.settings().getNexusLogin(username, password)) { - m_OrganizerCore.doAfterLogin(boost::bind(&MainWindow::endorseMod, this, mod)); - NexusInterface::instance(&m_PluginContainer)->getAccessManager()->login(username, password); - } else { - MessageDialog::showMessage(tr("You need to be logged in with Nexus to endorse"), this); - } - } -} - - -void MainWindow::endorse_clicked() -{ - QItemSelectionModel *selection = ui->modList->selectionModel(); - if (selection->hasSelection() && selection->selectedRows().count() > 1) { - if (NexusInterface::instance(&m_PluginContainer)->getAccessManager()->loggedIn()) { - MessageDialog::showMessage(tr("Endorsing multiple mods will take a while. Please wait..."), this); - for (QModelIndex idx : selection->selectedRows()) { - ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt())->endorse(true); - } - } - else { - QString username, password; - if (m_OrganizerCore.settings().getNexusLogin(username, password)) { - MessageDialog::showMessage(tr("Endorsing multiple mods will take a while. Please wait..."), this); - for (QModelIndex idx : selection->selectedRows()) { - ModInfo::Ptr modInfo = ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt()); - m_OrganizerCore.doAfterLogin(boost::bind(&MainWindow::endorseMod, this, modInfo)); - } - NexusInterface::instance(&m_PluginContainer)->getAccessManager()->login(username, password); - } else { - MessageDialog::showMessage(tr("You need to be logged in with Nexus to endorse"), this); - return; - } - } - } - else { - endorseMod(ModInfo::getByIndex(m_ContextRow)); - } -} - -void MainWindow::dontendorse_clicked() -{ - QItemSelectionModel *selection = ui->modList->selectionModel(); - if (selection->hasSelection() && selection->selectedRows().count() > 1) { - for (QModelIndex idx : selection->selectedRows()) { - ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt())->setNeverEndorse(); - } - } - else { - ModInfo::getByIndex(m_ContextRow)->setNeverEndorse(); - } -} - - -void MainWindow::unendorseMod(ModInfo::Ptr mod) -{ - QString username, password; - if (NexusInterface::instance(&m_PluginContainer)->getAccessManager()->loggedIn()) { - ModInfo::getByIndex(m_ContextRow)->endorse(false); - } else { - if (m_OrganizerCore.settings().getNexusLogin(username, password)) { - m_OrganizerCore.doAfterLogin([this] () { this->unendorse_clicked(); }); - NexusInterface::instance(&m_PluginContainer)->getAccessManager()->login(username, password); - } else { - MessageDialog::showMessage(tr("You need to be logged in with Nexus to endorse"), this); - } - } -} - - -void MainWindow::unendorse_clicked() -{ - QItemSelectionModel *selection = ui->modList->selectionModel(); - if (selection->hasSelection() && selection->selectedRows().count() > 1) { - if (NexusInterface::instance(&m_PluginContainer)->getAccessManager()->loggedIn()) { - MessageDialog::showMessage(tr("Unendorsing multiple mods will take a while. Please wait..."), this); - for (QModelIndex idx : selection->selectedRows()) { - ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt())->endorse(false); - } - } - else { - QString username, password; - if (m_OrganizerCore.settings().getNexusLogin(username, password)) { - MessageDialog::showMessage(tr("Unendorsing multiple mods will take a while. Please wait..."), this); - for (QModelIndex idx : selection->selectedRows()) { - ModInfo::Ptr modInfo = ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt()); - m_OrganizerCore.doAfterLogin(boost::bind(&MainWindow::unendorseMod, this, modInfo)); - } - NexusInterface::instance(&m_PluginContainer)->getAccessManager()->login(username, password); - } else { - MessageDialog::showMessage(tr("You need to be logged in with Nexus to endorse"), this); - return; - } - } - } - else { - unendorseMod(ModInfo::getByIndex(m_ContextRow)); - } -} - -void MainWindow::loginFailed(const QString &error) -{ - qDebug("login failed: %s", qUtf8Printable(error)); - statusBar()->hide(); -} - -void MainWindow::windowTutorialFinished(const QString &windowName) -{ - m_OrganizerCore.settings().directInterface().setValue(QString("CompletedWindowTutorials/") + windowName, true); -} - -void MainWindow::overwriteClosed(int) -{ - OverwriteInfoDialog *dialog = this->findChild("__overwriteDialog"); - if (dialog != nullptr) { - m_OrganizerCore.modList()->modInfoChanged(dialog->modInfo()); - QSettings &settings = m_OrganizerCore.settings().directInterface(); - QString key = QString("geometry/%1").arg(dialog->objectName()); - settings.setValue(key, dialog->saveGeometry()); - dialog->deleteLater(); - } - m_OrganizerCore.refreshDirectoryStructure(); -} - - -void MainWindow::displayModInformation(ModInfo::Ptr modInfo, unsigned int index, int tab) -{ - if (!m_OrganizerCore.modList()->modInfoAboutToChange(modInfo)) { - qDebug("A different mod information dialog is open. If this is incorrect, please restart MO"); - return; - } - std::vector flags = modInfo->getFlags(); - if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end()) { - QDialog *dialog = this->findChild("__overwriteDialog"); - try { - if (dialog == nullptr) { - dialog = new OverwriteInfoDialog(modInfo, this); - dialog->setObjectName("__overwriteDialog"); - } else { - qobject_cast(dialog)->setModInfo(modInfo); - } - QSettings &settings = m_OrganizerCore.settings().directInterface(); - QString key = QString("geometry/%1").arg(dialog->objectName()); - if (settings.contains(key)) { - dialog->restoreGeometry(settings.value(key).toByteArray()); - } - dialog->show(); - dialog->raise(); - dialog->activateWindow(); - connect(dialog, SIGNAL(finished(int)), this, SLOT(overwriteClosed(int))); - } catch (const std::exception &e) { - reportError(tr("Failed to display overwrite dialog: %1").arg(e.what())); - } - } else { - modInfo->saveMeta(); - ModInfoDialog dialog(modInfo, m_OrganizerCore.directoryStructure(), modInfo->hasFlag(ModInfo::FLAG_FOREIGN), &m_OrganizerCore, &m_PluginContainer, this); - connect(&dialog, SIGNAL(linkActivated(QString)), this, SLOT(linkClicked(QString))); - connect(&dialog, SIGNAL(downloadRequest(QString)), &m_OrganizerCore, SLOT(downloadRequestedNXM(QString))); - connect(&dialog, SIGNAL(modOpen(QString, int)), this, SLOT(displayModInformation(QString, int)), Qt::QueuedConnection); - connect(&dialog, SIGNAL(modOpenNext(int)), this, SLOT(modOpenNext(int)), Qt::QueuedConnection); - connect(&dialog, SIGNAL(modOpenPrev(int)), this, SLOT(modOpenPrev(int)), Qt::QueuedConnection); - connect(&dialog, SIGNAL(originModified(int)), this, SLOT(originModified(int))); - connect(&dialog, SIGNAL(endorseMod(ModInfo::Ptr)), this, SLOT(endorseMod(ModInfo::Ptr))); - - //Open the tab first if we want to use the standard indexes of the tabs. - if (tab != -1) { - dialog.openTab(tab); - } - - dialog.restoreTabState(m_OrganizerCore.settings().directInterface().value("mod_info_tabs").toByteArray()); - QSettings &settings = m_OrganizerCore.settings().directInterface(); - QString key = QString("geometry/%1").arg(dialog.objectName()); - if (settings.contains(key)) { - dialog.restoreGeometry(settings.value(key).toByteArray()); - } - - //If no tab was specified use the first tab from the left based on the user order. - if (tab == -1) { - for (int i = 0; i < dialog.findChild("tabWidget")->count(); ++i) { - if (dialog.findChild("tabWidget")->isTabEnabled(i)) { - dialog.findChild("tabWidget")->setCurrentIndex(i); - break; - } - } - } - - dialog.exec(); - m_OrganizerCore.settings().directInterface().setValue("mod_info_tabs", dialog.saveTabState()); - settings.setValue(key, dialog.saveGeometry()); - - modInfo->saveMeta(); - emit modInfoDisplayed(); - m_OrganizerCore.modList()->modInfoChanged(modInfo); - } - - if (m_OrganizerCore.currentProfile()->modEnabled(index) - && !modInfo->hasFlag(ModInfo::FLAG_FOREIGN)) { - FilesOrigin& origin = m_OrganizerCore.directoryStructure()->getOriginByName(ToWString(modInfo->name())); - origin.enable(false); - - if (m_OrganizerCore.directoryStructure()->originExists(ToWString(modInfo->name()))) { - FilesOrigin& origin = m_OrganizerCore.directoryStructure()->getOriginByName(ToWString(modInfo->name())); - origin.enable(false); - - m_OrganizerCore.directoryRefresher()->addModToStructure(m_OrganizerCore.directoryStructure() - , modInfo->name() - , m_OrganizerCore.currentProfile()->getModPriority(index) - , modInfo->absolutePath() - , modInfo->stealFiles() - , modInfo->archives()); - DirectoryRefresher::cleanStructure(m_OrganizerCore.directoryStructure()); - m_OrganizerCore.directoryStructure()->getFileRegister()->sortOrigins(); - m_OrganizerCore.refreshLists(); - } - } -} - -bool MainWindow::closeWindow() -{ - return close(); -} - -void MainWindow::setWindowEnabled(bool enabled) -{ - setEnabled(enabled); -} - - -void MainWindow::modOpenNext(int tab) -{ - QModelIndex index = m_ModListSortProxy->mapFromSource(m_OrganizerCore.modList()->index(m_ContextRow, 0)); - index = m_ModListSortProxy->index((index.row() + 1) % m_ModListSortProxy->rowCount(), 0); - - m_ContextRow = m_ModListSortProxy->mapToSource(index).row(); - ModInfo::Ptr mod = ModInfo::getByIndex(m_ContextRow); - std::vector flags = mod->getFlags(); - if ((std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end()) || - (std::find(flags.begin(), flags.end(), ModInfo::FLAG_BACKUP) != flags.end()) || - (std::find(flags.begin(), flags.end(), ModInfo::FLAG_SEPARATOR) != flags.end())) { - // skip overwrite and backups and separators - modOpenNext(tab); - } else { - displayModInformation(m_ContextRow,tab); - } -} - -void MainWindow::modOpenPrev(int tab) -{ - QModelIndex index = m_ModListSortProxy->mapFromSource(m_OrganizerCore.modList()->index(m_ContextRow, 0)); - int row = index.row() - 1; - if (row == -1) { - row = m_ModListSortProxy->rowCount() - 1; - } - - m_ContextRow = m_ModListSortProxy->mapToSource(m_ModListSortProxy->index(row, 0)).row(); - ModInfo::Ptr mod = ModInfo::getByIndex(m_ContextRow); - std::vector flags = mod->getFlags(); - if ((std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end()) || - (std::find(flags.begin(), flags.end(), ModInfo::FLAG_BACKUP) != flags.end()) || - (std::find(flags.begin(), flags.end(), ModInfo::FLAG_SEPARATOR) != flags.end())) { - // skip overwrite and backups and separators - modOpenPrev(tab); - } else { - displayModInformation(m_ContextRow,tab); - } -} - -void MainWindow::displayModInformation(const QString &modName, int tab) -{ - unsigned int index = ModInfo::getIndex(modName); - if (index == UINT_MAX) { - qCritical("failed to resolve mod name %s", qUtf8Printable(modName)); - return; - } - - ModInfo::Ptr modInfo = ModInfo::getByIndex(index); - displayModInformation(modInfo, index, tab); -} - - -void MainWindow::displayModInformation(int row, int tab) -{ - ModInfo::Ptr modInfo = ModInfo::getByIndex(row); - displayModInformation(modInfo, row, tab); -} - - -void MainWindow::ignoreMissingData_clicked() -{ - QItemSelectionModel *selection = ui->modList->selectionModel(); - if (selection->hasSelection() && selection->selectedRows().count() > 1) { - for (QModelIndex idx : selection->selectedRows()) { - int row_idx = idx.data(Qt::UserRole + 1).toInt(); - ModInfo::Ptr info = ModInfo::getByIndex(row_idx); - //QDir(info->absolutePath()).mkdir("textures"); - info->testValid(); - info->markValidated(true); - connect(this, SIGNAL(modListDataChanged(QModelIndex, QModelIndex)), m_OrganizerCore.modList(), SIGNAL(dataChanged(QModelIndex, QModelIndex))); - - emit modListDataChanged(m_OrganizerCore.modList()->index(row_idx, 0), m_OrganizerCore.modList()->index(row_idx, m_OrganizerCore.modList()->columnCount() - 1)); - } - } else { - ModInfo::Ptr info = ModInfo::getByIndex(m_ContextRow); - //QDir(info->absolutePath()).mkdir("textures"); - info->testValid(); - info->markValidated(true); - connect(this, SIGNAL(modListDataChanged(QModelIndex, QModelIndex)), m_OrganizerCore.modList(), SIGNAL(dataChanged(QModelIndex, QModelIndex))); - - emit modListDataChanged(m_OrganizerCore.modList()->index(m_ContextRow, 0), m_OrganizerCore.modList()->index(m_ContextRow, m_OrganizerCore.modList()->columnCount() - 1)); - } -} - -void MainWindow::markConverted_clicked() -{ - QItemSelectionModel *selection = ui->modList->selectionModel(); - if (selection->hasSelection() && selection->selectedRows().count() > 1) { - for (QModelIndex idx : selection->selectedRows()) { - int row_idx = idx.data(Qt::UserRole + 1).toInt(); - ModInfo::Ptr info = ModInfo::getByIndex(row_idx); - info->markConverted(true); - connect(this, SIGNAL(modListDataChanged(QModelIndex, QModelIndex)), m_OrganizerCore.modList(), SIGNAL(dataChanged(QModelIndex, QModelIndex))); - emit modListDataChanged(m_OrganizerCore.modList()->index(row_idx, 0), m_OrganizerCore.modList()->index(row_idx, m_OrganizerCore.modList()->columnCount() - 1)); - } - } else { - ModInfo::Ptr info = ModInfo::getByIndex(m_ContextRow); - info->markConverted(true); - connect(this, SIGNAL(modListDataChanged(QModelIndex, QModelIndex)), m_OrganizerCore.modList(), SIGNAL(dataChanged(QModelIndex, QModelIndex))); - emit modListDataChanged(m_OrganizerCore.modList()->index(m_ContextRow, 0), m_OrganizerCore.modList()->index(m_ContextRow, m_OrganizerCore.modList()->columnCount() - 1)); - } -} - - -void MainWindow::visitOnNexus_clicked() -{ - QItemSelectionModel *selection = ui->modList->selectionModel(); - if (selection->hasSelection() && selection->selectedRows().count() > 1) { - int count = selection->selectedRows().count(); - if (count > 10) { - if (QMessageBox::question(this, tr("Opening Nexus Links"), - tr("You are trying to open %1 links to Nexus Mods. Are you sure you want to do this?").arg(count), - QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) { - return; - } - } - int row_idx; - ModInfo::Ptr info; - QString gameName; - QString webUrl; - for (QModelIndex idx : selection->selectedRows()) { - row_idx = idx.data(Qt::UserRole + 1).toInt(); - info = ModInfo::getByIndex(row_idx); - int modID = info->getNexusID(); - webUrl = info->getURL(); - gameName = info->getGameName(); - if (modID > 0) { - linkClicked(NexusInterface::instance(&m_PluginContainer)->getModURL(modID, gameName)); - } - else if (webUrl != "") { - linkClicked(webUrl); - } - } - } - else { - int modID = m_OrganizerCore.modList()->data(m_OrganizerCore.modList()->index(m_ContextRow, 0), Qt::UserRole).toInt(); - QString gameName = m_OrganizerCore.modList()->data(m_OrganizerCore.modList()->index(m_ContextRow, 0), Qt::UserRole + 4).toString(); - if (modID > 0) { - linkClicked(NexusInterface::instance(&m_PluginContainer)->getModURL(modID, gameName)); - } else { - MessageDialog::showMessage(tr("Nexus ID for this Mod is unknown"), this); - } - } -} - -void MainWindow::visitWebPage_clicked() -{ - - QItemSelectionModel *selection = ui->modList->selectionModel(); - if (selection->hasSelection() && selection->selectedRows().count() > 1) { - int count = selection->selectedRows().count(); - if (count > 10) { - if (QMessageBox::question(this, tr("Opening Web Pages"), - tr("You are trying to open %1 Web Pages. Are you sure you want to do this?").arg(count), - QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) { - return; - } - } - int row_idx; - ModInfo::Ptr info; - QString gameName; - QString webUrl; - for (QModelIndex idx : selection->selectedRows()) { - row_idx = idx.data(Qt::UserRole + 1).toInt(); - info = ModInfo::getByIndex(row_idx); - int modID = info->getNexusID(); - webUrl = info->getURL(); - gameName = info->getGameName(); - if (modID > 0) { - linkClicked(NexusInterface::instance(&m_PluginContainer)->getModURL(modID, gameName)); - } - else if (webUrl != "") { - linkClicked(webUrl); - } - } - } - else { - ModInfo::Ptr info = ModInfo::getByIndex(m_ContextRow); - if (info->getURL() != "") { - linkClicked(info->getURL()); - } - else { - MessageDialog::showMessage(tr("Web page for this mod is unknown"), this); - } - } -} - -void MainWindow::openExplorer_clicked() -{ - QItemSelectionModel *selection = ui->modList->selectionModel(); - if (selection->hasSelection() && selection->selectedRows().count() > 1) { - for (QModelIndex idx : selection->selectedRows()) { - ModInfo::Ptr info = ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt()); - ::ShellExecuteW(nullptr, L"explore", ToWString(info->absolutePath()).c_str(), nullptr, nullptr, SW_SHOWNORMAL); - } - } - else { - ModInfo::Ptr modInfo = ModInfo::getByIndex(m_ContextRow); - ::ShellExecuteW(nullptr, L"explore", ToWString(modInfo->absolutePath()).c_str(), nullptr, nullptr, SW_SHOWNORMAL); - } -} - -void MainWindow::openOriginExplorer_clicked() -{ - QItemSelectionModel *selection = ui->espList->selectionModel(); - if (selection->hasSelection() && selection->selectedRows().count() > 0) { - for (QModelIndex idx : selection->selectedRows()) { - QString fileName = idx.data().toString(); - unsigned int modIndex = ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(fileName)); - if (modIndex == UINT_MAX) { - continue; - } - ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); - std::vector flags = modInfo->getFlags(); - - ::ShellExecuteW(nullptr, L"explore", ToWString(modInfo->absolutePath()).c_str(), nullptr, nullptr, SW_SHOWNORMAL); - } - } - else { - QModelIndex idx = selection->currentIndex(); - QString fileName = idx.data().toString(); - ModInfo::Ptr modInfo = ModInfo::getByIndex(ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(fileName))); - std::vector flags = modInfo->getFlags(); - - ::ShellExecuteW(nullptr, L"explore", ToWString(modInfo->absolutePath()).c_str(), nullptr, nullptr, SW_SHOWNORMAL); - } -} - -void MainWindow::openExplorer_activated() -{ - if (ui->modList->hasFocus()) { - QItemSelectionModel *selection = ui->modList->selectionModel(); - if (selection->hasSelection() && selection->selectedRows().count() == 1 ) { - - QModelIndex idx = selection->currentIndex(); - ModInfo::Ptr modInfo = ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt()); - std::vector flags = modInfo->getFlags(); - - if (modInfo->isRegular() || (std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end())) { - ::ShellExecuteW(nullptr, L"explore", ToWString(modInfo->absolutePath()).c_str(), nullptr, nullptr, SW_SHOWNORMAL); - } - - } - } - - if (ui->espList->hasFocus()) { - QItemSelectionModel *selection = ui->espList->selectionModel(); - - if (selection->hasSelection() && selection->selectedRows().count() == 1) { - - QModelIndex idx = selection->currentIndex(); - QString fileName = idx.data().toString(); - - - unsigned int modInfoIndex = ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(fileName)); - if (modInfoIndex != UINT_MAX) { - ModInfo::Ptr modInfo = ModInfo::getByIndex(modInfoIndex); - std::vector flags = modInfo->getFlags(); - - if (modInfo->isRegular() || (std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end())) { - ::ShellExecuteW(nullptr, L"explore", ToWString(modInfo->absolutePath()).c_str(), nullptr, nullptr, SW_SHOWNORMAL); - } - } - } - } -} - -void MainWindow::refreshProfile_activated() -{ - m_OrganizerCore.profileRefresh(); -} - -void MainWindow::search_activated() -{ - if (ui->modList->hasFocus() || ui->modFilterEdit->hasFocus()) { - ui->modFilterEdit->setFocus(); - ui->modFilterEdit->setSelection(0, INT_MAX); - } - - else if (ui->espList->hasFocus() || ui->espFilterEdit->hasFocus()) { - ui->espFilterEdit->setFocus(); - ui->espFilterEdit->setSelection(0, INT_MAX); - } - - else if (ui->downloadView->hasFocus() || ui->downloadFilterEdit->hasFocus()) { - ui->downloadFilterEdit->setFocus(); - ui->downloadFilterEdit->setSelection(0, INT_MAX); - } -} - -void MainWindow::searchClear_activated() -{ - if (ui->modList->hasFocus() || ui->modFilterEdit->hasFocus()) { - ui->modFilterEdit->clear(); - ui->modList->setFocus(); - } - - else if (ui->espList->hasFocus() || ui->espFilterEdit->hasFocus()) { - ui->espFilterEdit->clear(); - ui->espList->setFocus(); - } - - else if (ui->downloadView->hasFocus() || ui->downloadFilterEdit->hasFocus()) { - ui->downloadFilterEdit->clear(); - ui->downloadView->setFocus(); - } -} - -void MainWindow::updateModCount() -{ - int activeCount = 0; - int visActiveCount = 0; - int backupCount = 0; - int visBackupCount = 0; - int foreignCount = 0; - int visForeignCount = 0; - int separatorCount = 0; - int visSeparatorCount = 0; - int regularCount = 0; - int visRegularCount = 0; - - QStringList allMods = m_OrganizerCore.modList()->allMods(); - - auto hasFlag = [](std::vector flags, ModInfo::EFlag filter) { - return std::find(flags.begin(), flags.end(), filter) != flags.end(); - }; - - bool isEnabled; - bool isVisible; - for (QString mod : allMods) { - int modIndex = ModInfo::getIndex(mod); - ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); - std::vector modFlags = modInfo->getFlags(); - isEnabled = m_OrganizerCore.currentProfile()->modEnabled(modIndex); - isVisible = m_ModListSortProxy->filterMatchesMod(modInfo, isEnabled); - - for (auto flag : modFlags) { - switch (flag) { - case ModInfo::FLAG_BACKUP: backupCount++; - if (isVisible) - visBackupCount++; - break; - case ModInfo::FLAG_FOREIGN: foreignCount++; - if (isVisible) - visForeignCount++; - break; - case ModInfo::FLAG_SEPARATOR: separatorCount++; - if (isVisible) - visSeparatorCount++; - break; - } - } - - if (!hasFlag(modFlags, ModInfo::FLAG_BACKUP) && - !hasFlag(modFlags, ModInfo::FLAG_FOREIGN) && - !hasFlag(modFlags, ModInfo::FLAG_SEPARATOR) && - !hasFlag(modFlags, ModInfo::FLAG_OVERWRITE)) { - if (isEnabled) { - activeCount++; - if (isVisible) - visActiveCount++; - } - if (isVisible) - visRegularCount++; - regularCount++; - } - } - - ui->activeModsCounter->display(visActiveCount); - ui->activeModsCounter->setToolTip(tr("" - "" - "" - "" - "" - "" - "
    TypeAllVisible
    Enabled mods: %1 / %2%3 / %4
    Unmanaged/DLCs: %5%6
    Mod backups: %7%8
    Separators: %9%10
    ") - .arg(activeCount) - .arg(regularCount) - .arg(visActiveCount) - .arg(visRegularCount) - .arg(foreignCount) - .arg(visForeignCount) - .arg(backupCount) - .arg(visBackupCount) - .arg(separatorCount) - .arg(visSeparatorCount) - ); -} - -void MainWindow::updatePluginCount() -{ - int activeMasterCount = 0; - int activeLightMasterCount = 0; - int activeRegularCount = 0; - int masterCount = 0; - int lightMasterCount = 0; - int regularCount = 0; - int activeVisibleCount = 0; - - PluginList *list = m_OrganizerCore.pluginList(); - QString filter = ui->espFilterEdit->text(); - - for (QString plugin : list->pluginNames()) { - bool active = list->isEnabled(plugin); - bool visible = m_PluginListSortProxy->filterMatchesPlugin(plugin); - if (list->isLight(plugin) || list->isLightFlagged(plugin)) { - lightMasterCount++; - activeLightMasterCount += active; - activeVisibleCount += visible && active; - } else if (list->isMaster(plugin)) { - masterCount++; - activeMasterCount += active; - activeVisibleCount += visible && active; - } else { - regularCount++; - activeRegularCount += active; - activeVisibleCount += visible && active; - } - } - - int activeCount = activeMasterCount + activeLightMasterCount + activeRegularCount; - int totalCount = masterCount + lightMasterCount + regularCount; - - ui->activePluginsCounter->display(activeVisibleCount); - ui->activePluginsCounter->setToolTip(tr("" - "" - "" - "" - "" - "" - "" - "
    TypeActive Total
    All plugins:%1 %2
    ESMs:%3 %4
    ESPs:%7 %8
    ESMs+ESPs:%9 %10
    ESLs:%5 %6
    ") - .arg(activeCount).arg(totalCount) - .arg(activeMasterCount).arg(masterCount) - .arg(activeLightMasterCount).arg(lightMasterCount) - .arg(activeRegularCount).arg(regularCount) - .arg(activeMasterCount+activeRegularCount).arg(masterCount+regularCount) - ); -} - -void MainWindow::information_clicked() -{ - try { - displayModInformation(m_ContextRow); - } catch (const std::exception &e) { - reportError(e.what()); - } -} - -void MainWindow::createEmptyMod_clicked() -{ - GuessedValue name; - name.setFilter(&fixDirectoryName); - - while (name->isEmpty()) { - bool ok; - name.update(QInputDialog::getText(this, tr("Create Mod..."), - tr("This will create an empty mod.\n" - "Please enter a name:"), QLineEdit::Normal, "", &ok), - GUESS_USER); - if (!ok) { - return; - } - } - - if (m_OrganizerCore.getMod(name) != nullptr) { - reportError(tr("A mod with this name already exists")); - return; - } - - int newPriority = -1; - if (m_ContextRow >= 0 && m_ModListSortProxy->sortColumn() == ModList::COL_PRIORITY) { - newPriority = m_OrganizerCore.currentProfile()->getModPriority(m_ContextRow); - } - - IModInterface *newMod = m_OrganizerCore.createMod(name); - if (newMod == nullptr) { - return; - } - - m_OrganizerCore.refreshModList(); - - if (newPriority >= 0) { - m_OrganizerCore.modList()->changeModPriority(ModInfo::getIndex(name), newPriority); - } -} - -void MainWindow::createSeparator_clicked() -{ - GuessedValue name; - name.setFilter(&fixDirectoryName); - while (name->isEmpty()) - { - bool ok; - name.update(QInputDialog::getText(this, tr("Create Separator..."), - tr("This will create a new separator.\n" - "Please enter a name:"), QLineEdit::Normal, "", &ok), - GUESS_USER); - if (!ok) { return; } - } - if (m_OrganizerCore.getMod(name) != nullptr) - { - reportError(tr("A separator with this name already exists")); - return; - } - name->append("_separator"); - if (m_OrganizerCore.getMod(name) != nullptr) - { - return; - } - - int newPriority = -1; - if (m_ContextRow >= 0 && m_ModListSortProxy->sortColumn() == ModList::COL_PRIORITY) - { - newPriority = m_OrganizerCore.currentProfile()->getModPriority(m_ContextRow); - } - - if (m_OrganizerCore.createMod(name) == nullptr) { return; } - m_OrganizerCore.refreshModList(); - - if (newPriority >= 0) - { - m_OrganizerCore.modList()->changeModPriority(ModInfo::getIndex(name), newPriority); - } - QSettings &settings = m_OrganizerCore.settings().directInterface(); - QColor previousColor = settings.value("previousSeparatorColor", QColor()).value(); - if (previousColor.isValid()) { - ModInfo::getByIndex(ModInfo::getIndex(name))->setColor(previousColor); - } - -} - -void MainWindow::setColor_clicked() -{ - QSettings &settings = m_OrganizerCore.settings().directInterface(); - ModInfo::Ptr modInfo = ModInfo::getByIndex(m_ContextRow); - QColorDialog dialog(this); - dialog.setOption(QColorDialog::ShowAlphaChannel); - QColor currentColor = modInfo->getColor(); - QColor previousColor = settings.value("previousSeparatorColor", QColor()).value(); - if (currentColor.isValid()) - dialog.setCurrentColor(currentColor); - else - dialog.setCurrentColor(previousColor); - if (!dialog.exec()) - return; - currentColor = dialog.currentColor(); - if (!currentColor.isValid()) - return; - settings.setValue("previousSeparatorColor", currentColor); - QItemSelectionModel *selection = ui->modList->selectionModel(); - if (selection->hasSelection() && selection->selectedRows().count() > 1) { - for (QModelIndex idx : selection->selectedRows()) { - ModInfo::Ptr info = ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt()); - auto flags = info->getFlags(); - if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_SEPARATOR) != flags.end()) - { - info->setColor(currentColor); - } - } - } - else { - modInfo->setColor(currentColor); - } -} - -void MainWindow::resetColor_clicked() -{ - ModInfo::Ptr modInfo = ModInfo::getByIndex(m_ContextRow); - QColor color = QColor(); - QItemSelectionModel *selection = ui->modList->selectionModel(); - if (selection->hasSelection() && selection->selectedRows().count() > 1) { - for (QModelIndex idx : selection->selectedRows()) { - ModInfo::Ptr info = ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt()); - auto flags = info->getFlags(); - if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_SEPARATOR) != flags.end()) - { - info->setColor(color); - } - } - } - else { - modInfo->setColor(color); - } - Settings::instance().directInterface().remove("previousSeparatorColor"); -} - -void MainWindow::createModFromOverwrite() -{ - GuessedValue name; - name.setFilter(&fixDirectoryName); - - while (name->isEmpty()) { - bool ok; - name.update(QInputDialog::getText(this, tr("Create Mod..."), - tr("This will move all files from overwrite into a new, regular mod.\n" - "Please enter a name:"), QLineEdit::Normal, "", &ok), - GUESS_USER); - if (!ok) { - return; - } - } - - if (m_OrganizerCore.getMod(name) != nullptr) { - reportError(tr("A mod with this name already exists")); - return; - } - - const IModInterface *newMod = m_OrganizerCore.createMod(name); - if (newMod == nullptr) { - return; - } - - doMoveOverwriteContentToMod(newMod->absolutePath()); -} - -void MainWindow::moveOverwriteContentToExistingMod() -{ - QStringList mods; - auto indexesByPriority = m_OrganizerCore.currentProfile()->getAllIndexesByPriority(); - for (auto & iter : indexesByPriority) { - if ((iter.second != UINT_MAX)) { - ModInfo::Ptr modInfo = ModInfo::getByIndex(iter.second); - if (!modInfo->hasFlag(ModInfo::FLAG_SEPARATOR) && !modInfo->hasFlag(ModInfo::FLAG_FOREIGN) && !modInfo->hasFlag(ModInfo::FLAG_OVERWRITE)) { - mods << modInfo->name(); - } - } - } - - ListDialog dialog(this); - QSettings &settings = m_OrganizerCore.settings().directInterface(); - QString key = QString("geometry/%1").arg(dialog.objectName()); - - dialog.setWindowTitle("Select a mod..."); - dialog.setChoices(mods); - - if (settings.contains(key)) { - dialog.restoreGeometry(settings.value(key).toByteArray()); - } - if (dialog.exec() == QDialog::Accepted) { - - QString result = dialog.getChoice(); - if (!result.isEmpty()) { - - QString modAbsolutePath; - - for (const auto& mod : m_OrganizerCore.modsSortedByProfilePriority()) { - if (result.compare(mod) == 0) { - ModInfo::Ptr modInfo = ModInfo::getByIndex(ModInfo::getIndex(mod)); - modAbsolutePath = modInfo->absolutePath(); - break; - } - } - - if (modAbsolutePath.isNull()) { - qWarning("Mod %s has not been found, for some reason", qUtf8Printable(result)); - return; - } - - doMoveOverwriteContentToMod(modAbsolutePath); - } - } - settings.setValue(key, dialog.saveGeometry()); -} - -void MainWindow::doMoveOverwriteContentToMod(const QString &modAbsolutePath) -{ - unsigned int overwriteIndex = ModInfo::findMod([](ModInfo::Ptr mod) -> bool { - std::vector flags = mod->getFlags(); - return std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end(); }); - - ModInfo::Ptr overwriteInfo = ModInfo::getByIndex(overwriteIndex); - bool successful = shellMove((QDir::toNativeSeparators(overwriteInfo->absolutePath()) + "\\*"), - (QDir::toNativeSeparators(modAbsolutePath)), false, this); - - if (successful) { - MessageDialog::showMessage(tr("Move successful."), this); - } - else { - qCritical("Move operation failed: %s", qUtf8Printable(windowsErrorString(::GetLastError()))); - } - - m_OrganizerCore.refreshModList(); -} - -void MainWindow::clearOverwrite() -{ - unsigned int overwriteIndex = ModInfo::findMod([](ModInfo::Ptr mod) -> bool { - std::vector flags = mod->getFlags(); - return std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) - != flags.end(); - }); - - ModInfo::Ptr modInfo = ModInfo::getByIndex(overwriteIndex); - if (modInfo) - { - QDir overwriteDir(modInfo->absolutePath()); - if (QMessageBox::question(this, tr("Are you sure?"), - tr("About to recursively delete:\n") + overwriteDir.absolutePath(), - QMessageBox::Ok | QMessageBox::Cancel) == QMessageBox::Ok) - { - QStringList delList; - for (auto f : overwriteDir.entryList(QDir::AllDirs | QDir::Files | QDir::NoDotAndDotDot)) - delList.push_back(overwriteDir.absoluteFilePath(f)); - shellDelete(delList, true); - updateProblemsButton(); - } - } -} - -void MainWindow::cancelModListEditor() -{ - ui->modList->setEnabled(false); - ui->modList->setEnabled(true); -} - -void MainWindow::on_modList_doubleClicked(const QModelIndex &index) -{ - if (!index.isValid()) { - return; - } - - if (m_OrganizerCore.modList()->timeElapsedSinceLastChecked() <= QApplication::doubleClickInterval()) { - // don't interpret double click if we only just checked a mod - return; - } - - QModelIndex sourceIdx = mapToModel(m_OrganizerCore.modList(), index); - if (!sourceIdx.isValid()) { - return; - } - - Qt::KeyboardModifiers modifiers = QApplication::queryKeyboardModifiers(); - if (modifiers.testFlag(Qt::ControlModifier)) { - try { - m_ContextRow = m_ModListSortProxy->mapToSource(index).row(); - openExplorer_clicked(); - // workaround to cancel the editor that might have opened because of - // selection-click - ui->modList->closePersistentEditor(index); - } - catch (const std::exception &e) { - reportError(e.what()); - } - } - else { - try { - m_ContextRow = m_ModListSortProxy->mapToSource(index).row(); - sourceIdx.column(); - int tab = -1; - switch (sourceIdx.column()) { - case ModList::COL_NOTES: tab = ModInfoDialog::TAB_NOTES; break; - case ModList::COL_VERSION: tab = ModInfoDialog::TAB_NEXUS; break; - case ModList::COL_MODID: tab = ModInfoDialog::TAB_NEXUS; break; - case ModList::COL_GAME: tab = ModInfoDialog::TAB_NEXUS; break; - case ModList::COL_CATEGORY: tab = ModInfoDialog::TAB_CATEGORIES; break; - case ModList::COL_FLAGS: tab = ModInfoDialog::TAB_CONFLICTS; break; - default: tab = -1; - } - displayModInformation(sourceIdx.row(), tab); - // workaround to cancel the editor that might have opened because of - // selection-click - ui->modList->closePersistentEditor(index); - } - catch (const std::exception &e) { - reportError(e.what()); - } - } -} - -void MainWindow::on_listOptionsBtn_pressed() -{ - m_ContextRow = -1; -} - -void MainWindow::openOriginInformation_clicked() -{ - try { - QItemSelectionModel *selection = ui->espList->selectionModel(); - //we don't want to open multiple modinfodialogs. - /*if (selection->hasSelection() && selection->selectedRows().count() > 0) { - - for (QModelIndex idx : selection->selectedRows()) { - QString fileName = idx.data().toString(); - ModInfo::Ptr modInfo = ModInfo::getByIndex(ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(fileName))); - std::vector flags = modInfo->getFlags(); - - if (modInfo->isRegular() || (std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end())) { - displayModInformation(ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(fileName))); - } - } - } - else {}*/ - QModelIndex idx = selection->currentIndex(); - QString fileName = idx.data().toString(); - - ModInfo::Ptr modInfo = ModInfo::getByIndex(ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(fileName))); - std::vector flags = modInfo->getFlags(); - - if (modInfo->isRegular() || (std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end())) { - displayModInformation(ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(fileName))); - } - } - catch (const std::exception &e) { - reportError(e.what()); - } -} - -void MainWindow::on_espList_doubleClicked(const QModelIndex &index) -{ - if (!index.isValid()) { - return; - } - - if (m_OrganizerCore.pluginList()->timeElapsedSinceLastChecked() <= QApplication::doubleClickInterval()) { - // don't interpret double click if we only just checked a plugin - return; - } - - QModelIndex sourceIdx = mapToModel(m_OrganizerCore.pluginList(), index); - if (!sourceIdx.isValid()) { - return; - } - try { - - QItemSelectionModel *selection = ui->espList->selectionModel(); - - if (selection->hasSelection() && selection->selectedRows().count() == 1) { - - QModelIndex idx = selection->currentIndex(); - QString fileName = idx.data().toString(); - - if (ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(fileName)) == UINT_MAX) - return; - - ModInfo::Ptr modInfo = ModInfo::getByIndex(ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(fileName))); - std::vector flags = modInfo->getFlags(); - - if (modInfo->isRegular() || (std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end())) { - - Qt::KeyboardModifiers modifiers = QApplication::queryKeyboardModifiers(); - if (modifiers.testFlag(Qt::ControlModifier)) { - openExplorer_activated(); - // workaround to cancel the editor that might have opened because of - // selection-click - ui->espList->closePersistentEditor(index); - } - else { - - displayModInformation(ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(fileName))); - // workaround to cancel the editor that might have opened because of - // selection-click - ui->espList->closePersistentEditor(index); - } - } - } - } - catch (const std::exception &e) { - reportError(e.what()); - } -} - -bool MainWindow::populateMenuCategories(QMenu *menu, int targetID) -{ - ModInfo::Ptr modInfo = ModInfo::getByIndex(m_ContextRow); - const std::set &categories = modInfo->getCategories(); - - bool childEnabled = false; - - for (unsigned int i = 1; i < m_CategoryFactory.numCategories(); ++i) { - if (m_CategoryFactory.getParentID(i) == targetID) { - QMenu *targetMenu = menu; - if (m_CategoryFactory.hasChildren(i)) { - targetMenu = menu->addMenu(m_CategoryFactory.getCategoryName(i).replace('&', "&&")); - } - - int id = m_CategoryFactory.getCategoryID(i); - QScopedPointer checkBox(new QCheckBox(targetMenu)); - bool enabled = categories.find(id) != categories.end(); - checkBox->setText(m_CategoryFactory.getCategoryName(i).replace('&', "&&")); - if (enabled) { - childEnabled = true; - } - checkBox->setChecked(enabled ? Qt::Checked : Qt::Unchecked); - - QScopedPointer checkableAction(new QWidgetAction(targetMenu)); - checkableAction->setDefaultWidget(checkBox.take()); - checkableAction->setData(id); - targetMenu->addAction(checkableAction.take()); - - if (m_CategoryFactory.hasChildren(i)) { - if (populateMenuCategories(targetMenu, m_CategoryFactory.getCategoryID(i)) || enabled) { - targetMenu->setIcon(QIcon(":/MO/gui/resources/check.png")); - } - } - } - } - return childEnabled; -} - -void MainWindow::replaceCategoriesFromMenu(QMenu *menu, int modRow) -{ - ModInfo::Ptr modInfo = ModInfo::getByIndex(modRow); - for (QAction* action : menu->actions()) { - if (action->menu() != nullptr) { - replaceCategoriesFromMenu(action->menu(), modRow); - } else { - QWidgetAction *widgetAction = qobject_cast(action); - if (widgetAction != nullptr) { - QCheckBox *checkbox = qobject_cast(widgetAction->defaultWidget()); - modInfo->setCategory(widgetAction->data().toInt(), checkbox->isChecked()); - } - } - } -} - -void MainWindow::addRemoveCategoriesFromMenu(QMenu *menu, int modRow, int referenceRow) -{ - if (referenceRow != -1 && referenceRow != modRow) { - ModInfo::Ptr editedModInfo = ModInfo::getByIndex(referenceRow); - for (QAction* action : menu->actions()) { - if (action->menu() != nullptr) { - addRemoveCategoriesFromMenu(action->menu(), modRow, referenceRow); - } else { - QWidgetAction *widgetAction = qobject_cast(action); - if (widgetAction != nullptr) { - QCheckBox *checkbox = qobject_cast(widgetAction->defaultWidget()); - int categoryId = widgetAction->data().toInt(); - bool checkedBefore = editedModInfo->categorySet(categoryId); - bool checkedAfter = checkbox->isChecked(); - - if (checkedBefore != checkedAfter) { // only update if the category was changed on the edited mod - ModInfo::Ptr currentModInfo = ModInfo::getByIndex(modRow); - currentModInfo->setCategory(categoryId, checkedAfter); - } - } - } - } - } else { - replaceCategoriesFromMenu(menu, modRow); - } -} - -void MainWindow::addRemoveCategories_MenuHandler() { - QMenu *menu = qobject_cast(sender()); - if (menu == nullptr) { - qCritical("not a menu?"); - return; - } - - QList selected; - for (const QModelIndex &idx : ui->modList->selectionModel()->selectedRows()) { - selected.append(QPersistentModelIndex(idx)); - } - - if (selected.size() > 0) { - int minRow = INT_MAX; - int maxRow = -1; - - for (const QPersistentModelIndex &idx : selected) { - qDebug("change categories on: %s", qUtf8Printable(idx.data().toString())); - QModelIndex modIdx = mapToModel(m_OrganizerCore.modList(), idx); - if (modIdx.row() != m_ContextIdx.row()) { - addRemoveCategoriesFromMenu(menu, modIdx.row(), m_ContextIdx.row()); - } - if (idx.row() < minRow) minRow = idx.row(); - if (idx.row() > maxRow) maxRow = idx.row(); - } - replaceCategoriesFromMenu(menu, m_ContextIdx.row()); - - m_OrganizerCore.modList()->notifyChange(minRow, maxRow + 1); - - for (const QPersistentModelIndex &idx : selected) { - ui->modList->selectionModel()->select(idx, QItemSelectionModel::Select | QItemSelectionModel::Rows); - } - } else { - //For single mod selections, just do a replace - replaceCategoriesFromMenu(menu, m_ContextRow); - m_OrganizerCore.modList()->notifyChange(m_ContextRow); - } - - refreshFilters(); -} - -void MainWindow::replaceCategories_MenuHandler() { - QMenu *menu = qobject_cast(sender()); - if (menu == nullptr) { - qCritical("not a menu?"); - return; - } - - QList selected; - for (const QModelIndex &idx : ui->modList->selectionModel()->selectedRows()) { - selected.append(QPersistentModelIndex(idx)); - } - - if (selected.size() > 0) { - QStringList selectedMods; - int minRow = INT_MAX; - int maxRow = -1; - for (int i = 0; i < selected.size(); ++i) { - QModelIndex temp = mapToModel(m_OrganizerCore.modList(), selected.at(i)); - selectedMods.append(temp.data().toString()); - replaceCategoriesFromMenu(menu, mapToModel(m_OrganizerCore.modList(), selected.at(i)).row()); - if (temp.row() < minRow) minRow = temp.row(); - if (temp.row() > maxRow) maxRow = temp.row(); - } - - m_OrganizerCore.modList()->notifyChange(minRow, maxRow + 1); - - // find mods by their name because indices are invalidated - QAbstractItemModel *model = ui->modList->model(); - for (const QString &mod : selectedMods) { - QModelIndexList matches = model->match(model->index(0, 0), Qt::DisplayRole, mod, 1, - Qt::MatchFixedString | Qt::MatchCaseSensitive | Qt::MatchRecursive); - if (matches.size() > 0) { - ui->modList->selectionModel()->select(matches.at(0), QItemSelectionModel::Select | QItemSelectionModel::Rows); - } - } - } else { - //For single mod selections, just do a replace - replaceCategoriesFromMenu(menu, m_ContextRow); - m_OrganizerCore.modList()->notifyChange(m_ContextRow); - } - - refreshFilters(); -} - -void MainWindow::saveArchiveList() -{ - if (m_OrganizerCore.isArchivesInit()) { - SafeWriteFile archiveFile(m_OrganizerCore.currentProfile()->getArchivesFileName()); - for (int i = 0; i < ui->bsaList->topLevelItemCount(); ++i) { - QTreeWidgetItem * tlItem = ui->bsaList->topLevelItem(i); - for (int j = 0; j < tlItem->childCount(); ++j) { - QTreeWidgetItem * item = tlItem->child(j); - if (item->checkState(0) == Qt::Checked) { - archiveFile->write(item->text(0).toUtf8().append("\r\n")); - } - } - } - if (archiveFile.commitIfDifferent(m_ArchiveListHash)) { - qDebug("%s saved", qUtf8Printable(QDir::toNativeSeparators(m_OrganizerCore.currentProfile()->getArchivesFileName()))); - } - } else { - qWarning("archive list not initialised"); - } -} - -void MainWindow::checkModsForUpdates() -{ - statusBar()->show(); - if (NexusInterface::instance(&m_PluginContainer)->getAccessManager()->loggedIn()) { - m_ModsToUpdate = ModInfo::checkAllForUpdate(&m_PluginContainer, this); - m_RefreshProgress->setRange(0, m_ModsToUpdate); - } else { - QString username, password; - if (m_OrganizerCore.settings().getNexusLogin(username, password)) { - m_OrganizerCore.doAfterLogin([this] () { this->checkModsForUpdates(); }); - NexusInterface::instance(&m_PluginContainer)->getAccessManager()->login(username, password); - } else { // otherwise there will be no endorsement info - MessageDialog::showMessage(tr("Not logged in, endorsement information will be wrong"), - this, true); - m_ModsToUpdate = ModInfo::checkAllForUpdate(&m_PluginContainer, this); - } - } -} - -void MainWindow::changeVersioningScheme() { - if (QMessageBox::question(this, tr("Continue?"), - tr("The versioning scheme decides which version is considered newer than another.\n" - "This function will guess the versioning scheme under the assumption that the installed version is outdated."), - QMessageBox::Yes | QMessageBox::Cancel) == QMessageBox::Yes) { - - ModInfo::Ptr info = ModInfo::getByIndex(m_ContextRow); - - bool success = false; - - static VersionInfo::VersionScheme schemes[] = { VersionInfo::SCHEME_REGULAR, VersionInfo::SCHEME_DECIMALMARK, VersionInfo::SCHEME_NUMBERSANDLETTERS }; - - for (int i = 0; i < sizeof(schemes) / sizeof(VersionInfo::VersionScheme) && !success; ++i) { - VersionInfo verOld(info->getVersion().canonicalString(), schemes[i]); - VersionInfo verNew(info->getNewestVersion().canonicalString(), schemes[i]); - if (verOld < verNew) { - info->setVersion(verOld); - info->setNewestVersion(verNew); - success = true; - } - } - if (!success) { - QMessageBox::information(this, tr("Sorry"), - tr("I don't know a versioning scheme where %1 is newer than %2.").arg(info->getNewestVersion().canonicalString()).arg(info->getVersion().canonicalString()), - QMessageBox::Ok); - } - } -} - -void MainWindow::ignoreUpdate() { - QItemSelectionModel *selection = ui->modList->selectionModel(); - if (selection->hasSelection() && selection->selectedRows().count() > 1) { - for (QModelIndex idx : selection->selectedRows()) { - ModInfo::Ptr info = ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt()); - info->ignoreUpdate(true); - } - } - else { - ModInfo::Ptr info = ModInfo::getByIndex(m_ContextRow); - info->ignoreUpdate(true); - } - if (m_ModListSortProxy != nullptr) { - m_ModListSortProxy->invalidate(); - } -} - -void MainWindow::unignoreUpdate() -{ - QItemSelectionModel *selection = ui->modList->selectionModel(); - if (selection->hasSelection() && selection->selectedRows().count() > 1) { - for (QModelIndex idx : selection->selectedRows()) { - ModInfo::Ptr info = ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt()); - info->ignoreUpdate(false); - } - } - else { - ModInfo::Ptr info = ModInfo::getByIndex(m_ContextRow); - info->ignoreUpdate(false); - } - if (m_ModListSortProxy != nullptr) { - m_ModListSortProxy->invalidate(); - } -} - -void MainWindow::addPrimaryCategoryCandidates(QMenu *primaryCategoryMenu, - ModInfo::Ptr info) { - const std::set &categories = info->getCategories(); - for (int categoryID : categories) { - int catIdx = m_CategoryFactory.getCategoryIndex(categoryID); - QWidgetAction *action = new QWidgetAction(primaryCategoryMenu); - try { - QRadioButton *categoryBox = new QRadioButton( - m_CategoryFactory.getCategoryName(catIdx).replace('&', "&&"), - primaryCategoryMenu); - connect(categoryBox, &QRadioButton::toggled, [info, categoryID](bool enable) { - if (enable) { - info->setPrimaryCategory(categoryID); - } - }); - categoryBox->setChecked(categoryID == info->getPrimaryCategory()); - action->setDefaultWidget(categoryBox); - } catch (const std::exception &e) { - qCritical("failed to create category checkbox: %s", e.what()); - } - - action->setData(categoryID); - primaryCategoryMenu->addAction(action); - } -} - -void MainWindow::addPrimaryCategoryCandidates() -{ - QMenu *menu = qobject_cast(sender()); - if (menu == nullptr) { - qCritical("not a menu?"); - return; - } - menu->clear(); - ModInfo::Ptr modInfo = ModInfo::getByIndex(m_ContextRow); - - addPrimaryCategoryCandidates(menu, modInfo); -} - -void MainWindow::enableVisibleMods() -{ - if (QMessageBox::question(nullptr, tr("Confirm"), tr("Really enable all visible mods?"), - QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { - m_ModListSortProxy->enableAllVisible(); - } -} - -void MainWindow::disableVisibleMods() -{ - if (QMessageBox::question(nullptr, tr("Confirm"), tr("Really disable all visible mods?"), - QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { - m_ModListSortProxy->disableAllVisible(); - } -} - -void MainWindow::openInstanceFolder() -{ - QString dataPath = qApp->property("dataPath").toString(); - ::ShellExecuteW(nullptr, L"explore", ToWString(dataPath).c_str(), nullptr, nullptr, SW_SHOWNORMAL); - - //opens BaseDirectory instead - //::ShellExecuteW(nullptr, L"explore", ToWString(m_OrganizerCore.settings().getBaseDirectory()).c_str(), nullptr, nullptr, SW_SHOWNORMAL); -} - -void MainWindow::openLogsFolder() -{ - QString logsPath = qApp->property("dataPath").toString() + "/" + QString::fromStdWString(AppConfig::logPath()); - ::ShellExecuteW(nullptr, L"explore", ToWString(logsPath).c_str(), nullptr, nullptr, SW_SHOWNORMAL); -} - -void MainWindow::openInstallFolder() -{ - ::ShellExecuteW(nullptr, L"explore", ToWString(qApp->applicationDirPath()).c_str(), nullptr, nullptr, SW_SHOWNORMAL); -} - -void MainWindow::openPluginsFolder() -{ - QString pluginsPath = QCoreApplication::applicationDirPath() + "/" + ToQString(AppConfig::pluginPath()); - ::ShellExecuteW(nullptr, L"explore", ToWString(pluginsPath).c_str(), nullptr, nullptr, SW_SHOWNORMAL); -} - - -void MainWindow::openProfileFolder() -{ - ::ShellExecuteW(nullptr, L"explore", ToWString(m_OrganizerCore.currentProfile()->absolutePath()).c_str(), nullptr, nullptr, SW_SHOWNORMAL); -} - -void MainWindow::openIniFolder() -{ - if (m_OrganizerCore.currentProfile()->localSettingsEnabled()) - { - ::ShellExecuteW(nullptr, L"explore", ToWString(m_OrganizerCore.currentProfile()->absolutePath()).c_str(), nullptr, nullptr, SW_SHOWNORMAL); - } - else { - ::ShellExecuteW(nullptr, L"explore", ToWString(m_OrganizerCore.managedGame()->documentsDirectory().absolutePath()).c_str(), nullptr, nullptr, SW_SHOWNORMAL); - } -} - -void MainWindow::openDownloadsFolder() -{ - ::ShellExecuteW(nullptr, L"explore", ToWString(m_OrganizerCore.settings().getDownloadDirectory()).c_str(), nullptr, nullptr, SW_SHOWNORMAL); -} - -void MainWindow::openModsFolder() -{ - ::ShellExecuteW(nullptr, L"explore", ToWString(m_OrganizerCore.settings().getModDirectory()).c_str(), nullptr, nullptr, SW_SHOWNORMAL); -} - -void MainWindow::openGameFolder() -{ - ::ShellExecuteW(nullptr, L"explore", ToWString(m_OrganizerCore.managedGame()->gameDirectory().absolutePath()).c_str(), nullptr, nullptr, SW_SHOWNORMAL); -} - -void MainWindow::openMyGamesFolder() -{ - ::ShellExecuteW(nullptr, L"explore", ToWString(m_OrganizerCore.managedGame()->documentsDirectory().absolutePath()).c_str(), nullptr, nullptr, SW_SHOWNORMAL); -} - - -void MainWindow::exportModListCSV() -{ - //SelectionDialog selection(tr("Choose what to export")); - - //selection.addChoice(tr("Everything"), tr("All installed mods are included in the list"), 0); - //selection.addChoice(tr("Active Mods"), tr("Only active (checked) mods from your current profile are included"), 1); - //selection.addChoice(tr("Visible"), tr("All mods visible in the mod list are included"), 2); - - QDialog selection(this); - QGridLayout *grid = new QGridLayout; - selection.setWindowTitle(tr("Export to csv")); - - QLabel *csvDescription = new QLabel(); - csvDescription->setText(tr("CSV (Comma Separated Values) is a format that can be imported in programs like Excel to create a spreadsheet.\nYou can also use online editors and converters instead.")); - grid->addWidget(csvDescription); - - QGroupBox *groupBoxRows = new QGroupBox(tr("Select what mods you want export:")); - QRadioButton *all = new QRadioButton(tr("All installed mods")); - QRadioButton *active = new QRadioButton(tr("Only active (checked) mods from your current profile")); - QRadioButton *visible = new QRadioButton(tr("All currently visible mods in the mod list")); - - QVBoxLayout *vbox = new QVBoxLayout; - vbox->addWidget(all); - vbox->addWidget(active); - vbox->addWidget(visible); - vbox->addStretch(1); - groupBoxRows->setLayout(vbox); - - - - grid->addWidget(groupBoxRows); - - QButtonGroup *buttonGroupRows = new QButtonGroup(); - buttonGroupRows->addButton(all, 0); - buttonGroupRows->addButton(active, 1); - buttonGroupRows->addButton(visible, 2); - buttonGroupRows->button(0)->setChecked(true); - - - - QGroupBox *groupBoxColumns = new QGroupBox(tr("Choose what Columns to export:")); - groupBoxColumns->setFlat(true); - - QCheckBox *mod_Priority = new QCheckBox(tr("Mod_Priority")); - mod_Priority->setChecked(true); - QCheckBox *mod_Name = new QCheckBox(tr("Mod_Name")); - mod_Name->setChecked(true); - QCheckBox *mod_Note = new QCheckBox(tr("Notes_column")); - QCheckBox *mod_Status = new QCheckBox(tr("Mod_Status")); - QCheckBox *primary_Category = new QCheckBox(tr("Primary_Category")); - QCheckBox *nexus_ID = new QCheckBox(tr("Nexus_ID")); - QCheckBox *mod_Nexus_URL = new QCheckBox(tr("Mod_Nexus_URL")); - QCheckBox *mod_Version = new QCheckBox(tr("Mod_Version")); - QCheckBox *install_Date = new QCheckBox(tr("Install_Date")); - QCheckBox *download_File_Name = new QCheckBox(tr("Download_File_Name")); - - QVBoxLayout *vbox1 = new QVBoxLayout; - vbox1->addWidget(mod_Priority); - vbox1->addWidget(mod_Name); - vbox1->addWidget(mod_Status); - vbox1->addWidget(mod_Note); - vbox1->addWidget(primary_Category); - vbox1->addWidget(nexus_ID); - vbox1->addWidget(mod_Nexus_URL); - vbox1->addWidget(mod_Version); - vbox1->addWidget(install_Date); - vbox1->addWidget(download_File_Name); - groupBoxColumns->setLayout(vbox1); - - grid->addWidget(groupBoxColumns); - - QPushButton *ok = new QPushButton("Ok"); - QPushButton *cancel = new QPushButton("Cancel"); - QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); - - connect(buttons, SIGNAL(accepted()), &selection, SLOT(accept())); - connect(buttons, SIGNAL(rejected()), &selection, SLOT(reject())); - - grid->addWidget(buttons); - - selection.setLayout(grid); - - - if (selection.exec() == QDialog::Accepted) { - - unsigned int numMods = ModInfo::getNumMods(); - int selectedRowID = buttonGroupRows->checkedId(); - - try { - QBuffer buffer; - buffer.open(QIODevice::ReadWrite); - CSVBuilder builder(&buffer); - builder.setEscapeMode(CSVBuilder::TYPE_STRING, CSVBuilder::QUOTE_ALWAYS); - std::vector > fields; - if (mod_Priority->isChecked()) - fields.push_back(std::make_pair(QString("#Mod_Priority"), CSVBuilder::TYPE_STRING)); - if (mod_Name->isChecked()) - fields.push_back(std::make_pair(QString("#Mod_Name"), CSVBuilder::TYPE_STRING)); - if (mod_Status->isChecked()) - fields.push_back(std::make_pair(QString("#Mod_Status"), CSVBuilder::TYPE_STRING)); - if (mod_Note->isChecked()) - fields.push_back(std::make_pair(QString("#Note"), CSVBuilder::TYPE_STRING)); - if (primary_Category->isChecked()) - fields.push_back(std::make_pair(QString("#Primary_Category"), CSVBuilder::TYPE_STRING)); - if (nexus_ID->isChecked()) - fields.push_back(std::make_pair(QString("#Nexus_ID"), CSVBuilder::TYPE_INTEGER)); - if (mod_Nexus_URL->isChecked()) - fields.push_back(std::make_pair(QString("#Mod_Nexus_URL"), CSVBuilder::TYPE_STRING)); - if (mod_Version->isChecked()) - fields.push_back(std::make_pair(QString("#Mod_Version"), CSVBuilder::TYPE_STRING)); - if (install_Date->isChecked()) - fields.push_back(std::make_pair(QString("#Install_Date"), CSVBuilder::TYPE_STRING)); - if (download_File_Name->isChecked()) - fields.push_back(std::make_pair(QString("#Download_File_Name"), CSVBuilder::TYPE_STRING)); - - builder.setFields(fields); - - builder.writeHeader(); - - for (unsigned int i = 0; i < numMods; ++i) { - ModInfo::Ptr info = ModInfo::getByIndex(i); - bool enabled = m_OrganizerCore.currentProfile()->modEnabled(i); - if ((selectedRowID == 1) && !enabled) { - continue; - } - else if ((selectedRowID == 2) && !m_ModListSortProxy->filterMatchesMod(info, enabled)) { - continue; - } - std::vector flags = info->getFlags(); - if ((std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) == flags.end()) && - (std::find(flags.begin(), flags.end(), ModInfo::FLAG_BACKUP) == flags.end())) { - if (mod_Priority->isChecked()) - builder.setRowField("#Mod_Priority", QString("%1").arg(m_OrganizerCore.currentProfile()->getModPriority(i), 4, 10, QChar('0'))); - if (mod_Name->isChecked()) - builder.setRowField("#Mod_Name", info->name()); - if (mod_Status->isChecked()) - builder.setRowField("#Mod_Status", (enabled)? "Enabled" : "Disabled"); - if (mod_Note->isChecked()) - builder.setRowField("#Note", QString("%1").arg(info->comments().remove(','))); - if (primary_Category->isChecked()) - builder.setRowField("#Primary_Category", (m_CategoryFactory.categoryExists(info->getPrimaryCategory())) ? m_CategoryFactory.getCategoryName(info->getPrimaryCategory()) : ""); - if (nexus_ID->isChecked()) - builder.setRowField("#Nexus_ID", info->getNexusID()); - if (mod_Nexus_URL->isChecked()) - builder.setRowField("#Mod_Nexus_URL",(info->getNexusID()>0)? NexusInterface::instance(&m_PluginContainer)->getModURL(info->getNexusID(), info->getGameName()) : ""); - if (mod_Version->isChecked()) - builder.setRowField("#Mod_Version", info->getVersion().canonicalString()); - if (install_Date->isChecked()) - builder.setRowField("#Install_Date", info->creationTime().toString("yyyy/MM/dd HH:mm:ss")); - if (download_File_Name->isChecked()) - builder.setRowField("#Download_File_Name", info->getInstallationFile()); - - builder.writeRow(); - } - } - - SaveTextAsDialog saveDialog(this); - saveDialog.setText(buffer.data()); - saveDialog.exec(); - } - catch (const std::exception &e) { - reportError(tr("export failed: %1").arg(e.what())); - } - } -} - -static void addMenuAsPushButton(QMenu *menu, QMenu *subMenu) -{ - QPushButton *pushBtn = new QPushButton(subMenu->title()); - pushBtn->setMenu(subMenu); - QWidgetAction *action = new QWidgetAction(menu); - action->setDefaultWidget(pushBtn); - menu->addAction(action); -} - -QMenu *MainWindow::openFolderMenu() -{ - - QMenu *FolderMenu = new QMenu(this); - - FolderMenu->addAction(tr("Open Game folder"), this, SLOT(openGameFolder())); - - FolderMenu->addAction(tr("Open MyGames folder"), this, SLOT(openMyGamesFolder())); - - FolderMenu->addAction(tr("Open INIs folder"), this, SLOT(openIniFolder())); - - FolderMenu->addSeparator(); - - FolderMenu->addAction(tr("Open Instance folder"), this, SLOT(openInstanceFolder())); - - FolderMenu->addAction(tr("Open Mods folder"), this, SLOT(openModsFolder())); - - FolderMenu->addAction(tr("Open Profile folder"), this, SLOT(openProfileFolder())); - - FolderMenu->addAction(tr("Open Downloads folder"), this, SLOT(openDownloadsFolder())); - - FolderMenu->addSeparator(); - - FolderMenu->addAction(tr("Open MO2 Install folder"), this, SLOT(openInstallFolder())); - - FolderMenu->addAction(tr("Open MO2 Plugins folder"), this, SLOT(openPluginsFolder())); - - FolderMenu->addAction(tr("Open MO2 Logs folder"), this, SLOT(openLogsFolder())); - - - return FolderMenu; -} - -void MainWindow::initModListContextMenu(QMenu *menu) -{ - menu->addAction(tr("Install Mod..."), this, SLOT(installMod_clicked())); - menu->addAction(tr("Create empty mod"), this, SLOT(createEmptyMod_clicked())); - menu->addAction(tr("Create Separator"), this, SLOT(createSeparator_clicked())); - - menu->addSeparator(); - - menu->addAction(tr("Enable all visible"), this, SLOT(enableVisibleMods())); - menu->addAction(tr("Disable all visible"), this, SLOT(disableVisibleMods())); - menu->addAction(tr("Check all for update"), this, SLOT(checkModsForUpdates())); - menu->addAction(tr("Refresh"), &m_OrganizerCore, SLOT(profileRefresh())); - menu->addAction(tr("Export to csv..."), this, SLOT(exportModListCSV())); -} - -void MainWindow::addModSendToContextMenu(QMenu *menu) -{ - if (m_ModListSortProxy->sortColumn() != ModList::COL_PRIORITY) - return; - - QMenu *sub_menu = new QMenu(menu); - sub_menu->setTitle(tr("Send to")); - sub_menu->addAction(tr("Top"), this, SLOT(sendSelectedModsToTop_clicked())); - sub_menu->addAction(tr("Bottom"), this, SLOT(sendSelectedModsToBottom_clicked())); - sub_menu->addAction(tr("Priority..."), this, SLOT(sendSelectedModsToPriority_clicked())); - sub_menu->addAction(tr("Separator..."), this, SLOT(sendSelectedModsToSeparator_clicked())); - - menu->addMenu(sub_menu); - menu->addSeparator(); -} - -void MainWindow::addPluginSendToContextMenu(QMenu *menu) -{ - if (m_PluginListSortProxy->sortColumn() != PluginList::COL_PRIORITY) - return; - - QMenu *sub_menu = new QMenu(this); - sub_menu->setTitle(tr("Send to")); - sub_menu->addAction(tr("Top"), this, SLOT(sendSelectedPluginsToTop_clicked())); - sub_menu->addAction(tr("Bottom"), this, SLOT(sendSelectedPluginsToBottom_clicked())); - sub_menu->addAction(tr("Priority..."), this, SLOT(sendSelectedPluginsToPriority_clicked())); - - menu->addMenu(sub_menu); - menu->addSeparator(); -} - -void MainWindow::on_modList_customContextMenuRequested(const QPoint &pos) -{ - try { - QTreeView *modList = findChild("modList"); - - m_ContextIdx = mapToModel(m_OrganizerCore.modList(), modList->indexAt(pos)); - m_ContextRow = m_ContextIdx.row(); - - if (m_ContextRow == -1) { - // no selection - QMenu menu(this); - initModListContextMenu(&menu); - menu.exec(modList->mapToGlobal(pos)); - } else { - QMenu menu(this); - - QMenu *allMods = new QMenu(&menu); - initModListContextMenu(allMods); - allMods->setTitle(tr("All Mods")); - menu.addMenu(allMods); - menu.addSeparator(); - - ModInfo::Ptr info = ModInfo::getByIndex(m_ContextRow); - std::vector flags = info->getFlags(); - if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end()) { - if (QDir(info->absolutePath()).count() > 2) { - menu.addAction(tr("Sync to Mods..."), &m_OrganizerCore, SLOT(syncOverwrite())); - menu.addAction(tr("Create Mod..."), this, SLOT(createModFromOverwrite())); - menu.addAction(tr("Move content to Mod..."), this, SLOT(moveOverwriteContentToExistingMod())); - menu.addAction(tr("Clear Overwrite..."), this, SLOT(clearOverwrite())); - } - menu.addAction(tr("Open in Explorer"), this, SLOT(openExplorer_clicked())); - } else if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_BACKUP) != flags.end()) { - menu.addAction(tr("Restore Backup"), this, SLOT(restoreBackup_clicked())); - menu.addAction(tr("Remove Backup..."), this, SLOT(removeMod_clicked())); - } else if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_SEPARATOR) != flags.end()){ - menu.addSeparator(); - QMenu *addRemoveCategoriesMenu = new QMenu(tr("Change Categories"), &menu); - populateMenuCategories(addRemoveCategoriesMenu, 0); - connect(addRemoveCategoriesMenu, SIGNAL(aboutToHide()), this, SLOT(addRemoveCategories_MenuHandler())); - addMenuAsPushButton(&menu, addRemoveCategoriesMenu); - QMenu *primaryCategoryMenu = new QMenu(tr("Primary Category"), &menu); - connect(primaryCategoryMenu, SIGNAL(aboutToShow()), this, SLOT(addPrimaryCategoryCandidates())); - addMenuAsPushButton(&menu, primaryCategoryMenu); - menu.addSeparator(); - menu.addAction(tr("Rename Separator..."), this, SLOT(renameMod_clicked())); - menu.addAction(tr("Remove Separator..."), this, SLOT(removeMod_clicked())); - menu.addSeparator(); - addModSendToContextMenu(&menu); - menu.addAction(tr("Select Color..."), this, SLOT(setColor_clicked())); - if(info->getColor().isValid()) - menu.addAction(tr("Reset Color"), this, SLOT(resetColor_clicked())); - menu.addSeparator(); - } else if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_FOREIGN) != flags.end()) { - addModSendToContextMenu(&menu); - } else { - QMenu *addRemoveCategoriesMenu = new QMenu(tr("Change Categories"), &menu); - populateMenuCategories(addRemoveCategoriesMenu, 0); - connect(addRemoveCategoriesMenu, SIGNAL(aboutToHide()), this, SLOT(addRemoveCategories_MenuHandler())); - addMenuAsPushButton(&menu, addRemoveCategoriesMenu); - - QMenu *primaryCategoryMenu = new QMenu(tr("Primary Category"), &menu); - connect(primaryCategoryMenu, SIGNAL(aboutToShow()), this, SLOT(addPrimaryCategoryCandidates())); - addMenuAsPushButton(&menu, primaryCategoryMenu); - - menu.addSeparator(); - - if (info->downgradeAvailable()) { - menu.addAction(tr("Change versioning scheme"), this, SLOT(changeVersioningScheme())); - } - - if (info->updateIgnored()) { - menu.addAction(tr("Un-ignore update"), this, SLOT(unignoreUpdate())); - } - else { - if (info->updateAvailable() || info->downgradeAvailable()) { - menu.addAction(tr("Ignore update"), this, SLOT(ignoreUpdate())); - } - } - menu.addSeparator(); - - menu.addAction(tr("Enable selected"), this, SLOT(enableSelectedMods_clicked())); - menu.addAction(tr("Disable selected"), this, SLOT(disableSelectedMods_clicked())); - - menu.addSeparator(); - - addModSendToContextMenu(&menu); - - menu.addAction(tr("Rename Mod..."), this, SLOT(renameMod_clicked())); - menu.addAction(tr("Reinstall Mod"), this, SLOT(reinstallMod_clicked())); - menu.addAction(tr("Remove Mod..."), this, SLOT(removeMod_clicked())); - menu.addAction(tr("Create Backup"), this, SLOT(backupMod_clicked())); - - menu.addSeparator(); - - if (info->getNexusID() > 0 && Settings::instance().endorsementIntegration()) { - switch (info->endorsedState()) { - case ModInfo::ENDORSED_TRUE: { - menu.addAction(tr("Un-Endorse"), this, SLOT(unendorse_clicked())); - } break; - case ModInfo::ENDORSED_FALSE: { - menu.addAction(tr("Endorse"), this, SLOT(endorse_clicked())); - menu.addAction(tr("Won't endorse"), this, SLOT(dontendorse_clicked())); - } break; - case ModInfo::ENDORSED_NEVER: { - menu.addAction(tr("Endorse"), this, SLOT(endorse_clicked())); - } break; - default: { - QAction *action = new QAction(tr("Endorsement state unknown"), &menu); - action->setEnabled(false); - menu.addAction(action); - } break; - } - } - - menu.addSeparator(); - - std::vector flags = info->getFlags(); - if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_INVALID) != flags.end()) { - menu.addAction(tr("Ignore missing data"), this, SLOT(ignoreMissingData_clicked())); - } - - if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_ALTERNATE_GAME) != flags.end()) { - menu.addAction(tr("Mark as converted/working"), this, SLOT(markConverted_clicked())); - } - - if (info->getNexusID() > 0) { - menu.addAction(tr("Visit on Nexus"), this, SLOT(visitOnNexus_clicked())); - } else if ((info->getURL() != "")) { - menu.addAction(tr("Visit web page"), this, SLOT(visitWebPage_clicked())); - } - - menu.addAction(tr("Open in Explorer"), this, SLOT(openExplorer_clicked())); - } - - if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_FOREIGN) == flags.end()) { - QAction *infoAction = menu.addAction(tr("Information..."), this, SLOT(information_clicked())); - menu.setDefaultAction(infoAction); - } - - menu.exec(modList->mapToGlobal(pos)); - } - } catch (const std::exception &e) { - reportError(tr("Exception: ").arg(e.what())); - } catch (...) { - reportError(tr("Unknown exception")); - } -} - - -void MainWindow::on_categoriesList_itemSelectionChanged() -{ - QModelIndexList indices = ui->categoriesList->selectionModel()->selectedRows(); - std::vector categories; - std::vector content; - for (const QModelIndex &index : indices) { - int filterType = index.data(Qt::UserRole + 1).toInt(); - if ((filterType == ModListSortProxy::TYPE_CATEGORY) - || (filterType == ModListSortProxy::TYPE_SPECIAL)) { - int categoryId = index.data(Qt::UserRole).toInt(); - if (categoryId != CategoryFactory::CATEGORY_NONE) { - categories.push_back(categoryId); - } - } else if (filterType == ModListSortProxy::TYPE_CONTENT) { - int contentId = index.data(Qt::UserRole).toInt(); - content.push_back(contentId); - } - } - - m_ModListSortProxy->setCategoryFilter(categories); - m_ModListSortProxy->setContentFilter(content); - ui->clickBlankButton->setEnabled(categories.size() > 0 || content.size() >0); - - if (indices.count() == 0) { - ui->currentCategoryLabel->setText(QString("(%1)").arg(tr(""))); - } else if (indices.count() > 1) { - ui->currentCategoryLabel->setText(QString("(%1)").arg(tr(""))); - } else { - ui->currentCategoryLabel->setText(QString("(%1)").arg(indices.first().data().toString())); - } - ui->modList->reset(); -} - - -void MainWindow::deleteSavegame_clicked() -{ - SaveGameInfo const *info = m_OrganizerCore.managedGame()->feature(); - - QString savesMsgLabel; - QStringList deleteFiles; - - int count = 0; - - for (const QModelIndex &idx : ui->savegameList->selectionModel()->selectedIndexes()) { - QString name = idx.data(Qt::UserRole).toString(); - - if (count < 10) { - savesMsgLabel += "
  • " + QFileInfo(name).completeBaseName() + "
  • "; - } - ++count; - - if (info == nullptr) { - deleteFiles.push_back(name); - } else { - ISaveGame const *save = info->getSaveGameInfo(name); - deleteFiles += save->allFiles(); - delete save; - } - } - - if (count > 10) { - savesMsgLabel += "
  • ... " + tr("%1 more").arg(count - 10) + "
  • "; - } - - if (QMessageBox::question(this, tr("Confirm"), - tr("Are you sure you want to remove the following %n save(s)?
    " - "
      %1

    " - "Removed saves will be sent to the Recycle Bin.", "", count) - .arg(savesMsgLabel), - QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { - shellDelete(deleteFiles, true); // recycle bin delete. - refreshSaveList(); - } -} - - -void MainWindow::fixMods_clicked(SaveGameInfo::MissingAssets const &missingAssets) -{ - ActivateModsDialog dialog(missingAssets, this); - if (dialog.exec() == QDialog::Accepted) { - // activate the required mods, then enable all esps - std::set modsToActivate = dialog.getModsToActivate(); - for (std::set::iterator iter = modsToActivate.begin(); iter != modsToActivate.end(); ++iter) { - if ((*iter != "") && (*iter != "")) { - unsigned int modIndex = ModInfo::getIndex(*iter); - m_OrganizerCore.currentProfile()->setModEnabled(modIndex, true); - } - } - - m_OrganizerCore.currentProfile()->writeModlist(); - m_OrganizerCore.refreshLists(); - - std::set espsToActivate = dialog.getESPsToActivate(); - for (std::set::iterator iter = espsToActivate.begin(); iter != espsToActivate.end(); ++iter) { - m_OrganizerCore.pluginList()->enableESP(*iter); - } - m_OrganizerCore.saveCurrentLists(); - } -} - - -void MainWindow::on_savegameList_customContextMenuRequested(const QPoint &pos) -{ - QItemSelectionModel *selection = ui->savegameList->selectionModel(); - - if (!selection->hasSelection()) { - return; - } - - QMenu menu; - QAction *action = menu.addAction(tr("Enable Mods...")); - action->setEnabled(false); - - if (selection->selectedIndexes().count() == 1) { - SaveGameInfo const *info = this->m_OrganizerCore.managedGame()->feature(); - if (info != nullptr) { - QString save = ui->savegameList->currentItem()->data(Qt::UserRole).toString(); - SaveGameInfo::MissingAssets missing = info->getMissingAssets(save); - if (missing.size() != 0) { - connect(action, &QAction::triggered, this, [this, missing]{ fixMods_clicked(missing); }); - action->setEnabled(true); - } - } - } - - QString deleteMenuLabel = tr("Delete %n save(s)", "", selection->selectedIndexes().count()); - - menu.addAction(deleteMenuLabel, this, SLOT(deleteSavegame_clicked())); - - menu.exec(ui->savegameList->mapToGlobal(pos)); -} - -void MainWindow::linkToolbar() -{ - Executable &exe(getSelectedExecutable()); - exe.showOnToolbar(!exe.isShownOnToolbar()); - ui->linkButton->menu()->actions().at(static_cast(ShortcutType::Toolbar))->setIcon(exe.isShownOnToolbar() ? QIcon(":/MO/gui/remove") : QIcon(":/MO/gui/link")); - updateToolBar(); -} - -namespace { -QString getLinkfile(const QString &dir, const Executable &exec) -{ - return QDir::fromNativeSeparators(dir) + "/" + exec.m_Title + ".lnk"; -} - -QString getDesktopLinkfile(const Executable &exec) -{ - return getLinkfile(getDesktopDirectory(), exec); -} - -QString getStartMenuLinkfile(const Executable &exec) -{ - return getLinkfile(getStartMenuDirectory(), exec); -} -} - -void MainWindow::addWindowsLink(const ShortcutType mapping) -{ - const Executable &selectedExecutable(getSelectedExecutable()); - QString const linkName = getLinkfile(mapping == ShortcutType::Desktop ? getDesktopDirectory() : getStartMenuDirectory(), - selectedExecutable); - - if (QFile::exists(linkName)) { - if (QFile::remove(linkName)) { - ui->linkButton->menu()->actions().at(static_cast(mapping))->setIcon(QIcon(":/MO/gui/link")); - } else { - reportError(tr("failed to remove %1").arg(linkName)); - } - } else { - QFileInfo const exeInfo(qApp->applicationFilePath()); - // create link - QString executable = QDir::toNativeSeparators(selectedExecutable.m_BinaryInfo.absoluteFilePath()); - - std::wstring targetFile = ToWString(exeInfo.absoluteFilePath()); - std::wstring parameter = ToWString( - QString("\"moshortcut://%1:%2\"").arg(InstanceManager::instance().currentInstance(),selectedExecutable.m_Title)); - std::wstring description = ToWString(QString("Run %1 with ModOrganizer").arg(selectedExecutable.m_Title)); - std::wstring iconFile = ToWString(executable); - std::wstring currentDirectory = ToWString(QDir::toNativeSeparators(qApp->applicationDirPath())); - - if (CreateShortcut(targetFile.c_str() - , parameter.c_str() - , QDir::toNativeSeparators(linkName).toUtf8().constData() - , description.c_str() - , (selectedExecutable.usesOwnIcon() ? iconFile.c_str() : nullptr), 0 - , currentDirectory.c_str()) == 0) { - ui->linkButton->menu()->actions().at(static_cast(mapping))->setIcon(QIcon(":/MO/gui/remove")); - } else { - reportError(tr("failed to create %1").arg(linkName)); - } - } -} - -void MainWindow::linkDesktop() -{ - addWindowsLink(ShortcutType::Desktop); -} - -void MainWindow::linkMenu() -{ - addWindowsLink(ShortcutType::StartMenu); -} - -void MainWindow::on_actionSettings_triggered() -{ - Settings &settings = m_OrganizerCore.settings(); - - QString oldModDirectory(settings.getModDirectory()); - QString oldCacheDirectory(settings.getCacheDirectory()); - QString oldProfilesDirectory(settings.getProfileDirectory()); - QString oldManagedGameDirectory(settings.getManagedGameDirectory()); - bool oldDisplayForeign(settings.displayForeign()); - bool proxy = settings.useProxy(); - DownloadManager *dlManager = m_OrganizerCore.downloadManager(); - - settings.query(&m_PluginContainer, this); - - if (oldManagedGameDirectory != settings.getManagedGameDirectory()) { - QMessageBox::about(this, tr("Restarting MO"), - tr("Changing the managed game directory requires restarting MO.\n" - "Any pending downloads will be paused.\n\n" - "Click OK to restart MO now.")); - dlManager->pauseAll(); - qApp->exit(INT_MAX); - } - - InstallationManager *instManager = m_OrganizerCore.installationManager(); - instManager->setModsDirectory(settings.getModDirectory()); - instManager->setDownloadDirectory(settings.getDownloadDirectory()); - - fixCategories(); - refreshFilters(); - - if (settings.getProfileDirectory() != oldProfilesDirectory) { - refreshProfiles(); - } - - if (dlManager->getOutputDirectory() != settings.getDownloadDirectory()) { - if (dlManager->downloadsInProgress()) { - MessageDialog::showMessage(tr("Can't change download directory while " - "downloads are in progress!"), - this); - } else { - dlManager->setOutputDirectory(settings.getDownloadDirectory()); - } - } - dlManager->setPreferredServers(settings.getPreferredServers()); - - if ((settings.getModDirectory() != oldModDirectory) - || (settings.displayForeign() != oldDisplayForeign)) { - m_OrganizerCore.profileRefresh(); - } - - const auto state = settings.archiveParsing(); - if (state != m_OrganizerCore.getArchiveParsing()) - { - m_OrganizerCore.setArchiveParsing(state); - if (!state) - { - ui->showArchiveDataCheckBox->setCheckState(Qt::Unchecked); - ui->showArchiveDataCheckBox->setEnabled(false); - m_showArchiveData = false; - } - else - { - ui->showArchiveDataCheckBox->setCheckState(Qt::Checked); - ui->showArchiveDataCheckBox->setEnabled(true); - m_showArchiveData = true; - } - m_OrganizerCore.refreshModList(); - m_OrganizerCore.refreshDirectoryStructure(); - m_OrganizerCore.refreshLists(); - } - - if (settings.getCacheDirectory() != oldCacheDirectory) { - NexusInterface::instance(&m_PluginContainer)->setCacheDirectory(settings.getCacheDirectory()); - } - - if (proxy != settings.useProxy()) { - activateProxy(settings.useProxy()); - } - - NexusInterface::instance(&m_PluginContainer)->setNMMVersion(settings.getNMMVersion()); - - updateDownloadView(); - - m_OrganizerCore.updateVFSParams(settings.logLevel(), settings.crashDumpsType(), settings.executablesBlacklist()); - m_OrganizerCore.cycleDiagnostics(); -} - - -void MainWindow::on_actionNexus_triggered() -{ - const IPluginGame *game = m_OrganizerCore.managedGame(); - QString gameName = game->gameShortName(); - if (game->gameNexusName().isEmpty() && game->primarySources().count()) - gameName = game->primarySources()[0]; - QDesktopServices::openUrl(QUrl(NexusInterface::instance(&m_PluginContainer)->getGameURL(gameName))); -} - - -void MainWindow::linkClicked(const QString &url) -{ - QDesktopServices::openUrl(QUrl(url)); -} - - -void MainWindow::installTranslator(const QString &name) -{ - QTranslator *translator = new QTranslator(this); - QString fileName = name + "_" + m_CurrentLanguage; - if (!translator->load(fileName, qApp->applicationDirPath() + "/translations")) { - if (m_CurrentLanguage.compare("en", Qt::CaseInsensitive)) { - qDebug("localization file %s not found", qUtf8Printable(fileName)); - } // we don't actually expect localization files for English - } - - qApp->installTranslator(translator); - m_Translators.push_back(translator); -} - - -void MainWindow::languageChange(const QString &newLanguage) -{ - for (QTranslator *trans : m_Translators) { - qApp->removeTranslator(trans); - } - m_Translators.clear(); - - m_CurrentLanguage = newLanguage; - - installTranslator("qt"); - installTranslator("qtbase"); - installTranslator(ToQString(AppConfig::translationPrefix())); - for (const QString &fileName : m_PluginContainer.pluginFileNames()) { - installTranslator(QFileInfo(fileName).baseName()); - } - ui->retranslateUi(this); - qDebug("loaded language %s", qUtf8Printable(newLanguage)); - - ui->profileBox->setItemText(0, QObject::tr("")); - - createHelpWidget(); - - updateDownloadView(); - updateProblemsButton(); - - QMenu *listOptionsMenu = new QMenu(ui->listOptionsBtn); - initModListContextMenu(listOptionsMenu); - ui->listOptionsBtn->setMenu(listOptionsMenu); - - ui->openFolderMenu->setMenu(openFolderMenu()); -} - -void MainWindow::writeDataToFile(QFile &file, const QString &directory, const DirectoryEntry &directoryEntry) -{ - for (FileEntry::Ptr current : directoryEntry.getFiles()) { - bool isArchive = false; - int origin = current->getOrigin(isArchive); - if (isArchive) { - // TODO: don't list files from archives. maybe make this an option? - continue; - } - QString fullName = directory + "\\" + ToQString(current->getName()); - file.write(fullName.toUtf8()); - - file.write("\t("); - file.write(ToQString(m_OrganizerCore.directoryStructure()->getOriginByID(origin).getName()).toUtf8()); - file.write(")\r\n"); - } - - // recurse into subdirectories - std::vector::const_iterator current, end; - directoryEntry.getSubDirectories(current, end); - for (; current != end; ++current) { - writeDataToFile(file, directory + "\\" + ToQString((*current)->getName()), **current); - } -} - -void MainWindow::writeDataToFile() -{ - QString fileName = QFileDialog::getSaveFileName(this); - if (!fileName.isEmpty()) { - QFile file(fileName); - if (!file.open(QIODevice::WriteOnly)) { - reportError(tr("failed to write to file %1").arg(fileName)); - } - - writeDataToFile(file, "data", *m_OrganizerCore.directoryStructure()); - file.close(); - - MessageDialog::showMessage(tr("%1 written").arg(QDir::toNativeSeparators(fileName)), this); - } -} - - -int MainWindow::getBinaryExecuteInfo(const QFileInfo &targetInfo, QFileInfo &binaryInfo, QString &arguments) -{ - QString extension = targetInfo.suffix(); - if ((extension.compare("cmd", Qt::CaseInsensitive) == 0) || - (extension.compare("com", Qt::CaseInsensitive) == 0) || - (extension.compare("bat", Qt::CaseInsensitive) == 0)) { - binaryInfo = QFileInfo("C:\\Windows\\System32\\cmd.exe"); - arguments = QString("/C \"%1\"").arg(QDir::toNativeSeparators(targetInfo.absoluteFilePath())); - return 1; - } else if (extension.compare("exe", Qt::CaseInsensitive) == 0) { - binaryInfo = targetInfo; - return 1; - } else if (extension.compare("jar", Qt::CaseInsensitive) == 0) { - // types that need to be injected into - std::wstring targetPathW = ToWString(targetInfo.absoluteFilePath()); - QString binaryPath; - - { // try to find java automatically - WCHAR buffer[MAX_PATH]; - if (::FindExecutableW(targetPathW.c_str(), nullptr, buffer) > (HINSTANCE)32) { - DWORD binaryType = 0UL; - if (!::GetBinaryTypeW(buffer, &binaryType)) { - qDebug("failed to determine binary type of \"%ls\": %lu", buffer, ::GetLastError()); - } else if (binaryType == SCS_32BIT_BINARY) { - binaryPath = ToQString(buffer); - } - } - } - if (binaryPath.isEmpty() && (extension == "jar")) { - // second attempt: look to the registry - QSettings javaReg("HKEY_LOCAL_MACHINE\\Software\\JavaSoft\\Java Runtime Environment", QSettings::NativeFormat); - if (javaReg.contains("CurrentVersion")) { - QString currentVersion = javaReg.value("CurrentVersion").toString(); - binaryPath = javaReg.value(QString("%1/JavaHome").arg(currentVersion)).toString().append("\\bin\\javaw.exe"); - } - } - if (binaryPath.isEmpty()) { - binaryPath = QFileDialog::getOpenFileName(this, tr("Select binary"), QString(), tr("Binary") + " (*.exe)"); - } - if (binaryPath.isEmpty()) { - return 0; - } - binaryInfo = QFileInfo(binaryPath); - if (extension == "jar") { - arguments = QString("-jar \"%1\"").arg(QDir::toNativeSeparators(targetInfo.absoluteFilePath())); - } else { - arguments = QString("\"%1\"").arg(QDir::toNativeSeparators(targetInfo.absoluteFilePath())); - } - return 1; - } else { - return 2; - } -} - - -void MainWindow::addAsExecutable() -{ - if (m_ContextItem != nullptr) { - QFileInfo targetInfo(m_ContextItem->data(0, Qt::UserRole).toString()); - QFileInfo binaryInfo; - QString arguments; - switch (getBinaryExecuteInfo(targetInfo, binaryInfo, arguments)) { - case 1: { - QString name = QInputDialog::getText(this, tr("Enter Name"), - tr("Please enter a name for the executable"), QLineEdit::Normal, - targetInfo.baseName()); - if (!name.isEmpty()) { - //Note: If this already exists, you'll lose custom settings - m_OrganizerCore.executablesList()->addExecutable(name, - binaryInfo.absoluteFilePath(), - arguments, - targetInfo.absolutePath(), - QString(), - Executable::CustomExecutable); - refreshExecutablesList(); - } - } break; - case 2: { - QMessageBox::information(this, tr("Not an executable"), tr("This is not a recognized executable.")); - } break; - default: { - // nop - } break; - } - } -} - - -void MainWindow::originModified(int originID) -{ - FilesOrigin &origin = m_OrganizerCore.directoryStructure()->getOriginByID(originID); - origin.enable(false); - m_OrganizerCore.directoryStructure()->addFromOrigin(origin.getName(), origin.getPath(), origin.getPriority()); - DirectoryRefresher::cleanStructure(m_OrganizerCore.directoryStructure()); -} - - -void MainWindow::hideFile() -{ - QString oldName = m_ContextItem->data(0, Qt::UserRole).toString(); - QString newName = oldName + ModInfo::s_HiddenExt; - - if (QFileInfo(newName).exists()) { - if (QMessageBox::question(this, tr("Replace file?"), tr("There already is a hidden version of this file. Replace it?"), - QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { - if (!QFile(newName).remove()) { - QMessageBox::critical(this, tr("File operation failed"), tr("Failed to remove \"%1\". Maybe you lack the required file permissions?").arg(newName)); - return; - } - } else { - return; - } - } - - if (QFile::rename(oldName, newName)) { - originModified(m_ContextItem->data(1, Qt::UserRole + 1).toInt()); - refreshDataTreeKeepExpandedNodes(); - } else { - reportError(tr("failed to rename \"%1\" to \"%2\"").arg(oldName).arg(QDir::toNativeSeparators(newName))); - } -} - - -void MainWindow::unhideFile() -{ - QString oldName = m_ContextItem->data(0, Qt::UserRole).toString(); - QString newName = oldName.left(oldName.length() - ModInfo::s_HiddenExt.length()); - if (QFileInfo(newName).exists()) { - if (QMessageBox::question(this, tr("Replace file?"), tr("There already is a visible version of this file. Replace it?"), - QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { - if (!QFile(newName).remove()) { - QMessageBox::critical(this, tr("File operation failed"), tr("Failed to remove \"%1\". Maybe you lack the required file permissions?").arg(newName)); - return; - } - } else { - return; - } - } - if (QFile::rename(oldName, newName)) { - originModified(m_ContextItem->data(1, Qt::UserRole + 1).toInt()); - refreshDataTreeKeepExpandedNodes(); - } else { - reportError(tr("failed to rename \"%1\" to \"%2\"").arg(QDir::toNativeSeparators(oldName)).arg(QDir::toNativeSeparators(newName))); - } -} - - -void MainWindow::enableSelectedPlugins_clicked() -{ - m_OrganizerCore.pluginList()->enableSelected(ui->espList->selectionModel()); -} - - -void MainWindow::disableSelectedPlugins_clicked() -{ - m_OrganizerCore.pluginList()->disableSelected(ui->espList->selectionModel()); -} - -void MainWindow::sendSelectedPluginsToTop_clicked() -{ - m_OrganizerCore.pluginList()->sendToPriority(ui->espList->selectionModel(), 0); -} - -void MainWindow::sendSelectedPluginsToBottom_clicked() -{ - m_OrganizerCore.pluginList()->sendToPriority(ui->espList->selectionModel(), INT_MAX); -} - -void MainWindow::sendSelectedPluginsToPriority_clicked() -{ - bool ok; - int newPriority = QInputDialog::getInt(this, - tr("Set Priority"), tr("Set the priority of the selected plugins"), - 0, 0, INT_MAX, 1, &ok); - if (!ok) return; - - m_OrganizerCore.pluginList()->sendToPriority(ui->espList->selectionModel(), newPriority); -} - - -void MainWindow::enableSelectedMods_clicked() -{ - m_OrganizerCore.modList()->enableSelected(ui->modList->selectionModel()); - if (m_ModListSortProxy != nullptr) { - m_ModListSortProxy->invalidate(); - } -} - - -void MainWindow::disableSelectedMods_clicked() -{ - m_OrganizerCore.modList()->disableSelected(ui->modList->selectionModel()); - if (m_ModListSortProxy != nullptr) { - m_ModListSortProxy->invalidate(); - } -} - - -void MainWindow::previewDataFile() -{ - QString fileName = QDir::fromNativeSeparators(m_ContextItem->data(0, Qt::UserRole).toString()); - - // what we have is an absolute path to the file in its actual location (for the primary origin) - // what we want is the path relative to the virtual data directory - - // we need to look in the virtual directory for the file to make sure the info is up to date. - - // check if the file comes from the actual data folder instead of a mod - QDir gameDirectory = m_OrganizerCore.managedGame()->dataDirectory().absolutePath(); - QString relativePath = gameDirectory.relativeFilePath(fileName); - QDir dirRelativePath = gameDirectory.relativeFilePath(fileName); - // if the file is on a different drive the dirRelativePath will actually be an absolute path so we make sure that is not the case - if (!dirRelativePath.isAbsolute() && !relativePath.startsWith("..")) { - fileName = relativePath; - } - else { - // crude: we search for the next slash after the base mod directory to skip everything up to the data-relative directory - int offset = m_OrganizerCore.settings().getModDirectory().size() + 1; - offset = fileName.indexOf("/", offset); - fileName = fileName.mid(offset + 1); - } - - - - const FileEntry::Ptr file = m_OrganizerCore.directoryStructure()->searchFile(ToWString(fileName), nullptr); - - if (file.get() == nullptr) { - reportError(tr("file not found: %1").arg(qUtf8Printable(fileName))); - return; - } - - // set up preview dialog - PreviewDialog preview(fileName); - auto addFunc = [&] (int originId) { - FilesOrigin &origin = m_OrganizerCore.directoryStructure()->getOriginByID(originId); - QString filePath = QDir::fromNativeSeparators(ToQString(origin.getPath())) + "/" + fileName; - if (QFile::exists(filePath)) { - // it's very possible the file doesn't exist, because it's inside an archive. we don't support that - QWidget *wid = m_PluginContainer.previewGenerator().genPreview(filePath); - if (wid == nullptr) { - reportError(tr("failed to generate preview for %1").arg(filePath)); - } else { - preview.addVariant(ToQString(origin.getName()), wid); - } - } - }; - - addFunc(file->getOrigin()); - for (auto alt : file->getAlternatives()) { - addFunc(alt.first); - } - if (preview.numVariants() > 0) { - QSettings &settings = m_OrganizerCore.settings().directInterface(); - QString key = QString("geometry/%1").arg(preview.objectName()); - if (settings.contains(key)) { - preview.restoreGeometry(settings.value(key).toByteArray()); - } - preview.exec(); - settings.setValue(key, preview.saveGeometry()); - } else { - QMessageBox::information(this, tr("Sorry"), tr("Sorry, can't preview anything. This function currently does not support extracting from bsas.")); - } -} - -void MainWindow::openDataFile() -{ - if (m_ContextItem != nullptr) { - QFileInfo targetInfo(m_ContextItem->data(0, Qt::UserRole).toString()); - QFileInfo binaryInfo; - QString arguments; - switch (getBinaryExecuteInfo(targetInfo, binaryInfo, arguments)) { - case 1: { - m_OrganizerCore.spawnBinaryDirect( - binaryInfo, arguments, m_OrganizerCore.currentProfile()->name(), - targetInfo.absolutePath(), "", ""); - } break; - case 2: { - ::ShellExecuteW(nullptr, L"open", - ToWString(targetInfo.absoluteFilePath()).c_str(), - nullptr, nullptr, SW_SHOWNORMAL); - } break; - default: { - // nop - } break; - } - } -} - - -void MainWindow::updateAvailable() -{ - for (QAction *action : ui->toolBar->actions()) { - if (action->text() == tr("Update")) { - action->setEnabled(true); - action->setToolTip(tr("Update available")); - break; - } - } -} - - -void MainWindow::motdReceived(const QString &motd) -{ - // don't show motd after 5 seconds, may be annoying. Hopefully the user's - // internet connection is faster next time - if (m_StartTime.secsTo(QTime::currentTime()) < 5) { - uint hash = qHash(motd); - if (hash != m_OrganizerCore.settings().getMotDHash()) { - MotDDialog dialog(motd); - dialog.exec(); - m_OrganizerCore.settings().setMotDHash(hash); - } - } - - ui->actionEndorseMO->setVisible(false); -} - - -void MainWindow::notEndorsedYet() -{ - if (!Settings::instance().directInterface().value("wont_endorse_MO", false).toBool()) { - ui->actionEndorseMO->setVisible(true); - } -} - - -void MainWindow::wontEndorse() -{ - Settings::instance().directInterface().setValue("wont_endorse_MO", true); - ui->actionEndorseMO->setVisible(false); -} - - -void MainWindow::on_dataTree_customContextMenuRequested(const QPoint &pos) -{ - QTreeWidget *dataTree = findChild("dataTree"); - m_ContextItem = dataTree->itemAt(pos.x(), pos.y()); - - QMenu menu; - if ((m_ContextItem != nullptr) && (m_ContextItem->childCount() == 0) - && (m_ContextItem->data(0, Qt::UserRole + 3).toBool() != true)) { - menu.addAction(tr("Open/Execute"), this, SLOT(openDataFile())); - menu.addAction(tr("Add as Executable"), this, SLOT(addAsExecutable())); - - QString fileName = m_ContextItem->text(0); - if (m_PluginContainer.previewGenerator().previewSupported(QFileInfo(fileName).suffix())) { - menu.addAction(tr("Preview"), this, SLOT(previewDataFile())); - } - - // offer to hide/unhide file, but not for files from archives - if (!m_ContextItem->data(0, Qt::UserRole + 1).toBool()) { - if (m_ContextItem->text(0).endsWith(ModInfo::s_HiddenExt)) { - menu.addAction(tr("Un-Hide"), this, SLOT(unhideFile())); - } else { - menu.addAction(tr("Hide"), this, SLOT(hideFile())); - } - } - - menu.addSeparator(); - } - menu.addAction(tr("Write To File..."), this, SLOT(writeDataToFile())); - menu.addAction(tr("Refresh"), this, SLOT(on_btnRefreshData_clicked())); - - menu.exec(dataTree->mapToGlobal(pos)); -} - -void MainWindow::on_conflictsCheckBox_toggled(bool) -{ - refreshDataTreeKeepExpandedNodes(); -} - - -void MainWindow::on_actionUpdate_triggered() -{ - m_OrganizerCore.startMOUpdate(); -} - - -void MainWindow::on_actionEndorseMO_triggered() -{ - // Normally this would be the managed game but MO2 is only uploaded to the Skyrim SE site right now - IPluginGame * game = m_OrganizerCore.getGame("skyrimse"); - if (!game) return; - - if (QMessageBox::question(this, tr("Endorse Mod Organizer"), - tr("Do you want to endorse Mod Organizer on %1 now?").arg( - NexusInterface::instance(&m_PluginContainer)->getGameURL(game->gameShortName())), - QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { - NexusInterface::instance(&m_PluginContainer)->requestToggleEndorsement( - game->gameShortName(), game->nexusModOrganizerID(), true, this, QVariant(), QString()); - } -} - - -void MainWindow::initDownloadView() -{ - DownloadList *sourceModel = new DownloadList(m_OrganizerCore.downloadManager(), ui->downloadView); - DownloadListSortProxy *sortProxy = new DownloadListSortProxy(m_OrganizerCore.downloadManager(), ui->downloadView); - sortProxy->setSourceModel(sourceModel); - connect(ui->downloadFilterEdit, SIGNAL(textChanged(QString)), sortProxy, SLOT(updateFilter(QString))); - connect(ui->downloadFilterEdit, SIGNAL(textChanged(QString)), this, SLOT(downloadFilterChanged(QString))); - - ui->downloadView->setSourceModel(sourceModel); - ui->downloadView->setModel(sortProxy); - ui->downloadView->setManager(m_OrganizerCore.downloadManager()); - ui->downloadView->setItemDelegate(new DownloadProgressDelegate(m_OrganizerCore.downloadManager(), sortProxy, ui->downloadView)); - updateDownloadView(); - - connect(ui->downloadView, SIGNAL(installDownload(int)), &m_OrganizerCore, SLOT(installDownload(int))); - connect(ui->downloadView, SIGNAL(queryInfo(int)), m_OrganizerCore.downloadManager(), SLOT(queryInfo(int))); - connect(ui->downloadView, SIGNAL(visitOnNexus(int)), m_OrganizerCore.downloadManager(), SLOT(visitOnNexus(int))); - connect(ui->downloadView, SIGNAL(openFile(int)), m_OrganizerCore.downloadManager(), SLOT(openFile(int))); - connect(ui->downloadView, SIGNAL(openInDownloadsFolder(int)), m_OrganizerCore.downloadManager(), SLOT(openInDownloadsFolder(int))); - connect(ui->downloadView, SIGNAL(removeDownload(int, bool)), m_OrganizerCore.downloadManager(), SLOT(removeDownload(int, bool))); - connect(ui->downloadView, SIGNAL(restoreDownload(int)), m_OrganizerCore.downloadManager(), SLOT(restoreDownload(int))); - connect(ui->downloadView, SIGNAL(cancelDownload(int)), m_OrganizerCore.downloadManager(), SLOT(cancelDownload(int))); - connect(ui->downloadView, SIGNAL(pauseDownload(int)), m_OrganizerCore.downloadManager(), SLOT(pauseDownload(int))); - connect(ui->downloadView, SIGNAL(resumeDownload(int)), this, SLOT(resumeDownload(int))); -} - -void MainWindow::updateDownloadView() -{ - // set the view attribute and default row sizes - if (m_OrganizerCore.settings().compactDownloads()) { - ui->downloadView->setProperty("downloadView", "compact"); - setStyleSheet("DownloadListWidget::item { padding: 4px 2px; }"); - } else { - ui->downloadView->setProperty("downloadView", "standard"); - setStyleSheet("DownloadListWidget::item { padding: 16px 4px; }"); - } - //setStyleSheet("DownloadListWidget::item:hover { padding: 0px; }"); - //setStyleSheet("DownloadListWidget::item:selected { padding: 0px; }"); - - // reapply global stylesheet on the widget level (!) to override the defaults - //ui->downloadView->setStyleSheet(styleSheet()); - - ui->downloadView->setMetaDisplay(m_OrganizerCore.settings().metaDownloads()); - ui->downloadView->style()->unpolish(ui->downloadView); - ui->downloadView->style()->polish(ui->downloadView); - qobject_cast(ui->downloadView->header())->customResizeSections(); - m_OrganizerCore.downloadManager()->refreshList(); -} - -void MainWindow::modDetailsUpdated(bool) -{ - if (--m_ModsToUpdate == 0) { - statusBar()->hide(); - m_ModListSortProxy->setCategoryFilter(boost::assign::list_of(CategoryFactory::CATEGORY_SPECIAL_UPDATEAVAILABLE)); - for (int i = 0; i < ui->categoriesList->topLevelItemCount(); ++i) { - if (ui->categoriesList->topLevelItem(i)->data(0, Qt::UserRole) == CategoryFactory::CATEGORY_SPECIAL_UPDATEAVAILABLE) { - ui->categoriesList->setCurrentItem(ui->categoriesList->topLevelItem(i)); - break; - } - } - m_RefreshProgress->setVisible(false); - } else { - m_RefreshProgress->setValue(m_RefreshProgress->maximum() - m_ModsToUpdate); - } -} - -void MainWindow::nxmUpdatesAvailable(const std::vector &modIDs, QVariant userData, QVariant resultData, int) -{ - m_ModsToUpdate -= static_cast(modIDs.size()); - QVariantList resultList = resultData.toList(); - for (auto iter = resultList.begin(); iter != resultList.end(); ++iter) { - QVariantMap result = iter->toMap(); - // Normally this would be the managed game but MO2 is only uploaded to the Skyrim SE site right now - IPluginGame * game = m_OrganizerCore.getGame("skyrimse"); - if (game - && result["id"].toInt() == game->nexusModOrganizerID() - && result["game_id"].toInt() == game->nexusGameID()) { - if (!result["voted_by_user"].toBool() && - Settings::instance().endorsementIntegration() && - !Settings::instance().directInterface().value("wont_endorse_MO", false).toBool()) { - ui->actionEndorseMO->setVisible(true); - } - } else { - QString gameName = m_OrganizerCore.managedGame()->gameShortName(); - bool sameNexus = false; - for (IPluginGame *game : m_PluginContainer.plugins()) { - if (game->nexusGameID() == result["game_id"].toInt()) { - gameName = game->gameShortName(); - if (game->nexusGameID() == m_OrganizerCore.managedGame()->nexusGameID()) - sameNexus = true; - break; - } - } - std::vector info = ModInfo::getByModID(gameName, result["id"].toInt()); - if (sameNexus) { - std::vector mainInfo = ModInfo::getByModID(m_OrganizerCore.managedGame()->gameShortName(), result["id"].toInt()); - info.reserve(info.size() + mainInfo.size()); - info.insert(info.end(), mainInfo.begin(), mainInfo.end()); - } - for (auto iter = info.begin(); iter != info.end(); ++iter) { - (*iter)->setNewestVersion(result["version"].toString()); - (*iter)->setNexusDescription(result["description"].toString()); - if (NexusInterface::instance(&m_PluginContainer)->getAccessManager()->loggedIn() && - result.contains("voted_by_user") && - Settings::instance().endorsementIntegration()) { - // don't use endorsement info if we're not logged in or if the response doesn't contain it - (*iter)->setIsEndorsed(result["voted_by_user"].toBool()); - } - } - } - } - - if (m_ModsToUpdate <= 0) { - statusBar()->hide(); - m_ModListSortProxy->setCategoryFilter(boost::assign::list_of(CategoryFactory::CATEGORY_SPECIAL_UPDATEAVAILABLE)); - for (int i = 0; i < ui->categoriesList->topLevelItemCount(); ++i) { - if (ui->categoriesList->topLevelItem(i)->data(0, Qt::UserRole) == CategoryFactory::CATEGORY_SPECIAL_UPDATEAVAILABLE) { - ui->categoriesList->setCurrentItem(ui->categoriesList->topLevelItem(i)); - break; - } - } - } else { - m_RefreshProgress->setValue(m_RefreshProgress->maximum() - m_ModsToUpdate); - } -} - -void MainWindow::nxmEndorsementToggled(QString, int, QVariant, QVariant resultData, int) -{ - if (resultData.toBool()) { - ui->actionEndorseMO->setVisible(false); - QMessageBox::information(this, tr("Thank you!"), tr("Thank you for your endorsement!")); - } - - if (!disconnect(sender(), SIGNAL(nxmEndorsementToggled(QString, int, QVariant, QVariant, int)), - this, SLOT(nxmEndorsementToggled(QString, int, QVariant, QVariant, int)))) { - qCritical("failed to disconnect endorsement slot"); - } -} - -void MainWindow::nxmDownloadURLs(QString, int, int, QVariant, QVariant resultData, int) -{ - QVariantList serverList = resultData.toList(); - - QList servers; - for (const QVariant &server : serverList) { - QVariantMap serverInfo = server.toMap(); - ServerInfo info; - info.name = serverInfo["Name"].toString(); - info.premium = serverInfo["IsPremium"].toBool(); - info.lastSeen = QDate::currentDate(); - info.preferred = !info.name.compare("CDN", Qt::CaseInsensitive); - // other keys: ConnectedUsers, Country, URI - servers.append(info); - } - m_OrganizerCore.settings().updateServers(servers); -} - - -void MainWindow::nxmRequestFailed(QString, int modID, int, QVariant, int, const QString &errorString) -{ - if (modID == -1) { - // must be the update-check that failed - m_ModsToUpdate = 0; - statusBar()->hide(); - } - MessageDialog::showMessage(tr("Request to Nexus failed: %1").arg(errorString), this); -} - - -BSA::EErrorCode MainWindow::extractBSA(BSA::Archive &archive, BSA::Folder::Ptr folder, const QString &destination, - QProgressDialog &progress) -{ - QDir().mkdir(destination); - BSA::EErrorCode result = BSA::ERROR_NONE; - QString errorFile; - - for (unsigned int i = 0; i < folder->getNumFiles(); ++i) { - BSA::File::Ptr file = folder->getFile(i); - BSA::EErrorCode res = archive.extract(file, qUtf8Printable(destination)); - if (res != BSA::ERROR_NONE) { - reportError(tr("failed to read %1: %2").arg(file->getName().c_str()).arg(res)); - result = res; - } - progress.setLabelText(file->getName().c_str()); - progress.setValue(progress.value() + 1); - QCoreApplication::processEvents(); - if (progress.wasCanceled()) { - result = BSA::ERROR_CANCELED; - } - } - - if (result != BSA::ERROR_NONE) { - if (QMessageBox::critical(this, tr("Error"), tr("failed to extract %1 (errorcode %2)").arg(errorFile).arg(result), - QMessageBox::Ok | QMessageBox::Cancel) == QMessageBox::Cancel) { - return result; - } - } - - for (unsigned int i = 0; i < folder->getNumSubFolders(); ++i) { - BSA::Folder::Ptr subFolder = folder->getSubFolder(i); - BSA::EErrorCode res = extractBSA(archive, subFolder, - destination.mid(0).append("/").append(subFolder->getName().c_str()), progress); - if (res != BSA::ERROR_NONE) { - return res; - } - } - return BSA::ERROR_NONE; -} - - -bool MainWindow::extractProgress(QProgressDialog &progress, int percentage, std::string fileName) -{ - progress.setLabelText(fileName.c_str()); - progress.setValue(percentage); - QCoreApplication::processEvents(); - return !progress.wasCanceled(); -} - - -void MainWindow::extractBSATriggered() -{ - QTreeWidgetItem *item = m_ContextItem; - QString origin; - - QString targetFolder = FileDialogMemory::getExistingDirectory("extractBSA", this, tr("Extract BSA")); - QStringList archives = {}; - if (!targetFolder.isEmpty()) { - if (!item->parent()) { - for (int i = 0; i < item->childCount(); ++i) { - archives.append(item->child(i)->text(0)); - } - origin = QDir::fromNativeSeparators(ToQString(m_OrganizerCore.directoryStructure()->getOriginByName(ToWString(item->text(0))).getPath())); - } else { - origin = QDir::fromNativeSeparators(ToQString(m_OrganizerCore.directoryStructure()->getOriginByName(ToWString(item->text(1))).getPath())); - archives = QStringList({ item->text(0) }); - } - - for (auto archiveName : archives) { - BSA::Archive archive; - QString archivePath = QString("%1\\%2").arg(origin).arg(archiveName); - BSA::EErrorCode result = archive.read(archivePath.toLocal8Bit().constData(), true); - if ((result != BSA::ERROR_NONE) && (result != BSA::ERROR_INVALIDHASHES)) { - reportError(tr("failed to read %1: %2").arg(archivePath).arg(result)); - return; - } - - QProgressDialog progress(this); - progress.setMaximum(100); - progress.setValue(0); - progress.show(); - archive.extractAll(QDir::toNativeSeparators(targetFolder).toLocal8Bit().constData(), - boost::bind(&MainWindow::extractProgress, this, boost::ref(progress), _1, _2)); - if (result == BSA::ERROR_INVALIDHASHES) { - reportError(tr("This archive contains invalid hashes. Some files may be broken.")); - } - archive.close(); - } - } -} - - -void MainWindow::displayColumnSelection(const QPoint &pos) -{ - QMenu menu; - - // display a list of all headers as checkboxes - QAbstractItemModel *model = ui->modList->header()->model(); - for (int i = 1; i < model->columnCount(); ++i) { - QString columnName = model->headerData(i, Qt::Horizontal).toString(); - QCheckBox *checkBox = new QCheckBox(&menu); - checkBox->setText(columnName); - checkBox->setChecked(!ui->modList->header()->isSectionHidden(i)); - QWidgetAction *checkableAction = new QWidgetAction(&menu); - checkableAction->setDefaultWidget(checkBox); - menu.addAction(checkableAction); - } - menu.exec(pos); - - // view/hide columns depending on check-state - int i = 1; - for (const QAction *action : menu.actions()) { - const QWidgetAction *widgetAction = qobject_cast(action); - if (widgetAction != nullptr) { - const QCheckBox *checkBox = qobject_cast(widgetAction->defaultWidget()); - if (checkBox != nullptr) { - ui->modList->header()->setSectionHidden(i, !checkBox->isChecked()); - } - } - ++i; - } -} - -void MainWindow::on_bsaList_customContextMenuRequested(const QPoint &pos) -{ - m_ContextItem = ui->bsaList->itemAt(pos); - -// m_ContextRow = ui->bsaList->indexOfTopLevelItem(ui->bsaList->itemAt(pos)); - - QMenu menu; - menu.addAction(tr("Extract..."), this, SLOT(extractBSATriggered())); - - menu.exec(ui->bsaList->mapToGlobal(pos)); -} - -void MainWindow::on_bsaList_itemChanged(QTreeWidgetItem*, int) -{ - m_ArchiveListWriter.write(); - m_CheckBSATimer.start(500); -} - -void MainWindow::on_actionNotifications_triggered() -{ - updateProblemsButton(); - ProblemsDialog problems(m_PluginContainer.plugins(), this); - if (problems.hasProblems()) { - QSettings &settings = m_OrganizerCore.settings().directInterface(); - QString key = QString("geometry/%1").arg(problems.objectName()); - if (settings.contains(key)) { - problems.restoreGeometry(settings.value(key).toByteArray()); - } - problems.exec(); - settings.setValue(key, problems.saveGeometry()); - updateProblemsButton(); - } -} - -void MainWindow::on_actionChange_Game_triggered() -{ - if (QMessageBox::question(this, tr("Are you sure?"), - tr("This will restart MO, continue?"), - QMessageBox::Yes | QMessageBox::Cancel) - == QMessageBox::Yes) { - InstanceManager::instance().clearCurrentInstance(); - qApp->exit(INT_MAX); - } -} - -void MainWindow::setCategoryListVisible(bool visible) -{ - if (visible) { - ui->categoriesGroup->show(); - ui->displayCategoriesBtn->setText(ToQString(L"\u00ab")); - } else { - ui->categoriesGroup->hide(); - ui->displayCategoriesBtn->setText(ToQString(L"\u00bb")); - } -} - -void MainWindow::on_displayCategoriesBtn_toggled(bool checked) -{ - setCategoryListVisible(checked); -} - -void MainWindow::editCategories() -{ - CategoriesDialog dialog(this); - QSettings &settings = m_OrganizerCore.settings().directInterface(); - QString key = QString("geometry/%1").arg(dialog.objectName()); - if (settings.contains(key)) { - dialog.restoreGeometry(settings.value(key).toByteArray()); - } - if (dialog.exec() == QDialog::Accepted) { - dialog.commitChanges(); - } - settings.setValue(key, dialog.saveGeometry()); - -} - -void MainWindow::deselectFilters() -{ - ui->categoriesList->clearSelection(); -} - -void MainWindow::on_categoriesList_customContextMenuRequested(const QPoint &pos) -{ - QMenu menu; - menu.addAction(tr("Edit Categories..."), this, SLOT(editCategories())); - menu.addAction(tr("Deselect filter"), this, SLOT(deselectFilters())); - - menu.exec(ui->categoriesList->mapToGlobal(pos)); -} - - -void MainWindow::updateESPLock(bool locked) -{ - QItemSelection currentSelection = ui->espList->selectionModel()->selection(); - if (currentSelection.count() == 0) { - // this path is probably useless - m_OrganizerCore.pluginList()->lockESPIndex(m_ContextRow, locked); - } else { - Q_FOREACH (const QModelIndex &idx, currentSelection.indexes()) { - if (m_OrganizerCore.pluginList()->isEnabled(mapToModel(m_OrganizerCore.pluginList(), idx).row())) { - m_OrganizerCore.pluginList()->lockESPIndex(mapToModel(m_OrganizerCore.pluginList(), idx).row(), locked); - } - } - } -} - - -void MainWindow::lockESPIndex() -{ - updateESPLock(true); -} - -void MainWindow::unlockESPIndex() -{ - updateESPLock(false); -} - - -void MainWindow::removeFromToolbar() -{ - try { - Executable &exe = m_OrganizerCore.executablesList()->find(m_ContextAction->text()); - exe.showOnToolbar(false); - } catch (const std::runtime_error&) { - qDebug("executable doesn't exist any more"); - } - - updateToolBar(); -} - - -void MainWindow::toolBar_customContextMenuRequested(const QPoint &point) -{ - QAction *action = ui->toolBar->actionAt(point); - if (action != nullptr) { - if (action->objectName().startsWith("custom_")) { - m_ContextAction = action; - QMenu menu; - menu.addAction(tr("Remove"), this, SLOT(removeFromToolbar())); - menu.exec(ui->toolBar->mapToGlobal(point)); - } - } -} - -void MainWindow::on_espList_customContextMenuRequested(const QPoint &pos) -{ - m_ContextRow = m_PluginListSortProxy->mapToSource(ui->espList->indexAt(pos)).row(); - - QMenu menu; - menu.addAction(tr("Enable selected"), this, SLOT(enableSelectedPlugins_clicked())); - menu.addAction(tr("Disable selected"), this, SLOT(disableSelectedPlugins_clicked())); - - menu.addSeparator(); - - menu.addAction(tr("Enable all"), m_OrganizerCore.pluginList(), SLOT(enableAll())); - menu.addAction(tr("Disable all"), m_OrganizerCore.pluginList(), SLOT(disableAll())); - - menu.addSeparator(); - - addPluginSendToContextMenu(&menu); - - QItemSelection currentSelection = ui->espList->selectionModel()->selection(); - bool hasLocked = false; - bool hasUnlocked = false; - for (const QModelIndex &idx : currentSelection.indexes()) { - int row = m_PluginListSortProxy->mapToSource(idx).row(); - if (m_OrganizerCore.pluginList()->isEnabled(row)) { - if (m_OrganizerCore.pluginList()->isESPLocked(row)) { - hasLocked = true; - } else { - hasUnlocked = true; - } - } - } - - if (hasLocked) { - menu.addAction(tr("Unlock load order"), this, SLOT(unlockESPIndex())); - } - if (hasUnlocked) { - menu.addAction(tr("Lock load order"), this, SLOT(lockESPIndex())); - } - - menu.addSeparator(); - - - QModelIndex idx = ui->espList->selectionModel()->currentIndex(); - unsigned int modInfoIndex = ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(idx.data().toString())); - //this is to avoid showing the option on game files like skyrim.esm - if (modInfoIndex != UINT_MAX) { - menu.addAction(tr("Open Origin in Explorer"), this, SLOT(openOriginExplorer_clicked())); - ModInfo::Ptr modInfo = ModInfo::getByIndex(modInfoIndex); - std::vector flags = modInfo->getFlags(); - - if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_FOREIGN) == flags.end()) { - QAction *infoAction = menu.addAction(tr("Open Origin Info..."), this, SLOT(openOriginInformation_clicked())); - menu.setDefaultAction(infoAction); - } - } - - try { - menu.exec(ui->espList->mapToGlobal(pos)); - } catch (const std::exception &e) { - reportError(tr("Exception: ").arg(e.what())); - } catch (...) { - reportError(tr("Unknown exception")); - } -} - -void MainWindow::on_groupCombo_currentIndexChanged(int index) -{ - if (m_ModListSortProxy == nullptr) { - return; - } - QAbstractProxyModel *newModel = nullptr; - switch (index) { - case 1: { - newModel = new QtGroupingProxy(m_OrganizerCore.modList(), QModelIndex(), ModList::COL_CATEGORY, Qt::UserRole, - 0, Qt::UserRole + 2); - } break; - case 2: { - newModel = new QtGroupingProxy(m_OrganizerCore.modList(), QModelIndex(), ModList::COL_MODID, Qt::DisplayRole, - QtGroupingProxy::FLAG_NOGROUPNAME | QtGroupingProxy::FLAG_NOSINGLE, - Qt::UserRole + 2); - } break; - default: { - newModel = nullptr; - } break; - } - - if (newModel != nullptr) { -#ifdef TEST_MODELS - new ModelTest(newModel, this); -#endif // TEST_MODELS - m_ModListSortProxy->setSourceModel(newModel); - connect(ui->modList, SIGNAL(expanded(QModelIndex)),newModel, SLOT(expanded(QModelIndex))); - connect(ui->modList, SIGNAL(collapsed(QModelIndex)), newModel, SLOT(collapsed(QModelIndex))); - connect(newModel, SIGNAL(expandItem(QModelIndex)), this, SLOT(expandModList(QModelIndex))); - } else { - m_ModListSortProxy->setSourceModel(m_OrganizerCore.modList()); - } - modFilterActive(m_ModListSortProxy->isFilterActive()); -} - -const Executable &MainWindow::getSelectedExecutable() const -{ - QString name = ui->executablesListBox->itemText(ui->executablesListBox->currentIndex()); - return m_OrganizerCore.executablesList()->find(name); -} - -Executable &MainWindow::getSelectedExecutable() -{ - QString name = ui->executablesListBox->itemText(ui->executablesListBox->currentIndex()); - return m_OrganizerCore.executablesList()->find(name); -} - -void MainWindow::on_linkButton_pressed() -{ - const Executable &selectedExecutable(getSelectedExecutable()); - - const QIcon addIcon(":/MO/gui/link"); - const QIcon removeIcon(":/MO/gui/remove"); - - const QFileInfo linkDesktopFile(getDesktopLinkfile(selectedExecutable)); - const QFileInfo linkMenuFile(getStartMenuLinkfile(selectedExecutable)); - - ui->linkButton->menu()->actions().at(static_cast(ShortcutType::Toolbar))->setIcon(selectedExecutable.isShownOnToolbar() ? removeIcon : addIcon); - ui->linkButton->menu()->actions().at(static_cast(ShortcutType::Desktop))->setIcon(linkDesktopFile.exists() ? removeIcon : addIcon); - ui->linkButton->menu()->actions().at(static_cast(ShortcutType::StartMenu))->setIcon(linkMenuFile.exists() ? removeIcon : addIcon); -} - -void MainWindow::on_showHiddenBox_toggled(bool checked) -{ - m_OrganizerCore.downloadManager()->setShowHidden(checked); -} - - -void MainWindow::createStdoutPipe(HANDLE *stdOutRead, HANDLE *stdOutWrite) -{ - SECURITY_ATTRIBUTES secAttributes; - secAttributes.nLength = sizeof(SECURITY_ATTRIBUTES); - secAttributes.bInheritHandle = TRUE; - secAttributes.lpSecurityDescriptor = nullptr; - - if (!::CreatePipe(stdOutRead, stdOutWrite, &secAttributes, 0)) { - qCritical("failed to create stdout reroute"); - } - - if (!::SetHandleInformation(*stdOutRead, HANDLE_FLAG_INHERIT, 0)) { - qCritical("failed to correctly set up the stdout reroute"); - *stdOutWrite = *stdOutRead = INVALID_HANDLE_VALUE; - } -} - -std::string MainWindow::readFromPipe(HANDLE stdOutRead) -{ - static const int chunkSize = 128; - std::string result; - - char buffer[chunkSize + 1]; - buffer[chunkSize] = '\0'; - - DWORD read = 1; - while (read > 0) { - if (!::ReadFile(stdOutRead, buffer, chunkSize, &read, nullptr)) { - break; - } - if (read > 0) { - result.append(buffer, read); - if (read < chunkSize) { - break; - } - } - } - return result; -} - -void MainWindow::processLOOTOut(const std::string &lootOut, std::string &errorMessages, QProgressDialog &dialog) -{ - std::vector lines; - boost::split(lines, lootOut, boost::is_any_of("\r\n")); - - std::regex exRequires("\"([^\"]*)\" requires \"([^\"]*)\", but it is missing\\."); - std::regex exIncompatible("\"([^\"]*)\" is incompatible with \"([^\"]*)\", but both are present\\."); - - for (const std::string &line : lines) { - if (line.length() > 0) { - size_t progidx = line.find("[progress]"); - size_t erroridx = line.find("[error]"); - if (progidx != std::string::npos) { - dialog.setLabelText(line.substr(progidx + 11).c_str()); - } else if (erroridx != std::string::npos) { - qWarning("%s", line.c_str()); - errorMessages.append(boost::algorithm::trim_copy(line.substr(erroridx + 8)) + "\n"); - } else { - std::smatch match; - if (std::regex_match(line, match, exRequires)) { - std::string modName(match[1].first, match[1].second); - std::string dependency(match[2].first, match[2].second); - m_OrganizerCore.pluginList()->addInformation(modName.c_str(), tr("depends on missing \"%1\"").arg(dependency.c_str())); - } else if (std::regex_match(line, match, exIncompatible)) { - std::string modName(match[1].first, match[1].second); - std::string dependency(match[2].first, match[2].second); - m_OrganizerCore.pluginList()->addInformation(modName.c_str(), tr("incompatible with \"%1\"").arg(dependency.c_str())); - } else { - qDebug("[loot] %s", line.c_str()); - } - } - } - } -} - -void MainWindow::on_bossButton_clicked() -{ - std::string reportURL; - std::string errorMessages; - - //m_OrganizerCore.currentProfile()->writeModlistNow(); - m_OrganizerCore.savePluginList(); - //Create a backup of the load orders w/ LOOT in name - //to make sure that any sorting is easily undo-able. - //Need to figure out how I want to do that. - - bool success = false; - - try { - setEnabled(false); - ON_BLOCK_EXIT([&] () { setEnabled(true); }); - QProgressDialog dialog(this); - dialog.setLabelText(tr("Please wait while LOOT is running")); - dialog.setMaximum(0); - dialog.show(); - - QString outPath = QDir::temp().absoluteFilePath("lootreport.json"); - - QStringList parameters; - parameters << "--game" << m_OrganizerCore.managedGame()->gameShortName() - << "--gamePath" << QString("\"%1\"").arg(m_OrganizerCore.managedGame()->gameDirectory().absolutePath()) - << "--pluginListPath" << QString("\"%1/loadorder.txt\"").arg(m_OrganizerCore.profilePath()) - << "--out" << QString("\"%1\"").arg(outPath); - - if (m_DidUpdateMasterList) { - parameters << "--skipUpdateMasterlist"; - } - HANDLE stdOutWrite = INVALID_HANDLE_VALUE; - HANDLE stdOutRead = INVALID_HANDLE_VALUE; - createStdoutPipe(&stdOutRead, &stdOutWrite); - try { - m_OrganizerCore.prepareVFS(); - } catch (const UsvfsConnectorException &e) { - qDebug(e.what()); - return; - } catch (const std::exception &e) { - QMessageBox::warning(qApp->activeWindow(), tr("Error"), e.what()); - return; - } - - HANDLE loot = startBinary(QFileInfo(qApp->applicationDirPath() + "/loot/lootcli.exe"), - parameters.join(" "), - qApp->applicationDirPath() + "/loot", - true, - stdOutWrite); - - // we don't use the write end - ::CloseHandle(stdOutWrite); - - m_OrganizerCore.pluginList()->clearAdditionalInformation(); - - DWORD retLen; - JOBOBJECT_BASIC_PROCESS_ID_LIST info; - HANDLE processHandle = loot; - - if (loot != INVALID_HANDLE_VALUE) { - bool isJobHandle = true; - ULONG lastProcessID; - DWORD res = ::MsgWaitForMultipleObjects(1, &loot, false, 100, QS_KEY | QS_MOUSE); - while ((res != WAIT_FAILED) && (res != WAIT_OBJECT_0)) { - if (isJobHandle) { - if (::QueryInformationJobObject(loot, JobObjectBasicProcessIdList, &info, sizeof(info), &retLen) > 0) { - if (info.NumberOfProcessIdsInList == 0) { - qDebug("no more processes in job"); - break; - } else { - if (lastProcessID != info.ProcessIdList[0]) { - lastProcessID = info.ProcessIdList[0]; - if (processHandle != loot) { - ::CloseHandle(processHandle); - } - processHandle = ::OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, lastProcessID); - } - } - } else { - // the info-object I passed only provides space for 1 process id. but since this code only cares about whether there - // is more than one that's good enough. ERROR_MORE_DATA simply signals there are at least two processes running. - // any other error probably means the handle is a regular process handle, probably caused by running MO in a job without - // the right to break out. - if (::GetLastError() != ERROR_MORE_DATA) { - isJobHandle = false; - } - } - } - - if (dialog.wasCanceled()) { - if (isJobHandle) { - ::TerminateJobObject(loot, 1); - } else { - ::TerminateProcess(loot, 1); - } - } - - // keep processing events so the app doesn't appear dead - QCoreApplication::processEvents(); - std::string lootOut = readFromPipe(stdOutRead); - processLOOTOut(lootOut, errorMessages, dialog); - - res = ::MsgWaitForMultipleObjects(1, &loot, false, 100, QS_KEY | QS_MOUSE); - } - - std::string remainder = readFromPipe(stdOutRead).c_str(); - if (remainder.length() > 0) { - processLOOTOut(remainder, errorMessages, dialog); - } - DWORD exitCode = 0UL; - ::GetExitCodeProcess(processHandle, &exitCode); - ::CloseHandle(processHandle); - if (exitCode != 0UL) { - reportError(tr("loot failed. Exit code was: %1").arg(exitCode)); - return; - } else { - success = true; - QFile outFile(outPath); - outFile.open(QIODevice::ReadOnly); - QJsonDocument doc = QJsonDocument::fromJson(outFile.readAll()); - QJsonArray array = doc.array(); - for (auto iter = array.begin(); iter != array.end(); ++iter) { - QJsonObject pluginObj = (*iter).toObject(); - QJsonArray pluginMessages = pluginObj["messages"].toArray(); - for (auto msgIter = pluginMessages.begin(); msgIter != pluginMessages.end(); ++msgIter) { - QJsonObject msg = (*msgIter).toObject(); - m_OrganizerCore.pluginList()->addInformation(pluginObj["name"].toString(), - QString("%1: %2").arg(msg["type"].toString(), msg["message"].toString())); - } - if (pluginObj["dirty"].toString() == "yes") - m_OrganizerCore.pluginList()->addInformation(pluginObj["name"].toString(), "dirty"); - } - - } - } else { - reportError(tr("failed to start loot")); - } - } catch (const std::exception &e) { - reportError(tr("failed to run loot: %1").arg(e.what())); - } - - if (errorMessages.length() > 0) { - QMessageBox *warn = new QMessageBox(QMessageBox::Warning, tr("Errors occured"), errorMessages.c_str(), QMessageBox::Ok, this); - warn->setModal(false); - warn->show(); - } - - if (success) { - m_DidUpdateMasterList = true; - if (reportURL.length() > 0) { - m_IntegratedBrowser.setWindowTitle("LOOT Report"); - QString report(reportURL.c_str()); - QStringList temp = report.split("?"); - QUrl url = QUrl::fromLocalFile(temp.at(0)); - if (temp.size() > 1) { - url.setQuery(temp.at(1).toUtf8()); - } - m_IntegratedBrowser.openUrl(url); - } - m_OrganizerCore.refreshESPList(false); - m_OrganizerCore.savePluginList(); - } -} - - -const char *MainWindow::PATTERN_BACKUP_GLOB = ".????_??_??_??_??_??"; -const char *MainWindow::PATTERN_BACKUP_REGEX = "\\.(\\d\\d\\d\\d_\\d\\d_\\d\\d_\\d\\d_\\d\\d_\\d\\d)"; -const char *MainWindow::PATTERN_BACKUP_DATE = "yyyy_MM_dd_hh_mm_ss"; - - -bool MainWindow::createBackup(const QString &filePath, const QDateTime &time) -{ - QString outPath = filePath + "." + time.toString(PATTERN_BACKUP_DATE); - if (shellCopy(QStringList(filePath), QStringList(outPath), this)) { - QFileInfo fileInfo(filePath); - removeOldFiles(fileInfo.absolutePath(), fileInfo.fileName() + PATTERN_BACKUP_GLOB, 10, QDir::Name); - return true; - } else { - return false; - } -} - -void MainWindow::on_saveButton_clicked() -{ - m_OrganizerCore.savePluginList(); - QDateTime now = QDateTime::currentDateTime(); - if (createBackup(m_OrganizerCore.currentProfile()->getPluginsFileName(), now) - && createBackup(m_OrganizerCore.currentProfile()->getLoadOrderFileName(), now) - && createBackup(m_OrganizerCore.currentProfile()->getLockedOrderFileName(), now)) { - MessageDialog::showMessage(tr("Backup of load order created"), this); - } -} - -QString MainWindow::queryRestore(const QString &filePath) -{ - QFileInfo pluginFileInfo(filePath); - QString pattern = pluginFileInfo.fileName() + ".*"; - QFileInfoList files = pluginFileInfo.absoluteDir().entryInfoList(QStringList(pattern), QDir::Files, QDir::Name); - - SelectionDialog dialog(tr("Choose backup to restore"), this); - QRegExp exp(pluginFileInfo.fileName() + PATTERN_BACKUP_REGEX); - QRegExp exp2(pluginFileInfo.fileName() + "\\.(.*)"); - for(const QFileInfo &info : boost::adaptors::reverse(files)) { - if (exp.exactMatch(info.fileName())) { - QDateTime time = QDateTime::fromString(exp.cap(1), PATTERN_BACKUP_DATE); - dialog.addChoice(time.toString(), "", exp.cap(1)); - } else if (exp2.exactMatch(info.fileName())) { - dialog.addChoice(exp2.cap(1), "", exp2.cap(1)); - } - } - - if (dialog.numChoices() == 0) { - QMessageBox::information(this, tr("No Backups"), tr("There are no backups to restore")); - return QString(); - } - - if (dialog.exec() == QDialog::Accepted) { - return dialog.getChoiceData().toString(); - } else { - return QString(); - } -} - -void MainWindow::on_restoreButton_clicked() -{ - QString pluginName = m_OrganizerCore.currentProfile()->getPluginsFileName(); - QString choice = queryRestore(pluginName); - if (!choice.isEmpty()) { - QString loadOrderName = m_OrganizerCore.currentProfile()->getLoadOrderFileName(); - QString lockedName = m_OrganizerCore.currentProfile()->getLockedOrderFileName(); - if (!shellCopy(pluginName + "." + choice, pluginName, true, this) || - !shellCopy(loadOrderName + "." + choice, loadOrderName, true, this) || - !shellCopy(lockedName + "." + choice, lockedName, true, this)) { - QMessageBox::critical(this, tr("Restore failed"), - tr("Failed to restore the backup. Errorcode: %1").arg(windowsErrorString(::GetLastError()))); - } - m_OrganizerCore.refreshESPList(true); - } -} - -void MainWindow::on_saveModsButton_clicked() -{ - m_OrganizerCore.currentProfile()->writeModlistNow(true); - QDateTime now = QDateTime::currentDateTime(); - if (createBackup(m_OrganizerCore.currentProfile()->getModlistFileName(), now)) { - MessageDialog::showMessage(tr("Backup of modlist created"), this); - } -} - -void MainWindow::on_restoreModsButton_clicked() -{ - QString modlistName = m_OrganizerCore.currentProfile()->getModlistFileName(); - QString choice = queryRestore(modlistName); - if (!choice.isEmpty()) { - if (!shellCopy(modlistName + "." + choice, modlistName, true, this)) { - QMessageBox::critical(this, tr("Restore failed"), - tr("Failed to restore the backup. Errorcode: %1").arg(windowsErrorString(::GetLastError()))); - } - m_OrganizerCore.refreshModList(false); - } -} - -void MainWindow::on_actionCopy_Log_to_Clipboard_triggered() -{ - QStringList lines; - QAbstractItemModel *model = ui->logList->model(); - for (int i = 0; i < model->rowCount(); ++i) { - lines.append(QString("%1 [%2] %3").arg(model->index(i, 0).data().toString()) - .arg(model->index(i, 1).data(Qt::UserRole).toString()) - .arg(model->index(i, 1).data().toString())); - } - QApplication::clipboard()->setText(lines.join("\n")); -} - -void MainWindow::on_categoriesAndBtn_toggled(bool checked) -{ - if (checked) { - m_ModListSortProxy->setFilterMode(ModListSortProxy::FILTER_AND); - } -} - -void MainWindow::on_categoriesOrBtn_toggled(bool checked) -{ - if (checked) { - m_ModListSortProxy->setFilterMode(ModListSortProxy::FILTER_OR); - } -} - -void MainWindow::on_managedArchiveLabel_linkHovered(const QString&) -{ - QToolTip::showText(QCursor::pos(), - ui->managedArchiveLabel->toolTip()); -} - -void MainWindow::dragEnterEvent(QDragEnterEvent *event) -{ - //Accept copy or move drags to the download window. Link drags are not - //meaningful (Well, they are - we could drop a link in the download folder, - //but you need privileges to do that). - if (ui->downloadTab->isVisible() && - (event->proposedAction() == Qt::CopyAction || - event->proposedAction() == Qt::MoveAction) && - event->answerRect().intersects(ui->downloadTab->rect())) { - - //If I read the documentation right, this won't work under a motif windows - //manager and the check needs to be done at the drop. However, that means - //the user might be allowed to drop things which we can't sanely process - QMimeData const *data = event->mimeData(); - - if (data->hasUrls()) { - QStringList extensions = - m_OrganizerCore.installationManager()->getSupportedExtensions(); - - //This is probably OK - scan to see if these are moderately sane archive - //types - QList urls = data->urls(); - bool ok = true; - for (const QUrl &url : urls) { - if (url.isLocalFile()) { - QString local = url.toLocalFile(); - bool fok = false; - for (auto ext : extensions) { - if (local.endsWith(ext, Qt::CaseInsensitive)) { - fok = true; - break; - } - } - if (! fok) { - ok = false; - break; - } - } - } - if (ok) { - event->accept(); - } - } - } -} - -void MainWindow::dropLocalFile(const QUrl &url, const QString &outputDir, bool move) -{ - QFileInfo file(url.toLocalFile()); - if (!file.exists()) { - qWarning("invalid source file: %s", qUtf8Printable(file.absoluteFilePath())); - return; - } - QString target = outputDir + "/" + file.fileName(); - if (QFile::exists(target)) { - QMessageBox box(QMessageBox::Question, - file.fileName(), - tr("A file with the same name has already been downloaded. " - "What would you like to do?")); - box.addButton(tr("Overwrite"), QMessageBox::ActionRole); - box.addButton(tr("Rename new file"), QMessageBox::YesRole); - box.addButton(tr("Ignore file"), QMessageBox::RejectRole); - - box.exec(); - switch (box.buttonRole(box.clickedButton())) { - case QMessageBox::RejectRole: - return; - case QMessageBox::ActionRole: - break; - default: - case QMessageBox::YesRole: - target = m_OrganizerCore.downloadManager()->getDownloadFileName(file.fileName()); - break; - } - } - - bool success = false; - if (move) { - success = shellMove(file.absoluteFilePath(), target, true, this); - } else { - success = shellCopy(file.absoluteFilePath(), target, true, this); - } - if (!success) { - qCritical("file operation failed: %s", qUtf8Printable(windowsErrorString(::GetLastError()))); - } -} - -bool MainWindow::registerWidgetState(const QString &name, QHeaderView *view, const char *oldSettingName) { - // register the view so it's geometry gets saved at exit - m_PersistedGeometry.push_back(std::make_pair(name, view)); - - // also, restore the geometry if it was saved before - QSettings &settings = m_OrganizerCore.settings().directInterface(); - - QString key = QString("geometry/%1").arg(name); - QByteArray data; - - if ((oldSettingName != nullptr) && settings.contains(oldSettingName)) { - data = settings.value(oldSettingName).toByteArray(); - settings.remove(oldSettingName); - } else if (settings.contains(key)) { - data = settings.value(key).toByteArray(); - } - - if (!data.isEmpty()) { - view->restoreState(data); - return true; - } else { - return false; - } -} - -void MainWindow::dropEvent(QDropEvent *event) -{ - Qt::DropAction action = event->proposedAction(); - QString outputDir = m_OrganizerCore.downloadManager()->getOutputDirectory(); - if (action == Qt::MoveAction) { - //Tell windows I'm taking control and will delete the source of a move. - event->setDropAction(Qt::TargetMoveAction); - } - for (const QUrl &url : event->mimeData()->urls()) { - if (url.isLocalFile()) { - dropLocalFile(url, outputDir, action == Qt::MoveAction); - } else { - m_OrganizerCore.downloadManager()->startDownloadURLs(QStringList() << url.url()); - } - } - event->accept(); -} - - -void MainWindow::on_clickBlankButton_clicked() -{ - deselectFilters(); -} - -void MainWindow::on_clearFiltersButton_clicked() -{ - ui->modFilterEdit->clear(); - deselectFilters(); -} - -void MainWindow::sendSelectedModsToPriority(int newPriority) -{ - QItemSelectionModel *selection = ui->modList->selectionModel(); - if (selection->hasSelection() && selection->selectedRows().count() > 1) { - std::vector modsToMove; - for (auto idx : selection->selectedRows(ModList::COL_PRIORITY)) { - modsToMove.push_back(m_OrganizerCore.currentProfile()->modIndexByPriority(idx.data().toInt())); - } - m_OrganizerCore.modList()->changeModPriority(modsToMove, newPriority); - } else { - m_OrganizerCore.modList()->changeModPriority(m_ContextRow, newPriority); - } -} - -void MainWindow::sendSelectedModsToTop_clicked() -{ - sendSelectedModsToPriority(0); -} - -void MainWindow::sendSelectedModsToBottom_clicked() -{ - sendSelectedModsToPriority(INT_MAX); -} - -void MainWindow::sendSelectedModsToPriority_clicked() -{ - bool ok; - int newPriority = QInputDialog::getInt(this, - tr("Set Priority"), tr("Set the priority of the selected mods"), - 0, 0, INT_MAX, 1, &ok); - if (!ok) return; - - sendSelectedModsToPriority(newPriority); -} - -void MainWindow::sendSelectedModsToSeparator_clicked() -{ - QStringList separators; - auto indexesByPriority = m_OrganizerCore.currentProfile()->getAllIndexesByPriority(); - for (auto iter = indexesByPriority.begin(); iter != indexesByPriority.end(); iter++) { - if ((iter->second != UINT_MAX)) { - ModInfo::Ptr modInfo = ModInfo::getByIndex(iter->second); - if (modInfo->hasFlag(ModInfo::FLAG_SEPARATOR)) { - separators << modInfo->name().chopped(10); // Chops the "_separator" away from the name - } - } - } - - ListDialog dialog(this); - QSettings &settings = m_OrganizerCore.settings().directInterface(); - QString key = QString("geometry/%1").arg(dialog.objectName()); - - dialog.setWindowTitle("Select a separator..."); - dialog.setChoices(separators); - dialog.restoreGeometry(settings.value(key).toByteArray()); - if (dialog.exec() == QDialog::Accepted) { - QString result = dialog.getChoice(); - if (!result.isEmpty()) { - result += "_separator"; - - int newPriority = INT_MAX; - bool foundSection = false; - for (auto mod : m_OrganizerCore.modsSortedByProfilePriority()) { - unsigned int modIndex = ModInfo::getIndex(mod); - ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); - if (!foundSection && result.compare(mod) == 0) { - foundSection = true; - } else if (foundSection && modInfo->hasFlag(ModInfo::FLAG_SEPARATOR)) { - newPriority = m_OrganizerCore.currentProfile()->getModPriority(modIndex); - break; - } - } - - QItemSelectionModel *selection = ui->modList->selectionModel(); - if (selection->hasSelection() && selection->selectedRows().count() > 1) { - std::vector modsToMove; - for (QModelIndex idx : selection->selectedRows(ModList::COL_PRIORITY)) { - modsToMove.push_back(m_OrganizerCore.currentProfile()->modIndexByPriority(idx.data().toInt())); - } - m_OrganizerCore.modList()->changeModPriority(modsToMove, newPriority); - } else { - int oldPriority = m_OrganizerCore.currentProfile()->getModPriority(m_ContextRow); - if (oldPriority < newPriority) - --newPriority; - m_OrganizerCore.modList()->changeModPriority(m_ContextRow, newPriority); - } - } - } - settings.setValue(key, dialog.saveGeometry()); -} - -void MainWindow::on_showArchiveDataCheckBox_toggled(const bool checked) -{ - if (m_OrganizerCore.getArchiveParsing() && checked) - { - m_showArchiveData = checked; - } - else - { - m_showArchiveData = false; - } - refreshDataTree(); -} - +/* +Copyright (C) 2012 Sebastian Herbord. All rights reserved. + +This file is part of Mod Organizer. + +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 . +*/ + +#include "mainwindow.h" +#include "ui_mainwindow.h" + +#include "directoryentry.h" +#include "directoryrefresher.h" +#include "executableinfo.h" +#include "executableslist.h" +#include "guessedvalue.h" +#include "imodinterface.h" +#include "iplugingame.h" +#include "iplugindiagnose.h" +#include "isavegame.h" +#include "isavegameinfowidget.h" +#include "nexusinterface.h" +#include "organizercore.h" +#include "pluginlistsortproxy.h" +#include "previewgenerator.h" +#include "serverinfo.h" +#include "savegameinfo.h" +#include "spawn.h" +#include "versioninfo.h" +#include "instancemanager.h" + +#include "report.h" +#include "modlist.h" +#include "modlistsortproxy.h" +#include "qtgroupingproxy.h" +#include "profile.h" +#include "pluginlist.h" +#include "profilesdialog.h" +#include "editexecutablesdialog.h" +#include "categories.h" +#include "categoriesdialog.h" +#include "modinfodialog.h" +#include "overwriteinfodialog.h" +#include "activatemodsdialog.h" +#include "downloadlist.h" +#include "downloadlistwidget.h" +#include "messagedialog.h" +#include "installationmanager.h" +#include "lockeddialog.h" +#include "waitingonclosedialog.h" +#include "logbuffer.h" +#include "downloadlistsortproxy.h" +#include "motddialog.h" +#include "filedialogmemory.h" +#include "tutorialmanager.h" +#include "modflagicondelegate.h" +#include "genericicondelegate.h" +#include "selectiondialog.h" +#include "csvbuilder.h" +#include "savetextasdialog.h" +#include "problemsdialog.h" +#include "previewdialog.h" +#include "browserdialog.h" +#include "aboutdialog.h" +#include +#include "nxmaccessmanager.h" +#include "appconfig.h" +#include "eventfilter.h" +#include +#include +#include +#include +#include +#include +#include "localsavegames.h" +#include "listdialog.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#ifndef Q_MOC_RUN +#include +#include +#include +#include +#include +#endif + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef TEST_MODELS +#include "modeltest.h" +#endif // TEST_MODELS + +#pragma warning( disable : 4428 ) + +using namespace MOBase; +using namespace MOShared; + + +MainWindow::MainWindow(QSettings &initSettings + , OrganizerCore &organizerCore + , PluginContainer &pluginContainer + , QWidget *parent) + : QMainWindow(parent) + , ui(new Ui::MainWindow) + , m_WasVisible(false) + , m_Tutorial(this, "MainWindow") + , m_OldProfileIndex(-1) + , m_ModListGroupingProxy(nullptr) + , m_ModListSortProxy(nullptr) + , m_OldExecutableIndex(-1) + , m_CategoryFactory(CategoryFactory::instance()) + , m_ContextItem(nullptr) + , m_ContextAction(nullptr) + , m_ContextRow(-1) + , m_CurrentSaveView(nullptr) + , m_OrganizerCore(organizerCore) + , m_PluginContainer(pluginContainer) + , m_DidUpdateMasterList(false) + , m_ArchiveListWriter(std::bind(&MainWindow::saveArchiveList, this)) +{ + QWebEngineProfile::defaultProfile()->setPersistentCookiesPolicy(QWebEngineProfile::NoPersistentCookies); + QWebEngineProfile::defaultProfile()->setHttpCacheMaximumSize(52428800); + QWebEngineProfile::defaultProfile()->setCachePath(m_OrganizerCore.settings().getCacheDirectory()); + QWebEngineProfile::defaultProfile()->setPersistentStoragePath(m_OrganizerCore.settings().getCacheDirectory()); + ui->setupUi(this); + updateWindowTitle(QString(), false); + + languageChange(m_OrganizerCore.settings().language()); + + m_CategoryFactory.loadCategories(); + + ui->logList->setModel(LogBuffer::instance()); + ui->logList->setColumnWidth(0, 100); + ui->logList->setAutoScroll(true); + ui->logList->scrollToBottom(); + ui->logList->addAction(ui->actionCopy_Log_to_Clipboard); + int splitterSize = this->size().height(); // actually total window size, but the splitter doesn't seem to return the true value + ui->topLevelSplitter->setSizes(QList() << splitterSize - 100 << 100); + connect(ui->logList->model(), SIGNAL(rowsInserted(const QModelIndex &, int, int)), + ui->logList, SLOT(scrollToBottom())); + connect(ui->logList->model(), SIGNAL(dataChanged(QModelIndex,QModelIndex)), + ui->logList, SLOT(scrollToBottom())); + + m_RefreshProgress = new QProgressBar(statusBar()); + m_RefreshProgress->setTextVisible(true); + m_RefreshProgress->setRange(0, 100); + m_RefreshProgress->setValue(0); + m_RefreshProgress->setVisible(false); + statusBar()->addWidget(m_RefreshProgress, 1000); + statusBar()->clearMessage(); + statusBar()->hide(); + + updateProblemsButton(); + + // Setup toolbar + QWidget *spacer = new QWidget(ui->toolBar); + spacer->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred); + QWidget *widget = ui->toolBar->widgetForAction(ui->actionTool); + QToolButton *toolBtn = qobject_cast(widget); + + if (toolBtn->menu() == nullptr) { + actionToToolButton(ui->actionTool); + } + + actionToToolButton(ui->actionHelp); + createHelpWidget(); + + actionToToolButton(ui->actionEndorseMO); + createEndorseWidget(); + ui->actionEndorseMO->setVisible(false); + + for (QAction *action : ui->toolBar->actions()) { + if (action->isSeparator()) { + // insert spacers + ui->toolBar->insertWidget(action, spacer); + m_Sep = action; + // m_Sep would only use the last separator anyway, and we only have the one anyway? + break; + } + } + + TaskProgressManager::instance().tryCreateTaskbar(); + + // set up mod list + m_ModListSortProxy = m_OrganizerCore.createModListProxyModel(); + + ui->modList->setModel(m_ModListSortProxy); + + GenericIconDelegate *contentDelegate = new GenericIconDelegate(ui->modList, Qt::UserRole + 3, ModList::COL_CONTENT, 150); + connect(ui->modList->header(), SIGNAL(sectionResized(int,int,int)), contentDelegate, SLOT(columnResized(int,int,int))); + ui->modList->sortByColumn(ModList::COL_PRIORITY, Qt::AscendingOrder); + ModFlagIconDelegate *flagDelegate = new ModFlagIconDelegate(ui->modList, ModList::COL_FLAGS, 120); + connect(ui->modList->header(), SIGNAL(sectionResized(int,int,int)), flagDelegate, SLOT(columnResized(int,int,int))); + ui->modList->setItemDelegateForColumn(ModList::COL_FLAGS, flagDelegate); + ui->modList->setItemDelegateForColumn(ModList::COL_CONTENT, contentDelegate); + ui->modList->header()->installEventFilter(m_OrganizerCore.modList()); + connect(ui->modList->header(), SIGNAL(sectionResized(int, int, int)), this, SLOT(modListSectionResized(int, int, int))); + + bool modListAdjusted = registerWidgetState(ui->modList->objectName(), ui->modList->header(), "mod_list_state"); + + if (modListAdjusted) { + // hack: force the resize-signal to be triggered because restoreState doesn't seem to do that + for (int column = 0; column <= ModList::COL_LASTCOLUMN; ++column) { + int sectionSize = ui->modList->header()->sectionSize(column); + ui->modList->header()->resizeSection(column, sectionSize + 1); + ui->modList->header()->resizeSection(column, sectionSize); + } + } else { + // hide these columns by default + ui->modList->header()->setSectionHidden(ModList::COL_CONTENT, true); + ui->modList->header()->setSectionHidden(ModList::COL_MODID, true); + ui->modList->header()->setSectionHidden(ModList::COL_GAME, true); + ui->modList->header()->setSectionHidden(ModList::COL_INSTALLTIME, true); + ui->modList->header()->setSectionHidden(ModList::COL_NOTES, true); + } + + ui->modList->header()->setSectionHidden(ModList::COL_NAME, false); // prevent the name-column from being hidden + ui->modList->installEventFilter(m_OrganizerCore.modList()); + + // set up plugin list + m_PluginListSortProxy = m_OrganizerCore.createPluginListProxyModel(); + + ui->espList->setModel(m_PluginListSortProxy); + ui->espList->sortByColumn(PluginList::COL_PRIORITY, Qt::AscendingOrder); + ui->espList->setItemDelegateForColumn(PluginList::COL_FLAGS, new GenericIconDelegate(ui->espList)); + ui->espList->installEventFilter(m_OrganizerCore.pluginList()); + + ui->bsaList->setLocalMoveOnly(true); + + initDownloadView(); + bool pluginListAdjusted = registerWidgetState(ui->espList->objectName(), ui->espList->header(), "plugin_list_state"); + registerWidgetState(ui->dataTree->objectName(), ui->dataTree->header()); + registerWidgetState(ui->downloadView->objectName(), + ui->downloadView->header()); + + ui->splitter->setStretchFactor(0, 3); + ui->splitter->setStretchFactor(1, 2); + + resizeLists(modListAdjusted, pluginListAdjusted); + + QMenu *linkMenu = new QMenu(this); + linkMenu->addAction(QIcon(":/MO/gui/link"), tr("Toolbar"), this, SLOT(linkToolbar())); + linkMenu->addAction(QIcon(":/MO/gui/link"), tr("Desktop"), this, SLOT(linkDesktop())); + linkMenu->addAction(QIcon(":/MO/gui/link"), tr("Start Menu"), this, SLOT(linkMenu())); + ui->linkButton->setMenu(linkMenu); + + QMenu *listOptionsMenu = new QMenu(ui->listOptionsBtn); + initModListContextMenu(listOptionsMenu); + ui->listOptionsBtn->setMenu(listOptionsMenu); + connect(ui->listOptionsBtn, SIGNAL(pressed()), this, SLOT(on_listOptionsBtn_pressed())); + + ui->openFolderMenu->setMenu(openFolderMenu()); + + ui->savegameList->installEventFilter(this); + ui->savegameList->setMouseTracking(true); + + // don't allow mouse wheel to switch grouping, too many people accidentally + // turn on grouping and then don't understand what happened + EventFilter *noWheel + = new EventFilter(this, [](QObject *, QEvent *event) -> bool { + return event->type() == QEvent::Wheel; + }); + + ui->groupCombo->installEventFilter(noWheel); + ui->profileBox->installEventFilter(noWheel); + + if (organizerCore.managedGame()->sortMechanism() == MOBase::IPluginGame::SortMechanism::NONE) { + ui->bossButton->setDisabled(true); + ui->bossButton->setToolTip(tr("There is no supported sort mechanism for this game. You will probably have to use a third-party tool.")); + } + + connect(ui->savegameList, SIGNAL(itemEntered(QListWidgetItem*)), this, SLOT(saveSelectionChanged(QListWidgetItem*))); + + connect(ui->modList, SIGNAL(dropModeUpdate(bool)), m_OrganizerCore.modList(), SLOT(dropModeUpdate(bool))); + + connect(ui->modList->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)), this, SLOT(modlistSelectionChanged(QModelIndex,QModelIndex))); + connect(m_ModListSortProxy, SIGNAL(filterActive(bool)), this, SLOT(modFilterActive(bool))); + connect(m_ModListSortProxy, SIGNAL(layoutChanged()), this, SLOT(updateModCount())); + connect(ui->modFilterEdit, SIGNAL(textChanged(QString)), m_ModListSortProxy, SLOT(updateFilter(QString))); + + connect(ui->espFilterEdit, SIGNAL(textChanged(QString)), m_PluginListSortProxy, SLOT(updateFilter(QString))); + connect(ui->espFilterEdit, SIGNAL(textChanged(QString)), this, SLOT(espFilterChanged(QString))); + + connect(ui->dataTree, SIGNAL(itemExpanded(QTreeWidgetItem*)), this, SLOT(expandDataTreeItem(QTreeWidgetItem*))); + + connect(m_OrganizerCore.directoryRefresher(), SIGNAL(refreshed()), this, SLOT(directory_refreshed())); + connect(m_OrganizerCore.directoryRefresher(), SIGNAL(progress(int)), this, SLOT(refresher_progress(int))); + connect(m_OrganizerCore.directoryRefresher(), SIGNAL(error(QString)), this, SLOT(showError(QString))); + + connect(&m_SavesWatcher, SIGNAL(directoryChanged(QString)), this, SLOT(refreshSavesIfOpen())); + + connect(&m_OrganizerCore.settings(), SIGNAL(languageChanged(QString)), this, SLOT(languageChange(QString))); + connect(&m_OrganizerCore.settings(), SIGNAL(styleChanged(QString)), this, SIGNAL(styleChanged(QString))); + + connect(m_OrganizerCore.updater(), SIGNAL(restart()), this, SLOT(close())); + connect(m_OrganizerCore.updater(), SIGNAL(updateAvailable()), this, SLOT(updateAvailable())); + connect(m_OrganizerCore.updater(), SIGNAL(motdAvailable(QString)), this, SLOT(motdReceived(QString))); + + connect(NexusInterface::instance(&pluginContainer), SIGNAL(requestNXMDownload(QString)), &m_OrganizerCore, SLOT(downloadRequestedNXM(QString))); + connect(NexusInterface::instance(&pluginContainer), SIGNAL(nxmDownloadURLsAvailable(QString,int,int,QVariant,QVariant,int)), this, SLOT(nxmDownloadURLs(QString,int,int,QVariant,QVariant,int))); + connect(NexusInterface::instance(&pluginContainer), SIGNAL(needLogin()), &m_OrganizerCore, SLOT(nexusLogin())); + connect(NexusInterface::instance(&pluginContainer)->getAccessManager(), SIGNAL(loginFailed(QString)), this, SLOT(loginFailed(QString))); + connect(NexusInterface::instance(&pluginContainer)->getAccessManager(), SIGNAL(credentialsReceived(const QString&, bool)), + this, SLOT(updateWindowTitle(const QString&, bool))); + + connect(&TutorialManager::instance(), SIGNAL(windowTutorialFinished(QString)), this, SLOT(windowTutorialFinished(QString))); + connect(ui->tabWidget, SIGNAL(currentChanged(int)), &TutorialManager::instance(), SIGNAL(tabChanged(int))); + connect(ui->modList->header(), SIGNAL(sortIndicatorChanged(int,Qt::SortOrder)), this, SLOT(modListSortIndicatorChanged(int,Qt::SortOrder))); + connect(ui->toolBar, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(toolBar_customContextMenuRequested(QPoint))); + + connect(&m_OrganizerCore, &OrganizerCore::modInstalled, this, &MainWindow::modInstalled); + connect(&m_OrganizerCore, &OrganizerCore::close, this, &QMainWindow::close); + + connect(&m_IntegratedBrowser, SIGNAL(requestDownload(QUrl,QNetworkReply*)), &m_OrganizerCore, SLOT(requestDownload(QUrl,QNetworkReply*))); + + connect(this, SIGNAL(styleChanged(QString)), this, SLOT(updateStyle(QString))); + + m_CheckBSATimer.setSingleShot(true); + connect(&m_CheckBSATimer, SIGNAL(timeout()), this, SLOT(checkBSAList())); + + connect(ui->espList->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this, SLOT(esplistSelectionsChanged(QItemSelection))); + connect(ui->modList->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this, SLOT(modlistSelectionsChanged(QItemSelection))); + + new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Enter), this, SLOT(openExplorer_activated())); + new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Return), this, SLOT(openExplorer_activated())); + + new QShortcut(QKeySequence::Refresh, this, SLOT(refreshProfile_activated())); + + new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_F), this, SLOT(search_activated())); + new QShortcut(QKeySequence(Qt::Key_Escape), this, SLOT(searchClear_activated())); + + m_UpdateProblemsTimer.setSingleShot(true); + connect(&m_UpdateProblemsTimer, SIGNAL(timeout()), this, SLOT(updateProblemsButton())); + + m_SaveMetaTimer.setSingleShot(false); + connect(&m_SaveMetaTimer, SIGNAL(timeout()), this, SLOT(saveModMetas())); + m_SaveMetaTimer.start(5000); + + setCategoryListVisible(initSettings.value("categorylist_visible", true).toBool()); + FileDialogMemory::restore(initSettings); + + fixCategories(); + + m_StartTime = QTime::currentTime(); + + m_Tutorial.expose("modList", m_OrganizerCore.modList()); + m_Tutorial.expose("espList", m_OrganizerCore.pluginList()); + + m_OrganizerCore.setUserInterface(this, this); + for (const QString &fileName : m_PluginContainer.pluginFileNames()) { + installTranslator(QFileInfo(fileName).baseName()); + } + + registerPluginTools(m_PluginContainer.plugins()); + + for (IPluginModPage *modPagePlugin : m_PluginContainer.plugins()) { + registerModPage(modPagePlugin); + } + + // refresh profiles so the current profile can be activated + refreshProfiles(false); + + ui->profileBox->setCurrentText(m_OrganizerCore.currentProfile()->name()); + + if (m_OrganizerCore.getArchiveParsing()) + { + ui->showArchiveDataCheckBox->setCheckState(Qt::Checked); + ui->showArchiveDataCheckBox->setEnabled(true); + m_showArchiveData = true; + } + else + { + ui->showArchiveDataCheckBox->setCheckState(Qt::Unchecked); + ui->showArchiveDataCheckBox->setEnabled(false); + m_showArchiveData = false; + } + + refreshExecutablesList(); + updateToolBar(); + + for (QAction *action : ui->toolBar->actions()) { + // set the name of the widget to the name of the action to allow styling + QWidget *actionWidget = ui->toolBar->widgetForAction(action); + actionWidget->setObjectName(action->objectName()); + actionWidget->style()->unpolish(actionWidget); + actionWidget->style()->polish(actionWidget); + } + + updatePluginCount(); + updateModCount(); +} + + +MainWindow::~MainWindow() +{ + try { + cleanup(); + + m_PluginContainer.setUserInterface(nullptr, nullptr); + m_OrganizerCore.setUserInterface(nullptr, nullptr); + m_IntegratedBrowser.close(); + delete ui; + } catch (std::exception &e) { + QMessageBox::critical(nullptr, tr("Crash on exit"), + tr("MO crashed while exiting. Some settings may not be saved.\n\nError: %1").arg(e.what()), + QMessageBox::Ok); + } +} + + +void MainWindow::updateWindowTitle(const QString &accountName, bool premium) +{ + QString title = QString("%1 Mod Organizer v%2").arg( + m_OrganizerCore.managedGame()->gameName(), + m_OrganizerCore.getVersion().displayString(3)); + + if (!accountName.isEmpty()) { + title.append(QString(" (%1%2)").arg(accountName, premium ? "*" : "")); + } + + this->setWindowTitle(title); +} + + +void MainWindow::disconnectPlugins() +{ + if (ui->actionTool->menu() != nullptr) { + ui->actionTool->menu()->clear(); + } +} + + +void MainWindow::resizeLists(bool modListCustom, bool pluginListCustom) +{ + if (!modListCustom) { + // resize mod list to fit content + for (int i = 0; i < ui->modList->header()->count(); ++i) { + ui->modList->header()->setSectionResizeMode(i, QHeaderView::ResizeToContents); + } + ui->modList->header()->setSectionResizeMode(ModList::COL_NAME, QHeaderView::Stretch); + } + + // ensure the columns aren't so small you can't see them any more + for (int i = 0; i < ui->modList->header()->count(); ++i) { + if (ui->modList->header()->sectionSize(i) < 10) { + ui->modList->header()->resizeSection(i, 10); + } + } + + if (!pluginListCustom) { + // resize plugin list to fit content + for (int i = 0; i < ui->espList->header()->count(); ++i) { + ui->espList->header()->setSectionResizeMode(i, QHeaderView::ResizeToContents); + } + ui->espList->header()->setSectionResizeMode(0, QHeaderView::Stretch); + } +} + + +void MainWindow::allowListResize() +{ + // allow resize on mod list + for (int i = 0; i < ui->modList->header()->count(); ++i) { + ui->modList->header()->setSectionResizeMode(i, QHeaderView::Interactive); + } + //ui->modList->header()->setSectionResizeMode(ui->modList->header()->count() - 1, QHeaderView::Stretch); + ui->modList->header()->setStretchLastSection(true); + + + // allow resize on plugin list + for (int i = 0; i < ui->espList->header()->count(); ++i) { + ui->espList->header()->setSectionResizeMode(i, QHeaderView::Interactive); + } + //ui->espList->header()->setSectionResizeMode(ui->espList->header()->count() - 1, QHeaderView::Stretch); + ui->espList->header()->setStretchLastSection(true); +} + +void MainWindow::updateStyle(const QString&) +{ + // no effect? + ensurePolished(); +} + +void MainWindow::resizeEvent(QResizeEvent *event) +{ + m_Tutorial.resize(event->size()); + QMainWindow::resizeEvent(event); +} + + +static QModelIndex mapToModel(const QAbstractItemModel *targetModel, QModelIndex idx) +{ + QModelIndex result = idx; + const QAbstractItemModel *model = idx.model(); + while (model != targetModel) { + if (model == nullptr) { + return QModelIndex(); + } + const QAbstractProxyModel *proxyModel = qobject_cast(model); + if (proxyModel == nullptr) { + return QModelIndex(); + } + result = proxyModel->mapToSource(result); + model = proxyModel->sourceModel(); + } + return result; +} + + +void MainWindow::actionToToolButton(QAction *&sourceAction) +{ + QToolButton *button = new QToolButton(ui->toolBar); + button->setObjectName(sourceAction->objectName()); + button->setIcon(sourceAction->icon()); + button->setText(sourceAction->text()); + button->setPopupMode(QToolButton::InstantPopup); + button->setToolButtonStyle(ui->toolBar->toolButtonStyle()); + button->setToolTip(sourceAction->toolTip()); + button->setShortcut(sourceAction->shortcut()); + QMenu *buttonMenu = new QMenu(sourceAction->text(), button); + button->setMenu(buttonMenu); + QAction *newAction = ui->toolBar->insertWidget(sourceAction, button); + newAction->setObjectName(sourceAction->objectName()); + newAction->setIcon(sourceAction->icon()); + newAction->setText(sourceAction->text()); + newAction->setToolTip(sourceAction->toolTip()); + newAction->setShortcut(sourceAction->shortcut()); + ui->toolBar->removeAction(sourceAction); + sourceAction->deleteLater(); + sourceAction = newAction; +} + +void MainWindow::updateToolBar() +{ + for (QAction *action : ui->toolBar->actions()) { + if (action->objectName().startsWith("custom__")) { + ui->toolBar->removeAction(action); + action->deleteLater(); + } + } + + std::vector::iterator begin, end; + m_OrganizerCore.executablesList()->getExecutables(begin, end); + for (auto iter = begin; iter != end; ++iter) { + if (iter->isShownOnToolbar()) { + QAction *exeAction = new QAction(iconForExecutable(iter->m_BinaryInfo.filePath()), + iter->m_Title, + ui->toolBar); + exeAction->setObjectName(QString("custom__") + iter->m_Title); + if (!connect(exeAction, SIGNAL(triggered()), this, SLOT(startExeAction()))) { + qDebug("failed to connect trigger?"); + } + ui->toolBar->insertAction(m_Sep, exeAction); + } + } +} + + +void MainWindow::scheduleUpdateButton() +{ + if (!m_UpdateProblemsTimer.isActive()) { + m_UpdateProblemsTimer.start(1000); + } +} + + +void MainWindow::updateProblemsButton() +{ + size_t numProblems = checkForProblems(); + if (numProblems > 0) { + ui->actionNotifications->setEnabled(true); + ui->actionNotifications->setIconText(tr("Notifications")); + ui->actionNotifications->setToolTip(tr("There are notifications to read")); + + QPixmap mergedIcon = QPixmap(":/MO/gui/warning").scaled(64, 64); + { + QPainter painter(&mergedIcon); + std::string badgeName = std::string(":/MO/gui/badge_") + (numProblems < 10 ? std::to_string(static_cast(numProblems)) : "more"); + painter.drawPixmap(32, 32, 32, 32, QPixmap(badgeName.c_str())); + } + ui->actionNotifications->setIcon(QIcon(mergedIcon)); + } else { + ui->actionNotifications->setEnabled(false); + ui->actionNotifications->setIconText(tr("No Notifications")); + ui->actionNotifications->setToolTip(tr("There are no notifications")); + ui->actionNotifications->setIcon(QIcon(":/MO/gui/warning")); + } +} + + +bool MainWindow::errorReported(QString &logFile) +{ + QDir dir(qApp->property("dataPath").toString() + "/" + QString::fromStdWString(AppConfig::logPath())); + QFileInfoList files = dir.entryInfoList(QStringList("ModOrganizer_??_??_??_??_??.log"), + QDir::Files, QDir::Name | QDir::Reversed); + + if (files.count() > 0) { + logFile = files.at(0).absoluteFilePath(); + QFile file(logFile); + if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { + char buffer[1024]; + int line = 0; + while (!file.atEnd()) { + file.readLine(buffer, 1024); + if (strncmp(buffer, "ERROR", 5) == 0) { + return true; + } + + // prevent this function from taking forever + if (line++ >= 50000) { + break; + } + } + } + } + + return false; +} + + +size_t MainWindow::checkForProblems() +{ + size_t numProblems = 0; + for (IPluginDiagnose *diagnose : m_PluginContainer.plugins()) { + numProblems += diagnose->activeProblems().size(); + } + return numProblems; +} + +void MainWindow::about() +{ + AboutDialog dialog(m_OrganizerCore.getVersion().displayString(3), this); + connect(&dialog, SIGNAL(linkClicked(QString)), this, SLOT(linkClicked(QString))); + dialog.exec(); +} + + +void MainWindow::createEndorseWidget() +{ + QToolButton *toolBtn = qobject_cast(ui->toolBar->widgetForAction(ui->actionEndorseMO)); + QMenu *buttonMenu = toolBtn->menu(); + if (buttonMenu == nullptr) { + return; + } + buttonMenu->clear(); + + QAction *endorseAction = new QAction(tr("Endorse"), buttonMenu); + connect(endorseAction, SIGNAL(triggered()), this, SLOT(on_actionEndorseMO_triggered())); + buttonMenu->addAction(endorseAction); + + QAction *wontEndorseAction = new QAction(tr("Won't Endorse"), buttonMenu); + connect(wontEndorseAction, SIGNAL(triggered()), this, SLOT(wontEndorse())); + buttonMenu->addAction(wontEndorseAction); +} + + +void MainWindow::createHelpWidget() +{ + QToolButton *toolBtn = qobject_cast(ui->toolBar->widgetForAction(ui->actionHelp)); + QMenu *buttonMenu = toolBtn->menu(); + if (buttonMenu == nullptr) { + return; + } + buttonMenu->clear(); + + QAction *helpAction = new QAction(tr("Help on UI"), buttonMenu); + connect(helpAction, SIGNAL(triggered()), this, SLOT(helpTriggered())); + buttonMenu->addAction(helpAction); + + QAction *wikiAction = new QAction(tr("Documentation"), buttonMenu); + connect(wikiAction, SIGNAL(triggered()), this, SLOT(wikiTriggered())); + buttonMenu->addAction(wikiAction); + + QAction *discordAction = new QAction(tr("Chat on Discord"), buttonMenu); + connect(discordAction, SIGNAL(triggered()), this, SLOT(discordTriggered())); + buttonMenu->addAction(discordAction); + + QAction *issueAction = new QAction(tr("Report Issue"), buttonMenu); + connect(issueAction, SIGNAL(triggered()), this, SLOT(issueTriggered())); + buttonMenu->addAction(issueAction); + + QMenu *tutorialMenu = new QMenu(tr("Tutorials"), buttonMenu); + + typedef std::vector > ActionList; + + ActionList tutorials; + + QDirIterator dirIter(QApplication::applicationDirPath() + "/tutorials", QStringList("*.js"), QDir::Files); + while (dirIter.hasNext()) { + dirIter.next(); + QString fileName = dirIter.fileName(); + + QFile file(dirIter.filePath()); + if (!file.open(QIODevice::ReadOnly)) { + qCritical() << "Failed to open " << fileName; + continue; + } + QString firstLine = QString::fromUtf8(file.readLine()); + if (firstLine.startsWith("//TL")) { + QStringList params = firstLine.mid(4).trimmed().split('#'); + if (params.size() != 2) { + qCritical() << "invalid header line for tutorial " << fileName << " expected 2 parameters"; + continue; + } + QAction *tutAction = new QAction(params.at(0), tutorialMenu); + tutAction->setData(fileName); + tutorials.push_back(std::make_pair(params.at(1).toInt(), tutAction)); + } + } + + std::sort(tutorials.begin(), tutorials.end(), + [] (const ActionList::value_type &LHS, const ActionList::value_type &RHS) { + return LHS.first < RHS.first; } ); + + for (auto iter = tutorials.begin(); iter != tutorials.end(); ++iter) { + connect(iter->second, SIGNAL(triggered()), this, SLOT(tutorialTriggered())); + tutorialMenu->addAction(iter->second); + } + + buttonMenu->addMenu(tutorialMenu); + buttonMenu->addAction(tr("About"), this, SLOT(about())); + buttonMenu->addAction(tr("About Qt"), qApp, SLOT(aboutQt())); +} + +void MainWindow::modFilterActive(bool filterActive) +{ + ui->clearFiltersButton->setVisible(filterActive); + if (filterActive) { +// m_OrganizerCore.modList()->setOverwriteMarkers(std::set(), std::set()); + ui->modList->setStyleSheet("QTreeView { border: 2px ridge #f00; }"); + ui->activeModsCounter->setStyleSheet("QLCDNumber { border: 2px ridge #f00; }"); + } else if (ui->groupCombo->currentIndex() != 0) { + ui->modList->setStyleSheet("QTreeView { border: 2px ridge #337733; }"); + ui->activeModsCounter->setStyleSheet(""); + } else { + ui->modList->setStyleSheet(""); + ui->activeModsCounter->setStyleSheet(""); + } +} + +void MainWindow::espFilterChanged(const QString &filter) +{ + if (!filter.isEmpty()) { + ui->espList->setStyleSheet("QTreeView { border: 2px ridge #f00; }"); + ui->activePluginsCounter->setStyleSheet("QLCDNumber { border: 2px ridge #f00; }"); + } else { + ui->espList->setStyleSheet(""); + ui->activePluginsCounter->setStyleSheet(""); + } + updatePluginCount(); +} + +void MainWindow::downloadFilterChanged(const QString &filter) +{ + if (!filter.isEmpty()) { + ui->downloadView->setStyleSheet("QTreeView { border: 2px ridge #f00; }"); + } else { + ui->downloadView->setStyleSheet(""); + } +} + +void MainWindow::expandModList(const QModelIndex &index) +{ + QAbstractItemModel *model = ui->modList->model(); +#pragma message("why is this so complicated? mapping the index doesn't work, probably a bug in QtGroupingProxy?") + for (int i = 0; i < model->rowCount(); ++i) { + QModelIndex targetIdx = model->index(i, 0); + if (model->data(targetIdx).toString() == index.data().toString()) { + ui->modList->expand(targetIdx); + break; + } + } +} + + +bool MainWindow::addProfile() +{ + QComboBox *profileBox = findChild("profileBox"); + bool okClicked = false; + + QString name = QInputDialog::getText(this, tr("Name"), + tr("Please enter a name for the new profile"), + QLineEdit::Normal, QString(), &okClicked); + if (okClicked && (name.size() > 0)) { + try { + profileBox->addItem(name); + profileBox->setCurrentIndex(profileBox->count() - 1); + return true; + } catch (const std::exception& e) { + reportError(tr("failed to create profile: %1").arg(e.what())); + return false; + } + } else { + return false; + } +} + +void MainWindow::hookUpWindowTutorials() +{ + QDirIterator dirIter(QApplication::applicationDirPath() + "/tutorials", QStringList("*.js"), QDir::Files); + while (dirIter.hasNext()) { + dirIter.next(); + QString fileName = dirIter.fileName(); + QFile file(dirIter.filePath()); + if (!file.open(QIODevice::ReadOnly)) { + qCritical() << "Failed to open " << fileName; + continue; + } + QString firstLine = QString::fromUtf8(file.readLine()); + if (firstLine.startsWith("//WIN")) { + QString windowName = firstLine.mid(6).trimmed(); + if (!m_OrganizerCore.settings().directInterface().value("CompletedWindowTutorials/" + windowName, false).toBool()) { + TutorialManager::instance().activateTutorial(windowName, fileName); + } + } + } +} + +void MainWindow::showEvent(QShowEvent *event) +{ + refreshFilters(); + + QMainWindow::showEvent(event); + + if (!m_WasVisible) { + // only the first time the window becomes visible + m_Tutorial.registerControl(); + + hookUpWindowTutorials(); + + if (m_OrganizerCore.settings().directInterface().value("first_start", true).toBool()) { + QString firstStepsTutorial = ToQString(AppConfig::firstStepsTutorial()); + if (TutorialManager::instance().hasTutorial(firstStepsTutorial)) { + if (QMessageBox::question(this, tr("Show tutorial?"), + tr("You are starting Mod Organizer for the first time. " + "Do you want to show a tutorial of its basic features? If you choose " + "no you can always start the tutorial from the \"Help\"-menu."), + QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { + TutorialManager::instance().activateTutorial("MainWindow", firstStepsTutorial); + } + } else { + qCritical() << firstStepsTutorial << " missing"; + QPoint pos = ui->toolBar->mapToGlobal(QPoint()); + pos.rx() += ui->toolBar->width() / 2; + pos.ry() += ui->toolBar->height(); + QWhatsThis::showText(pos, + QObject::tr("Please use \"Help\" from the toolbar to get usage instructions to all elements")); + } + + m_OrganizerCore.settings().directInterface().setValue("first_start", false); + } + + // this has no visible impact when called before the ui is visible + int grouping = m_OrganizerCore.settings().directInterface().value("group_state").toInt(); + ui->groupCombo->setCurrentIndex(grouping); + + allowListResize(); + + m_OrganizerCore.settings().registerAsNXMHandler(false); + m_WasVisible = true; + updateProblemsButton(); + } +} + + +void MainWindow::closeEvent(QCloseEvent* event) +{ + m_closing = true; + + if (m_OrganizerCore.downloadManager()->downloadsInProgressNoPause()) { + if (QMessageBox::question(this, tr("Downloads in progress"), + tr("There are still downloads in progress, do you really want to quit?"), + QMessageBox::Yes | QMessageBox::Cancel) == QMessageBox::Cancel) { + event->ignore(); + return; + } else { + m_OrganizerCore.downloadManager()->pauseAll(); + } + } + + std::vector hiddenList; + hiddenList.push_back(QFileInfo(QCoreApplication::applicationFilePath()).fileName()); + HANDLE injected_process_still_running = m_OrganizerCore.findAndOpenAUSVFSProcess(hiddenList, GetCurrentProcessId()); + if (injected_process_still_running != INVALID_HANDLE_VALUE) + { + m_OrganizerCore.waitForApplication(injected_process_still_running); + if (!m_closing) { // if operation cancelled + event->ignore(); + return; + } + } + + setCursor(Qt::WaitCursor); +} + +void MainWindow::cleanup() +{ + if (ui->logList->model() != nullptr) { + disconnect(ui->logList->model(), nullptr, nullptr, nullptr); + ui->logList->setModel(nullptr); + } + + QWebEngineProfile::defaultProfile()->clearAllVisitedLinks(); + m_IntegratedBrowser.close(); + m_SaveMetaTimer.stop(); + m_MetaSave.waitForFinished(); +} + + +void MainWindow::setBrowserGeometry(const QByteArray &geometry) +{ + m_IntegratedBrowser.restoreGeometry(geometry); +} + +void MainWindow::displaySaveGameInfo(QListWidgetItem *newItem) +{ + QString const &save = newItem->data(Qt::UserRole).toString(); + if (m_CurrentSaveView == nullptr) { + IPluginGame const *game = m_OrganizerCore.managedGame(); + SaveGameInfo const *info = game->feature(); + if (info != nullptr) { + m_CurrentSaveView = info->getSaveGameWidget(this); + } + if (m_CurrentSaveView == nullptr) { + return; + } + } + m_CurrentSaveView->setSave(save); + + QRect screenRect = QApplication::desktop()->availableGeometry(m_CurrentSaveView); + + QPoint pos = QCursor::pos(); + if (pos.x() + m_CurrentSaveView->width() > screenRect.right()) { + pos.rx() -= (m_CurrentSaveView->width() + 2); + } else { + pos.rx() += 5; + } + + if (pos.y() + m_CurrentSaveView->height() > screenRect.bottom()) { + pos.ry() -= (m_CurrentSaveView->height() + 10); + } else { + pos.ry() += 20; + } + m_CurrentSaveView->move(pos); + + m_CurrentSaveView->show(); + m_CurrentSaveView->setProperty("displayItem", qVariantFromValue(static_cast(newItem))); + + ui->savegameList->activateWindow(); +} + + +void MainWindow::saveSelectionChanged(QListWidgetItem *newItem) +{ + if (newItem == nullptr) { + hideSaveGameInfo(); + } else if (m_CurrentSaveView == nullptr || newItem != m_CurrentSaveView->property("displayItem").value()) { + displaySaveGameInfo(newItem); + } +} + + +void MainWindow::hideSaveGameInfo() +{ + if (m_CurrentSaveView != nullptr) { + m_CurrentSaveView->deleteLater(); + m_CurrentSaveView = nullptr; + } +} + +bool MainWindow::eventFilter(QObject *object, QEvent *event) +{ + if ((object == ui->savegameList) && + ((event->type() == QEvent::Leave) || (event->type() == QEvent::WindowDeactivate))) { + hideSaveGameInfo(); + } + return false; +} + + +void MainWindow::toolPluginInvoke() +{ + QAction *triggeredAction = qobject_cast(sender()); + IPluginTool *plugin = qobject_cast(triggeredAction->data().value()); + if (plugin != nullptr) { + try { + plugin->display(); + } catch (const std::exception &e) { + reportError(tr("Plugin \"%1\" failed: %2").arg(plugin->name()).arg(e.what())); + } catch (...) { + reportError(tr("Plugin \"%1\" failed").arg(plugin->name())); + } + } +} + +void MainWindow::modPagePluginInvoke() +{ + QAction *triggeredAction = qobject_cast(sender()); + IPluginModPage *plugin = qobject_cast(triggeredAction->data().value()); + if (plugin != nullptr) { + if (plugin->useIntegratedBrowser()) { + m_IntegratedBrowser.setWindowTitle(plugin->displayName()); + m_IntegratedBrowser.openUrl(plugin->pageURL()); + } else { + QDesktopServices::openUrl(QUrl(plugin->pageURL())); + } + } +} + +void MainWindow::registerPluginTool(IPluginTool *tool, QString name, QMenu *menu) +{ + if (name.isEmpty()) + name = tool->displayName(); + + QAction *action = new QAction(tool->icon(), name, ui->toolBar); + action->setToolTip(tool->tooltip()); + tool->setParentWidget(this); + action->setData(qVariantFromValue((QObject*)tool)); + connect(action, SIGNAL(triggered()), this, SLOT(toolPluginInvoke()), Qt::QueuedConnection); + + if (menu == nullptr) { + QToolButton *toolBtn = qobject_cast(ui->toolBar->widgetForAction(ui->actionTool)); + toolBtn->menu()->addAction(action); + } else { + menu->addAction(action); + } +} + +void MainWindow::registerPluginTools(std::vector toolPlugins) +{ + // Sort the plugins by display name + std::sort(toolPlugins.begin(), toolPlugins.end(), + [](IPluginTool *left, IPluginTool *right) { + return left->displayName().toLower() < right->displayName().toLower(); + } + ); + + // Group the plugins into submenus + QMap>> submenuMap; + for (auto toolPlugin : toolPlugins) { + QStringList toolName = toolPlugin->displayName().split("/"); + QString submenu = toolName[0]; + toolName.pop_front(); + submenuMap[submenu].append(QPair(toolName.join("/"), toolPlugin)); + } + + // Start registering plugins + for (auto submenuKey : submenuMap.keys()) { + if (submenuMap[submenuKey].length() > 1) { + QMenu *submenu = new QMenu(submenuKey, this); + for (auto info : submenuMap[submenuKey]) { + registerPluginTool(info.second, info.first, submenu); + } + QToolButton *toolBtn = qobject_cast(ui->toolBar->widgetForAction(ui->actionTool)); + toolBtn->menu()->addMenu(submenu); + } + else { + registerPluginTool(submenuMap[submenuKey].front().second); + } + } +} + +void MainWindow::registerModPage(IPluginModPage *modPage) +{ + // turn the browser action into a drop-down menu if necessary + if (ui->actionNexus->menu() == nullptr) { + QAction *nexusAction = ui->actionNexus; + // TODO: use a different icon for nexus! + ui->actionNexus = new QAction(nexusAction->icon(), tr("Browse Mod Page"), ui->toolBar); + ui->toolBar->insertAction(nexusAction, ui->actionNexus); + ui->toolBar->removeAction(nexusAction); + actionToToolButton(ui->actionNexus); + + QToolButton *browserBtn = qobject_cast(ui->toolBar->widgetForAction(ui->actionNexus)); + browserBtn->menu()->addAction(nexusAction); + } + + QAction *action = new QAction(modPage->icon(), modPage->displayName(), ui->toolBar); + modPage->setParentWidget(this); + action->setData(qVariantFromValue(reinterpret_cast(modPage))); + + connect(action, SIGNAL(triggered()), this, SLOT(modPagePluginInvoke()), Qt::QueuedConnection); + QToolButton *toolBtn = qobject_cast(ui->toolBar->widgetForAction(ui->actionNexus)); + toolBtn->menu()->addAction(action); +} + + +void MainWindow::startExeAction() +{ + QAction *action = qobject_cast(sender()); + if (action != nullptr) { + const Executable &selectedExecutable(m_OrganizerCore.executablesList()->find(action->text())); + QString customOverwrite = m_OrganizerCore.currentProfile()->setting("custom_overwrites", selectedExecutable.m_Title).toString(); + auto forcedLibraries = m_OrganizerCore.currentProfile()->determineForcedLibraries(selectedExecutable.m_Title); + if (!m_OrganizerCore.currentProfile()->forcedLibrariesEnabled(selectedExecutable.m_Title)) { + forcedLibraries.clear(); + } + m_OrganizerCore.spawnBinary( + selectedExecutable.m_BinaryInfo, selectedExecutable.m_Arguments, + selectedExecutable.m_WorkingDirectory.length() != 0 + ? selectedExecutable.m_WorkingDirectory + : selectedExecutable.m_BinaryInfo.absolutePath(), + selectedExecutable.m_SteamAppID, + customOverwrite, + forcedLibraries); + } else { + qCritical("not an action?"); + } +} + + +void MainWindow::setExecutableIndex(int index) +{ + QComboBox *executableBox = findChild("executablesListBox"); + + if ((index != 0) && (executableBox->count() > index)) { + executableBox->setCurrentIndex(index); + } else { + executableBox->setCurrentIndex(1); + } +} + +void MainWindow::activateSelectedProfile() +{ + m_OrganizerCore.setCurrentProfile(ui->profileBox->currentText()); + + m_ModListSortProxy->setProfile(m_OrganizerCore.currentProfile()); + + refreshSaveList(); + m_OrganizerCore.refreshModList(); + updateModCount(); + updatePluginCount(); +} + +void MainWindow::on_profileBox_currentIndexChanged(int index) +{ + if (ui->profileBox->isEnabled()) { + int previousIndex = m_OldProfileIndex; + m_OldProfileIndex = index; + + if ((previousIndex != -1) && + (m_OrganizerCore.currentProfile() != nullptr) && + m_OrganizerCore.currentProfile()->exists()) { + m_OrganizerCore.saveCurrentLists(); + } + + // ensure the new index is valid + if (index < 0 || index >= ui->profileBox->count()) { + qDebug("invalid profile index, using last profile"); + ui->profileBox->setCurrentIndex(ui->profileBox->count() - 1); + } + + if (ui->profileBox->currentIndex() == 0) { + ui->profileBox->setCurrentIndex(previousIndex); + ProfilesDialog(ui->profileBox->currentText(), m_OrganizerCore.managedGame(), this).exec(); + while (!refreshProfiles()) { + ProfilesDialog(ui->profileBox->currentText(), m_OrganizerCore.managedGame(), this).exec(); + } + } else { + activateSelectedProfile(); + } + + LocalSavegames *saveGames = m_OrganizerCore.managedGame()->feature(); + if (saveGames != nullptr) { + if (saveGames->prepareProfile(m_OrganizerCore.currentProfile())) + refreshSaveList(); + } + + BSAInvalidation *invalidation = m_OrganizerCore.managedGame()->feature(); + if (invalidation != nullptr) { + if (invalidation->prepareProfile(m_OrganizerCore.currentProfile())) + QTimer::singleShot(5, &m_OrganizerCore, SLOT(profileRefresh())); + } + } +} + +void MainWindow::updateTo(QTreeWidgetItem *subTree, const std::wstring &directorySoFar, const DirectoryEntry &directoryEntry, bool conflictsOnly, QIcon *fileIcon, QIcon *folderIcon) +{ + bool isDirectory = true; + //QIcon folderIcon = (new QFileIconProvider())->icon(QFileIconProvider::Folder); + //QIcon fileIcon = (new QFileIconProvider())->icon(QFileIconProvider::File); + + std::wostringstream temp; + temp << directorySoFar << "\\" << directoryEntry.getName(); + { + std::vector::const_iterator current, end; + directoryEntry.getSubDirectories(current, end); + for (; current != end; ++current) { + QString pathName = ToQString((*current)->getName()); + QStringList columns(pathName); + columns.append(""); + if (!(*current)->isEmpty()) { + QTreeWidgetItem *directoryChild = new QTreeWidgetItem(columns); + directoryChild->setData(0, Qt::DecorationRole, *folderIcon); + directoryChild->setData(0, Qt::UserRole + 3, isDirectory); + + if (conflictsOnly || !m_showArchiveData) { + updateTo(directoryChild, temp.str(), **current, conflictsOnly, fileIcon, folderIcon); + if (directoryChild->childCount() != 0) { + subTree->addChild(directoryChild); + } + else { + delete directoryChild; + } + } + else { + QTreeWidgetItem *onDemandLoad = new QTreeWidgetItem(QStringList()); + onDemandLoad->setData(0, Qt::UserRole + 0, "__loaded_on_demand__"); + onDemandLoad->setData(0, Qt::UserRole + 1, ToQString(temp.str())); + onDemandLoad->setData(0, Qt::UserRole + 2, conflictsOnly); + directoryChild->addChild(onDemandLoad); + subTree->addChild(directoryChild); + } + } + else { + QTreeWidgetItem *directoryChild = new QTreeWidgetItem(columns); + directoryChild->setData(0, Qt::DecorationRole, *folderIcon); + directoryChild->setData(0, Qt::UserRole + 3, isDirectory); + subTree->addChild(directoryChild); + } + } + } + + + isDirectory = false; + { + for (const FileEntry::Ptr current : directoryEntry.getFiles()) { + if (conflictsOnly && (current->getAlternatives().size() == 0)) { + continue; + } + + bool isArchive = false; + int originID = current->getOrigin(isArchive); + if (!m_showArchiveData && isArchive) { + continue; + } + + QString fileName = ToQString(current->getName()); + QStringList columns(fileName); + FilesOrigin origin = m_OrganizerCore.directoryStructure()->getOriginByID(originID); + QString source("data"); + unsigned int modIndex = ModInfo::getIndex(ToQString(origin.getName())); + if (modIndex != UINT_MAX) { + ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); + source = modInfo->name(); + } + + std::pair archive = current->getArchive(); + if (archive.first.length() != 0) { + source.append(" (").append(ToQString(archive.first)).append(")"); + } + columns.append(source); + QTreeWidgetItem *fileChild = new QTreeWidgetItem(columns); + if (isArchive) { + QFont font = fileChild->font(0); + font.setItalic(true); + fileChild->setFont(0, font); + fileChild->setFont(1, font); + } else if (fileName.endsWith(ModInfo::s_HiddenExt)) { + QFont font = fileChild->font(0); + font.setStrikeOut(true); + fileChild->setFont(0, font); + fileChild->setFont(1, font); + } + fileChild->setData(0, Qt::UserRole, ToQString(current->getFullPath())); + fileChild->setData(0, Qt::DecorationRole, *fileIcon); + fileChild->setData(0, Qt::UserRole + 3, isDirectory); + fileChild->setData(0, Qt::UserRole + 1, isArchive); + fileChild->setData(1, Qt::UserRole, source); + fileChild->setData(1, Qt::UserRole + 1, originID); + + std::vector>> alternatives = current->getAlternatives(); + + if (!alternatives.empty()) { + std::wostringstream altString; + altString << ToWString(tr("Also in:
    ")); + for (std::vector>>::iterator altIter = alternatives.begin(); + altIter != alternatives.end(); ++altIter) { + if (altIter != alternatives.begin()) { + altString << " , "; + } + altString << "" << m_OrganizerCore.directoryStructure()->getOriginByID(altIter->first).getName() << ""; + } + fileChild->setToolTip(1, QString("%1").arg(ToQString(altString.str()))); + fileChild->setForeground(1, QBrush(Qt::red)); + } else { + fileChild->setToolTip(1, tr("No conflict")); + } + subTree->addChild(fileChild); + } + } + + + //subTree->sortChildren(0, Qt::AscendingOrder); +} + +void MainWindow::delayedRemove() +{ + for (QTreeWidgetItem *item : m_RemoveWidget) { + item->removeChild(item->child(0)); + } + m_RemoveWidget.clear(); +} + +void MainWindow::expandDataTreeItem(QTreeWidgetItem *item) +{ + if ((item->childCount() == 1) && (item->child(0)->data(0, Qt::UserRole).toString() == "__loaded_on_demand__")) { + // read the data we need from the sub-item, then dispose of it + QTreeWidgetItem *onDemandDataItem = item->child(0); + std::wstring path = ToWString(onDemandDataItem->data(0, Qt::UserRole + 1).toString()); + bool conflictsOnly = onDemandDataItem->data(0, Qt::UserRole + 2).toBool(); + + std::wstring virtualPath = (path + L"\\").substr(6) + ToWString(item->text(0)); + DirectoryEntry *dir = m_OrganizerCore.directoryStructure()->findSubDirectoryRecursive(virtualPath); + if (dir != nullptr) { + QIcon folderIcon = (new QFileIconProvider())->icon(QFileIconProvider::Folder); + QIcon fileIcon = (new QFileIconProvider())->icon(QFileIconProvider::File); + updateTo(item, path, *dir, conflictsOnly, &fileIcon, &folderIcon); + } else { + qWarning("failed to update view of %ls", path.c_str()); + } + m_RemoveWidget.push_back(item); + QTimer::singleShot(5, this, SLOT(delayedRemove())); + } +} + + +bool MainWindow::refreshProfiles(bool selectProfile) +{ + QComboBox* profileBox = findChild("profileBox"); + + QString currentProfileName = profileBox->currentText(); + + profileBox->blockSignals(true); + profileBox->clear(); + profileBox->addItem(QObject::tr("")); + + QDir profilesDir(Settings::instance().getProfileDirectory()); + profilesDir.setFilter(QDir::AllDirs | QDir::NoDotAndDotDot); + + QDirIterator profileIter(profilesDir); + + while (profileIter.hasNext()) { + profileIter.next(); + try { + profileBox->addItem(profileIter.fileName()); + } catch (const std::runtime_error& error) { + reportError(QObject::tr("failed to parse profile %1: %2").arg(profileIter.fileName()).arg(error.what())); + } + } + + // now select one of the profiles, preferably the one that was selected before + profileBox->blockSignals(false); + + if (selectProfile) { + if (profileBox->count() > 1) { + profileBox->setCurrentText(currentProfileName); + if (profileBox->currentIndex() == 0) { + profileBox->setCurrentIndex(1); + } + } + } + return profileBox->count() > 1; +} + + +void MainWindow::refreshExecutablesList() +{ + QComboBox* executablesList = findChild("executablesListBox"); + executablesList->setEnabled(false); + executablesList->clear(); + executablesList->addItem(tr("")); + + QAbstractItemModel *model = executablesList->model(); + + std::vector::const_iterator current, end; + m_OrganizerCore.executablesList()->getExecutables(current, end); + for(int i = 0; current != end; ++current, ++i) { + QIcon icon = iconForExecutable(current->m_BinaryInfo.filePath()); + executablesList->addItem(icon, current->m_Title); + model->setData(model->index(i, 0), QSize(0, executablesList->iconSize().height() + 4), Qt::SizeHintRole); + } + + setExecutableIndex(1); + executablesList->setEnabled(true); +} + + +void MainWindow::refreshDataTree() +{ + QCheckBox *conflictsBox = findChild("conflictsCheckBox"); + QTreeWidget *tree = findChild("dataTree"); + QIcon folderIcon = (new QFileIconProvider())->icon(QFileIconProvider::Folder); + QIcon fileIcon = (new QFileIconProvider())->icon(QFileIconProvider::File); + tree->clear(); + QStringList columns("data"); + columns.append(""); + QTreeWidgetItem *subTree = new QTreeWidgetItem(columns); + subTree->setData(0, Qt::DecorationRole, (new QFileIconProvider())->icon(QFileIconProvider::Folder)); + updateTo(subTree, L"", *m_OrganizerCore.directoryStructure(), conflictsBox->isChecked(), &fileIcon, &folderIcon); + tree->insertTopLevelItem(0, subTree); + subTree->setExpanded(true); +} + +void MainWindow::refreshDataTreeKeepExpandedNodes() +{ + QCheckBox *conflictsBox = findChild("conflictsCheckBox"); + QTreeWidget *tree = findChild("dataTree"); + QIcon folderIcon = (new QFileIconProvider())->icon(QFileIconProvider::Folder); + QIcon fileIcon = (new QFileIconProvider())->icon(QFileIconProvider::File); + QStringList expandedNodes; + QTreeWidgetItemIterator it1(tree, QTreeWidgetItemIterator::NotHidden | QTreeWidgetItemIterator::HasChildren); + while (*it1) { + QTreeWidgetItem *current = (*it1); + if (current->isExpanded() && !(current->text(0)=="data")) { + expandedNodes.append(current->text(0)+"/"+current->parent()->text(0)); + } + ++it1; + } + + tree->clear(); + QStringList columns("data"); + columns.append(""); + QTreeWidgetItem *subTree = new QTreeWidgetItem(columns); + subTree->setData(0, Qt::DecorationRole, (new QFileIconProvider())->icon(QFileIconProvider::Folder)); + updateTo(subTree, L"", *m_OrganizerCore.directoryStructure(), conflictsBox->isChecked(), &fileIcon, &folderIcon); + tree->insertTopLevelItem(0, subTree); + subTree->setExpanded(true); + QTreeWidgetItemIterator it2(tree, QTreeWidgetItemIterator::HasChildren); + while (*it2) { + QTreeWidgetItem *current = (*it2); + if (!(current->text(0)=="data") && expandedNodes.contains(current->text(0)+"/"+current->parent()->text(0))) { + current->setExpanded(true); + } + ++it2; + } +} + + +void MainWindow::refreshSavesIfOpen() +{ + if (ui->tabWidget->currentIndex() == 3) { + refreshSaveList(); + } +} + +QDir MainWindow::currentSavesDir() const +{ + QDir savesDir; + if (m_OrganizerCore.currentProfile()->localSavesEnabled()) { + savesDir.setPath(m_OrganizerCore.currentProfile()->savePath()); + } else { + QString iniPath = m_OrganizerCore.currentProfile()->localSettingsEnabled() + ? m_OrganizerCore.currentProfile()->absolutePath() + : m_OrganizerCore.managedGame()->documentsDirectory().absolutePath(); + iniPath += "/" + m_OrganizerCore.managedGame()->iniFiles()[0]; + + wchar_t path[MAX_PATH]; + ::GetPrivateProfileStringW( + L"General", L"SLocalSavePath", L"Saves", + path, MAX_PATH, + iniPath.toStdWString().c_str() + ); + savesDir.setPath(m_OrganizerCore.managedGame()->documentsDirectory().absoluteFilePath(QString::fromWCharArray(path))); + } + + return savesDir; +} + +void MainWindow::startMonitorSaves() +{ + stopMonitorSaves(); + + QDir savesDir = currentSavesDir(); + + m_SavesWatcher.addPath(savesDir.absolutePath()); +} + +void MainWindow::stopMonitorSaves() +{ + if (m_SavesWatcher.directories().length() > 0) { + m_SavesWatcher.removePaths(m_SavesWatcher.directories()); + } +} + +void MainWindow::refreshSaveList() +{ + ui->savegameList->clear(); + + startMonitorSaves(); // re-starts monitoring + + QStringList filters; + filters << QString("*.") + m_OrganizerCore.managedGame()->savegameExtension(); + + QDir savesDir = currentSavesDir(); + savesDir.setNameFilters(filters); + qDebug("reading save games from %s", qUtf8Printable(savesDir.absolutePath())); + + QFileInfoList files = savesDir.entryInfoList(QDir::Files, QDir::Time); + for (const QFileInfo &file : files) { + QListWidgetItem *item = new QListWidgetItem(file.fileName()); + item->setData(Qt::UserRole, file.absoluteFilePath()); + ui->savegameList->addItem(item); + } +} + + +static bool BySortValue(const std::pair &LHS, const std::pair &RHS) +{ + return LHS.first < RHS.first; +} + +template +static QStringList toStringList(InputIterator current, InputIterator end) +{ + QStringList result; + for (; current != end; ++current) { + result.append(*current); + } + return result; +} + +void MainWindow::updateBSAList(const QStringList &defaultArchives, const QStringList &activeArchives) +{ + m_DefaultArchives = defaultArchives; + ui->bsaList->clear(); + ui->bsaList->header()->setSectionResizeMode(QHeaderView::ResizeToContents); + std::vector> items; + + BSAInvalidation * invalidation = m_OrganizerCore.managedGame()->feature(); + std::vector files = m_OrganizerCore.directoryStructure()->getFiles(); + + QStringList plugins = m_OrganizerCore.findFiles("", [](const QString &fileName) -> bool { + return fileName.endsWith(".esp", Qt::CaseInsensitive) + || fileName.endsWith(".esm", Qt::CaseInsensitive) + || fileName.endsWith(".esl", Qt::CaseInsensitive); + }); + + auto hasAssociatedPlugin = [&](const QString &bsaName) -> bool { + for (const QString &pluginName : plugins) { + QFileInfo pluginInfo(pluginName); + if (bsaName.startsWith(QFileInfo(pluginName).baseName(), Qt::CaseInsensitive) + && (m_OrganizerCore.pluginList()->state(pluginInfo.fileName()) == IPluginList::STATE_ACTIVE)) { + return true; + } + } + return false; + }; + + for (FileEntry::Ptr current : files) { + QFileInfo fileInfo(ToQString(current->getName().c_str())); + + if (fileInfo.suffix().toLower() == "bsa" || fileInfo.suffix().toLower() == "ba2") { + int index = activeArchives.indexOf(fileInfo.fileName()); + if (index == -1) { + index = 0xFFFF; + } + else { + index += 2; + } + + if ((invalidation != nullptr) && invalidation->isInvalidationBSA(fileInfo.fileName())) { + index = 1; + } + + int originId = current->getOrigin(); + FilesOrigin & origin = m_OrganizerCore.directoryStructure()->getOriginByID(originId); + + QTreeWidgetItem * newItem = new QTreeWidgetItem(QStringList() + << fileInfo.fileName() + << ToQString(origin.getName())); + newItem->setData(0, Qt::UserRole, index); + newItem->setData(1, Qt::UserRole, originId); + newItem->setFlags(newItem->flags() & ~(Qt::ItemIsDropEnabled | Qt::ItemIsUserCheckable)); + newItem->setCheckState(0, (index != -1) ? Qt::Checked : Qt::Unchecked); + newItem->setData(0, Qt::UserRole, false); + if (m_OrganizerCore.settings().forceEnableCoreFiles() + && defaultArchives.contains(fileInfo.fileName())) { + newItem->setCheckState(0, Qt::Checked); + newItem->setDisabled(true); + newItem->setData(0, Qt::UserRole, true); + } else if (fileInfo.fileName().compare("update.bsa", Qt::CaseInsensitive) == 0) { + newItem->setCheckState(0, Qt::Checked); + newItem->setDisabled(true); + } else if (hasAssociatedPlugin(fileInfo.fileName())) { + newItem->setCheckState(0, Qt::Checked); + newItem->setDisabled(true); + } else { + newItem->setCheckState(0, Qt::Unchecked); + newItem->setDisabled(true); + } + if (index < 0) index = 0; + + UINT32 sortValue = ((origin.getPriority() & 0xFFFF) << 16) | (index & 0xFFFF); + items.push_back(std::make_pair(sortValue, newItem)); + } + } + std::sort(items.begin(), items.end(), BySortValue); + + for (auto iter = items.begin(); iter != items.end(); ++iter) { + int originID = iter->second->data(1, Qt::UserRole).toInt(); + + FilesOrigin origin = m_OrganizerCore.directoryStructure()->getOriginByID(originID); + QString modName("data"); + unsigned int modIndex = ModInfo::getIndex(ToQString(origin.getName())); + if (modIndex != UINT_MAX) { + ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); + modName = modInfo->name(); + } + QList items = ui->bsaList->findItems(modName, Qt::MatchFixedString); + QTreeWidgetItem * subItem = nullptr; + if (items.length() > 0) { + subItem = items.at(0); + } + else { + subItem = new QTreeWidgetItem(QStringList(modName)); + subItem->setFlags(subItem->flags() & ~Qt::ItemIsDragEnabled); + ui->bsaList->addTopLevelItem(subItem); + } + subItem->addChild(iter->second); + subItem->setExpanded(true); + } + checkBSAList(); +} + +void MainWindow::checkBSAList() +{ + DataArchives * archives = m_OrganizerCore.managedGame()->feature(); + + if (archives != nullptr) { + ui->bsaList->blockSignals(true); + ON_BLOCK_EXIT([&]() { ui->bsaList->blockSignals(false); }); + + QStringList defaultArchives = archives->archives(m_OrganizerCore.currentProfile()); + + bool warning = false; + + for (int i = 0; i < ui->bsaList->topLevelItemCount(); ++i) { + bool modWarning = false; + QTreeWidgetItem * tlItem = ui->bsaList->topLevelItem(i); + for (int j = 0; j < tlItem->childCount(); ++j) { + QTreeWidgetItem * item = tlItem->child(j); + QString filename = item->text(0); + item->setIcon(0, QIcon()); + item->setToolTip(0, QString()); + + if (item->checkState(0) == Qt::Unchecked) { + if (defaultArchives.contains(filename)) { + item->setIcon(0, QIcon(":/MO/gui/warning")); + item->setToolTip(0, tr("This bsa is enabled in the ini file so it may be required!")); + modWarning = true; + } + } + } + if (modWarning) { + ui->bsaList->expandItem(ui->bsaList->topLevelItem(i)); + warning = true; + } + } + if (warning) { + ui->tabWidget->setTabIcon(1, QIcon(":/MO/gui/warning")); + } else { + ui->tabWidget->setTabIcon(1, QIcon()); + } + } +} + +void MainWindow::saveModMetas() +{ + if (m_MetaSave.isFinished()) { + m_MetaSave = QtConcurrent::run([this]() { + for (unsigned int i = 0; i < ModInfo::getNumMods(); ++i) { + ModInfo::Ptr modInfo = ModInfo::getByIndex(i); + modInfo->saveMeta(); + } + }); + } +} + +void MainWindow::fixCategories() +{ + for (unsigned int i = 0; i < ModInfo::getNumMods(); ++i) { + ModInfo::Ptr modInfo = ModInfo::getByIndex(i); + std::set categories = modInfo->getCategories(); + for (std::set::iterator iter = categories.begin(); + iter != categories.end(); ++iter) { + if (!m_CategoryFactory.categoryExists(*iter)) { + modInfo->setCategory(*iter, false); + } + } + } +} + + +void MainWindow::setupNetworkProxy(bool activate) +{ + QNetworkProxyFactory::setUseSystemConfiguration(activate); +/* QNetworkProxyQuery query(QUrl("http://www.google.com"), QNetworkProxyQuery::UrlRequest); + query.setProtocolTag("http"); + QList proxies = QNetworkProxyFactory::systemProxyForQuery(query); + if ((proxies.size() > 0) && (proxies.at(0).type() != QNetworkProxy::NoProxy)) { + qDebug("Using proxy: %s", qUtf8Printable(proxies.at(0).hostName())); + QNetworkProxy::setApplicationProxy(proxies[0]); + } else { + qDebug("Not using proxy"); + }*/ +} + + +void MainWindow::activateProxy(bool activate) +{ + QProgressDialog busyDialog(tr("Activating Network Proxy"), QString(), 0, 0, parentWidget()); + busyDialog.setWindowFlags(busyDialog.windowFlags() & ~Qt::WindowContextHelpButtonHint); + busyDialog.setWindowModality(Qt::WindowModal); + busyDialog.show(); + QFuture future = QtConcurrent::run(MainWindow::setupNetworkProxy, activate); + while (!future.isFinished()) { + QCoreApplication::processEvents(); + ::Sleep(100); + } + busyDialog.hide(); +} + +void MainWindow::readSettings() +{ + QSettings settings(qApp->property("dataPath").toString() + "/" + QString::fromStdWString(AppConfig::iniFileName()), QSettings::IniFormat); + + if (settings.contains("window_geometry")) { + restoreGeometry(settings.value("window_geometry").toByteArray()); + } + + if (settings.contains("window_split")) { + ui->splitter->restoreState(settings.value("window_split").toByteArray()); + } + + if (settings.contains("log_split")) { + ui->topLevelSplitter->restoreState(settings.value("log_split").toByteArray()); + } + + bool filtersVisible = settings.value("filters_visible", false).toBool(); + setCategoryListVisible(filtersVisible); + ui->displayCategoriesBtn->setChecked(filtersVisible); + + int selectedExecutable = settings.value("selected_executable").toInt(); + setExecutableIndex(selectedExecutable); + + if (settings.value("Settings/use_proxy", false).toBool()) { + activateProxy(true); + } +} + +void MainWindow::processUpdates() { + QSettings settings(qApp->property("dataPath").toString() + "/" + QString::fromStdWString(AppConfig::iniFileName()), QSettings::IniFormat); + QVersionNumber lastVersion = QVersionNumber::fromString(settings.value("version", "2.1.2").toString()).normalized(); + QVersionNumber currentVersion = QVersionNumber::fromString(m_OrganizerCore.getVersion().displayString()).normalized(); + if (!m_OrganizerCore.settings().directInterface().value("first_start", true).toBool()) { + if (lastVersion < QVersionNumber(2, 1, 3)) { + bool lastHidden = true; + for (int i = ModList::COL_GAME; i < ui->modList->model()->columnCount(); ++i) { + bool hidden = ui->modList->header()->isSectionHidden(i); + ui->modList->header()->setSectionHidden(i, lastHidden); + lastHidden = hidden; + } + } + if (lastVersion < QVersionNumber(2,1,6)) { + ui->modList->header()->setSectionHidden(ModList::COL_NOTES, true); + } + } + + if (currentVersion > lastVersion) { + //NOP + } else if (currentVersion < lastVersion) + qWarning() << tr("Notice: Your current MO version (%1) is lower than the previously used one (%2). " + "The GUI may not downgrade gracefully, so you may experience oddities. " + "However, there should be no serious issues.").arg(currentVersion.toString()).arg(lastVersion.toString()).toStdWString(); + //save version in all case + settings.setValue("version", currentVersion.toString()); +} + +void MainWindow::storeSettings(QSettings &settings) { + settings.setValue("group_state", ui->groupCombo->currentIndex()); + settings.setValue("selected_executable", + ui->executablesListBox->currentIndex()); + + if (settings.value("reset_geometry", false).toBool()) { + settings.remove("window_geometry"); + settings.remove("window_split"); + settings.remove("log_split"); + settings.remove("filters_visible"); + settings.remove("browser_geometry"); + settings.remove("geometry"); + settings.remove("reset_geometry"); + } else { + settings.setValue("window_geometry", saveGeometry()); + settings.setValue("window_split", ui->splitter->saveState()); + settings.setValue("log_split", ui->topLevelSplitter->saveState()); + settings.setValue("browser_geometry", m_IntegratedBrowser.saveGeometry()); + settings.setValue("filters_visible", ui->displayCategoriesBtn->isChecked()); + for (const std::pair kv : m_PersistedGeometry) { + QString key = QString("geometry/") + kv.first; + settings.setValue(key, kv.second->saveState()); + } + } +} + +ILockedWaitingForProcess* MainWindow::lock() +{ + if (m_LockDialog != nullptr) { + ++m_LockCount; + return m_LockDialog; + } + if (m_closing) + m_LockDialog = new WaitingOnCloseDialog(this); + else + m_LockDialog = new LockedDialog(this, true); + m_LockDialog->setModal(true); + m_LockDialog->show(); + setEnabled(false); + m_LockDialog->setEnabled(true); //What's the point otherwise? + ++m_LockCount; + return m_LockDialog; +} + +void MainWindow::unlock() +{ + //If you come through here with a null lock pointer, it's a bug! + if (m_LockDialog == nullptr) { + qDebug("Unlocking main window when already unlocked"); + return; + } + --m_LockCount; + if (m_LockCount == 0) { + if (m_closing && m_LockDialog->canceled()) + m_closing = false; + m_LockDialog->hide(); + m_LockDialog->deleteLater(); + m_LockDialog = nullptr; + setEnabled(true); + } +} + +void MainWindow::on_btnRefreshData_clicked() +{ + m_OrganizerCore.refreshDirectoryStructure(); +} + +void MainWindow::on_btnRefreshDownloads_clicked() +{ + m_OrganizerCore.downloadManager()->refreshList(); +} + +void MainWindow::on_tabWidget_currentChanged(int index) +{ + if (index == 0) { + m_OrganizerCore.refreshESPList(); + } else if (index == 1) { + m_OrganizerCore.refreshBSAList(); + } else if (index == 2) { + refreshDataTreeKeepExpandedNodes(); + } else if (index == 3) { + refreshSaveList(); + } +} + + +void MainWindow::installMod(QString fileName) +{ + try { + if (fileName.isEmpty()) { + QStringList extensions = m_OrganizerCore.installationManager()->getSupportedExtensions(); + for (auto iter = extensions.begin(); iter != extensions.end(); ++iter) { + *iter = "*." + *iter; + } + + fileName = FileDialogMemory::getOpenFileName("installMod", this, tr("Choose Mod"), QString(), + tr("Mod Archive").append(QString(" (%1)").arg(extensions.join(" ")))); + } + + if (fileName.isEmpty()) { + return; + } else { + m_OrganizerCore.installMod(fileName, QString()); + } + } catch (const std::exception &e) { + reportError(e.what()); + } +} + +void MainWindow::on_startButton_clicked() { + ui->startButton->setEnabled(false); + try { + const Executable &selectedExecutable(getSelectedExecutable()); + QString customOverwrite = m_OrganizerCore.currentProfile()->setting("custom_overwrites", selectedExecutable.m_Title).toString(); + auto forcedLibraries = m_OrganizerCore.currentProfile()->determineForcedLibraries(selectedExecutable.m_Title); + if (!m_OrganizerCore.currentProfile()->forcedLibrariesEnabled(selectedExecutable.m_Title)) { + forcedLibraries.clear(); + } + m_OrganizerCore.spawnBinary( + selectedExecutable.m_BinaryInfo, selectedExecutable.m_Arguments, + selectedExecutable.m_WorkingDirectory.length() != 0 + ? selectedExecutable.m_WorkingDirectory + : selectedExecutable.m_BinaryInfo.absolutePath(), + selectedExecutable.m_SteamAppID, + customOverwrite, + forcedLibraries); + } catch (...) { + ui->startButton->setEnabled(true); + throw; + } + ui->startButton->setEnabled(true); +} + +static HRESULT CreateShortcut(LPCWSTR targetFileName, LPCWSTR arguments, + LPCSTR linkFileName, LPCWSTR description, + LPCTSTR iconFileName, int iconNumber, + LPCWSTR currentDirectory) +{ + HRESULT result = E_INVALIDARG; + if ((targetFileName != nullptr) && (wcslen(targetFileName) > 0) && + (arguments != nullptr) && + (linkFileName != nullptr) && (strlen(linkFileName) > 0) && + (description != nullptr) && + (currentDirectory != nullptr)) { + + IShellLink* shellLink; + result = CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, + IID_IShellLink, (LPVOID*)&shellLink); + + if (!SUCCEEDED(result)) { + qCritical("failed to create IShellLink instance"); + return result; + } + + result = shellLink->SetPath(targetFileName); + if (!SUCCEEDED(result)) { + qCritical("failed to set target path %ls", targetFileName); + shellLink->Release(); + return result; + } + + result = shellLink->SetArguments(arguments); + if (!SUCCEEDED(result)) { + qCritical("failed to set arguments: %ls", arguments); + shellLink->Release(); + return result; + } + + if (wcslen(description) > 0) { + result = shellLink->SetDescription(description); + if (!SUCCEEDED(result)) { + qCritical("failed to set description: %ls", description); + shellLink->Release(); + return result; + } + } + + if (wcslen(currentDirectory) > 0) { + result = shellLink->SetWorkingDirectory(currentDirectory); + if (!SUCCEEDED(result)) { + qCritical("failed to set working directory: %ls", currentDirectory); + shellLink->Release(); + return result; + } + } + + if (iconFileName != nullptr) { + result = shellLink->SetIconLocation(iconFileName, iconNumber); + if (!SUCCEEDED(result)) { + qCritical("failed to load program icon: %ls %d", iconFileName, iconNumber); + shellLink->Release(); + return result; + } + } + + IPersistFile *persistFile; + result = shellLink->QueryInterface(IID_IPersistFile, (LPVOID*)&persistFile); + if (SUCCEEDED(result)) { + wchar_t linkFileNameW[MAX_PATH]; + if (MultiByteToWideChar(CP_ACP, 0, linkFileName, -1, linkFileNameW, MAX_PATH) > 0) { + result = persistFile->Save(linkFileNameW, TRUE); + } else { + qCritical("failed to create link: %s", linkFileName); + } + persistFile->Release(); + } else { + qCritical("failed to create IPersistFile instance"); + } + + shellLink->Release(); + } + return result; +} + + +bool MainWindow::modifyExecutablesDialog() +{ + bool result = false; + try { + EditExecutablesDialog dialog(*m_OrganizerCore.executablesList(), + *m_OrganizerCore.modList(), + m_OrganizerCore.currentProfile(), + m_OrganizerCore.managedGame()); + QSettings &settings = m_OrganizerCore.settings().directInterface(); + QString key = QString("geometry/%1").arg(dialog.objectName()); + if (settings.contains(key)) { + dialog.restoreGeometry(settings.value(key).toByteArray()); + } + if (dialog.exec() == QDialog::Accepted) { + m_OrganizerCore.setExecutablesList(dialog.getExecutablesList()); + result = true; + } + settings.setValue(key, dialog.saveGeometry()); + refreshExecutablesList(); + } catch (const std::exception &e) { + reportError(e.what()); + } + return result; +} + +void MainWindow::on_executablesListBox_currentIndexChanged(int index) +{ + QComboBox* executablesList = findChild("executablesListBox"); + + int previousIndex = m_OldExecutableIndex; + m_OldExecutableIndex = index; + + if (executablesList->isEnabled()) { + //I think the 2nd test is impossible + if ((index == 0) || (index > static_cast(m_OrganizerCore.executablesList()->size()))) { + if (modifyExecutablesDialog()) { + setExecutableIndex(previousIndex); + } + } else { + setExecutableIndex(index); + } + } +} + +void MainWindow::helpTriggered() +{ + QWhatsThis::enterWhatsThisMode(); +} + +void MainWindow::wikiTriggered() +{ + QDesktopServices::openUrl(QUrl("https://modorganizer2.github.io/")); +} + +void MainWindow::discordTriggered() +{ + QDesktopServices::openUrl(QUrl("https://discord.gg/cYwdcxj")); +} + +void MainWindow::issueTriggered() +{ + QDesktopServices::openUrl(QUrl("https://github.com/Modorganizer2/modorganizer/issues")); +} + +void MainWindow::tutorialTriggered() +{ + QAction *tutorialAction = qobject_cast(sender()); + if (tutorialAction != nullptr) { + if (QMessageBox::question(this, tr("Start Tutorial?"), + tr("You're about to start a tutorial. For technical reasons it's not possible to end " + "the tutorial early. Continue?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { + TutorialManager::instance().activateTutorial("MainWindow", tutorialAction->data().toString()); + } + } +} + + +void MainWindow::on_actionInstallMod_triggered() +{ + installMod(); +} + +void MainWindow::on_actionAdd_Profile_triggered() +{ + for (;;) { + ProfilesDialog profilesDialog(m_OrganizerCore.currentProfile()->name(), + m_OrganizerCore.managedGame(), + this); + QSettings &settings = m_OrganizerCore.settings().directInterface(); + QString key = QString("geometry/%1").arg(profilesDialog.objectName()); + if (settings.contains(key)) { + profilesDialog.restoreGeometry(settings.value(key).toByteArray()); + } + // workaround: need to disable monitoring of the saves directory, otherwise the active + // profile directory is locked + stopMonitorSaves(); + profilesDialog.exec(); + settings.setValue(key, profilesDialog.saveGeometry()); + refreshSaveList(); // since the save list may now be outdated we have to refresh it completely + if (refreshProfiles() && !profilesDialog.failed()) { + break; + } + } + + LocalSavegames *saveGames = m_OrganizerCore.managedGame()->feature(); + if (saveGames != nullptr) { + if (saveGames->prepareProfile(m_OrganizerCore.currentProfile())) + refreshSaveList(); + } + + BSAInvalidation *invalidation = m_OrganizerCore.managedGame()->feature(); + if (invalidation != nullptr) { + if (invalidation->prepareProfile(m_OrganizerCore.currentProfile())) + QTimer::singleShot(5, &m_OrganizerCore, SLOT(profileRefresh())); + } +} + +void MainWindow::on_actionModify_Executables_triggered() +{ + if (modifyExecutablesDialog()) { + setExecutableIndex(m_OldExecutableIndex); + } +} + + +void MainWindow::setModListSorting(int index) +{ + Qt::SortOrder order = ((index & 0x01) != 0) ? Qt::DescendingOrder : Qt::AscendingOrder; + int column = index >> 1; + ui->modList->header()->setSortIndicator(column, order); +} + + +void MainWindow::setESPListSorting(int index) +{ + switch (index) { + case 0: { + ui->espList->header()->setSortIndicator(1, Qt::AscendingOrder); + } break; + case 1: { + ui->espList->header()->setSortIndicator(1, Qt::DescendingOrder); + } break; + case 2: { + ui->espList->header()->setSortIndicator(0, Qt::AscendingOrder); + } break; + case 3: { + ui->espList->header()->setSortIndicator(0, Qt::DescendingOrder); + } break; + } +} + +void MainWindow::refresher_progress(int percent) +{ + if (percent == 100) { + m_RefreshProgress->setVisible(false); + statusBar()->hide(); + this->setEnabled(true); + } else if (!m_RefreshProgress->isVisible()) { + this->setEnabled(false); + statusBar()->show(); + m_RefreshProgress->setVisible(true); + m_RefreshProgress->setRange(0, 100); + m_RefreshProgress->setValue(percent); + } +} + +void MainWindow::directory_refreshed() +{ + // some problem-reports may rely on the virtual directory tree so they need to be updated + // now + refreshDataTreeKeepExpandedNodes(); + updateProblemsButton(); + statusBar()->hide(); +} + +void MainWindow::esplist_changed() +{ + updatePluginCount(); +} + +void MainWindow::modorder_changed() +{ + for (unsigned int i = 0; i < m_OrganizerCore.currentProfile()->numMods(); ++i) { + int priority = m_OrganizerCore.currentProfile()->getModPriority(i); + if (m_OrganizerCore.currentProfile()->modEnabled(i)) { + ModInfo::Ptr modInfo = ModInfo::getByIndex(i); + // priorities in the directory structure are one higher because data is 0 + m_OrganizerCore.directoryStructure()->getOriginByName(ToWString(modInfo->internalName())).setPriority(priority + 1); + } + } + m_OrganizerCore.refreshBSAList(); + m_OrganizerCore.currentProfile()->writeModlist(); + m_ArchiveListWriter.write(); + m_OrganizerCore.directoryStructure()->getFileRegister()->sortOrigins(); + + { // refresh selection + QModelIndex current = ui->modList->currentIndex(); + if (current.isValid()) { + ModInfo::Ptr modInfo = ModInfo::getByIndex(current.data(Qt::UserRole + 1).toInt()); + // clear caches on all mods conflicting with the moved mod + for (int i : modInfo->getModOverwrite()) { + ModInfo::getByIndex(i)->clearCaches(); + } + for (int i : modInfo->getModOverwritten()) { + ModInfo::getByIndex(i)->clearCaches(); + } + for (int i : modInfo->getModArchiveOverwrite()) { + ModInfo::getByIndex(i)->clearCaches(); + } + for (int i : modInfo->getModArchiveOverwritten()) { + ModInfo::getByIndex(i)->clearCaches(); + } + for (int i : modInfo->getModArchiveLooseOverwrite()) { + ModInfo::getByIndex(i)->clearCaches(); + } + for (int i : modInfo->getModArchiveLooseOverwritten()) { + ModInfo::getByIndex(i)->clearCaches(); + } + // update conflict check on the moved mod + modInfo->doConflictCheck(); + m_OrganizerCore.modList()->setOverwriteMarkers(modInfo->getModOverwrite(), modInfo->getModOverwritten()); + m_OrganizerCore.modList()->setArchiveOverwriteMarkers(modInfo->getModArchiveOverwrite(), modInfo->getModArchiveOverwritten()); + m_OrganizerCore.modList()->setArchiveLooseOverwriteMarkers(modInfo->getModArchiveLooseOverwrite(), modInfo->getModArchiveLooseOverwritten()); + if (m_ModListSortProxy != nullptr) { + m_ModListSortProxy->invalidate(); + } + ui->modList->verticalScrollBar()->repaint(); + } + } +} + +void MainWindow::modInstalled(const QString &modName) +{ + QModelIndexList posList = + m_OrganizerCore.modList()->match(m_OrganizerCore.modList()->index(0, 0), Qt::DisplayRole, modName); + if (posList.count() == 1) { + ui->modList->scrollTo(posList.at(0)); + } +} + +void MainWindow::procError(QProcess::ProcessError error) +{ + reportError(tr("failed to spawn notepad.exe: %1").arg(error)); + this->sender()->deleteLater(); +} + +void MainWindow::procFinished(int, QProcess::ExitStatus) +{ + this->sender()->deleteLater(); +} + +void MainWindow::showMessage(const QString &message) +{ + MessageDialog::showMessage(message, this); +} + +void MainWindow::showError(const QString &message) +{ + reportError(message); +} + +void MainWindow::installMod_clicked() +{ + installMod(); +} + +void MainWindow::modRenamed(const QString &oldName, const QString &newName) +{ + Profile::renameModInAllProfiles(oldName, newName); + + // immediately refresh the active profile because the data in memory is invalid + m_OrganizerCore.currentProfile()->refreshModStatus(); + + // also fix the directory structure + try { + if (m_OrganizerCore.directoryStructure()->originExists(ToWString(oldName))) { + FilesOrigin &origin = m_OrganizerCore.directoryStructure()->getOriginByName(ToWString(oldName)); + origin.setName(ToWString(newName)); + } else { + + } + } catch (const std::exception &e) { + reportError(tr("failed to change origin name: %1").arg(e.what())); + } +} + +void MainWindow::fileMoved(const QString &filePath, const QString &oldOriginName, const QString &newOriginName) +{ + const FileEntry::Ptr filePtr = m_OrganizerCore.directoryStructure()->findFile(ToWString(filePath)); + if (filePtr.get() != nullptr) { + try { + if (m_OrganizerCore.directoryStructure()->originExists(ToWString(newOriginName))) { + FilesOrigin &newOrigin = m_OrganizerCore.directoryStructure()->getOriginByName(ToWString(newOriginName)); + + QString fullNewPath = ToQString(newOrigin.getPath()) + "\\" + filePath; + WIN32_FIND_DATAW findData; + HANDLE hFind; + hFind = ::FindFirstFileW(ToWString(fullNewPath).c_str(), &findData); + filePtr->addOrigin(newOrigin.getID(), findData.ftCreationTime, L"", -1); + FindClose(hFind); + } + if (m_OrganizerCore.directoryStructure()->originExists(ToWString(oldOriginName))) { + FilesOrigin &oldOrigin = m_OrganizerCore.directoryStructure()->getOriginByName(ToWString(oldOriginName)); + filePtr->removeOrigin(oldOrigin.getID()); + } + } catch (const std::exception &e) { + reportError(tr("failed to move \"%1\" from mod \"%2\" to \"%3\": %4").arg(filePath).arg(oldOriginName).arg(newOriginName).arg(e.what())); + } + } else { + // this is probably not an error, the specified path is likely a directory + } +} + +QTreeWidgetItem *MainWindow::addFilterItem(QTreeWidgetItem *root, const QString &name, int categoryID, ModListSortProxy::FilterType type) +{ + QTreeWidgetItem *item = new QTreeWidgetItem(QStringList(name)); + item->setData(0, Qt::ToolTipRole, name); + item->setData(0, Qt::UserRole, categoryID); + item->setData(0, Qt::UserRole + 1, type); + if (root != nullptr) { + root->addChild(item); + } else { + ui->categoriesList->addTopLevelItem(item); + } + return item; +} + +void MainWindow::addContentFilters() +{ + for (unsigned i = 0; i < ModInfo::NUM_CONTENT_TYPES; ++i) { + addFilterItem(nullptr, tr("").arg(ModInfo::getContentTypeName(i)), i, ModListSortProxy::TYPE_CONTENT); + } +} + +void MainWindow::addCategoryFilters(QTreeWidgetItem *root, const std::set &categoriesUsed, int targetID) +{ + for (unsigned int i = 1; + i < static_cast(m_CategoryFactory.numCategories()); ++i) { + if ((m_CategoryFactory.getParentID(i) == targetID)) { + int categoryID = m_CategoryFactory.getCategoryID(i); + if (categoriesUsed.find(categoryID) != categoriesUsed.end()) { + QTreeWidgetItem *item = + addFilterItem(root, m_CategoryFactory.getCategoryName(i), + categoryID, ModListSortProxy::TYPE_CATEGORY); + if (m_CategoryFactory.hasChildren(i)) { + addCategoryFilters(item, categoriesUsed, categoryID); + } + } + } + } +} + +void MainWindow::refreshFilters() +{ + QItemSelection currentSelection = ui->modList->selectionModel()->selection(); + + QVariant currentIndexName = ui->modList->currentIndex().data(); + ui->modList->setCurrentIndex(QModelIndex()); + + QStringList selectedItems; + for (QTreeWidgetItem *item : ui->categoriesList->selectedItems()) { + selectedItems.append(item->text(0)); + } + + ui->categoriesList->clear(); + addFilterItem(nullptr, tr(""), CategoryFactory::CATEGORY_SPECIAL_CHECKED, ModListSortProxy::TYPE_SPECIAL); + addFilterItem(nullptr, tr(""), CategoryFactory::CATEGORY_SPECIAL_UNCHECKED, ModListSortProxy::TYPE_SPECIAL); + addFilterItem(nullptr, tr(""), CategoryFactory::CATEGORY_SPECIAL_UPDATEAVAILABLE, ModListSortProxy::TYPE_SPECIAL); + addFilterItem(nullptr, tr(""), CategoryFactory::CATEGORY_SPECIAL_BACKUP, ModListSortProxy::TYPE_SPECIAL); + addFilterItem(nullptr, tr(""), CategoryFactory::CATEGORY_SPECIAL_MANAGED, ModListSortProxy::TYPE_SPECIAL); + addFilterItem(nullptr, tr(""), CategoryFactory::CATEGORY_SPECIAL_UNMANAGED, ModListSortProxy::TYPE_SPECIAL); + addFilterItem(nullptr, tr(""), CategoryFactory::CATEGORY_SPECIAL_NOCATEGORY, ModListSortProxy::TYPE_SPECIAL); + addFilterItem(nullptr, tr(""), CategoryFactory::CATEGORY_SPECIAL_CONFLICT, ModListSortProxy::TYPE_SPECIAL); + addFilterItem(nullptr, tr(""), CategoryFactory::CATEGORY_SPECIAL_NOTENDORSED, ModListSortProxy::TYPE_SPECIAL); + + addContentFilters(); + std::set categoriesUsed; + for (unsigned int modIdx = 0; modIdx < ModInfo::getNumMods(); ++modIdx) { + ModInfo::Ptr modInfo = ModInfo::getByIndex(modIdx); + for (int categoryID : modInfo->getCategories()) { + int currentID = categoryID; + std::set cycleTest; + // also add parents so they show up in the tree + while (currentID != 0) { + categoriesUsed.insert(currentID); + if (!cycleTest.insert(currentID).second) { + qWarning("cycle in categories: %s", qUtf8Printable(SetJoin(cycleTest, ", "))); + break; + } + currentID = m_CategoryFactory.getParentID(m_CategoryFactory.getCategoryIndex(currentID)); + } + } + } + + addCategoryFilters(nullptr, categoriesUsed, 0); + + for (const QString &item : selectedItems) { + QList matches = ui->categoriesList->findItems(item, Qt::MatchFixedString | Qt::MatchRecursive); + if (matches.size() > 0) { + matches.at(0)->setSelected(true); + } + } + ui->modList->selectionModel()->select(currentSelection, QItemSelectionModel::Select); + QModelIndexList matchList; + if (currentIndexName.isValid()) { + matchList = ui->modList->model()->match(ui->modList->model()->index(0, 0), Qt::DisplayRole, currentIndexName); + } + + if (matchList.size() > 0) { + ui->modList->setCurrentIndex(matchList.at(0)); + } +} + + +void MainWindow::renameMod_clicked() +{ + try { + ui->modList->edit(ui->modList->currentIndex()); + } catch (const std::exception &e) { + reportError(tr("failed to rename mod: %1").arg(e.what())); + } +} + + +void MainWindow::restoreBackup_clicked() +{ + QRegExp backupRegEx("(.*)_backup[0-9]*$"); + ModInfo::Ptr modInfo = ModInfo::getByIndex(m_ContextRow); + if (backupRegEx.indexIn(modInfo->name()) != -1) { + QString regName = backupRegEx.cap(1); + QDir modDir(QDir::fromNativeSeparators(m_OrganizerCore.settings().getModDirectory())); + if (!modDir.exists(regName) || + (QMessageBox::question(this, tr("Overwrite?"), + tr("This will replace the existing mod \"%1\". Continue?").arg(regName), + QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes)) { + if (modDir.exists(regName) && !shellDelete(QStringList(modDir.absoluteFilePath(regName)))) { + reportError(tr("failed to remove mod \"%1\"").arg(regName)); + } else { + QString destinationPath = QDir::fromNativeSeparators(m_OrganizerCore.settings().getModDirectory()) + "/" + regName; + if (!modDir.rename(modInfo->absolutePath(), destinationPath)) { + reportError(tr("failed to rename \"%1\" to \"%2\"").arg(modInfo->absolutePath()).arg(destinationPath)); + } + m_OrganizerCore.refreshModList(); + } + } + } +} + +void MainWindow::modlistChanged(const QModelIndex&, int) +{ + m_OrganizerCore.currentProfile()->writeModlist(); + updateModCount(); +} + +void MainWindow::modlistChanged(const QModelIndexList&, int) +{ + m_OrganizerCore.currentProfile()->writeModlist(); + updateModCount(); +} + +void MainWindow::modlistSelectionChanged(const QModelIndex ¤t, const QModelIndex&) +{ + if (current.isValid()) { + ModInfo::Ptr selectedMod = ModInfo::getByIndex(current.data(Qt::UserRole + 1).toInt()); + m_OrganizerCore.modList()->setOverwriteMarkers(selectedMod->getModOverwrite(), selectedMod->getModOverwritten()); + m_OrganizerCore.modList()->setArchiveOverwriteMarkers(selectedMod->getModArchiveOverwrite(), selectedMod->getModArchiveOverwritten()); + m_OrganizerCore.modList()->setArchiveLooseOverwriteMarkers(selectedMod->getModArchiveLooseOverwrite(), selectedMod->getModArchiveLooseOverwritten()); + } else { + m_OrganizerCore.modList()->setOverwriteMarkers(std::set(), std::set()); + m_OrganizerCore.modList()->setArchiveOverwriteMarkers(std::set(), std::set()); + m_OrganizerCore.modList()->setArchiveLooseOverwriteMarkers(std::set(), std::set()); + } +/* if ((m_ModListSortProxy != nullptr) + && !m_ModListSortProxy->beingInvalidated()) { + m_ModListSortProxy->invalidate(); + }*/ + ui->modList->verticalScrollBar()->repaint(); +} + +void MainWindow::modlistSelectionsChanged(const QItemSelection &selected) +{ + m_OrganizerCore.pluginList()->highlightPlugins(ui->modList->selectionModel(), *m_OrganizerCore.directoryStructure(), *m_OrganizerCore.currentProfile()); + ui->espList->verticalScrollBar()->repaint(); +} + +void MainWindow::esplistSelectionsChanged(const QItemSelection &selected) +{ + m_OrganizerCore.modList()->highlightMods(ui->espList->selectionModel(), *m_OrganizerCore.directoryStructure()); + ui->modList->verticalScrollBar()->repaint(); +} + +void MainWindow::modListSortIndicatorChanged(int, Qt::SortOrder) +{ + ui->modList->verticalScrollBar()->repaint(); +} + +void MainWindow::modListSectionResized(int logicalIndex, int oldSize, int newSize) +{ + bool enabled = (newSize != 0); + qobject_cast(ui->modList->model())->setColumnVisible(logicalIndex, enabled); +} + +void MainWindow::removeMod_clicked() +{ + try { + QItemSelectionModel *selection = ui->modList->selectionModel(); + if (selection->hasSelection() && selection->selectedRows().count() > 1) { + QString mods; + QStringList modNames; + for (QModelIndex idx : selection->selectedRows()) { + QString name = idx.data().toString(); + if (!ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt())->isRegular()) { + continue; + } + mods += "
  • " + name + "
  • "; + modNames.append(ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt())->name()); + } + if (QMessageBox::question(this, tr("Confirm"), + tr("Remove the following mods?
      %1
    ").arg(mods), + QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { + // use mod names instead of indexes because those become invalid during the removal + DownloadManager::startDisableDirWatcher(); + for (QString name : modNames) { + m_OrganizerCore.modList()->removeRowForce(ModInfo::getIndex(name), QModelIndex()); + } + DownloadManager::endDisableDirWatcher(); + } + } else { + m_OrganizerCore.modList()->removeRow(m_ContextRow, QModelIndex()); + } + updateModCount(); + updatePluginCount(); + } catch (const std::exception &e) { + reportError(tr("failed to remove mod: %1").arg(e.what())); + } +} + + +void MainWindow::modRemoved(const QString &fileName) +{ + if (!fileName.isEmpty() && !QFileInfo(fileName).isAbsolute()) { + m_OrganizerCore.downloadManager()->markUninstalled(fileName); + } +} + + +void MainWindow::reinstallMod_clicked() +{ + ModInfo::Ptr modInfo = ModInfo::getByIndex(m_ContextRow); + QString installationFile = modInfo->getInstallationFile(); + if (installationFile.length() != 0) { + QString fullInstallationFile; + QFileInfo fileInfo(installationFile); + if (fileInfo.isAbsolute()) { + if (fileInfo.exists()) { + fullInstallationFile = installationFile; + } else { + fullInstallationFile = m_OrganizerCore.downloadManager()->getOutputDirectory() + "/" + fileInfo.fileName(); + } + } else { + fullInstallationFile = m_OrganizerCore.downloadManager()->getOutputDirectory() + "/" + installationFile; + } + if (QFile::exists(fullInstallationFile)) { + m_OrganizerCore.installMod(fullInstallationFile, modInfo->name()); + } else { + QMessageBox::information(this, tr("Failed"), tr("Installation file no longer exists")); + } + } else { + QMessageBox::information(this, tr("Failed"), + tr("Mods installed with old versions of MO can't be reinstalled in this way.")); + } +} + +void MainWindow::backupMod_clicked() +{ + ModInfo::Ptr modInfo = ModInfo::getByIndex(m_ContextRow); + QString backupDirectory = m_OrganizerCore.installationManager()->generateBackupName(modInfo->absolutePath()); + if (!copyDir(modInfo->absolutePath(), backupDirectory, false)) { + QMessageBox::information(this, tr("Failed"), + tr("Failed to create backup.")); + } + m_OrganizerCore.refreshModList(); +} + +void MainWindow::resumeDownload(int downloadIndex) +{ + if (NexusInterface::instance(&m_PluginContainer)->getAccessManager()->validated()) { + m_OrganizerCore.downloadManager()->resumeDownload(downloadIndex); + } else { + QString apiKey; + if (m_OrganizerCore.settings().getNexusApiKey(apiKey)) { + m_OrganizerCore.doAfterLogin([this, downloadIndex] () { + this->resumeDownload(downloadIndex); + }); + NexusInterface::instance(&m_PluginContainer)->getAccessManager()->apiCheck(apiKey); + } else { + MessageDialog::showMessage(tr("You need to be logged in with Nexus to resume a download"), this); + } + } +} + + +void MainWindow::endorseMod(ModInfo::Ptr mod) +{ + if (NexusInterface::instance(&m_PluginContainer)->getAccessManager()->validated()) { + mod->endorse(true); + } else { + QString apiKey; + if (m_OrganizerCore.settings().getNexusApiKey(apiKey)) { + m_OrganizerCore.doAfterLogin(boost::bind(&MainWindow::endorseMod, this, mod)); + NexusInterface::instance(&m_PluginContainer)->getAccessManager()->apiCheck(apiKey); + } else { + MessageDialog::showMessage(tr("You need to be logged in with Nexus to endorse"), this); + } + } +} + + +void MainWindow::endorse_clicked() +{ + QItemSelectionModel *selection = ui->modList->selectionModel(); + if (selection->hasSelection() && selection->selectedRows().count() > 1) { + if (NexusInterface::instance(&m_PluginContainer)->getAccessManager()->loggedIn()) { + MessageDialog::showMessage(tr("Endorsing multiple mods will take a while. Please wait..."), this); + for (QModelIndex idx : selection->selectedRows()) { + ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt())->endorse(true); + } + } + else { + QString username, password; + if (m_OrganizerCore.settings().getNexusLogin(username, password)) { + MessageDialog::showMessage(tr("Endorsing multiple mods will take a while. Please wait..."), this); + for (QModelIndex idx : selection->selectedRows()) { + ModInfo::Ptr modInfo = ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt()); + m_OrganizerCore.doAfterLogin(boost::bind(&MainWindow::endorseMod, this, modInfo)); + } + NexusInterface::instance(&m_PluginContainer)->getAccessManager()->login(username, password); + } else { + MessageDialog::showMessage(tr("You need to be logged in with Nexus to endorse"), this); + return; + } + } + } + else { + endorseMod(ModInfo::getByIndex(m_ContextRow)); + } +} + +void MainWindow::dontendorse_clicked() +{ + QItemSelectionModel *selection = ui->modList->selectionModel(); + if (selection->hasSelection() && selection->selectedRows().count() > 1) { + for (QModelIndex idx : selection->selectedRows()) { + ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt())->setNeverEndorse(); + } + } + else { + ModInfo::getByIndex(m_ContextRow)->setNeverEndorse(); + } +} + + +void MainWindow::unendorseMod(ModInfo::Ptr mod) +{ + QString apiKey; + if (NexusInterface::instance(&m_PluginContainer)->getAccessManager()->validated()) { + ModInfo::getByIndex(m_ContextRow)->endorse(false); + } else { + if (m_OrganizerCore.settings().getNexusApiKey(apiKey)) { + m_OrganizerCore.doAfterLogin([this] () { this->unendorse_clicked(); }); + NexusInterface::instance(&m_PluginContainer)->getAccessManager()->apiCheck(apiKey); + } else { + MessageDialog::showMessage(tr("You need to be logged in with Nexus to endorse"), this); + } + } +} + + +void MainWindow::unendorse_clicked() +{ + QItemSelectionModel *selection = ui->modList->selectionModel(); + if (selection->hasSelection() && selection->selectedRows().count() > 1) { + if (NexusInterface::instance(&m_PluginContainer)->getAccessManager()->loggedIn()) { + MessageDialog::showMessage(tr("Unendorsing multiple mods will take a while. Please wait..."), this); + for (QModelIndex idx : selection->selectedRows()) { + ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt())->endorse(false); + } + } + else { + QString username, password; + if (m_OrganizerCore.settings().getNexusLogin(username, password)) { + MessageDialog::showMessage(tr("Unendorsing multiple mods will take a while. Please wait..."), this); + for (QModelIndex idx : selection->selectedRows()) { + ModInfo::Ptr modInfo = ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt()); + m_OrganizerCore.doAfterLogin(boost::bind(&MainWindow::unendorseMod, this, modInfo)); + } + NexusInterface::instance(&m_PluginContainer)->getAccessManager()->login(username, password); + } else { + MessageDialog::showMessage(tr("You need to be logged in with Nexus to endorse"), this); + return; + } + } + } + else { + unendorseMod(ModInfo::getByIndex(m_ContextRow)); + } +} + +void MainWindow::loginFailed(const QString &error) +{ + qDebug("login failed: %s", qUtf8Printable(error)); + statusBar()->hide(); +} + +void MainWindow::windowTutorialFinished(const QString &windowName) +{ + m_OrganizerCore.settings().directInterface().setValue(QString("CompletedWindowTutorials/") + windowName, true); +} + +void MainWindow::overwriteClosed(int) +{ + OverwriteInfoDialog *dialog = this->findChild("__overwriteDialog"); + if (dialog != nullptr) { + m_OrganizerCore.modList()->modInfoChanged(dialog->modInfo()); + QSettings &settings = m_OrganizerCore.settings().directInterface(); + QString key = QString("geometry/%1").arg(dialog->objectName()); + settings.setValue(key, dialog->saveGeometry()); + dialog->deleteLater(); + } + m_OrganizerCore.refreshDirectoryStructure(); +} + + +void MainWindow::displayModInformation(ModInfo::Ptr modInfo, unsigned int index, int tab) +{ + if (!m_OrganizerCore.modList()->modInfoAboutToChange(modInfo)) { + qDebug("A different mod information dialog is open. If this is incorrect, please restart MO"); + return; + } + std::vector flags = modInfo->getFlags(); + if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end()) { + QDialog *dialog = this->findChild("__overwriteDialog"); + try { + if (dialog == nullptr) { + dialog = new OverwriteInfoDialog(modInfo, this); + dialog->setObjectName("__overwriteDialog"); + } else { + qobject_cast(dialog)->setModInfo(modInfo); + } + QSettings &settings = m_OrganizerCore.settings().directInterface(); + QString key = QString("geometry/%1").arg(dialog->objectName()); + if (settings.contains(key)) { + dialog->restoreGeometry(settings.value(key).toByteArray()); + } + dialog->show(); + dialog->raise(); + dialog->activateWindow(); + connect(dialog, SIGNAL(finished(int)), this, SLOT(overwriteClosed(int))); + } catch (const std::exception &e) { + reportError(tr("Failed to display overwrite dialog: %1").arg(e.what())); + } + } else { + modInfo->saveMeta(); + ModInfoDialog dialog(modInfo, m_OrganizerCore.directoryStructure(), modInfo->hasFlag(ModInfo::FLAG_FOREIGN), &m_OrganizerCore, &m_PluginContainer, this); + connect(&dialog, SIGNAL(linkActivated(QString)), this, SLOT(linkClicked(QString))); + connect(&dialog, SIGNAL(downloadRequest(QString)), &m_OrganizerCore, SLOT(downloadRequestedNXM(QString))); + connect(&dialog, SIGNAL(modOpen(QString, int)), this, SLOT(displayModInformation(QString, int)), Qt::QueuedConnection); + connect(&dialog, SIGNAL(modOpenNext(int)), this, SLOT(modOpenNext(int)), Qt::QueuedConnection); + connect(&dialog, SIGNAL(modOpenPrev(int)), this, SLOT(modOpenPrev(int)), Qt::QueuedConnection); + connect(&dialog, SIGNAL(originModified(int)), this, SLOT(originModified(int))); + connect(&dialog, SIGNAL(endorseMod(ModInfo::Ptr)), this, SLOT(endorseMod(ModInfo::Ptr))); + + //Open the tab first if we want to use the standard indexes of the tabs. + if (tab != -1) { + dialog.openTab(tab); + } + + dialog.restoreTabState(m_OrganizerCore.settings().directInterface().value("mod_info_tabs").toByteArray()); + QSettings &settings = m_OrganizerCore.settings().directInterface(); + QString key = QString("geometry/%1").arg(dialog.objectName()); + if (settings.contains(key)) { + dialog.restoreGeometry(settings.value(key).toByteArray()); + } + + //If no tab was specified use the first tab from the left based on the user order. + if (tab == -1) { + for (int i = 0; i < dialog.findChild("tabWidget")->count(); ++i) { + if (dialog.findChild("tabWidget")->isTabEnabled(i)) { + dialog.findChild("tabWidget")->setCurrentIndex(i); + break; + } + } + } + + dialog.exec(); + m_OrganizerCore.settings().directInterface().setValue("mod_info_tabs", dialog.saveTabState()); + settings.setValue(key, dialog.saveGeometry()); + + modInfo->saveMeta(); + emit modInfoDisplayed(); + m_OrganizerCore.modList()->modInfoChanged(modInfo); + } + + if (m_OrganizerCore.currentProfile()->modEnabled(index) + && !modInfo->hasFlag(ModInfo::FLAG_FOREIGN)) { + FilesOrigin& origin = m_OrganizerCore.directoryStructure()->getOriginByName(ToWString(modInfo->name())); + origin.enable(false); + + if (m_OrganizerCore.directoryStructure()->originExists(ToWString(modInfo->name()))) { + FilesOrigin& origin = m_OrganizerCore.directoryStructure()->getOriginByName(ToWString(modInfo->name())); + origin.enable(false); + + m_OrganizerCore.directoryRefresher()->addModToStructure(m_OrganizerCore.directoryStructure() + , modInfo->name() + , m_OrganizerCore.currentProfile()->getModPriority(index) + , modInfo->absolutePath() + , modInfo->stealFiles() + , modInfo->archives()); + DirectoryRefresher::cleanStructure(m_OrganizerCore.directoryStructure()); + m_OrganizerCore.directoryStructure()->getFileRegister()->sortOrigins(); + m_OrganizerCore.refreshLists(); + } + } +} + +bool MainWindow::closeWindow() +{ + return close(); +} + +void MainWindow::setWindowEnabled(bool enabled) +{ + setEnabled(enabled); +} + + +void MainWindow::modOpenNext(int tab) +{ + QModelIndex index = m_ModListSortProxy->mapFromSource(m_OrganizerCore.modList()->index(m_ContextRow, 0)); + index = m_ModListSortProxy->index((index.row() + 1) % m_ModListSortProxy->rowCount(), 0); + + m_ContextRow = m_ModListSortProxy->mapToSource(index).row(); + ModInfo::Ptr mod = ModInfo::getByIndex(m_ContextRow); + std::vector flags = mod->getFlags(); + if ((std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end()) || + (std::find(flags.begin(), flags.end(), ModInfo::FLAG_BACKUP) != flags.end()) || + (std::find(flags.begin(), flags.end(), ModInfo::FLAG_SEPARATOR) != flags.end())) { + // skip overwrite and backups and separators + modOpenNext(tab); + } else { + displayModInformation(m_ContextRow,tab); + } +} + +void MainWindow::modOpenPrev(int tab) +{ + QModelIndex index = m_ModListSortProxy->mapFromSource(m_OrganizerCore.modList()->index(m_ContextRow, 0)); + int row = index.row() - 1; + if (row == -1) { + row = m_ModListSortProxy->rowCount() - 1; + } + + m_ContextRow = m_ModListSortProxy->mapToSource(m_ModListSortProxy->index(row, 0)).row(); + ModInfo::Ptr mod = ModInfo::getByIndex(m_ContextRow); + std::vector flags = mod->getFlags(); + if ((std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end()) || + (std::find(flags.begin(), flags.end(), ModInfo::FLAG_BACKUP) != flags.end()) || + (std::find(flags.begin(), flags.end(), ModInfo::FLAG_SEPARATOR) != flags.end())) { + // skip overwrite and backups and separators + modOpenPrev(tab); + } else { + displayModInformation(m_ContextRow,tab); + } +} + +void MainWindow::displayModInformation(const QString &modName, int tab) +{ + unsigned int index = ModInfo::getIndex(modName); + if (index == UINT_MAX) { + qCritical("failed to resolve mod name %s", qUtf8Printable(modName)); + return; + } + + ModInfo::Ptr modInfo = ModInfo::getByIndex(index); + displayModInformation(modInfo, index, tab); +} + + +void MainWindow::displayModInformation(int row, int tab) +{ + ModInfo::Ptr modInfo = ModInfo::getByIndex(row); + displayModInformation(modInfo, row, tab); +} + + +void MainWindow::ignoreMissingData_clicked() +{ + QItemSelectionModel *selection = ui->modList->selectionModel(); + if (selection->hasSelection() && selection->selectedRows().count() > 1) { + for (QModelIndex idx : selection->selectedRows()) { + int row_idx = idx.data(Qt::UserRole + 1).toInt(); + ModInfo::Ptr info = ModInfo::getByIndex(row_idx); + //QDir(info->absolutePath()).mkdir("textures"); + info->testValid(); + info->markValidated(true); + connect(this, SIGNAL(modListDataChanged(QModelIndex, QModelIndex)), m_OrganizerCore.modList(), SIGNAL(dataChanged(QModelIndex, QModelIndex))); + + emit modListDataChanged(m_OrganizerCore.modList()->index(row_idx, 0), m_OrganizerCore.modList()->index(row_idx, m_OrganizerCore.modList()->columnCount() - 1)); + } + } else { + ModInfo::Ptr info = ModInfo::getByIndex(m_ContextRow); + //QDir(info->absolutePath()).mkdir("textures"); + info->testValid(); + info->markValidated(true); + connect(this, SIGNAL(modListDataChanged(QModelIndex, QModelIndex)), m_OrganizerCore.modList(), SIGNAL(dataChanged(QModelIndex, QModelIndex))); + + emit modListDataChanged(m_OrganizerCore.modList()->index(m_ContextRow, 0), m_OrganizerCore.modList()->index(m_ContextRow, m_OrganizerCore.modList()->columnCount() - 1)); + } +} + +void MainWindow::markConverted_clicked() +{ + QItemSelectionModel *selection = ui->modList->selectionModel(); + if (selection->hasSelection() && selection->selectedRows().count() > 1) { + for (QModelIndex idx : selection->selectedRows()) { + int row_idx = idx.data(Qt::UserRole + 1).toInt(); + ModInfo::Ptr info = ModInfo::getByIndex(row_idx); + info->markConverted(true); + connect(this, SIGNAL(modListDataChanged(QModelIndex, QModelIndex)), m_OrganizerCore.modList(), SIGNAL(dataChanged(QModelIndex, QModelIndex))); + emit modListDataChanged(m_OrganizerCore.modList()->index(row_idx, 0), m_OrganizerCore.modList()->index(row_idx, m_OrganizerCore.modList()->columnCount() - 1)); + } + } else { + ModInfo::Ptr info = ModInfo::getByIndex(m_ContextRow); + info->markConverted(true); + connect(this, SIGNAL(modListDataChanged(QModelIndex, QModelIndex)), m_OrganizerCore.modList(), SIGNAL(dataChanged(QModelIndex, QModelIndex))); + emit modListDataChanged(m_OrganizerCore.modList()->index(m_ContextRow, 0), m_OrganizerCore.modList()->index(m_ContextRow, m_OrganizerCore.modList()->columnCount() - 1)); + } +} + + +void MainWindow::visitOnNexus_clicked() +{ + QItemSelectionModel *selection = ui->modList->selectionModel(); + if (selection->hasSelection() && selection->selectedRows().count() > 1) { + int count = selection->selectedRows().count(); + if (count > 10) { + if (QMessageBox::question(this, tr("Opening Nexus Links"), + tr("You are trying to open %1 links to Nexus Mods. Are you sure you want to do this?").arg(count), + QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) { + return; + } + } + int row_idx; + ModInfo::Ptr info; + QString gameName; + QString webUrl; + for (QModelIndex idx : selection->selectedRows()) { + row_idx = idx.data(Qt::UserRole + 1).toInt(); + info = ModInfo::getByIndex(row_idx); + int modID = info->getNexusID(); + webUrl = info->getURL(); + gameName = info->getGameName(); + if (modID > 0) { + linkClicked(NexusInterface::instance(&m_PluginContainer)->getModURL(modID, gameName)); + } + else if (webUrl != "") { + linkClicked(webUrl); + } + } + } + else { + int modID = m_OrganizerCore.modList()->data(m_OrganizerCore.modList()->index(m_ContextRow, 0), Qt::UserRole).toInt(); + QString gameName = m_OrganizerCore.modList()->data(m_OrganizerCore.modList()->index(m_ContextRow, 0), Qt::UserRole + 4).toString(); + if (modID > 0) { + linkClicked(NexusInterface::instance(&m_PluginContainer)->getModURL(modID, gameName)); + } else { + MessageDialog::showMessage(tr("Nexus ID for this Mod is unknown"), this); + } + } +} + +void MainWindow::visitWebPage_clicked() +{ + + QItemSelectionModel *selection = ui->modList->selectionModel(); + if (selection->hasSelection() && selection->selectedRows().count() > 1) { + int count = selection->selectedRows().count(); + if (count > 10) { + if (QMessageBox::question(this, tr("Opening Web Pages"), + tr("You are trying to open %1 Web Pages. Are you sure you want to do this?").arg(count), + QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) { + return; + } + } + int row_idx; + ModInfo::Ptr info; + QString gameName; + QString webUrl; + for (QModelIndex idx : selection->selectedRows()) { + row_idx = idx.data(Qt::UserRole + 1).toInt(); + info = ModInfo::getByIndex(row_idx); + int modID = info->getNexusID(); + webUrl = info->getURL(); + gameName = info->getGameName(); + if (modID > 0) { + linkClicked(NexusInterface::instance(&m_PluginContainer)->getModURL(modID, gameName)); + } + else if (webUrl != "") { + linkClicked(webUrl); + } + } + } + else { + ModInfo::Ptr info = ModInfo::getByIndex(m_ContextRow); + if (info->getURL() != "") { + linkClicked(info->getURL()); + } + else { + MessageDialog::showMessage(tr("Web page for this mod is unknown"), this); + } + } +} + +void MainWindow::openExplorer_clicked() +{ + QItemSelectionModel *selection = ui->modList->selectionModel(); + if (selection->hasSelection() && selection->selectedRows().count() > 1) { + for (QModelIndex idx : selection->selectedRows()) { + ModInfo::Ptr info = ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt()); + ::ShellExecuteW(nullptr, L"explore", ToWString(info->absolutePath()).c_str(), nullptr, nullptr, SW_SHOWNORMAL); + } + } + else { + ModInfo::Ptr modInfo = ModInfo::getByIndex(m_ContextRow); + ::ShellExecuteW(nullptr, L"explore", ToWString(modInfo->absolutePath()).c_str(), nullptr, nullptr, SW_SHOWNORMAL); + } +} + +void MainWindow::openOriginExplorer_clicked() +{ + QItemSelectionModel *selection = ui->espList->selectionModel(); + if (selection->hasSelection() && selection->selectedRows().count() > 0) { + for (QModelIndex idx : selection->selectedRows()) { + QString fileName = idx.data().toString(); + unsigned int modIndex = ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(fileName)); + if (modIndex == UINT_MAX) { + continue; + } + ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); + std::vector flags = modInfo->getFlags(); + + ::ShellExecuteW(nullptr, L"explore", ToWString(modInfo->absolutePath()).c_str(), nullptr, nullptr, SW_SHOWNORMAL); + } + } + else { + QModelIndex idx = selection->currentIndex(); + QString fileName = idx.data().toString(); + ModInfo::Ptr modInfo = ModInfo::getByIndex(ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(fileName))); + std::vector flags = modInfo->getFlags(); + + ::ShellExecuteW(nullptr, L"explore", ToWString(modInfo->absolutePath()).c_str(), nullptr, nullptr, SW_SHOWNORMAL); + } +} + +void MainWindow::openExplorer_activated() +{ + if (ui->modList->hasFocus()) { + QItemSelectionModel *selection = ui->modList->selectionModel(); + if (selection->hasSelection() && selection->selectedRows().count() == 1 ) { + + QModelIndex idx = selection->currentIndex(); + ModInfo::Ptr modInfo = ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt()); + std::vector flags = modInfo->getFlags(); + + if (modInfo->isRegular() || (std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end())) { + ::ShellExecuteW(nullptr, L"explore", ToWString(modInfo->absolutePath()).c_str(), nullptr, nullptr, SW_SHOWNORMAL); + } + + } + } + + if (ui->espList->hasFocus()) { + QItemSelectionModel *selection = ui->espList->selectionModel(); + + if (selection->hasSelection() && selection->selectedRows().count() == 1) { + + QModelIndex idx = selection->currentIndex(); + QString fileName = idx.data().toString(); + + + unsigned int modInfoIndex = ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(fileName)); + if (modInfoIndex != UINT_MAX) { + ModInfo::Ptr modInfo = ModInfo::getByIndex(modInfoIndex); + std::vector flags = modInfo->getFlags(); + + if (modInfo->isRegular() || (std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end())) { + ::ShellExecuteW(nullptr, L"explore", ToWString(modInfo->absolutePath()).c_str(), nullptr, nullptr, SW_SHOWNORMAL); + } + } + } + } +} + +void MainWindow::refreshProfile_activated() +{ + m_OrganizerCore.profileRefresh(); +} + +void MainWindow::search_activated() +{ + if (ui->modList->hasFocus() || ui->modFilterEdit->hasFocus()) { + ui->modFilterEdit->setFocus(); + ui->modFilterEdit->setSelection(0, INT_MAX); + } + + else if (ui->espList->hasFocus() || ui->espFilterEdit->hasFocus()) { + ui->espFilterEdit->setFocus(); + ui->espFilterEdit->setSelection(0, INT_MAX); + } + + else if (ui->downloadView->hasFocus() || ui->downloadFilterEdit->hasFocus()) { + ui->downloadFilterEdit->setFocus(); + ui->downloadFilterEdit->setSelection(0, INT_MAX); + } +} + +void MainWindow::searchClear_activated() +{ + if (ui->modList->hasFocus() || ui->modFilterEdit->hasFocus()) { + ui->modFilterEdit->clear(); + ui->modList->setFocus(); + } + + else if (ui->espList->hasFocus() || ui->espFilterEdit->hasFocus()) { + ui->espFilterEdit->clear(); + ui->espList->setFocus(); + } + + else if (ui->downloadView->hasFocus() || ui->downloadFilterEdit->hasFocus()) { + ui->downloadFilterEdit->clear(); + ui->downloadView->setFocus(); + } +} + +void MainWindow::updateModCount() +{ + int activeCount = 0; + int visActiveCount = 0; + int backupCount = 0; + int visBackupCount = 0; + int foreignCount = 0; + int visForeignCount = 0; + int separatorCount = 0; + int visSeparatorCount = 0; + int regularCount = 0; + int visRegularCount = 0; + + QStringList allMods = m_OrganizerCore.modList()->allMods(); + + auto hasFlag = [](std::vector flags, ModInfo::EFlag filter) { + return std::find(flags.begin(), flags.end(), filter) != flags.end(); + }; + + bool isEnabled; + bool isVisible; + for (QString mod : allMods) { + int modIndex = ModInfo::getIndex(mod); + ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); + std::vector modFlags = modInfo->getFlags(); + isEnabled = m_OrganizerCore.currentProfile()->modEnabled(modIndex); + isVisible = m_ModListSortProxy->filterMatchesMod(modInfo, isEnabled); + + for (auto flag : modFlags) { + switch (flag) { + case ModInfo::FLAG_BACKUP: backupCount++; + if (isVisible) + visBackupCount++; + break; + case ModInfo::FLAG_FOREIGN: foreignCount++; + if (isVisible) + visForeignCount++; + break; + case ModInfo::FLAG_SEPARATOR: separatorCount++; + if (isVisible) + visSeparatorCount++; + break; + } + } + + if (!hasFlag(modFlags, ModInfo::FLAG_BACKUP) && + !hasFlag(modFlags, ModInfo::FLAG_FOREIGN) && + !hasFlag(modFlags, ModInfo::FLAG_SEPARATOR) && + !hasFlag(modFlags, ModInfo::FLAG_OVERWRITE)) { + if (isEnabled) { + activeCount++; + if (isVisible) + visActiveCount++; + } + if (isVisible) + visRegularCount++; + regularCount++; + } + } + + ui->activeModsCounter->display(visActiveCount); + ui->activeModsCounter->setToolTip(tr("" + "" + "" + "" + "" + "" + "
    TypeAllVisible
    Enabled mods: %1 / %2%3 / %4
    Unmanaged/DLCs: %5%6
    Mod backups: %7%8
    Separators: %9%10
    ") + .arg(activeCount) + .arg(regularCount) + .arg(visActiveCount) + .arg(visRegularCount) + .arg(foreignCount) + .arg(visForeignCount) + .arg(backupCount) + .arg(visBackupCount) + .arg(separatorCount) + .arg(visSeparatorCount) + ); +} + +void MainWindow::updatePluginCount() +{ + int activeMasterCount = 0; + int activeLightMasterCount = 0; + int activeRegularCount = 0; + int masterCount = 0; + int lightMasterCount = 0; + int regularCount = 0; + int activeVisibleCount = 0; + + PluginList *list = m_OrganizerCore.pluginList(); + QString filter = ui->espFilterEdit->text(); + + for (QString plugin : list->pluginNames()) { + bool active = list->isEnabled(plugin); + bool visible = m_PluginListSortProxy->filterMatchesPlugin(plugin); + if (list->isLight(plugin) || list->isLightFlagged(plugin)) { + lightMasterCount++; + activeLightMasterCount += active; + activeVisibleCount += visible && active; + } else if (list->isMaster(plugin)) { + masterCount++; + activeMasterCount += active; + activeVisibleCount += visible && active; + } else { + regularCount++; + activeRegularCount += active; + activeVisibleCount += visible && active; + } + } + + int activeCount = activeMasterCount + activeLightMasterCount + activeRegularCount; + int totalCount = masterCount + lightMasterCount + regularCount; + + ui->activePluginsCounter->display(activeVisibleCount); + ui->activePluginsCounter->setToolTip(tr("" + "" + "" + "" + "" + "" + "" + "
    TypeActive Total
    All plugins:%1 %2
    ESMs:%3 %4
    ESPs:%7 %8
    ESMs+ESPs:%9 %10
    ESLs:%5 %6
    ") + .arg(activeCount).arg(totalCount) + .arg(activeMasterCount).arg(masterCount) + .arg(activeLightMasterCount).arg(lightMasterCount) + .arg(activeRegularCount).arg(regularCount) + .arg(activeMasterCount+activeRegularCount).arg(masterCount+regularCount) + ); +} + +void MainWindow::information_clicked() +{ + try { + displayModInformation(m_ContextRow); + } catch (const std::exception &e) { + reportError(e.what()); + } +} + +void MainWindow::createEmptyMod_clicked() +{ + GuessedValue name; + name.setFilter(&fixDirectoryName); + + while (name->isEmpty()) { + bool ok; + name.update(QInputDialog::getText(this, tr("Create Mod..."), + tr("This will create an empty mod.\n" + "Please enter a name:"), QLineEdit::Normal, "", &ok), + GUESS_USER); + if (!ok) { + return; + } + } + + if (m_OrganizerCore.getMod(name) != nullptr) { + reportError(tr("A mod with this name already exists")); + return; + } + + int newPriority = -1; + if (m_ContextRow >= 0 && m_ModListSortProxy->sortColumn() == ModList::COL_PRIORITY) { + newPriority = m_OrganizerCore.currentProfile()->getModPriority(m_ContextRow); + } + + IModInterface *newMod = m_OrganizerCore.createMod(name); + if (newMod == nullptr) { + return; + } + + m_OrganizerCore.refreshModList(); + + if (newPriority >= 0) { + m_OrganizerCore.modList()->changeModPriority(ModInfo::getIndex(name), newPriority); + } +} + +void MainWindow::createSeparator_clicked() +{ + GuessedValue name; + name.setFilter(&fixDirectoryName); + while (name->isEmpty()) + { + bool ok; + name.update(QInputDialog::getText(this, tr("Create Separator..."), + tr("This will create a new separator.\n" + "Please enter a name:"), QLineEdit::Normal, "", &ok), + GUESS_USER); + if (!ok) { return; } + } + if (m_OrganizerCore.getMod(name) != nullptr) + { + reportError(tr("A separator with this name already exists")); + return; + } + name->append("_separator"); + if (m_OrganizerCore.getMod(name) != nullptr) + { + return; + } + + int newPriority = -1; + if (m_ContextRow >= 0 && m_ModListSortProxy->sortColumn() == ModList::COL_PRIORITY) + { + newPriority = m_OrganizerCore.currentProfile()->getModPriority(m_ContextRow); + } + + if (m_OrganizerCore.createMod(name) == nullptr) { return; } + m_OrganizerCore.refreshModList(); + + if (newPriority >= 0) + { + m_OrganizerCore.modList()->changeModPriority(ModInfo::getIndex(name), newPriority); + } + QSettings &settings = m_OrganizerCore.settings().directInterface(); + QColor previousColor = settings.value("previousSeparatorColor", QColor()).value(); + if (previousColor.isValid()) { + ModInfo::getByIndex(ModInfo::getIndex(name))->setColor(previousColor); + } + +} + +void MainWindow::setColor_clicked() +{ + QSettings &settings = m_OrganizerCore.settings().directInterface(); + ModInfo::Ptr modInfo = ModInfo::getByIndex(m_ContextRow); + QColorDialog dialog(this); + dialog.setOption(QColorDialog::ShowAlphaChannel); + QColor currentColor = modInfo->getColor(); + QColor previousColor = settings.value("previousSeparatorColor", QColor()).value(); + if (currentColor.isValid()) + dialog.setCurrentColor(currentColor); + else + dialog.setCurrentColor(previousColor); + if (!dialog.exec()) + return; + currentColor = dialog.currentColor(); + if (!currentColor.isValid()) + return; + settings.setValue("previousSeparatorColor", currentColor); + QItemSelectionModel *selection = ui->modList->selectionModel(); + if (selection->hasSelection() && selection->selectedRows().count() > 1) { + for (QModelIndex idx : selection->selectedRows()) { + ModInfo::Ptr info = ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt()); + auto flags = info->getFlags(); + if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_SEPARATOR) != flags.end()) + { + info->setColor(currentColor); + } + } + } + else { + modInfo->setColor(currentColor); + } +} + +void MainWindow::resetColor_clicked() +{ + ModInfo::Ptr modInfo = ModInfo::getByIndex(m_ContextRow); + QColor color = QColor(); + QItemSelectionModel *selection = ui->modList->selectionModel(); + if (selection->hasSelection() && selection->selectedRows().count() > 1) { + for (QModelIndex idx : selection->selectedRows()) { + ModInfo::Ptr info = ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt()); + auto flags = info->getFlags(); + if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_SEPARATOR) != flags.end()) + { + info->setColor(color); + } + } + } + else { + modInfo->setColor(color); + } + Settings::instance().directInterface().remove("previousSeparatorColor"); +} + +void MainWindow::createModFromOverwrite() +{ + GuessedValue name; + name.setFilter(&fixDirectoryName); + + while (name->isEmpty()) { + bool ok; + name.update(QInputDialog::getText(this, tr("Create Mod..."), + tr("This will move all files from overwrite into a new, regular mod.\n" + "Please enter a name:"), QLineEdit::Normal, "", &ok), + GUESS_USER); + if (!ok) { + return; + } + } + + if (m_OrganizerCore.getMod(name) != nullptr) { + reportError(tr("A mod with this name already exists")); + return; + } + + const IModInterface *newMod = m_OrganizerCore.createMod(name); + if (newMod == nullptr) { + return; + } + + doMoveOverwriteContentToMod(newMod->absolutePath()); +} + +void MainWindow::moveOverwriteContentToExistingMod() +{ + QStringList mods; + auto indexesByPriority = m_OrganizerCore.currentProfile()->getAllIndexesByPriority(); + for (auto & iter : indexesByPriority) { + if ((iter.second != UINT_MAX)) { + ModInfo::Ptr modInfo = ModInfo::getByIndex(iter.second); + if (!modInfo->hasFlag(ModInfo::FLAG_SEPARATOR) && !modInfo->hasFlag(ModInfo::FLAG_FOREIGN) && !modInfo->hasFlag(ModInfo::FLAG_OVERWRITE)) { + mods << modInfo->name(); + } + } + } + + ListDialog dialog(this); + QSettings &settings = m_OrganizerCore.settings().directInterface(); + QString key = QString("geometry/%1").arg(dialog.objectName()); + + dialog.setWindowTitle("Select a mod..."); + dialog.setChoices(mods); + + if (settings.contains(key)) { + dialog.restoreGeometry(settings.value(key).toByteArray()); + } + if (dialog.exec() == QDialog::Accepted) { + + QString result = dialog.getChoice(); + if (!result.isEmpty()) { + + QString modAbsolutePath; + + for (const auto& mod : m_OrganizerCore.modsSortedByProfilePriority()) { + if (result.compare(mod) == 0) { + ModInfo::Ptr modInfo = ModInfo::getByIndex(ModInfo::getIndex(mod)); + modAbsolutePath = modInfo->absolutePath(); + break; + } + } + + if (modAbsolutePath.isNull()) { + qWarning("Mod %s has not been found, for some reason", qUtf8Printable(result)); + return; + } + + doMoveOverwriteContentToMod(modAbsolutePath); + } + } + settings.setValue(key, dialog.saveGeometry()); +} + +void MainWindow::doMoveOverwriteContentToMod(const QString &modAbsolutePath) +{ + unsigned int overwriteIndex = ModInfo::findMod([](ModInfo::Ptr mod) -> bool { + std::vector flags = mod->getFlags(); + return std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end(); }); + + ModInfo::Ptr overwriteInfo = ModInfo::getByIndex(overwriteIndex); + bool successful = shellMove((QDir::toNativeSeparators(overwriteInfo->absolutePath()) + "\\*"), + (QDir::toNativeSeparators(modAbsolutePath)), false, this); + + if (successful) { + MessageDialog::showMessage(tr("Move successful."), this); + } + else { + qCritical("Move operation failed: %s", qUtf8Printable(windowsErrorString(::GetLastError()))); + } + + m_OrganizerCore.refreshModList(); +} + +void MainWindow::clearOverwrite() +{ + unsigned int overwriteIndex = ModInfo::findMod([](ModInfo::Ptr mod) -> bool { + std::vector flags = mod->getFlags(); + return std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) + != flags.end(); + }); + + ModInfo::Ptr modInfo = ModInfo::getByIndex(overwriteIndex); + if (modInfo) + { + QDir overwriteDir(modInfo->absolutePath()); + if (QMessageBox::question(this, tr("Are you sure?"), + tr("About to recursively delete:\n") + overwriteDir.absolutePath(), + QMessageBox::Ok | QMessageBox::Cancel) == QMessageBox::Ok) + { + QStringList delList; + for (auto f : overwriteDir.entryList(QDir::AllDirs | QDir::Files | QDir::NoDotAndDotDot)) + delList.push_back(overwriteDir.absoluteFilePath(f)); + shellDelete(delList, true); + updateProblemsButton(); + } + } +} + +void MainWindow::cancelModListEditor() +{ + ui->modList->setEnabled(false); + ui->modList->setEnabled(true); +} + +void MainWindow::on_modList_doubleClicked(const QModelIndex &index) +{ + if (!index.isValid()) { + return; + } + + if (m_OrganizerCore.modList()->timeElapsedSinceLastChecked() <= QApplication::doubleClickInterval()) { + // don't interpret double click if we only just checked a mod + return; + } + + QModelIndex sourceIdx = mapToModel(m_OrganizerCore.modList(), index); + if (!sourceIdx.isValid()) { + return; + } + + Qt::KeyboardModifiers modifiers = QApplication::queryKeyboardModifiers(); + if (modifiers.testFlag(Qt::ControlModifier)) { + try { + m_ContextRow = m_ModListSortProxy->mapToSource(index).row(); + openExplorer_clicked(); + // workaround to cancel the editor that might have opened because of + // selection-click + ui->modList->closePersistentEditor(index); + } + catch (const std::exception &e) { + reportError(e.what()); + } + } + else { + try { + m_ContextRow = m_ModListSortProxy->mapToSource(index).row(); + sourceIdx.column(); + int tab = -1; + switch (sourceIdx.column()) { + case ModList::COL_NOTES: tab = ModInfoDialog::TAB_NOTES; break; + case ModList::COL_VERSION: tab = ModInfoDialog::TAB_NEXUS; break; + case ModList::COL_MODID: tab = ModInfoDialog::TAB_NEXUS; break; + case ModList::COL_GAME: tab = ModInfoDialog::TAB_NEXUS; break; + case ModList::COL_CATEGORY: tab = ModInfoDialog::TAB_CATEGORIES; break; + case ModList::COL_FLAGS: tab = ModInfoDialog::TAB_CONFLICTS; break; + default: tab = -1; + } + displayModInformation(sourceIdx.row(), tab); + // workaround to cancel the editor that might have opened because of + // selection-click + ui->modList->closePersistentEditor(index); + } + catch (const std::exception &e) { + reportError(e.what()); + } + } +} + +void MainWindow::on_listOptionsBtn_pressed() +{ + m_ContextRow = -1; +} + +void MainWindow::openOriginInformation_clicked() +{ + try { + QItemSelectionModel *selection = ui->espList->selectionModel(); + //we don't want to open multiple modinfodialogs. + /*if (selection->hasSelection() && selection->selectedRows().count() > 0) { + + for (QModelIndex idx : selection->selectedRows()) { + QString fileName = idx.data().toString(); + ModInfo::Ptr modInfo = ModInfo::getByIndex(ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(fileName))); + std::vector flags = modInfo->getFlags(); + + if (modInfo->isRegular() || (std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end())) { + displayModInformation(ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(fileName))); + } + } + } + else {}*/ + QModelIndex idx = selection->currentIndex(); + QString fileName = idx.data().toString(); + + ModInfo::Ptr modInfo = ModInfo::getByIndex(ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(fileName))); + std::vector flags = modInfo->getFlags(); + + if (modInfo->isRegular() || (std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end())) { + displayModInformation(ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(fileName))); + } + } + catch (const std::exception &e) { + reportError(e.what()); + } +} + +void MainWindow::on_espList_doubleClicked(const QModelIndex &index) +{ + if (!index.isValid()) { + return; + } + + if (m_OrganizerCore.pluginList()->timeElapsedSinceLastChecked() <= QApplication::doubleClickInterval()) { + // don't interpret double click if we only just checked a plugin + return; + } + + QModelIndex sourceIdx = mapToModel(m_OrganizerCore.pluginList(), index); + if (!sourceIdx.isValid()) { + return; + } + try { + + QItemSelectionModel *selection = ui->espList->selectionModel(); + + if (selection->hasSelection() && selection->selectedRows().count() == 1) { + + QModelIndex idx = selection->currentIndex(); + QString fileName = idx.data().toString(); + + if (ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(fileName)) == UINT_MAX) + return; + + ModInfo::Ptr modInfo = ModInfo::getByIndex(ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(fileName))); + std::vector flags = modInfo->getFlags(); + + if (modInfo->isRegular() || (std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end())) { + + Qt::KeyboardModifiers modifiers = QApplication::queryKeyboardModifiers(); + if (modifiers.testFlag(Qt::ControlModifier)) { + openExplorer_activated(); + // workaround to cancel the editor that might have opened because of + // selection-click + ui->espList->closePersistentEditor(index); + } + else { + + displayModInformation(ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(fileName))); + // workaround to cancel the editor that might have opened because of + // selection-click + ui->espList->closePersistentEditor(index); + } + } + } + } + catch (const std::exception &e) { + reportError(e.what()); + } +} + +bool MainWindow::populateMenuCategories(QMenu *menu, int targetID) +{ + ModInfo::Ptr modInfo = ModInfo::getByIndex(m_ContextRow); + const std::set &categories = modInfo->getCategories(); + + bool childEnabled = false; + + for (unsigned int i = 1; i < m_CategoryFactory.numCategories(); ++i) { + if (m_CategoryFactory.getParentID(i) == targetID) { + QMenu *targetMenu = menu; + if (m_CategoryFactory.hasChildren(i)) { + targetMenu = menu->addMenu(m_CategoryFactory.getCategoryName(i).replace('&', "&&")); + } + + int id = m_CategoryFactory.getCategoryID(i); + QScopedPointer checkBox(new QCheckBox(targetMenu)); + bool enabled = categories.find(id) != categories.end(); + checkBox->setText(m_CategoryFactory.getCategoryName(i).replace('&', "&&")); + if (enabled) { + childEnabled = true; + } + checkBox->setChecked(enabled ? Qt::Checked : Qt::Unchecked); + + QScopedPointer checkableAction(new QWidgetAction(targetMenu)); + checkableAction->setDefaultWidget(checkBox.take()); + checkableAction->setData(id); + targetMenu->addAction(checkableAction.take()); + + if (m_CategoryFactory.hasChildren(i)) { + if (populateMenuCategories(targetMenu, m_CategoryFactory.getCategoryID(i)) || enabled) { + targetMenu->setIcon(QIcon(":/MO/gui/resources/check.png")); + } + } + } + } + return childEnabled; +} + +void MainWindow::replaceCategoriesFromMenu(QMenu *menu, int modRow) +{ + ModInfo::Ptr modInfo = ModInfo::getByIndex(modRow); + for (QAction* action : menu->actions()) { + if (action->menu() != nullptr) { + replaceCategoriesFromMenu(action->menu(), modRow); + } else { + QWidgetAction *widgetAction = qobject_cast(action); + if (widgetAction != nullptr) { + QCheckBox *checkbox = qobject_cast(widgetAction->defaultWidget()); + modInfo->setCategory(widgetAction->data().toInt(), checkbox->isChecked()); + } + } + } +} + +void MainWindow::addRemoveCategoriesFromMenu(QMenu *menu, int modRow, int referenceRow) +{ + if (referenceRow != -1 && referenceRow != modRow) { + ModInfo::Ptr editedModInfo = ModInfo::getByIndex(referenceRow); + for (QAction* action : menu->actions()) { + if (action->menu() != nullptr) { + addRemoveCategoriesFromMenu(action->menu(), modRow, referenceRow); + } else { + QWidgetAction *widgetAction = qobject_cast(action); + if (widgetAction != nullptr) { + QCheckBox *checkbox = qobject_cast(widgetAction->defaultWidget()); + int categoryId = widgetAction->data().toInt(); + bool checkedBefore = editedModInfo->categorySet(categoryId); + bool checkedAfter = checkbox->isChecked(); + + if (checkedBefore != checkedAfter) { // only update if the category was changed on the edited mod + ModInfo::Ptr currentModInfo = ModInfo::getByIndex(modRow); + currentModInfo->setCategory(categoryId, checkedAfter); + } + } + } + } + } else { + replaceCategoriesFromMenu(menu, modRow); + } +} + +void MainWindow::addRemoveCategories_MenuHandler() { + QMenu *menu = qobject_cast(sender()); + if (menu == nullptr) { + qCritical("not a menu?"); + return; + } + + QList selected; + for (const QModelIndex &idx : ui->modList->selectionModel()->selectedRows()) { + selected.append(QPersistentModelIndex(idx)); + } + + if (selected.size() > 0) { + int minRow = INT_MAX; + int maxRow = -1; + + for (const QPersistentModelIndex &idx : selected) { + qDebug("change categories on: %s", qUtf8Printable(idx.data().toString())); + QModelIndex modIdx = mapToModel(m_OrganizerCore.modList(), idx); + if (modIdx.row() != m_ContextIdx.row()) { + addRemoveCategoriesFromMenu(menu, modIdx.row(), m_ContextIdx.row()); + } + if (idx.row() < minRow) minRow = idx.row(); + if (idx.row() > maxRow) maxRow = idx.row(); + } + replaceCategoriesFromMenu(menu, m_ContextIdx.row()); + + m_OrganizerCore.modList()->notifyChange(minRow, maxRow + 1); + + for (const QPersistentModelIndex &idx : selected) { + ui->modList->selectionModel()->select(idx, QItemSelectionModel::Select | QItemSelectionModel::Rows); + } + } else { + //For single mod selections, just do a replace + replaceCategoriesFromMenu(menu, m_ContextRow); + m_OrganizerCore.modList()->notifyChange(m_ContextRow); + } + + refreshFilters(); +} + +void MainWindow::replaceCategories_MenuHandler() { + QMenu *menu = qobject_cast(sender()); + if (menu == nullptr) { + qCritical("not a menu?"); + return; + } + + QList selected; + for (const QModelIndex &idx : ui->modList->selectionModel()->selectedRows()) { + selected.append(QPersistentModelIndex(idx)); + } + + if (selected.size() > 0) { + QStringList selectedMods; + int minRow = INT_MAX; + int maxRow = -1; + for (int i = 0; i < selected.size(); ++i) { + QModelIndex temp = mapToModel(m_OrganizerCore.modList(), selected.at(i)); + selectedMods.append(temp.data().toString()); + replaceCategoriesFromMenu(menu, mapToModel(m_OrganizerCore.modList(), selected.at(i)).row()); + if (temp.row() < minRow) minRow = temp.row(); + if (temp.row() > maxRow) maxRow = temp.row(); + } + + m_OrganizerCore.modList()->notifyChange(minRow, maxRow + 1); + + // find mods by their name because indices are invalidated + QAbstractItemModel *model = ui->modList->model(); + for (const QString &mod : selectedMods) { + QModelIndexList matches = model->match(model->index(0, 0), Qt::DisplayRole, mod, 1, + Qt::MatchFixedString | Qt::MatchCaseSensitive | Qt::MatchRecursive); + if (matches.size() > 0) { + ui->modList->selectionModel()->select(matches.at(0), QItemSelectionModel::Select | QItemSelectionModel::Rows); + } + } + } else { + //For single mod selections, just do a replace + replaceCategoriesFromMenu(menu, m_ContextRow); + m_OrganizerCore.modList()->notifyChange(m_ContextRow); + } + + refreshFilters(); +} + +void MainWindow::saveArchiveList() +{ + if (m_OrganizerCore.isArchivesInit()) { + SafeWriteFile archiveFile(m_OrganizerCore.currentProfile()->getArchivesFileName()); + for (int i = 0; i < ui->bsaList->topLevelItemCount(); ++i) { + QTreeWidgetItem * tlItem = ui->bsaList->topLevelItem(i); + for (int j = 0; j < tlItem->childCount(); ++j) { + QTreeWidgetItem * item = tlItem->child(j); + if (item->checkState(0) == Qt::Checked) { + archiveFile->write(item->text(0).toUtf8().append("\r\n")); + } + } + } + if (archiveFile.commitIfDifferent(m_ArchiveListHash)) { + qDebug("%s saved", qUtf8Printable(QDir::toNativeSeparators(m_OrganizerCore.currentProfile()->getArchivesFileName()))); + } + } else { + qWarning("archive list not initialised"); + } +} + +void MainWindow::checkModsForUpdates() +{ + statusBar()->show(); + if (NexusInterface::instance(&m_PluginContainer)->getAccessManager()->validated()) { + m_ModsToUpdate = ModInfo::checkAllForUpdate(&m_PluginContainer, this); + m_RefreshProgress->setRange(0, m_ModsToUpdate); + } else { + QString apiKey; + if (m_OrganizerCore.settings().getNexusApiKey(apiKey)) { + m_OrganizerCore.doAfterLogin([this] () { this->checkModsForUpdates(); }); + NexusInterface::instance(&m_PluginContainer)->getAccessManager()->apiCheck(apiKey); + } else { // otherwise there will be no endorsement info + MessageDialog::showMessage(tr("Not logged in, endorsement information will be wrong"), + this, true); + m_ModsToUpdate = ModInfo::checkAllForUpdate(&m_PluginContainer, this); + } + } +} + +void MainWindow::changeVersioningScheme() { + if (QMessageBox::question(this, tr("Continue?"), + tr("The versioning scheme decides which version is considered newer than another.\n" + "This function will guess the versioning scheme under the assumption that the installed version is outdated."), + QMessageBox::Yes | QMessageBox::Cancel) == QMessageBox::Yes) { + + ModInfo::Ptr info = ModInfo::getByIndex(m_ContextRow); + + bool success = false; + + static VersionInfo::VersionScheme schemes[] = { VersionInfo::SCHEME_REGULAR, VersionInfo::SCHEME_DECIMALMARK, VersionInfo::SCHEME_NUMBERSANDLETTERS }; + + for (int i = 0; i < sizeof(schemes) / sizeof(VersionInfo::VersionScheme) && !success; ++i) { + VersionInfo verOld(info->getVersion().canonicalString(), schemes[i]); + VersionInfo verNew(info->getNewestVersion().canonicalString(), schemes[i]); + if (verOld < verNew) { + info->setVersion(verOld); + info->setNewestVersion(verNew); + success = true; + } + } + if (!success) { + QMessageBox::information(this, tr("Sorry"), + tr("I don't know a versioning scheme where %1 is newer than %2.").arg(info->getNewestVersion().canonicalString()).arg(info->getVersion().canonicalString()), + QMessageBox::Ok); + } + } +} + +void MainWindow::ignoreUpdate() { + QItemSelectionModel *selection = ui->modList->selectionModel(); + if (selection->hasSelection() && selection->selectedRows().count() > 1) { + for (QModelIndex idx : selection->selectedRows()) { + ModInfo::Ptr info = ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt()); + info->ignoreUpdate(true); + } + } + else { + ModInfo::Ptr info = ModInfo::getByIndex(m_ContextRow); + info->ignoreUpdate(true); + } + if (m_ModListSortProxy != nullptr) { + m_ModListSortProxy->invalidate(); + } +} + +void MainWindow::unignoreUpdate() +{ + QItemSelectionModel *selection = ui->modList->selectionModel(); + if (selection->hasSelection() && selection->selectedRows().count() > 1) { + for (QModelIndex idx : selection->selectedRows()) { + ModInfo::Ptr info = ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt()); + info->ignoreUpdate(false); + } + } + else { + ModInfo::Ptr info = ModInfo::getByIndex(m_ContextRow); + info->ignoreUpdate(false); + } + if (m_ModListSortProxy != nullptr) { + m_ModListSortProxy->invalidate(); + } +} + +void MainWindow::addPrimaryCategoryCandidates(QMenu *primaryCategoryMenu, + ModInfo::Ptr info) { + const std::set &categories = info->getCategories(); + for (int categoryID : categories) { + int catIdx = m_CategoryFactory.getCategoryIndex(categoryID); + QWidgetAction *action = new QWidgetAction(primaryCategoryMenu); + try { + QRadioButton *categoryBox = new QRadioButton( + m_CategoryFactory.getCategoryName(catIdx).replace('&', "&&"), + primaryCategoryMenu); + connect(categoryBox, &QRadioButton::toggled, [info, categoryID](bool enable) { + if (enable) { + info->setPrimaryCategory(categoryID); + } + }); + categoryBox->setChecked(categoryID == info->getPrimaryCategory()); + action->setDefaultWidget(categoryBox); + } catch (const std::exception &e) { + qCritical("failed to create category checkbox: %s", e.what()); + } + + action->setData(categoryID); + primaryCategoryMenu->addAction(action); + } +} + +void MainWindow::addPrimaryCategoryCandidates() +{ + QMenu *menu = qobject_cast(sender()); + if (menu == nullptr) { + qCritical("not a menu?"); + return; + } + menu->clear(); + ModInfo::Ptr modInfo = ModInfo::getByIndex(m_ContextRow); + + addPrimaryCategoryCandidates(menu, modInfo); +} + +void MainWindow::enableVisibleMods() +{ + if (QMessageBox::question(nullptr, tr("Confirm"), tr("Really enable all visible mods?"), + QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { + m_ModListSortProxy->enableAllVisible(); + } +} + +void MainWindow::disableVisibleMods() +{ + if (QMessageBox::question(nullptr, tr("Confirm"), tr("Really disable all visible mods?"), + QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { + m_ModListSortProxy->disableAllVisible(); + } +} + +void MainWindow::openInstanceFolder() +{ + QString dataPath = qApp->property("dataPath").toString(); + ::ShellExecuteW(nullptr, L"explore", ToWString(dataPath).c_str(), nullptr, nullptr, SW_SHOWNORMAL); + + //opens BaseDirectory instead + //::ShellExecuteW(nullptr, L"explore", ToWString(m_OrganizerCore.settings().getBaseDirectory()).c_str(), nullptr, nullptr, SW_SHOWNORMAL); +} + +void MainWindow::openLogsFolder() +{ + QString logsPath = qApp->property("dataPath").toString() + "/" + QString::fromStdWString(AppConfig::logPath()); + ::ShellExecuteW(nullptr, L"explore", ToWString(logsPath).c_str(), nullptr, nullptr, SW_SHOWNORMAL); +} + +void MainWindow::openInstallFolder() +{ + ::ShellExecuteW(nullptr, L"explore", ToWString(qApp->applicationDirPath()).c_str(), nullptr, nullptr, SW_SHOWNORMAL); +} + +void MainWindow::openPluginsFolder() +{ + QString pluginsPath = QCoreApplication::applicationDirPath() + "/" + ToQString(AppConfig::pluginPath()); + ::ShellExecuteW(nullptr, L"explore", ToWString(pluginsPath).c_str(), nullptr, nullptr, SW_SHOWNORMAL); +} + + +void MainWindow::openProfileFolder() +{ + ::ShellExecuteW(nullptr, L"explore", ToWString(m_OrganizerCore.currentProfile()->absolutePath()).c_str(), nullptr, nullptr, SW_SHOWNORMAL); +} + +void MainWindow::openIniFolder() +{ + if (m_OrganizerCore.currentProfile()->localSettingsEnabled()) + { + ::ShellExecuteW(nullptr, L"explore", ToWString(m_OrganizerCore.currentProfile()->absolutePath()).c_str(), nullptr, nullptr, SW_SHOWNORMAL); + } + else { + ::ShellExecuteW(nullptr, L"explore", ToWString(m_OrganizerCore.managedGame()->documentsDirectory().absolutePath()).c_str(), nullptr, nullptr, SW_SHOWNORMAL); + } +} + +void MainWindow::openDownloadsFolder() +{ + ::ShellExecuteW(nullptr, L"explore", ToWString(m_OrganizerCore.settings().getDownloadDirectory()).c_str(), nullptr, nullptr, SW_SHOWNORMAL); +} + +void MainWindow::openModsFolder() +{ + ::ShellExecuteW(nullptr, L"explore", ToWString(m_OrganizerCore.settings().getModDirectory()).c_str(), nullptr, nullptr, SW_SHOWNORMAL); +} + +void MainWindow::openGameFolder() +{ + ::ShellExecuteW(nullptr, L"explore", ToWString(m_OrganizerCore.managedGame()->gameDirectory().absolutePath()).c_str(), nullptr, nullptr, SW_SHOWNORMAL); +} + +void MainWindow::openMyGamesFolder() +{ + ::ShellExecuteW(nullptr, L"explore", ToWString(m_OrganizerCore.managedGame()->documentsDirectory().absolutePath()).c_str(), nullptr, nullptr, SW_SHOWNORMAL); +} + + +void MainWindow::exportModListCSV() +{ + //SelectionDialog selection(tr("Choose what to export")); + + //selection.addChoice(tr("Everything"), tr("All installed mods are included in the list"), 0); + //selection.addChoice(tr("Active Mods"), tr("Only active (checked) mods from your current profile are included"), 1); + //selection.addChoice(tr("Visible"), tr("All mods visible in the mod list are included"), 2); + + QDialog selection(this); + QGridLayout *grid = new QGridLayout; + selection.setWindowTitle(tr("Export to csv")); + + QLabel *csvDescription = new QLabel(); + csvDescription->setText(tr("CSV (Comma Separated Values) is a format that can be imported in programs like Excel to create a spreadsheet.\nYou can also use online editors and converters instead.")); + grid->addWidget(csvDescription); + + QGroupBox *groupBoxRows = new QGroupBox(tr("Select what mods you want export:")); + QRadioButton *all = new QRadioButton(tr("All installed mods")); + QRadioButton *active = new QRadioButton(tr("Only active (checked) mods from your current profile")); + QRadioButton *visible = new QRadioButton(tr("All currently visible mods in the mod list")); + + QVBoxLayout *vbox = new QVBoxLayout; + vbox->addWidget(all); + vbox->addWidget(active); + vbox->addWidget(visible); + vbox->addStretch(1); + groupBoxRows->setLayout(vbox); + + + + grid->addWidget(groupBoxRows); + + QButtonGroup *buttonGroupRows = new QButtonGroup(); + buttonGroupRows->addButton(all, 0); + buttonGroupRows->addButton(active, 1); + buttonGroupRows->addButton(visible, 2); + buttonGroupRows->button(0)->setChecked(true); + + + + QGroupBox *groupBoxColumns = new QGroupBox(tr("Choose what Columns to export:")); + groupBoxColumns->setFlat(true); + + QCheckBox *mod_Priority = new QCheckBox(tr("Mod_Priority")); + mod_Priority->setChecked(true); + QCheckBox *mod_Name = new QCheckBox(tr("Mod_Name")); + mod_Name->setChecked(true); + QCheckBox *mod_Note = new QCheckBox(tr("Notes_column")); + QCheckBox *mod_Status = new QCheckBox(tr("Mod_Status")); + QCheckBox *primary_Category = new QCheckBox(tr("Primary_Category")); + QCheckBox *nexus_ID = new QCheckBox(tr("Nexus_ID")); + QCheckBox *mod_Nexus_URL = new QCheckBox(tr("Mod_Nexus_URL")); + QCheckBox *mod_Version = new QCheckBox(tr("Mod_Version")); + QCheckBox *install_Date = new QCheckBox(tr("Install_Date")); + QCheckBox *download_File_Name = new QCheckBox(tr("Download_File_Name")); + + QVBoxLayout *vbox1 = new QVBoxLayout; + vbox1->addWidget(mod_Priority); + vbox1->addWidget(mod_Name); + vbox1->addWidget(mod_Status); + vbox1->addWidget(mod_Note); + vbox1->addWidget(primary_Category); + vbox1->addWidget(nexus_ID); + vbox1->addWidget(mod_Nexus_URL); + vbox1->addWidget(mod_Version); + vbox1->addWidget(install_Date); + vbox1->addWidget(download_File_Name); + groupBoxColumns->setLayout(vbox1); + + grid->addWidget(groupBoxColumns); + + QPushButton *ok = new QPushButton("Ok"); + QPushButton *cancel = new QPushButton("Cancel"); + QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + + connect(buttons, SIGNAL(accepted()), &selection, SLOT(accept())); + connect(buttons, SIGNAL(rejected()), &selection, SLOT(reject())); + + grid->addWidget(buttons); + + selection.setLayout(grid); + + + if (selection.exec() == QDialog::Accepted) { + + unsigned int numMods = ModInfo::getNumMods(); + int selectedRowID = buttonGroupRows->checkedId(); + + try { + QBuffer buffer; + buffer.open(QIODevice::ReadWrite); + CSVBuilder builder(&buffer); + builder.setEscapeMode(CSVBuilder::TYPE_STRING, CSVBuilder::QUOTE_ALWAYS); + std::vector > fields; + if (mod_Priority->isChecked()) + fields.push_back(std::make_pair(QString("#Mod_Priority"), CSVBuilder::TYPE_STRING)); + if (mod_Name->isChecked()) + fields.push_back(std::make_pair(QString("#Mod_Name"), CSVBuilder::TYPE_STRING)); + if (mod_Status->isChecked()) + fields.push_back(std::make_pair(QString("#Mod_Status"), CSVBuilder::TYPE_STRING)); + if (mod_Note->isChecked()) + fields.push_back(std::make_pair(QString("#Note"), CSVBuilder::TYPE_STRING)); + if (primary_Category->isChecked()) + fields.push_back(std::make_pair(QString("#Primary_Category"), CSVBuilder::TYPE_STRING)); + if (nexus_ID->isChecked()) + fields.push_back(std::make_pair(QString("#Nexus_ID"), CSVBuilder::TYPE_INTEGER)); + if (mod_Nexus_URL->isChecked()) + fields.push_back(std::make_pair(QString("#Mod_Nexus_URL"), CSVBuilder::TYPE_STRING)); + if (mod_Version->isChecked()) + fields.push_back(std::make_pair(QString("#Mod_Version"), CSVBuilder::TYPE_STRING)); + if (install_Date->isChecked()) + fields.push_back(std::make_pair(QString("#Install_Date"), CSVBuilder::TYPE_STRING)); + if (download_File_Name->isChecked()) + fields.push_back(std::make_pair(QString("#Download_File_Name"), CSVBuilder::TYPE_STRING)); + + builder.setFields(fields); + + builder.writeHeader(); + + for (unsigned int i = 0; i < numMods; ++i) { + ModInfo::Ptr info = ModInfo::getByIndex(i); + bool enabled = m_OrganizerCore.currentProfile()->modEnabled(i); + if ((selectedRowID == 1) && !enabled) { + continue; + } + else if ((selectedRowID == 2) && !m_ModListSortProxy->filterMatchesMod(info, enabled)) { + continue; + } + std::vector flags = info->getFlags(); + if ((std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) == flags.end()) && + (std::find(flags.begin(), flags.end(), ModInfo::FLAG_BACKUP) == flags.end())) { + if (mod_Priority->isChecked()) + builder.setRowField("#Mod_Priority", QString("%1").arg(m_OrganizerCore.currentProfile()->getModPriority(i), 4, 10, QChar('0'))); + if (mod_Name->isChecked()) + builder.setRowField("#Mod_Name", info->name()); + if (mod_Status->isChecked()) + builder.setRowField("#Mod_Status", (enabled)? "Enabled" : "Disabled"); + if (mod_Note->isChecked()) + builder.setRowField("#Note", QString("%1").arg(info->comments().remove(','))); + if (primary_Category->isChecked()) + builder.setRowField("#Primary_Category", (m_CategoryFactory.categoryExists(info->getPrimaryCategory())) ? m_CategoryFactory.getCategoryName(info->getPrimaryCategory()) : ""); + if (nexus_ID->isChecked()) + builder.setRowField("#Nexus_ID", info->getNexusID()); + if (mod_Nexus_URL->isChecked()) + builder.setRowField("#Mod_Nexus_URL",(info->getNexusID()>0)? NexusInterface::instance(&m_PluginContainer)->getModURL(info->getNexusID(), info->getGameName()) : ""); + if (mod_Version->isChecked()) + builder.setRowField("#Mod_Version", info->getVersion().canonicalString()); + if (install_Date->isChecked()) + builder.setRowField("#Install_Date", info->creationTime().toString("yyyy/MM/dd HH:mm:ss")); + if (download_File_Name->isChecked()) + builder.setRowField("#Download_File_Name", info->getInstallationFile()); + + builder.writeRow(); + } + } + + SaveTextAsDialog saveDialog(this); + saveDialog.setText(buffer.data()); + saveDialog.exec(); + } + catch (const std::exception &e) { + reportError(tr("export failed: %1").arg(e.what())); + } + } +} + +static void addMenuAsPushButton(QMenu *menu, QMenu *subMenu) +{ + QPushButton *pushBtn = new QPushButton(subMenu->title()); + pushBtn->setMenu(subMenu); + QWidgetAction *action = new QWidgetAction(menu); + action->setDefaultWidget(pushBtn); + menu->addAction(action); +} + +QMenu *MainWindow::openFolderMenu() +{ + + QMenu *FolderMenu = new QMenu(this); + + FolderMenu->addAction(tr("Open Game folder"), this, SLOT(openGameFolder())); + + FolderMenu->addAction(tr("Open MyGames folder"), this, SLOT(openMyGamesFolder())); + + FolderMenu->addAction(tr("Open INIs folder"), this, SLOT(openIniFolder())); + + FolderMenu->addSeparator(); + + FolderMenu->addAction(tr("Open Instance folder"), this, SLOT(openInstanceFolder())); + + FolderMenu->addAction(tr("Open Mods folder"), this, SLOT(openModsFolder())); + + FolderMenu->addAction(tr("Open Profile folder"), this, SLOT(openProfileFolder())); + + FolderMenu->addAction(tr("Open Downloads folder"), this, SLOT(openDownloadsFolder())); + + FolderMenu->addSeparator(); + + FolderMenu->addAction(tr("Open MO2 Install folder"), this, SLOT(openInstallFolder())); + + FolderMenu->addAction(tr("Open MO2 Plugins folder"), this, SLOT(openPluginsFolder())); + + FolderMenu->addAction(tr("Open MO2 Logs folder"), this, SLOT(openLogsFolder())); + + + return FolderMenu; +} + +void MainWindow::initModListContextMenu(QMenu *menu) +{ + menu->addAction(tr("Install Mod..."), this, SLOT(installMod_clicked())); + menu->addAction(tr("Create empty mod"), this, SLOT(createEmptyMod_clicked())); + menu->addAction(tr("Create Separator"), this, SLOT(createSeparator_clicked())); + + menu->addSeparator(); + + menu->addAction(tr("Enable all visible"), this, SLOT(enableVisibleMods())); + menu->addAction(tr("Disable all visible"), this, SLOT(disableVisibleMods())); + menu->addAction(tr("Check all for update"), this, SLOT(checkModsForUpdates())); + menu->addAction(tr("Refresh"), &m_OrganizerCore, SLOT(profileRefresh())); + menu->addAction(tr("Export to csv..."), this, SLOT(exportModListCSV())); +} + +void MainWindow::addModSendToContextMenu(QMenu *menu) +{ + if (m_ModListSortProxy->sortColumn() != ModList::COL_PRIORITY) + return; + + QMenu *sub_menu = new QMenu(menu); + sub_menu->setTitle(tr("Send to")); + sub_menu->addAction(tr("Top"), this, SLOT(sendSelectedModsToTop_clicked())); + sub_menu->addAction(tr("Bottom"), this, SLOT(sendSelectedModsToBottom_clicked())); + sub_menu->addAction(tr("Priority..."), this, SLOT(sendSelectedModsToPriority_clicked())); + sub_menu->addAction(tr("Separator..."), this, SLOT(sendSelectedModsToSeparator_clicked())); + + menu->addMenu(sub_menu); + menu->addSeparator(); +} + +void MainWindow::addPluginSendToContextMenu(QMenu *menu) +{ + if (m_PluginListSortProxy->sortColumn() != PluginList::COL_PRIORITY) + return; + + QMenu *sub_menu = new QMenu(this); + sub_menu->setTitle(tr("Send to")); + sub_menu->addAction(tr("Top"), this, SLOT(sendSelectedPluginsToTop_clicked())); + sub_menu->addAction(tr("Bottom"), this, SLOT(sendSelectedPluginsToBottom_clicked())); + sub_menu->addAction(tr("Priority..."), this, SLOT(sendSelectedPluginsToPriority_clicked())); + + menu->addMenu(sub_menu); + menu->addSeparator(); +} + +void MainWindow::on_modList_customContextMenuRequested(const QPoint &pos) +{ + try { + QTreeView *modList = findChild("modList"); + + m_ContextIdx = mapToModel(m_OrganizerCore.modList(), modList->indexAt(pos)); + m_ContextRow = m_ContextIdx.row(); + + if (m_ContextRow == -1) { + // no selection + QMenu menu(this); + initModListContextMenu(&menu); + menu.exec(modList->mapToGlobal(pos)); + } else { + QMenu menu(this); + + QMenu *allMods = new QMenu(&menu); + initModListContextMenu(allMods); + allMods->setTitle(tr("All Mods")); + menu.addMenu(allMods); + menu.addSeparator(); + + ModInfo::Ptr info = ModInfo::getByIndex(m_ContextRow); + std::vector flags = info->getFlags(); + if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end()) { + if (QDir(info->absolutePath()).count() > 2) { + menu.addAction(tr("Sync to Mods..."), &m_OrganizerCore, SLOT(syncOverwrite())); + menu.addAction(tr("Create Mod..."), this, SLOT(createModFromOverwrite())); + menu.addAction(tr("Move content to Mod..."), this, SLOT(moveOverwriteContentToExistingMod())); + menu.addAction(tr("Clear Overwrite..."), this, SLOT(clearOverwrite())); + } + menu.addAction(tr("Open in Explorer"), this, SLOT(openExplorer_clicked())); + } else if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_BACKUP) != flags.end()) { + menu.addAction(tr("Restore Backup"), this, SLOT(restoreBackup_clicked())); + menu.addAction(tr("Remove Backup..."), this, SLOT(removeMod_clicked())); + } else if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_SEPARATOR) != flags.end()){ + menu.addSeparator(); + QMenu *addRemoveCategoriesMenu = new QMenu(tr("Change Categories"), &menu); + populateMenuCategories(addRemoveCategoriesMenu, 0); + connect(addRemoveCategoriesMenu, SIGNAL(aboutToHide()), this, SLOT(addRemoveCategories_MenuHandler())); + addMenuAsPushButton(&menu, addRemoveCategoriesMenu); + QMenu *primaryCategoryMenu = new QMenu(tr("Primary Category"), &menu); + connect(primaryCategoryMenu, SIGNAL(aboutToShow()), this, SLOT(addPrimaryCategoryCandidates())); + addMenuAsPushButton(&menu, primaryCategoryMenu); + menu.addSeparator(); + menu.addAction(tr("Rename Separator..."), this, SLOT(renameMod_clicked())); + menu.addAction(tr("Remove Separator..."), this, SLOT(removeMod_clicked())); + menu.addSeparator(); + addModSendToContextMenu(&menu); + menu.addAction(tr("Select Color..."), this, SLOT(setColor_clicked())); + if(info->getColor().isValid()) + menu.addAction(tr("Reset Color"), this, SLOT(resetColor_clicked())); + menu.addSeparator(); + } else if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_FOREIGN) != flags.end()) { + addModSendToContextMenu(&menu); + } else { + QMenu *addRemoveCategoriesMenu = new QMenu(tr("Change Categories"), &menu); + populateMenuCategories(addRemoveCategoriesMenu, 0); + connect(addRemoveCategoriesMenu, SIGNAL(aboutToHide()), this, SLOT(addRemoveCategories_MenuHandler())); + addMenuAsPushButton(&menu, addRemoveCategoriesMenu); + + QMenu *primaryCategoryMenu = new QMenu(tr("Primary Category"), &menu); + connect(primaryCategoryMenu, SIGNAL(aboutToShow()), this, SLOT(addPrimaryCategoryCandidates())); + addMenuAsPushButton(&menu, primaryCategoryMenu); + + menu.addSeparator(); + + if (info->downgradeAvailable()) { + menu.addAction(tr("Change versioning scheme"), this, SLOT(changeVersioningScheme())); + } + + if (info->updateIgnored()) { + menu.addAction(tr("Un-ignore update"), this, SLOT(unignoreUpdate())); + } + else { + if (info->updateAvailable() || info->downgradeAvailable()) { + menu.addAction(tr("Ignore update"), this, SLOT(ignoreUpdate())); + } + } + menu.addSeparator(); + + menu.addAction(tr("Enable selected"), this, SLOT(enableSelectedMods_clicked())); + menu.addAction(tr("Disable selected"), this, SLOT(disableSelectedMods_clicked())); + + menu.addSeparator(); + + addModSendToContextMenu(&menu); + + menu.addAction(tr("Rename Mod..."), this, SLOT(renameMod_clicked())); + menu.addAction(tr("Reinstall Mod"), this, SLOT(reinstallMod_clicked())); + menu.addAction(tr("Remove Mod..."), this, SLOT(removeMod_clicked())); + menu.addAction(tr("Create Backup"), this, SLOT(backupMod_clicked())); + + menu.addSeparator(); + + if (info->getNexusID() > 0 && Settings::instance().endorsementIntegration()) { + switch (info->endorsedState()) { + case ModInfo::ENDORSED_TRUE: { + menu.addAction(tr("Un-Endorse"), this, SLOT(unendorse_clicked())); + } break; + case ModInfo::ENDORSED_FALSE: { + menu.addAction(tr("Endorse"), this, SLOT(endorse_clicked())); + menu.addAction(tr("Won't endorse"), this, SLOT(dontendorse_clicked())); + } break; + case ModInfo::ENDORSED_NEVER: { + menu.addAction(tr("Endorse"), this, SLOT(endorse_clicked())); + } break; + default: { + QAction *action = new QAction(tr("Endorsement state unknown"), &menu); + action->setEnabled(false); + menu.addAction(action); + } break; + } + } + + menu.addSeparator(); + + std::vector flags = info->getFlags(); + if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_INVALID) != flags.end()) { + menu.addAction(tr("Ignore missing data"), this, SLOT(ignoreMissingData_clicked())); + } + + if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_ALTERNATE_GAME) != flags.end()) { + menu.addAction(tr("Mark as converted/working"), this, SLOT(markConverted_clicked())); + } + + if (info->getNexusID() > 0) { + menu.addAction(tr("Visit on Nexus"), this, SLOT(visitOnNexus_clicked())); + } else if ((info->getURL() != "")) { + menu.addAction(tr("Visit web page"), this, SLOT(visitWebPage_clicked())); + } + + menu.addAction(tr("Open in Explorer"), this, SLOT(openExplorer_clicked())); + } + + if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_FOREIGN) == flags.end()) { + QAction *infoAction = menu.addAction(tr("Information..."), this, SLOT(information_clicked())); + menu.setDefaultAction(infoAction); + } + + menu.exec(modList->mapToGlobal(pos)); + } + } catch (const std::exception &e) { + reportError(tr("Exception: ").arg(e.what())); + } catch (...) { + reportError(tr("Unknown exception")); + } +} + + +void MainWindow::on_categoriesList_itemSelectionChanged() +{ + QModelIndexList indices = ui->categoriesList->selectionModel()->selectedRows(); + std::vector categories; + std::vector content; + for (const QModelIndex &index : indices) { + int filterType = index.data(Qt::UserRole + 1).toInt(); + if ((filterType == ModListSortProxy::TYPE_CATEGORY) + || (filterType == ModListSortProxy::TYPE_SPECIAL)) { + int categoryId = index.data(Qt::UserRole).toInt(); + if (categoryId != CategoryFactory::CATEGORY_NONE) { + categories.push_back(categoryId); + } + } else if (filterType == ModListSortProxy::TYPE_CONTENT) { + int contentId = index.data(Qt::UserRole).toInt(); + content.push_back(contentId); + } + } + + m_ModListSortProxy->setCategoryFilter(categories); + m_ModListSortProxy->setContentFilter(content); + ui->clickBlankButton->setEnabled(categories.size() > 0 || content.size() >0); + + if (indices.count() == 0) { + ui->currentCategoryLabel->setText(QString("(%1)").arg(tr(""))); + } else if (indices.count() > 1) { + ui->currentCategoryLabel->setText(QString("(%1)").arg(tr(""))); + } else { + ui->currentCategoryLabel->setText(QString("(%1)").arg(indices.first().data().toString())); + } + ui->modList->reset(); +} + + +void MainWindow::deleteSavegame_clicked() +{ + SaveGameInfo const *info = m_OrganizerCore.managedGame()->feature(); + + QString savesMsgLabel; + QStringList deleteFiles; + + int count = 0; + + for (const QModelIndex &idx : ui->savegameList->selectionModel()->selectedIndexes()) { + QString name = idx.data(Qt::UserRole).toString(); + + if (count < 10) { + savesMsgLabel += "
  • " + QFileInfo(name).completeBaseName() + "
  • "; + } + ++count; + + if (info == nullptr) { + deleteFiles.push_back(name); + } else { + ISaveGame const *save = info->getSaveGameInfo(name); + deleteFiles += save->allFiles(); + delete save; + } + } + + if (count > 10) { + savesMsgLabel += "
  • ... " + tr("%1 more").arg(count - 10) + "
  • "; + } + + if (QMessageBox::question(this, tr("Confirm"), + tr("Are you sure you want to remove the following %n save(s)?
    " + "
      %1

    " + "Removed saves will be sent to the Recycle Bin.", "", count) + .arg(savesMsgLabel), + QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { + shellDelete(deleteFiles, true); // recycle bin delete. + refreshSaveList(); + } +} + + +void MainWindow::fixMods_clicked(SaveGameInfo::MissingAssets const &missingAssets) +{ + ActivateModsDialog dialog(missingAssets, this); + if (dialog.exec() == QDialog::Accepted) { + // activate the required mods, then enable all esps + std::set modsToActivate = dialog.getModsToActivate(); + for (std::set::iterator iter = modsToActivate.begin(); iter != modsToActivate.end(); ++iter) { + if ((*iter != "") && (*iter != "")) { + unsigned int modIndex = ModInfo::getIndex(*iter); + m_OrganizerCore.currentProfile()->setModEnabled(modIndex, true); + } + } + + m_OrganizerCore.currentProfile()->writeModlist(); + m_OrganizerCore.refreshLists(); + + std::set espsToActivate = dialog.getESPsToActivate(); + for (std::set::iterator iter = espsToActivate.begin(); iter != espsToActivate.end(); ++iter) { + m_OrganizerCore.pluginList()->enableESP(*iter); + } + m_OrganizerCore.saveCurrentLists(); + } +} + + +void MainWindow::on_savegameList_customContextMenuRequested(const QPoint &pos) +{ + QItemSelectionModel *selection = ui->savegameList->selectionModel(); + + if (!selection->hasSelection()) { + return; + } + + QMenu menu; + QAction *action = menu.addAction(tr("Enable Mods...")); + action->setEnabled(false); + + if (selection->selectedIndexes().count() == 1) { + SaveGameInfo const *info = this->m_OrganizerCore.managedGame()->feature(); + if (info != nullptr) { + QString save = ui->savegameList->currentItem()->data(Qt::UserRole).toString(); + SaveGameInfo::MissingAssets missing = info->getMissingAssets(save); + if (missing.size() != 0) { + connect(action, &QAction::triggered, this, [this, missing]{ fixMods_clicked(missing); }); + action->setEnabled(true); + } + } + } + + QString deleteMenuLabel = tr("Delete %n save(s)", "", selection->selectedIndexes().count()); + + menu.addAction(deleteMenuLabel, this, SLOT(deleteSavegame_clicked())); + + menu.exec(ui->savegameList->mapToGlobal(pos)); +} + +void MainWindow::linkToolbar() +{ + Executable &exe(getSelectedExecutable()); + exe.showOnToolbar(!exe.isShownOnToolbar()); + ui->linkButton->menu()->actions().at(static_cast(ShortcutType::Toolbar))->setIcon(exe.isShownOnToolbar() ? QIcon(":/MO/gui/remove") : QIcon(":/MO/gui/link")); + updateToolBar(); +} + +namespace { +QString getLinkfile(const QString &dir, const Executable &exec) +{ + return QDir::fromNativeSeparators(dir) + "/" + exec.m_Title + ".lnk"; +} + +QString getDesktopLinkfile(const Executable &exec) +{ + return getLinkfile(getDesktopDirectory(), exec); +} + +QString getStartMenuLinkfile(const Executable &exec) +{ + return getLinkfile(getStartMenuDirectory(), exec); +} +} + +void MainWindow::addWindowsLink(const ShortcutType mapping) +{ + const Executable &selectedExecutable(getSelectedExecutable()); + QString const linkName = getLinkfile(mapping == ShortcutType::Desktop ? getDesktopDirectory() : getStartMenuDirectory(), + selectedExecutable); + + if (QFile::exists(linkName)) { + if (QFile::remove(linkName)) { + ui->linkButton->menu()->actions().at(static_cast(mapping))->setIcon(QIcon(":/MO/gui/link")); + } else { + reportError(tr("failed to remove %1").arg(linkName)); + } + } else { + QFileInfo const exeInfo(qApp->applicationFilePath()); + // create link + QString executable = QDir::toNativeSeparators(selectedExecutable.m_BinaryInfo.absoluteFilePath()); + + std::wstring targetFile = ToWString(exeInfo.absoluteFilePath()); + std::wstring parameter = ToWString( + QString("\"moshortcut://%1:%2\"").arg(InstanceManager::instance().currentInstance(),selectedExecutable.m_Title)); + std::wstring description = ToWString(QString("Run %1 with ModOrganizer").arg(selectedExecutable.m_Title)); + std::wstring iconFile = ToWString(executable); + std::wstring currentDirectory = ToWString(QDir::toNativeSeparators(qApp->applicationDirPath())); + + if (CreateShortcut(targetFile.c_str() + , parameter.c_str() + , QDir::toNativeSeparators(linkName).toUtf8().constData() + , description.c_str() + , (selectedExecutable.usesOwnIcon() ? iconFile.c_str() : nullptr), 0 + , currentDirectory.c_str()) == 0) { + ui->linkButton->menu()->actions().at(static_cast(mapping))->setIcon(QIcon(":/MO/gui/remove")); + } else { + reportError(tr("failed to create %1").arg(linkName)); + } + } +} + +void MainWindow::linkDesktop() +{ + addWindowsLink(ShortcutType::Desktop); +} + +void MainWindow::linkMenu() +{ + addWindowsLink(ShortcutType::StartMenu); +} + +void MainWindow::on_actionSettings_triggered() +{ + Settings &settings = m_OrganizerCore.settings(); + + QString oldModDirectory(settings.getModDirectory()); + QString oldCacheDirectory(settings.getCacheDirectory()); + QString oldProfilesDirectory(settings.getProfileDirectory()); + QString oldManagedGameDirectory(settings.getManagedGameDirectory()); + bool oldDisplayForeign(settings.displayForeign()); + bool proxy = settings.useProxy(); + DownloadManager *dlManager = m_OrganizerCore.downloadManager(); + + settings.query(&m_PluginContainer, this); + + if (oldManagedGameDirectory != settings.getManagedGameDirectory()) { + QMessageBox::about(this, tr("Restarting MO"), + tr("Changing the managed game directory requires restarting MO.\n" + "Any pending downloads will be paused.\n\n" + "Click OK to restart MO now.")); + dlManager->pauseAll(); + qApp->exit(INT_MAX); + } + + InstallationManager *instManager = m_OrganizerCore.installationManager(); + instManager->setModsDirectory(settings.getModDirectory()); + instManager->setDownloadDirectory(settings.getDownloadDirectory()); + + fixCategories(); + refreshFilters(); + + if (settings.getProfileDirectory() != oldProfilesDirectory) { + refreshProfiles(); + } + + if (dlManager->getOutputDirectory() != settings.getDownloadDirectory()) { + if (dlManager->downloadsInProgress()) { + MessageDialog::showMessage(tr("Can't change download directory while " + "downloads are in progress!"), + this); + } else { + dlManager->setOutputDirectory(settings.getDownloadDirectory()); + } + } + dlManager->setPreferredServers(settings.getPreferredServers()); + + if ((settings.getModDirectory() != oldModDirectory) + || (settings.displayForeign() != oldDisplayForeign)) { + m_OrganizerCore.profileRefresh(); + } + + const auto state = settings.archiveParsing(); + if (state != m_OrganizerCore.getArchiveParsing()) + { + m_OrganizerCore.setArchiveParsing(state); + if (!state) + { + ui->showArchiveDataCheckBox->setCheckState(Qt::Unchecked); + ui->showArchiveDataCheckBox->setEnabled(false); + m_showArchiveData = false; + } + else + { + ui->showArchiveDataCheckBox->setCheckState(Qt::Checked); + ui->showArchiveDataCheckBox->setEnabled(true); + m_showArchiveData = true; + } + m_OrganizerCore.refreshModList(); + m_OrganizerCore.refreshDirectoryStructure(); + m_OrganizerCore.refreshLists(); + } + + if (settings.getCacheDirectory() != oldCacheDirectory) { + NexusInterface::instance(&m_PluginContainer)->setCacheDirectory(settings.getCacheDirectory()); + } + + if (proxy != settings.useProxy()) { + activateProxy(settings.useProxy()); + } + + NexusInterface::instance(&m_PluginContainer)->setNMMVersion(settings.getNMMVersion()); + + updateDownloadView(); + + m_OrganizerCore.updateVFSParams(settings.logLevel(), settings.crashDumpsType(), settings.executablesBlacklist()); + m_OrganizerCore.cycleDiagnostics(); +} + + +void MainWindow::on_actionNexus_triggered() +{ + const IPluginGame *game = m_OrganizerCore.managedGame(); + QString gameName = game->gameShortName(); + if (game->gameNexusName().isEmpty() && game->primarySources().count()) + gameName = game->primarySources()[0]; + QDesktopServices::openUrl(QUrl(NexusInterface::instance(&m_PluginContainer)->getGameURL(gameName))); +} + + +void MainWindow::linkClicked(const QString &url) +{ + QDesktopServices::openUrl(QUrl(url)); +} + + +void MainWindow::installTranslator(const QString &name) +{ + QTranslator *translator = new QTranslator(this); + QString fileName = name + "_" + m_CurrentLanguage; + if (!translator->load(fileName, qApp->applicationDirPath() + "/translations")) { + if (m_CurrentLanguage.compare("en", Qt::CaseInsensitive)) { + qDebug("localization file %s not found", qUtf8Printable(fileName)); + } // we don't actually expect localization files for English + } + + qApp->installTranslator(translator); + m_Translators.push_back(translator); +} + + +void MainWindow::languageChange(const QString &newLanguage) +{ + for (QTranslator *trans : m_Translators) { + qApp->removeTranslator(trans); + } + m_Translators.clear(); + + m_CurrentLanguage = newLanguage; + + installTranslator("qt"); + installTranslator("qtbase"); + installTranslator(ToQString(AppConfig::translationPrefix())); + for (const QString &fileName : m_PluginContainer.pluginFileNames()) { + installTranslator(QFileInfo(fileName).baseName()); + } + ui->retranslateUi(this); + qDebug("loaded language %s", qUtf8Printable(newLanguage)); + + ui->profileBox->setItemText(0, QObject::tr("")); + + createHelpWidget(); + + updateDownloadView(); + updateProblemsButton(); + + QMenu *listOptionsMenu = new QMenu(ui->listOptionsBtn); + initModListContextMenu(listOptionsMenu); + ui->listOptionsBtn->setMenu(listOptionsMenu); + + ui->openFolderMenu->setMenu(openFolderMenu()); +} + +void MainWindow::writeDataToFile(QFile &file, const QString &directory, const DirectoryEntry &directoryEntry) +{ + for (FileEntry::Ptr current : directoryEntry.getFiles()) { + bool isArchive = false; + int origin = current->getOrigin(isArchive); + if (isArchive) { + // TODO: don't list files from archives. maybe make this an option? + continue; + } + QString fullName = directory + "\\" + ToQString(current->getName()); + file.write(fullName.toUtf8()); + + file.write("\t("); + file.write(ToQString(m_OrganizerCore.directoryStructure()->getOriginByID(origin).getName()).toUtf8()); + file.write(")\r\n"); + } + + // recurse into subdirectories + std::vector::const_iterator current, end; + directoryEntry.getSubDirectories(current, end); + for (; current != end; ++current) { + writeDataToFile(file, directory + "\\" + ToQString((*current)->getName()), **current); + } +} + +void MainWindow::writeDataToFile() +{ + QString fileName = QFileDialog::getSaveFileName(this); + if (!fileName.isEmpty()) { + QFile file(fileName); + if (!file.open(QIODevice::WriteOnly)) { + reportError(tr("failed to write to file %1").arg(fileName)); + } + + writeDataToFile(file, "data", *m_OrganizerCore.directoryStructure()); + file.close(); + + MessageDialog::showMessage(tr("%1 written").arg(QDir::toNativeSeparators(fileName)), this); + } +} + + +int MainWindow::getBinaryExecuteInfo(const QFileInfo &targetInfo, QFileInfo &binaryInfo, QString &arguments) +{ + QString extension = targetInfo.suffix(); + if ((extension.compare("cmd", Qt::CaseInsensitive) == 0) || + (extension.compare("com", Qt::CaseInsensitive) == 0) || + (extension.compare("bat", Qt::CaseInsensitive) == 0)) { + binaryInfo = QFileInfo("C:\\Windows\\System32\\cmd.exe"); + arguments = QString("/C \"%1\"").arg(QDir::toNativeSeparators(targetInfo.absoluteFilePath())); + return 1; + } else if (extension.compare("exe", Qt::CaseInsensitive) == 0) { + binaryInfo = targetInfo; + return 1; + } else if (extension.compare("jar", Qt::CaseInsensitive) == 0) { + // types that need to be injected into + std::wstring targetPathW = ToWString(targetInfo.absoluteFilePath()); + QString binaryPath; + + { // try to find java automatically + WCHAR buffer[MAX_PATH]; + if (::FindExecutableW(targetPathW.c_str(), nullptr, buffer) > (HINSTANCE)32) { + DWORD binaryType = 0UL; + if (!::GetBinaryTypeW(buffer, &binaryType)) { + qDebug("failed to determine binary type of \"%ls\": %lu", buffer, ::GetLastError()); + } else if (binaryType == SCS_32BIT_BINARY) { + binaryPath = ToQString(buffer); + } + } + } + if (binaryPath.isEmpty() && (extension == "jar")) { + // second attempt: look to the registry + QSettings javaReg("HKEY_LOCAL_MACHINE\\Software\\JavaSoft\\Java Runtime Environment", QSettings::NativeFormat); + if (javaReg.contains("CurrentVersion")) { + QString currentVersion = javaReg.value("CurrentVersion").toString(); + binaryPath = javaReg.value(QString("%1/JavaHome").arg(currentVersion)).toString().append("\\bin\\javaw.exe"); + } + } + if (binaryPath.isEmpty()) { + binaryPath = QFileDialog::getOpenFileName(this, tr("Select binary"), QString(), tr("Binary") + " (*.exe)"); + } + if (binaryPath.isEmpty()) { + return 0; + } + binaryInfo = QFileInfo(binaryPath); + if (extension == "jar") { + arguments = QString("-jar \"%1\"").arg(QDir::toNativeSeparators(targetInfo.absoluteFilePath())); + } else { + arguments = QString("\"%1\"").arg(QDir::toNativeSeparators(targetInfo.absoluteFilePath())); + } + return 1; + } else { + return 2; + } +} + + +void MainWindow::addAsExecutable() +{ + if (m_ContextItem != nullptr) { + QFileInfo targetInfo(m_ContextItem->data(0, Qt::UserRole).toString()); + QFileInfo binaryInfo; + QString arguments; + switch (getBinaryExecuteInfo(targetInfo, binaryInfo, arguments)) { + case 1: { + QString name = QInputDialog::getText(this, tr("Enter Name"), + tr("Please enter a name for the executable"), QLineEdit::Normal, + targetInfo.baseName()); + if (!name.isEmpty()) { + //Note: If this already exists, you'll lose custom settings + m_OrganizerCore.executablesList()->addExecutable(name, + binaryInfo.absoluteFilePath(), + arguments, + targetInfo.absolutePath(), + QString(), + Executable::CustomExecutable); + refreshExecutablesList(); + } + } break; + case 2: { + QMessageBox::information(this, tr("Not an executable"), tr("This is not a recognized executable.")); + } break; + default: { + // nop + } break; + } + } +} + + +void MainWindow::originModified(int originID) +{ + FilesOrigin &origin = m_OrganizerCore.directoryStructure()->getOriginByID(originID); + origin.enable(false); + m_OrganizerCore.directoryStructure()->addFromOrigin(origin.getName(), origin.getPath(), origin.getPriority()); + DirectoryRefresher::cleanStructure(m_OrganizerCore.directoryStructure()); +} + + +void MainWindow::hideFile() +{ + QString oldName = m_ContextItem->data(0, Qt::UserRole).toString(); + QString newName = oldName + ModInfo::s_HiddenExt; + + if (QFileInfo(newName).exists()) { + if (QMessageBox::question(this, tr("Replace file?"), tr("There already is a hidden version of this file. Replace it?"), + QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { + if (!QFile(newName).remove()) { + QMessageBox::critical(this, tr("File operation failed"), tr("Failed to remove \"%1\". Maybe you lack the required file permissions?").arg(newName)); + return; + } + } else { + return; + } + } + + if (QFile::rename(oldName, newName)) { + originModified(m_ContextItem->data(1, Qt::UserRole + 1).toInt()); + refreshDataTreeKeepExpandedNodes(); + } else { + reportError(tr("failed to rename \"%1\" to \"%2\"").arg(oldName).arg(QDir::toNativeSeparators(newName))); + } +} + + +void MainWindow::unhideFile() +{ + QString oldName = m_ContextItem->data(0, Qt::UserRole).toString(); + QString newName = oldName.left(oldName.length() - ModInfo::s_HiddenExt.length()); + if (QFileInfo(newName).exists()) { + if (QMessageBox::question(this, tr("Replace file?"), tr("There already is a visible version of this file. Replace it?"), + QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { + if (!QFile(newName).remove()) { + QMessageBox::critical(this, tr("File operation failed"), tr("Failed to remove \"%1\". Maybe you lack the required file permissions?").arg(newName)); + return; + } + } else { + return; + } + } + if (QFile::rename(oldName, newName)) { + originModified(m_ContextItem->data(1, Qt::UserRole + 1).toInt()); + refreshDataTreeKeepExpandedNodes(); + } else { + reportError(tr("failed to rename \"%1\" to \"%2\"").arg(QDir::toNativeSeparators(oldName)).arg(QDir::toNativeSeparators(newName))); + } +} + + +void MainWindow::enableSelectedPlugins_clicked() +{ + m_OrganizerCore.pluginList()->enableSelected(ui->espList->selectionModel()); +} + + +void MainWindow::disableSelectedPlugins_clicked() +{ + m_OrganizerCore.pluginList()->disableSelected(ui->espList->selectionModel()); +} + +void MainWindow::sendSelectedPluginsToTop_clicked() +{ + m_OrganizerCore.pluginList()->sendToPriority(ui->espList->selectionModel(), 0); +} + +void MainWindow::sendSelectedPluginsToBottom_clicked() +{ + m_OrganizerCore.pluginList()->sendToPriority(ui->espList->selectionModel(), INT_MAX); +} + +void MainWindow::sendSelectedPluginsToPriority_clicked() +{ + bool ok; + int newPriority = QInputDialog::getInt(this, + tr("Set Priority"), tr("Set the priority of the selected plugins"), + 0, 0, INT_MAX, 1, &ok); + if (!ok) return; + + m_OrganizerCore.pluginList()->sendToPriority(ui->espList->selectionModel(), newPriority); +} + + +void MainWindow::enableSelectedMods_clicked() +{ + m_OrganizerCore.modList()->enableSelected(ui->modList->selectionModel()); + if (m_ModListSortProxy != nullptr) { + m_ModListSortProxy->invalidate(); + } +} + + +void MainWindow::disableSelectedMods_clicked() +{ + m_OrganizerCore.modList()->disableSelected(ui->modList->selectionModel()); + if (m_ModListSortProxy != nullptr) { + m_ModListSortProxy->invalidate(); + } +} + + +void MainWindow::previewDataFile() +{ + QString fileName = QDir::fromNativeSeparators(m_ContextItem->data(0, Qt::UserRole).toString()); + + // what we have is an absolute path to the file in its actual location (for the primary origin) + // what we want is the path relative to the virtual data directory + + // we need to look in the virtual directory for the file to make sure the info is up to date. + + // check if the file comes from the actual data folder instead of a mod + QDir gameDirectory = m_OrganizerCore.managedGame()->dataDirectory().absolutePath(); + QString relativePath = gameDirectory.relativeFilePath(fileName); + QDir dirRelativePath = gameDirectory.relativeFilePath(fileName); + // if the file is on a different drive the dirRelativePath will actually be an absolute path so we make sure that is not the case + if (!dirRelativePath.isAbsolute() && !relativePath.startsWith("..")) { + fileName = relativePath; + } + else { + // crude: we search for the next slash after the base mod directory to skip everything up to the data-relative directory + int offset = m_OrganizerCore.settings().getModDirectory().size() + 1; + offset = fileName.indexOf("/", offset); + fileName = fileName.mid(offset + 1); + } + + + + const FileEntry::Ptr file = m_OrganizerCore.directoryStructure()->searchFile(ToWString(fileName), nullptr); + + if (file.get() == nullptr) { + reportError(tr("file not found: %1").arg(qUtf8Printable(fileName))); + return; + } + + // set up preview dialog + PreviewDialog preview(fileName); + auto addFunc = [&] (int originId) { + FilesOrigin &origin = m_OrganizerCore.directoryStructure()->getOriginByID(originId); + QString filePath = QDir::fromNativeSeparators(ToQString(origin.getPath())) + "/" + fileName; + if (QFile::exists(filePath)) { + // it's very possible the file doesn't exist, because it's inside an archive. we don't support that + QWidget *wid = m_PluginContainer.previewGenerator().genPreview(filePath); + if (wid == nullptr) { + reportError(tr("failed to generate preview for %1").arg(filePath)); + } else { + preview.addVariant(ToQString(origin.getName()), wid); + } + } + }; + + addFunc(file->getOrigin()); + for (auto alt : file->getAlternatives()) { + addFunc(alt.first); + } + if (preview.numVariants() > 0) { + QSettings &settings = m_OrganizerCore.settings().directInterface(); + QString key = QString("geometry/%1").arg(preview.objectName()); + if (settings.contains(key)) { + preview.restoreGeometry(settings.value(key).toByteArray()); + } + preview.exec(); + settings.setValue(key, preview.saveGeometry()); + } else { + QMessageBox::information(this, tr("Sorry"), tr("Sorry, can't preview anything. This function currently does not support extracting from bsas.")); + } +} + +void MainWindow::openDataFile() +{ + if (m_ContextItem != nullptr) { + QFileInfo targetInfo(m_ContextItem->data(0, Qt::UserRole).toString()); + QFileInfo binaryInfo; + QString arguments; + switch (getBinaryExecuteInfo(targetInfo, binaryInfo, arguments)) { + case 1: { + m_OrganizerCore.spawnBinaryDirect( + binaryInfo, arguments, m_OrganizerCore.currentProfile()->name(), + targetInfo.absolutePath(), "", ""); + } break; + case 2: { + ::ShellExecuteW(nullptr, L"open", + ToWString(targetInfo.absoluteFilePath()).c_str(), + nullptr, nullptr, SW_SHOWNORMAL); + } break; + default: { + // nop + } break; + } + } +} + + +void MainWindow::updateAvailable() +{ + for (QAction *action : ui->toolBar->actions()) { + if (action->text() == tr("Update")) { + action->setEnabled(true); + action->setToolTip(tr("Update available")); + break; + } + } +} + + +void MainWindow::motdReceived(const QString &motd) +{ + // don't show motd after 5 seconds, may be annoying. Hopefully the user's + // internet connection is faster next time + if (m_StartTime.secsTo(QTime::currentTime()) < 5) { + uint hash = qHash(motd); + if (hash != m_OrganizerCore.settings().getMotDHash()) { + MotDDialog dialog(motd); + dialog.exec(); + m_OrganizerCore.settings().setMotDHash(hash); + } + } + + ui->actionEndorseMO->setVisible(false); +} + + +void MainWindow::notEndorsedYet() +{ + if (!Settings::instance().directInterface().value("wont_endorse_MO", false).toBool()) { + ui->actionEndorseMO->setVisible(true); + } +} + + +void MainWindow::wontEndorse() +{ + Settings::instance().directInterface().setValue("wont_endorse_MO", true); + ui->actionEndorseMO->setVisible(false); +} + + +void MainWindow::on_dataTree_customContextMenuRequested(const QPoint &pos) +{ + QTreeWidget *dataTree = findChild("dataTree"); + m_ContextItem = dataTree->itemAt(pos.x(), pos.y()); + + QMenu menu; + if ((m_ContextItem != nullptr) && (m_ContextItem->childCount() == 0) + && (m_ContextItem->data(0, Qt::UserRole + 3).toBool() != true)) { + menu.addAction(tr("Open/Execute"), this, SLOT(openDataFile())); + menu.addAction(tr("Add as Executable"), this, SLOT(addAsExecutable())); + + QString fileName = m_ContextItem->text(0); + if (m_PluginContainer.previewGenerator().previewSupported(QFileInfo(fileName).suffix())) { + menu.addAction(tr("Preview"), this, SLOT(previewDataFile())); + } + + // offer to hide/unhide file, but not for files from archives + if (!m_ContextItem->data(0, Qt::UserRole + 1).toBool()) { + if (m_ContextItem->text(0).endsWith(ModInfo::s_HiddenExt)) { + menu.addAction(tr("Un-Hide"), this, SLOT(unhideFile())); + } else { + menu.addAction(tr("Hide"), this, SLOT(hideFile())); + } + } + + menu.addSeparator(); + } + menu.addAction(tr("Write To File..."), this, SLOT(writeDataToFile())); + menu.addAction(tr("Refresh"), this, SLOT(on_btnRefreshData_clicked())); + + menu.exec(dataTree->mapToGlobal(pos)); +} + +void MainWindow::on_conflictsCheckBox_toggled(bool) +{ + refreshDataTreeKeepExpandedNodes(); +} + + +void MainWindow::on_actionUpdate_triggered() +{ + m_OrganizerCore.startMOUpdate(); +} + + +void MainWindow::on_actionEndorseMO_triggered() +{ + // Normally this would be the managed game but MO2 is only uploaded to the Skyrim SE site right now + IPluginGame * game = m_OrganizerCore.getGame("skyrimse"); + if (!game) return; + + if (QMessageBox::question(this, tr("Endorse Mod Organizer"), + tr("Do you want to endorse Mod Organizer on %1 now?").arg( + NexusInterface::instance(&m_PluginContainer)->getGameURL(game->gameShortName())), + QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { + NexusInterface::instance(&m_PluginContainer)->requestToggleEndorsement( + game->gameShortName(), game->nexusModOrganizerID(), m_OrganizerCore.getVersion().canonicalString(), true, this, QVariant(), QString()); + } +} + + +void MainWindow::initDownloadView() +{ + DownloadList *sourceModel = new DownloadList(m_OrganizerCore.downloadManager(), ui->downloadView); + DownloadListSortProxy *sortProxy = new DownloadListSortProxy(m_OrganizerCore.downloadManager(), ui->downloadView); + sortProxy->setSourceModel(sourceModel); + connect(ui->downloadFilterEdit, SIGNAL(textChanged(QString)), sortProxy, SLOT(updateFilter(QString))); + connect(ui->downloadFilterEdit, SIGNAL(textChanged(QString)), this, SLOT(downloadFilterChanged(QString))); + + ui->downloadView->setSourceModel(sourceModel); + ui->downloadView->setModel(sortProxy); + ui->downloadView->setManager(m_OrganizerCore.downloadManager()); + ui->downloadView->setItemDelegate(new DownloadProgressDelegate(m_OrganizerCore.downloadManager(), sortProxy, ui->downloadView)); + updateDownloadView(); + + connect(ui->downloadView, SIGNAL(installDownload(int)), &m_OrganizerCore, SLOT(installDownload(int))); + connect(ui->downloadView, SIGNAL(queryInfo(int)), m_OrganizerCore.downloadManager(), SLOT(queryInfo(int))); + connect(ui->downloadView, SIGNAL(visitOnNexus(int)), m_OrganizerCore.downloadManager(), SLOT(visitOnNexus(int))); + connect(ui->downloadView, SIGNAL(openFile(int)), m_OrganizerCore.downloadManager(), SLOT(openFile(int))); + connect(ui->downloadView, SIGNAL(openInDownloadsFolder(int)), m_OrganizerCore.downloadManager(), SLOT(openInDownloadsFolder(int))); + connect(ui->downloadView, SIGNAL(removeDownload(int, bool)), m_OrganizerCore.downloadManager(), SLOT(removeDownload(int, bool))); + connect(ui->downloadView, SIGNAL(restoreDownload(int)), m_OrganizerCore.downloadManager(), SLOT(restoreDownload(int))); + connect(ui->downloadView, SIGNAL(cancelDownload(int)), m_OrganizerCore.downloadManager(), SLOT(cancelDownload(int))); + connect(ui->downloadView, SIGNAL(pauseDownload(int)), m_OrganizerCore.downloadManager(), SLOT(pauseDownload(int))); + connect(ui->downloadView, SIGNAL(resumeDownload(int)), this, SLOT(resumeDownload(int))); +} + +void MainWindow::updateDownloadView() +{ + // set the view attribute and default row sizes + if (m_OrganizerCore.settings().compactDownloads()) { + ui->downloadView->setProperty("downloadView", "compact"); + setStyleSheet("DownloadListWidget::item { padding: 4px 2px; }"); + } else { + ui->downloadView->setProperty("downloadView", "standard"); + setStyleSheet("DownloadListWidget::item { padding: 16px 4px; }"); + } + //setStyleSheet("DownloadListWidget::item:hover { padding: 0px; }"); + //setStyleSheet("DownloadListWidget::item:selected { padding: 0px; }"); + + // reapply global stylesheet on the widget level (!) to override the defaults + //ui->downloadView->setStyleSheet(styleSheet()); + + ui->downloadView->setMetaDisplay(m_OrganizerCore.settings().metaDownloads()); + ui->downloadView->style()->unpolish(ui->downloadView); + ui->downloadView->style()->polish(ui->downloadView); + qobject_cast(ui->downloadView->header())->customResizeSections(); + m_OrganizerCore.downloadManager()->refreshList(); +} + +void MainWindow::modDetailsUpdated(bool) +{ + if (--m_ModsToUpdate == 0) { + statusBar()->hide(); + m_ModListSortProxy->setCategoryFilter(boost::assign::list_of(CategoryFactory::CATEGORY_SPECIAL_UPDATEAVAILABLE)); + for (int i = 0; i < ui->categoriesList->topLevelItemCount(); ++i) { + if (ui->categoriesList->topLevelItem(i)->data(0, Qt::UserRole) == CategoryFactory::CATEGORY_SPECIAL_UPDATEAVAILABLE) { + ui->categoriesList->setCurrentItem(ui->categoriesList->topLevelItem(i)); + break; + } + } + m_RefreshProgress->setVisible(false); + } else { + m_RefreshProgress->setValue(m_RefreshProgress->maximum() - m_ModsToUpdate); + } +} + +void MainWindow::nxmUpdatesAvailable(const std::vector &modIDs, QVariant userData, QVariant resultData, int) +{ + m_ModsToUpdate -= static_cast(modIDs.size()); + QVariantList resultList = resultData.toList(); + for (auto iter = resultList.begin(); iter != resultList.end(); ++iter) { + QVariantMap result = iter->toMap(); + // Normally this would be the managed game but MO2 is only uploaded to the Skyrim SE site right now + IPluginGame * game = m_OrganizerCore.getGame("skyrimse"); + if (game + && result["id"].toInt() == game->nexusModOrganizerID() + && result["game_id"].toInt() == game->nexusGameID()) { + if (!result["voted_by_user"].toBool() && + Settings::instance().endorsementIntegration() && + !Settings::instance().directInterface().value("wont_endorse_MO", false).toBool()) { + ui->actionEndorseMO->setVisible(true); + } + } else { + QString gameName = m_OrganizerCore.managedGame()->gameShortName(); + bool sameNexus = false; + for (IPluginGame *game : m_PluginContainer.plugins()) { + if (game->nexusGameID() == result["game_id"].toInt()) { + gameName = game->gameShortName(); + if (game->nexusGameID() == m_OrganizerCore.managedGame()->nexusGameID()) + sameNexus = true; + break; + } + } + std::vector info = ModInfo::getByModID(gameName, result["id"].toInt()); + if (sameNexus) { + std::vector mainInfo = ModInfo::getByModID(m_OrganizerCore.managedGame()->gameShortName(), result["id"].toInt()); + info.reserve(info.size() + mainInfo.size()); + info.insert(info.end(), mainInfo.begin(), mainInfo.end()); + } + for (auto iter = info.begin(); iter != info.end(); ++iter) { + (*iter)->setNewestVersion(result["version"].toString()); + (*iter)->setNexusDescription(result["description"].toString()); + if (NexusInterface::instance(&m_PluginContainer)->getAccessManager()->validated() && + result.contains("voted_by_user") && + Settings::instance().endorsementIntegration()) { + // don't use endorsement info if we're not logged in or if the response doesn't contain it + (*iter)->setIsEndorsed(result["voted_by_user"].toBool()); + } + } + } + } + + if (m_ModsToUpdate <= 0) { + statusBar()->hide(); + m_ModListSortProxy->setCategoryFilter(boost::assign::list_of(CategoryFactory::CATEGORY_SPECIAL_UPDATEAVAILABLE)); + for (int i = 0; i < ui->categoriesList->topLevelItemCount(); ++i) { + if (ui->categoriesList->topLevelItem(i)->data(0, Qt::UserRole) == CategoryFactory::CATEGORY_SPECIAL_UPDATEAVAILABLE) { + ui->categoriesList->setCurrentItem(ui->categoriesList->topLevelItem(i)); + break; + } + } + } else { + m_RefreshProgress->setValue(m_RefreshProgress->maximum() - m_ModsToUpdate); + } +} + +void MainWindow::nxmEndorsementToggled(QString, int, QVariant, QVariant resultData, int) +{ + QMap results = resultData.toMap(); + if (results["code"].toInt() == 200) { + if (results["status"].toString().compare("Endorsed") == 0) { + QMessageBox::information(this, tr("Thank you!"), tr("Thank you for your endorsement!")); + } else { + QMessageBox::information(this, tr("Okay."), tr("This mod will not be endorsed and will no longer ask you to endorse.")); + } + ui->actionEndorseMO->setVisible(false); + if (!disconnect(sender(), SIGNAL(nxmEndorsementToggled(QString, int, QVariant, QVariant, int)), + this, SLOT(nxmEndorsementToggled(QString, int, QVariant, QVariant, int)))) { + qCritical("failed to disconnect endorsement slot"); + } + } +} + +void MainWindow::nxmDownloadURLs(QString, int, int, QVariant, QVariant resultData, int) +{ + QVariantList serverList = resultData.toList(); + + QList servers; + for (const QVariant &server : serverList) { + QVariantMap serverInfo = server.toMap(); + ServerInfo info; + info.name = serverInfo["Name"].toString(); + info.premium = serverInfo["IsPremium"].toBool(); + info.lastSeen = QDate::currentDate(); + info.preferred = !info.name.compare("CDN", Qt::CaseInsensitive); + // other keys: ConnectedUsers, Country, URI + servers.append(info); + } + m_OrganizerCore.settings().updateServers(servers); +} + + +void MainWindow::nxmRequestFailed(QString, int modID, int, QVariant, int, const QString &errorString) +{ + if (modID == -1) { + // must be the update-check that failed + m_ModsToUpdate = 0; + statusBar()->hide(); + } + MessageDialog::showMessage(tr("Request to Nexus failed: %1").arg(errorString), this); +} + + +BSA::EErrorCode MainWindow::extractBSA(BSA::Archive &archive, BSA::Folder::Ptr folder, const QString &destination, + QProgressDialog &progress) +{ + QDir().mkdir(destination); + BSA::EErrorCode result = BSA::ERROR_NONE; + QString errorFile; + + for (unsigned int i = 0; i < folder->getNumFiles(); ++i) { + BSA::File::Ptr file = folder->getFile(i); + BSA::EErrorCode res = archive.extract(file, qUtf8Printable(destination)); + if (res != BSA::ERROR_NONE) { + reportError(tr("failed to read %1: %2").arg(file->getName().c_str()).arg(res)); + result = res; + } + progress.setLabelText(file->getName().c_str()); + progress.setValue(progress.value() + 1); + QCoreApplication::processEvents(); + if (progress.wasCanceled()) { + result = BSA::ERROR_CANCELED; + } + } + + if (result != BSA::ERROR_NONE) { + if (QMessageBox::critical(this, tr("Error"), tr("failed to extract %1 (errorcode %2)").arg(errorFile).arg(result), + QMessageBox::Ok | QMessageBox::Cancel) == QMessageBox::Cancel) { + return result; + } + } + + for (unsigned int i = 0; i < folder->getNumSubFolders(); ++i) { + BSA::Folder::Ptr subFolder = folder->getSubFolder(i); + BSA::EErrorCode res = extractBSA(archive, subFolder, + destination.mid(0).append("/").append(subFolder->getName().c_str()), progress); + if (res != BSA::ERROR_NONE) { + return res; + } + } + return BSA::ERROR_NONE; +} + + +bool MainWindow::extractProgress(QProgressDialog &progress, int percentage, std::string fileName) +{ + progress.setLabelText(fileName.c_str()); + progress.setValue(percentage); + QCoreApplication::processEvents(); + return !progress.wasCanceled(); +} + + +void MainWindow::extractBSATriggered() +{ + QTreeWidgetItem *item = m_ContextItem; + QString origin; + + QString targetFolder = FileDialogMemory::getExistingDirectory("extractBSA", this, tr("Extract BSA")); + QStringList archives = {}; + if (!targetFolder.isEmpty()) { + if (!item->parent()) { + for (int i = 0; i < item->childCount(); ++i) { + archives.append(item->child(i)->text(0)); + } + origin = QDir::fromNativeSeparators(ToQString(m_OrganizerCore.directoryStructure()->getOriginByName(ToWString(item->text(0))).getPath())); + } else { + origin = QDir::fromNativeSeparators(ToQString(m_OrganizerCore.directoryStructure()->getOriginByName(ToWString(item->text(1))).getPath())); + archives = QStringList({ item->text(0) }); + } + + for (auto archiveName : archives) { + BSA::Archive archive; + QString archivePath = QString("%1\\%2").arg(origin).arg(archiveName); + BSA::EErrorCode result = archive.read(archivePath.toLocal8Bit().constData(), true); + if ((result != BSA::ERROR_NONE) && (result != BSA::ERROR_INVALIDHASHES)) { + reportError(tr("failed to read %1: %2").arg(archivePath).arg(result)); + return; + } + + QProgressDialog progress(this); + progress.setMaximum(100); + progress.setValue(0); + progress.show(); + archive.extractAll(QDir::toNativeSeparators(targetFolder).toLocal8Bit().constData(), + boost::bind(&MainWindow::extractProgress, this, boost::ref(progress), _1, _2)); + if (result == BSA::ERROR_INVALIDHASHES) { + reportError(tr("This archive contains invalid hashes. Some files may be broken.")); + } + archive.close(); + } + } +} + + +void MainWindow::displayColumnSelection(const QPoint &pos) +{ + QMenu menu; + + // display a list of all headers as checkboxes + QAbstractItemModel *model = ui->modList->header()->model(); + for (int i = 1; i < model->columnCount(); ++i) { + QString columnName = model->headerData(i, Qt::Horizontal).toString(); + QCheckBox *checkBox = new QCheckBox(&menu); + checkBox->setText(columnName); + checkBox->setChecked(!ui->modList->header()->isSectionHidden(i)); + QWidgetAction *checkableAction = new QWidgetAction(&menu); + checkableAction->setDefaultWidget(checkBox); + menu.addAction(checkableAction); + } + menu.exec(pos); + + // view/hide columns depending on check-state + int i = 1; + for (const QAction *action : menu.actions()) { + const QWidgetAction *widgetAction = qobject_cast(action); + if (widgetAction != nullptr) { + const QCheckBox *checkBox = qobject_cast(widgetAction->defaultWidget()); + if (checkBox != nullptr) { + ui->modList->header()->setSectionHidden(i, !checkBox->isChecked()); + } + } + ++i; + } +} + +void MainWindow::on_bsaList_customContextMenuRequested(const QPoint &pos) +{ + m_ContextItem = ui->bsaList->itemAt(pos); + +// m_ContextRow = ui->bsaList->indexOfTopLevelItem(ui->bsaList->itemAt(pos)); + + QMenu menu; + menu.addAction(tr("Extract..."), this, SLOT(extractBSATriggered())); + + menu.exec(ui->bsaList->mapToGlobal(pos)); +} + +void MainWindow::on_bsaList_itemChanged(QTreeWidgetItem*, int) +{ + m_ArchiveListWriter.write(); + m_CheckBSATimer.start(500); +} + +void MainWindow::on_actionNotifications_triggered() +{ + updateProblemsButton(); + ProblemsDialog problems(m_PluginContainer.plugins(), this); + if (problems.hasProblems()) { + QSettings &settings = m_OrganizerCore.settings().directInterface(); + QString key = QString("geometry/%1").arg(problems.objectName()); + if (settings.contains(key)) { + problems.restoreGeometry(settings.value(key).toByteArray()); + } + problems.exec(); + settings.setValue(key, problems.saveGeometry()); + updateProblemsButton(); + } +} + +void MainWindow::on_actionChange_Game_triggered() +{ + if (QMessageBox::question(this, tr("Are you sure?"), + tr("This will restart MO, continue?"), + QMessageBox::Yes | QMessageBox::Cancel) + == QMessageBox::Yes) { + InstanceManager::instance().clearCurrentInstance(); + qApp->exit(INT_MAX); + } +} + +void MainWindow::setCategoryListVisible(bool visible) +{ + if (visible) { + ui->categoriesGroup->show(); + ui->displayCategoriesBtn->setText(ToQString(L"\u00ab")); + } else { + ui->categoriesGroup->hide(); + ui->displayCategoriesBtn->setText(ToQString(L"\u00bb")); + } +} + +void MainWindow::on_displayCategoriesBtn_toggled(bool checked) +{ + setCategoryListVisible(checked); +} + +void MainWindow::editCategories() +{ + CategoriesDialog dialog(this); + QSettings &settings = m_OrganizerCore.settings().directInterface(); + QString key = QString("geometry/%1").arg(dialog.objectName()); + if (settings.contains(key)) { + dialog.restoreGeometry(settings.value(key).toByteArray()); + } + if (dialog.exec() == QDialog::Accepted) { + dialog.commitChanges(); + } + settings.setValue(key, dialog.saveGeometry()); + +} + +void MainWindow::deselectFilters() +{ + ui->categoriesList->clearSelection(); +} + +void MainWindow::on_categoriesList_customContextMenuRequested(const QPoint &pos) +{ + QMenu menu; + menu.addAction(tr("Edit Categories..."), this, SLOT(editCategories())); + menu.addAction(tr("Deselect filter"), this, SLOT(deselectFilters())); + + menu.exec(ui->categoriesList->mapToGlobal(pos)); +} + + +void MainWindow::updateESPLock(bool locked) +{ + QItemSelection currentSelection = ui->espList->selectionModel()->selection(); + if (currentSelection.count() == 0) { + // this path is probably useless + m_OrganizerCore.pluginList()->lockESPIndex(m_ContextRow, locked); + } else { + Q_FOREACH (const QModelIndex &idx, currentSelection.indexes()) { + if (m_OrganizerCore.pluginList()->isEnabled(mapToModel(m_OrganizerCore.pluginList(), idx).row())) { + m_OrganizerCore.pluginList()->lockESPIndex(mapToModel(m_OrganizerCore.pluginList(), idx).row(), locked); + } + } + } +} + + +void MainWindow::lockESPIndex() +{ + updateESPLock(true); +} + +void MainWindow::unlockESPIndex() +{ + updateESPLock(false); +} + + +void MainWindow::removeFromToolbar() +{ + try { + Executable &exe = m_OrganizerCore.executablesList()->find(m_ContextAction->text()); + exe.showOnToolbar(false); + } catch (const std::runtime_error&) { + qDebug("executable doesn't exist any more"); + } + + updateToolBar(); +} + + +void MainWindow::toolBar_customContextMenuRequested(const QPoint &point) +{ + QAction *action = ui->toolBar->actionAt(point); + if (action != nullptr) { + if (action->objectName().startsWith("custom_")) { + m_ContextAction = action; + QMenu menu; + menu.addAction(tr("Remove"), this, SLOT(removeFromToolbar())); + menu.exec(ui->toolBar->mapToGlobal(point)); + } + } +} + +void MainWindow::on_espList_customContextMenuRequested(const QPoint &pos) +{ + m_ContextRow = m_PluginListSortProxy->mapToSource(ui->espList->indexAt(pos)).row(); + + QMenu menu; + menu.addAction(tr("Enable selected"), this, SLOT(enableSelectedPlugins_clicked())); + menu.addAction(tr("Disable selected"), this, SLOT(disableSelectedPlugins_clicked())); + + menu.addSeparator(); + + menu.addAction(tr("Enable all"), m_OrganizerCore.pluginList(), SLOT(enableAll())); + menu.addAction(tr("Disable all"), m_OrganizerCore.pluginList(), SLOT(disableAll())); + + menu.addSeparator(); + + addPluginSendToContextMenu(&menu); + + QItemSelection currentSelection = ui->espList->selectionModel()->selection(); + bool hasLocked = false; + bool hasUnlocked = false; + for (const QModelIndex &idx : currentSelection.indexes()) { + int row = m_PluginListSortProxy->mapToSource(idx).row(); + if (m_OrganizerCore.pluginList()->isEnabled(row)) { + if (m_OrganizerCore.pluginList()->isESPLocked(row)) { + hasLocked = true; + } else { + hasUnlocked = true; + } + } + } + + if (hasLocked) { + menu.addAction(tr("Unlock load order"), this, SLOT(unlockESPIndex())); + } + if (hasUnlocked) { + menu.addAction(tr("Lock load order"), this, SLOT(lockESPIndex())); + } + + menu.addSeparator(); + + + QModelIndex idx = ui->espList->selectionModel()->currentIndex(); + unsigned int modInfoIndex = ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(idx.data().toString())); + //this is to avoid showing the option on game files like skyrim.esm + if (modInfoIndex != UINT_MAX) { + menu.addAction(tr("Open Origin in Explorer"), this, SLOT(openOriginExplorer_clicked())); + ModInfo::Ptr modInfo = ModInfo::getByIndex(modInfoIndex); + std::vector flags = modInfo->getFlags(); + + if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_FOREIGN) == flags.end()) { + QAction *infoAction = menu.addAction(tr("Open Origin Info..."), this, SLOT(openOriginInformation_clicked())); + menu.setDefaultAction(infoAction); + } + } + + try { + menu.exec(ui->espList->mapToGlobal(pos)); + } catch (const std::exception &e) { + reportError(tr("Exception: ").arg(e.what())); + } catch (...) { + reportError(tr("Unknown exception")); + } +} + +void MainWindow::on_groupCombo_currentIndexChanged(int index) +{ + if (m_ModListSortProxy == nullptr) { + return; + } + QAbstractProxyModel *newModel = nullptr; + switch (index) { + case 1: { + newModel = new QtGroupingProxy(m_OrganizerCore.modList(), QModelIndex(), ModList::COL_CATEGORY, Qt::UserRole, + 0, Qt::UserRole + 2); + } break; + case 2: { + newModel = new QtGroupingProxy(m_OrganizerCore.modList(), QModelIndex(), ModList::COL_MODID, Qt::DisplayRole, + QtGroupingProxy::FLAG_NOGROUPNAME | QtGroupingProxy::FLAG_NOSINGLE, + Qt::UserRole + 2); + } break; + default: { + newModel = nullptr; + } break; + } + + if (newModel != nullptr) { +#ifdef TEST_MODELS + new ModelTest(newModel, this); +#endif // TEST_MODELS + m_ModListSortProxy->setSourceModel(newModel); + connect(ui->modList, SIGNAL(expanded(QModelIndex)),newModel, SLOT(expanded(QModelIndex))); + connect(ui->modList, SIGNAL(collapsed(QModelIndex)), newModel, SLOT(collapsed(QModelIndex))); + connect(newModel, SIGNAL(expandItem(QModelIndex)), this, SLOT(expandModList(QModelIndex))); + } else { + m_ModListSortProxy->setSourceModel(m_OrganizerCore.modList()); + } + modFilterActive(m_ModListSortProxy->isFilterActive()); +} + +const Executable &MainWindow::getSelectedExecutable() const +{ + QString name = ui->executablesListBox->itemText(ui->executablesListBox->currentIndex()); + return m_OrganizerCore.executablesList()->find(name); +} + +Executable &MainWindow::getSelectedExecutable() +{ + QString name = ui->executablesListBox->itemText(ui->executablesListBox->currentIndex()); + return m_OrganizerCore.executablesList()->find(name); +} + +void MainWindow::on_linkButton_pressed() +{ + const Executable &selectedExecutable(getSelectedExecutable()); + + const QIcon addIcon(":/MO/gui/link"); + const QIcon removeIcon(":/MO/gui/remove"); + + const QFileInfo linkDesktopFile(getDesktopLinkfile(selectedExecutable)); + const QFileInfo linkMenuFile(getStartMenuLinkfile(selectedExecutable)); + + ui->linkButton->menu()->actions().at(static_cast(ShortcutType::Toolbar))->setIcon(selectedExecutable.isShownOnToolbar() ? removeIcon : addIcon); + ui->linkButton->menu()->actions().at(static_cast(ShortcutType::Desktop))->setIcon(linkDesktopFile.exists() ? removeIcon : addIcon); + ui->linkButton->menu()->actions().at(static_cast(ShortcutType::StartMenu))->setIcon(linkMenuFile.exists() ? removeIcon : addIcon); +} + +void MainWindow::on_showHiddenBox_toggled(bool checked) +{ + m_OrganizerCore.downloadManager()->setShowHidden(checked); +} + + +void MainWindow::createStdoutPipe(HANDLE *stdOutRead, HANDLE *stdOutWrite) +{ + SECURITY_ATTRIBUTES secAttributes; + secAttributes.nLength = sizeof(SECURITY_ATTRIBUTES); + secAttributes.bInheritHandle = TRUE; + secAttributes.lpSecurityDescriptor = nullptr; + + if (!::CreatePipe(stdOutRead, stdOutWrite, &secAttributes, 0)) { + qCritical("failed to create stdout reroute"); + } + + if (!::SetHandleInformation(*stdOutRead, HANDLE_FLAG_INHERIT, 0)) { + qCritical("failed to correctly set up the stdout reroute"); + *stdOutWrite = *stdOutRead = INVALID_HANDLE_VALUE; + } +} + +std::string MainWindow::readFromPipe(HANDLE stdOutRead) +{ + static const int chunkSize = 128; + std::string result; + + char buffer[chunkSize + 1]; + buffer[chunkSize] = '\0'; + + DWORD read = 1; + while (read > 0) { + if (!::ReadFile(stdOutRead, buffer, chunkSize, &read, nullptr)) { + break; + } + if (read > 0) { + result.append(buffer, read); + if (read < chunkSize) { + break; + } + } + } + return result; +} + +void MainWindow::processLOOTOut(const std::string &lootOut, std::string &errorMessages, QProgressDialog &dialog) +{ + std::vector lines; + boost::split(lines, lootOut, boost::is_any_of("\r\n")); + + std::regex exRequires("\"([^\"]*)\" requires \"([^\"]*)\", but it is missing\\."); + std::regex exIncompatible("\"([^\"]*)\" is incompatible with \"([^\"]*)\", but both are present\\."); + + for (const std::string &line : lines) { + if (line.length() > 0) { + size_t progidx = line.find("[progress]"); + size_t erroridx = line.find("[error]"); + if (progidx != std::string::npos) { + dialog.setLabelText(line.substr(progidx + 11).c_str()); + } else if (erroridx != std::string::npos) { + qWarning("%s", line.c_str()); + errorMessages.append(boost::algorithm::trim_copy(line.substr(erroridx + 8)) + "\n"); + } else { + std::smatch match; + if (std::regex_match(line, match, exRequires)) { + std::string modName(match[1].first, match[1].second); + std::string dependency(match[2].first, match[2].second); + m_OrganizerCore.pluginList()->addInformation(modName.c_str(), tr("depends on missing \"%1\"").arg(dependency.c_str())); + } else if (std::regex_match(line, match, exIncompatible)) { + std::string modName(match[1].first, match[1].second); + std::string dependency(match[2].first, match[2].second); + m_OrganizerCore.pluginList()->addInformation(modName.c_str(), tr("incompatible with \"%1\"").arg(dependency.c_str())); + } else { + qDebug("[loot] %s", line.c_str()); + } + } + } + } +} + +void MainWindow::on_bossButton_clicked() +{ + std::string reportURL; + std::string errorMessages; + + //m_OrganizerCore.currentProfile()->writeModlistNow(); + m_OrganizerCore.savePluginList(); + //Create a backup of the load orders w/ LOOT in name + //to make sure that any sorting is easily undo-able. + //Need to figure out how I want to do that. + + bool success = false; + + try { + setEnabled(false); + ON_BLOCK_EXIT([&] () { setEnabled(true); }); + QProgressDialog dialog(this); + dialog.setLabelText(tr("Please wait while LOOT is running")); + dialog.setMaximum(0); + dialog.show(); + + QString outPath = QDir::temp().absoluteFilePath("lootreport.json"); + + QStringList parameters; + parameters << "--game" << m_OrganizerCore.managedGame()->gameShortName() + << "--gamePath" << QString("\"%1\"").arg(m_OrganizerCore.managedGame()->gameDirectory().absolutePath()) + << "--pluginListPath" << QString("\"%1/loadorder.txt\"").arg(m_OrganizerCore.profilePath()) + << "--out" << QString("\"%1\"").arg(outPath); + + if (m_DidUpdateMasterList) { + parameters << "--skipUpdateMasterlist"; + } + HANDLE stdOutWrite = INVALID_HANDLE_VALUE; + HANDLE stdOutRead = INVALID_HANDLE_VALUE; + createStdoutPipe(&stdOutRead, &stdOutWrite); + try { + m_OrganizerCore.prepareVFS(); + } catch (const UsvfsConnectorException &e) { + qDebug(e.what()); + return; + } catch (const std::exception &e) { + QMessageBox::warning(qApp->activeWindow(), tr("Error"), e.what()); + return; + } + + HANDLE loot = startBinary(QFileInfo(qApp->applicationDirPath() + "/loot/lootcli.exe"), + parameters.join(" "), + qApp->applicationDirPath() + "/loot", + true, + stdOutWrite); + + // we don't use the write end + ::CloseHandle(stdOutWrite); + + m_OrganizerCore.pluginList()->clearAdditionalInformation(); + + DWORD retLen; + JOBOBJECT_BASIC_PROCESS_ID_LIST info; + HANDLE processHandle = loot; + + if (loot != INVALID_HANDLE_VALUE) { + bool isJobHandle = true; + ULONG lastProcessID; + DWORD res = ::MsgWaitForMultipleObjects(1, &loot, false, 100, QS_KEY | QS_MOUSE); + while ((res != WAIT_FAILED) && (res != WAIT_OBJECT_0)) { + if (isJobHandle) { + if (::QueryInformationJobObject(loot, JobObjectBasicProcessIdList, &info, sizeof(info), &retLen) > 0) { + if (info.NumberOfProcessIdsInList == 0) { + qDebug("no more processes in job"); + break; + } else { + if (lastProcessID != info.ProcessIdList[0]) { + lastProcessID = info.ProcessIdList[0]; + if (processHandle != loot) { + ::CloseHandle(processHandle); + } + processHandle = ::OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, lastProcessID); + } + } + } else { + // the info-object I passed only provides space for 1 process id. but since this code only cares about whether there + // is more than one that's good enough. ERROR_MORE_DATA simply signals there are at least two processes running. + // any other error probably means the handle is a regular process handle, probably caused by running MO in a job without + // the right to break out. + if (::GetLastError() != ERROR_MORE_DATA) { + isJobHandle = false; + } + } + } + + if (dialog.wasCanceled()) { + if (isJobHandle) { + ::TerminateJobObject(loot, 1); + } else { + ::TerminateProcess(loot, 1); + } + } + + // keep processing events so the app doesn't appear dead + QCoreApplication::processEvents(); + std::string lootOut = readFromPipe(stdOutRead); + processLOOTOut(lootOut, errorMessages, dialog); + + res = ::MsgWaitForMultipleObjects(1, &loot, false, 100, QS_KEY | QS_MOUSE); + } + + std::string remainder = readFromPipe(stdOutRead).c_str(); + if (remainder.length() > 0) { + processLOOTOut(remainder, errorMessages, dialog); + } + DWORD exitCode = 0UL; + ::GetExitCodeProcess(processHandle, &exitCode); + ::CloseHandle(processHandle); + if (exitCode != 0UL) { + reportError(tr("loot failed. Exit code was: %1").arg(exitCode)); + return; + } else { + success = true; + QFile outFile(outPath); + outFile.open(QIODevice::ReadOnly); + QJsonDocument doc = QJsonDocument::fromJson(outFile.readAll()); + QJsonArray array = doc.array(); + for (auto iter = array.begin(); iter != array.end(); ++iter) { + QJsonObject pluginObj = (*iter).toObject(); + QJsonArray pluginMessages = pluginObj["messages"].toArray(); + for (auto msgIter = pluginMessages.begin(); msgIter != pluginMessages.end(); ++msgIter) { + QJsonObject msg = (*msgIter).toObject(); + m_OrganizerCore.pluginList()->addInformation(pluginObj["name"].toString(), + QString("%1: %2").arg(msg["type"].toString(), msg["message"].toString())); + } + if (pluginObj["dirty"].toString() == "yes") + m_OrganizerCore.pluginList()->addInformation(pluginObj["name"].toString(), "dirty"); + } + + } + } else { + reportError(tr("failed to start loot")); + } + } catch (const std::exception &e) { + reportError(tr("failed to run loot: %1").arg(e.what())); + } + + if (errorMessages.length() > 0) { + QMessageBox *warn = new QMessageBox(QMessageBox::Warning, tr("Errors occured"), errorMessages.c_str(), QMessageBox::Ok, this); + warn->setModal(false); + warn->show(); + } + + if (success) { + m_DidUpdateMasterList = true; + if (reportURL.length() > 0) { + m_IntegratedBrowser.setWindowTitle("LOOT Report"); + QString report(reportURL.c_str()); + QStringList temp = report.split("?"); + QUrl url = QUrl::fromLocalFile(temp.at(0)); + if (temp.size() > 1) { + url.setQuery(temp.at(1).toUtf8()); + } + m_IntegratedBrowser.openUrl(url); + } + m_OrganizerCore.refreshESPList(false); + m_OrganizerCore.savePluginList(); + } +} + + +const char *MainWindow::PATTERN_BACKUP_GLOB = ".????_??_??_??_??_??"; +const char *MainWindow::PATTERN_BACKUP_REGEX = "\\.(\\d\\d\\d\\d_\\d\\d_\\d\\d_\\d\\d_\\d\\d_\\d\\d)"; +const char *MainWindow::PATTERN_BACKUP_DATE = "yyyy_MM_dd_hh_mm_ss"; + + +bool MainWindow::createBackup(const QString &filePath, const QDateTime &time) +{ + QString outPath = filePath + "." + time.toString(PATTERN_BACKUP_DATE); + if (shellCopy(QStringList(filePath), QStringList(outPath), this)) { + QFileInfo fileInfo(filePath); + removeOldFiles(fileInfo.absolutePath(), fileInfo.fileName() + PATTERN_BACKUP_GLOB, 10, QDir::Name); + return true; + } else { + return false; + } +} + +void MainWindow::on_saveButton_clicked() +{ + m_OrganizerCore.savePluginList(); + QDateTime now = QDateTime::currentDateTime(); + if (createBackup(m_OrganizerCore.currentProfile()->getPluginsFileName(), now) + && createBackup(m_OrganizerCore.currentProfile()->getLoadOrderFileName(), now) + && createBackup(m_OrganizerCore.currentProfile()->getLockedOrderFileName(), now)) { + MessageDialog::showMessage(tr("Backup of load order created"), this); + } +} + +QString MainWindow::queryRestore(const QString &filePath) +{ + QFileInfo pluginFileInfo(filePath); + QString pattern = pluginFileInfo.fileName() + ".*"; + QFileInfoList files = pluginFileInfo.absoluteDir().entryInfoList(QStringList(pattern), QDir::Files, QDir::Name); + + SelectionDialog dialog(tr("Choose backup to restore"), this); + QRegExp exp(pluginFileInfo.fileName() + PATTERN_BACKUP_REGEX); + QRegExp exp2(pluginFileInfo.fileName() + "\\.(.*)"); + for(const QFileInfo &info : boost::adaptors::reverse(files)) { + if (exp.exactMatch(info.fileName())) { + QDateTime time = QDateTime::fromString(exp.cap(1), PATTERN_BACKUP_DATE); + dialog.addChoice(time.toString(), "", exp.cap(1)); + } else if (exp2.exactMatch(info.fileName())) { + dialog.addChoice(exp2.cap(1), "", exp2.cap(1)); + } + } + + if (dialog.numChoices() == 0) { + QMessageBox::information(this, tr("No Backups"), tr("There are no backups to restore")); + return QString(); + } + + if (dialog.exec() == QDialog::Accepted) { + return dialog.getChoiceData().toString(); + } else { + return QString(); + } +} + +void MainWindow::on_restoreButton_clicked() +{ + QString pluginName = m_OrganizerCore.currentProfile()->getPluginsFileName(); + QString choice = queryRestore(pluginName); + if (!choice.isEmpty()) { + QString loadOrderName = m_OrganizerCore.currentProfile()->getLoadOrderFileName(); + QString lockedName = m_OrganizerCore.currentProfile()->getLockedOrderFileName(); + if (!shellCopy(pluginName + "." + choice, pluginName, true, this) || + !shellCopy(loadOrderName + "." + choice, loadOrderName, true, this) || + !shellCopy(lockedName + "." + choice, lockedName, true, this)) { + QMessageBox::critical(this, tr("Restore failed"), + tr("Failed to restore the backup. Errorcode: %1").arg(windowsErrorString(::GetLastError()))); + } + m_OrganizerCore.refreshESPList(true); + } +} + +void MainWindow::on_saveModsButton_clicked() +{ + m_OrganizerCore.currentProfile()->writeModlistNow(true); + QDateTime now = QDateTime::currentDateTime(); + if (createBackup(m_OrganizerCore.currentProfile()->getModlistFileName(), now)) { + MessageDialog::showMessage(tr("Backup of modlist created"), this); + } +} + +void MainWindow::on_restoreModsButton_clicked() +{ + QString modlistName = m_OrganizerCore.currentProfile()->getModlistFileName(); + QString choice = queryRestore(modlistName); + if (!choice.isEmpty()) { + if (!shellCopy(modlistName + "." + choice, modlistName, true, this)) { + QMessageBox::critical(this, tr("Restore failed"), + tr("Failed to restore the backup. Errorcode: %1").arg(windowsErrorString(::GetLastError()))); + } + m_OrganizerCore.refreshModList(false); + } +} + +void MainWindow::on_actionCopy_Log_to_Clipboard_triggered() +{ + QStringList lines; + QAbstractItemModel *model = ui->logList->model(); + for (int i = 0; i < model->rowCount(); ++i) { + lines.append(QString("%1 [%2] %3").arg(model->index(i, 0).data().toString()) + .arg(model->index(i, 1).data(Qt::UserRole).toString()) + .arg(model->index(i, 1).data().toString())); + } + QApplication::clipboard()->setText(lines.join("\n")); +} + +void MainWindow::on_categoriesAndBtn_toggled(bool checked) +{ + if (checked) { + m_ModListSortProxy->setFilterMode(ModListSortProxy::FILTER_AND); + } +} + +void MainWindow::on_categoriesOrBtn_toggled(bool checked) +{ + if (checked) { + m_ModListSortProxy->setFilterMode(ModListSortProxy::FILTER_OR); + } +} + +void MainWindow::on_managedArchiveLabel_linkHovered(const QString&) +{ + QToolTip::showText(QCursor::pos(), + ui->managedArchiveLabel->toolTip()); +} + +void MainWindow::dragEnterEvent(QDragEnterEvent *event) +{ + //Accept copy or move drags to the download window. Link drags are not + //meaningful (Well, they are - we could drop a link in the download folder, + //but you need privileges to do that). + if (ui->downloadTab->isVisible() && + (event->proposedAction() == Qt::CopyAction || + event->proposedAction() == Qt::MoveAction) && + event->answerRect().intersects(ui->downloadTab->rect())) { + + //If I read the documentation right, this won't work under a motif windows + //manager and the check needs to be done at the drop. However, that means + //the user might be allowed to drop things which we can't sanely process + QMimeData const *data = event->mimeData(); + + if (data->hasUrls()) { + QStringList extensions = + m_OrganizerCore.installationManager()->getSupportedExtensions(); + + //This is probably OK - scan to see if these are moderately sane archive + //types + QList urls = data->urls(); + bool ok = true; + for (const QUrl &url : urls) { + if (url.isLocalFile()) { + QString local = url.toLocalFile(); + bool fok = false; + for (auto ext : extensions) { + if (local.endsWith(ext, Qt::CaseInsensitive)) { + fok = true; + break; + } + } + if (! fok) { + ok = false; + break; + } + } + } + if (ok) { + event->accept(); + } + } + } +} + +void MainWindow::dropLocalFile(const QUrl &url, const QString &outputDir, bool move) +{ + QFileInfo file(url.toLocalFile()); + if (!file.exists()) { + qWarning("invalid source file: %s", qUtf8Printable(file.absoluteFilePath())); + return; + } + QString target = outputDir + "/" + file.fileName(); + if (QFile::exists(target)) { + QMessageBox box(QMessageBox::Question, + file.fileName(), + tr("A file with the same name has already been downloaded. " + "What would you like to do?")); + box.addButton(tr("Overwrite"), QMessageBox::ActionRole); + box.addButton(tr("Rename new file"), QMessageBox::YesRole); + box.addButton(tr("Ignore file"), QMessageBox::RejectRole); + + box.exec(); + switch (box.buttonRole(box.clickedButton())) { + case QMessageBox::RejectRole: + return; + case QMessageBox::ActionRole: + break; + default: + case QMessageBox::YesRole: + target = m_OrganizerCore.downloadManager()->getDownloadFileName(file.fileName()); + break; + } + } + + bool success = false; + if (move) { + success = shellMove(file.absoluteFilePath(), target, true, this); + } else { + success = shellCopy(file.absoluteFilePath(), target, true, this); + } + if (!success) { + qCritical("file operation failed: %s", qUtf8Printable(windowsErrorString(::GetLastError()))); + } +} + +bool MainWindow::registerWidgetState(const QString &name, QHeaderView *view, const char *oldSettingName) { + // register the view so it's geometry gets saved at exit + m_PersistedGeometry.push_back(std::make_pair(name, view)); + + // also, restore the geometry if it was saved before + QSettings &settings = m_OrganizerCore.settings().directInterface(); + + QString key = QString("geometry/%1").arg(name); + QByteArray data; + + if ((oldSettingName != nullptr) && settings.contains(oldSettingName)) { + data = settings.value(oldSettingName).toByteArray(); + settings.remove(oldSettingName); + } else if (settings.contains(key)) { + data = settings.value(key).toByteArray(); + } + + if (!data.isEmpty()) { + view->restoreState(data); + return true; + } else { + return false; + } +} + +void MainWindow::dropEvent(QDropEvent *event) +{ + Qt::DropAction action = event->proposedAction(); + QString outputDir = m_OrganizerCore.downloadManager()->getOutputDirectory(); + if (action == Qt::MoveAction) { + //Tell windows I'm taking control and will delete the source of a move. + event->setDropAction(Qt::TargetMoveAction); + } + for (const QUrl &url : event->mimeData()->urls()) { + if (url.isLocalFile()) { + dropLocalFile(url, outputDir, action == Qt::MoveAction); + } else { + m_OrganizerCore.downloadManager()->startDownloadURLs(QStringList() << url.url()); + } + } + event->accept(); +} + + +void MainWindow::on_clickBlankButton_clicked() +{ + deselectFilters(); +} + +void MainWindow::on_clearFiltersButton_clicked() +{ + ui->modFilterEdit->clear(); + deselectFilters(); +} + +void MainWindow::sendSelectedModsToPriority(int newPriority) +{ + QItemSelectionModel *selection = ui->modList->selectionModel(); + if (selection->hasSelection() && selection->selectedRows().count() > 1) { + std::vector modsToMove; + for (auto idx : selection->selectedRows(ModList::COL_PRIORITY)) { + modsToMove.push_back(m_OrganizerCore.currentProfile()->modIndexByPriority(idx.data().toInt())); + } + m_OrganizerCore.modList()->changeModPriority(modsToMove, newPriority); + } else { + m_OrganizerCore.modList()->changeModPriority(m_ContextRow, newPriority); + } +} + +void MainWindow::sendSelectedModsToTop_clicked() +{ + sendSelectedModsToPriority(0); +} + +void MainWindow::sendSelectedModsToBottom_clicked() +{ + sendSelectedModsToPriority(INT_MAX); +} + +void MainWindow::sendSelectedModsToPriority_clicked() +{ + bool ok; + int newPriority = QInputDialog::getInt(this, + tr("Set Priority"), tr("Set the priority of the selected mods"), + 0, 0, INT_MAX, 1, &ok); + if (!ok) return; + + sendSelectedModsToPriority(newPriority); +} + +void MainWindow::sendSelectedModsToSeparator_clicked() +{ + QStringList separators; + auto indexesByPriority = m_OrganizerCore.currentProfile()->getAllIndexesByPriority(); + for (auto iter = indexesByPriority.begin(); iter != indexesByPriority.end(); iter++) { + if ((iter->second != UINT_MAX)) { + ModInfo::Ptr modInfo = ModInfo::getByIndex(iter->second); + if (modInfo->hasFlag(ModInfo::FLAG_SEPARATOR)) { + separators << modInfo->name().chopped(10); // Chops the "_separator" away from the name + } + } + } + + ListDialog dialog(this); + QSettings &settings = m_OrganizerCore.settings().directInterface(); + QString key = QString("geometry/%1").arg(dialog.objectName()); + + dialog.setWindowTitle("Select a separator..."); + dialog.setChoices(separators); + dialog.restoreGeometry(settings.value(key).toByteArray()); + if (dialog.exec() == QDialog::Accepted) { + QString result = dialog.getChoice(); + if (!result.isEmpty()) { + result += "_separator"; + + int newPriority = INT_MAX; + bool foundSection = false; + for (auto mod : m_OrganizerCore.modsSortedByProfilePriority()) { + unsigned int modIndex = ModInfo::getIndex(mod); + ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); + if (!foundSection && result.compare(mod) == 0) { + foundSection = true; + } else if (foundSection && modInfo->hasFlag(ModInfo::FLAG_SEPARATOR)) { + newPriority = m_OrganizerCore.currentProfile()->getModPriority(modIndex); + break; + } + } + + QItemSelectionModel *selection = ui->modList->selectionModel(); + if (selection->hasSelection() && selection->selectedRows().count() > 1) { + std::vector modsToMove; + for (QModelIndex idx : selection->selectedRows(ModList::COL_PRIORITY)) { + modsToMove.push_back(m_OrganizerCore.currentProfile()->modIndexByPriority(idx.data().toInt())); + } + m_OrganizerCore.modList()->changeModPriority(modsToMove, newPriority); + } else { + int oldPriority = m_OrganizerCore.currentProfile()->getModPriority(m_ContextRow); + if (oldPriority < newPriority) + --newPriority; + m_OrganizerCore.modList()->changeModPriority(m_ContextRow, newPriority); + } + } + } + settings.setValue(key, dialog.saveGeometry()); +} + +void MainWindow::on_showArchiveDataCheckBox_toggled(const bool checked) +{ + if (m_OrganizerCore.getArchiveParsing() && checked) + { + m_showArchiveData = checked; + } + else + { + m_showArchiveData = false; + } + refreshDataTree(); +} + diff --git a/src/modinforegular.cpp b/src/modinforegular.cpp index 529f20cb..3523feae 100644 --- a/src/modinforegular.cpp +++ b/src/modinforegular.cpp @@ -216,8 +216,10 @@ void ModInfoRegular::nxmDescriptionAvailable(QString, int, QVariant, QVariant re setNewestVersion(VersionInfo(result["version"].toString())); setNexusDescription(result["description"].toString()); - if ((m_EndorsedState != ENDORSED_NEVER) && (result.contains("voted_by_user"))) { - setEndorsedState(result["voted_by_user"].toBool() ? ENDORSED_TRUE : ENDORSED_FALSE); + if ((m_EndorsedState != ENDORSED_NEVER) && (result.contains("endorsement"))) { + QVariantMap endorsement = result["endorsement"].toMap(); + QString endorsementStatus = endorsement["endorse_status"].toString(); + setEndorsedState(endorsementStatus.compare("Endorsed") == 0 ? ENDORSED_TRUE : ENDORSED_FALSE); } m_LastNexusQuery = QDateTime::currentDateTime(); //m_MetaInfoChanged = true; @@ -228,10 +230,17 @@ void ModInfoRegular::nxmDescriptionAvailable(QString, int, QVariant, QVariant re void ModInfoRegular::nxmEndorsementToggled(QString, int, QVariant, QVariant resultData) { - m_EndorsedState = resultData.toBool() ? ENDORSED_TRUE : ENDORSED_FALSE; - m_MetaInfoChanged = true; - saveMeta(); - emit modDetailsUpdated(true); + QMap results = resultData.toMap(); + if (results["code"].toInt() == 200 || results["code"].toInt() == 201) { + if (results["status"].toString().compare("Endorsed") == 0) { + m_EndorsedState = ENDORSED_TRUE; + } else { + m_EndorsedState = ENDORSED_FALSE; + } + m_MetaInfoChanged = true; + saveMeta(); + emit modDetailsUpdated(true); + } } @@ -435,7 +444,7 @@ bool ModInfoRegular::remove() void ModInfoRegular::endorse(bool doEndorse) { if (doEndorse != (m_EndorsedState == ENDORSED_TRUE)) { - m_NexusBridge.requestToggleEndorsement(m_GameName, getNexusID(), doEndorse, QVariant(1)); + m_NexusBridge.requestToggleEndorsement(m_GameName, getNexusID(), m_Version.canonicalString(), doEndorse, QVariant(1)); } } diff --git a/src/nexusinterface.cpp b/src/nexusinterface.cpp index 993ae41e..4fe86136 100644 --- a/src/nexusinterface.cpp +++ b/src/nexusinterface.cpp @@ -28,6 +28,7 @@ along with Mod Organizer. If not, see . #include #include +#include #include @@ -62,9 +63,9 @@ void NexusBridge::requestDownloadURL(QString gameName, int modID, int fileID, QV m_RequestIDs.insert(m_Interface->requestDownloadURL(gameName, modID, fileID, this, userData, m_SubModule)); } -void NexusBridge::requestToggleEndorsement(QString gameName, int modID, bool endorse, QVariant userData) +void NexusBridge::requestToggleEndorsement(QString gameName, int modID, QString modVersion, bool endorse, QVariant userData) { - m_RequestIDs.insert(m_Interface->requestToggleEndorsement(gameName, modID, endorse, this, userData, m_SubModule)); + m_RequestIDs.insert(m_Interface->requestToggleEndorsement(gameName, modID, modVersion, endorse, this, userData, m_SubModule)); } void NexusBridge::nxmDescriptionAvailable(QString gameName, int modID, QVariant userData, QVariant resultData, int requestID) @@ -85,17 +86,18 @@ void NexusBridge::nxmFilesAvailable(QString gameName, int modID, QVariant userDa QList fileInfoList; - QVariantList resultList = resultData.toList(); + QVariantMap resultInfo = resultData.toMap(); + QList resultList = resultInfo["files"].toList(); for (const QVariant &file : resultList) { ModRepositoryFileInfo temp; QVariantMap fileInfo = file.toMap(); - temp.uri = fileInfo["uri"].toString(); + temp.uri = fileInfo["file_name"].toString(); temp.name = fileInfo["name"].toString(); - temp.description = fileInfo["description"].toString(); + temp.description = fileInfo["changelog_html"].toString(); temp.version = VersionInfo(fileInfo["version"].toString()); temp.categoryID = fileInfo["category_id"].toInt(); - temp.fileID = fileInfo["id"].toInt(); + temp.fileID = fileInfo["file_id"].toInt(); temp.fileSize = fileInfo["size"].toInt(); fileInfoList.append(temp); } @@ -399,10 +401,10 @@ int NexusInterface::requestDownloadURL(QString gameName, int modID, int fileID, } -int NexusInterface::requestToggleEndorsement(QString gameName, int modID, bool endorse, QObject *receiver, QVariant userData, +int NexusInterface::requestToggleEndorsement(QString gameName, int modID, QString modVersion, bool endorse, QObject *receiver, QVariant userData, const QString &subModule, MOBase::IPluginGame const *game) { - NXMRequestInfo requestInfo(modID, NXMRequestInfo::TYPE_TOGGLEENDORSEMENT, userData, subModule, game); + NXMRequestInfo requestInfo(modID, modVersion, NXMRequestInfo::TYPE_TOGGLEENDORSEMENT, userData, subModule, game); requestInfo.m_Endorse = endorse; m_RequestQueue.enqueue(requestInfo); @@ -456,11 +458,11 @@ void NexusInterface::nextRequest() return; } - if (requiresLogin(m_RequestQueue.head()) && !getAccessManager()->loggedIn()) { - if (!getAccessManager()->loginAttempted()) { + if (requiresLogin(m_RequestQueue.head()) && !getAccessManager()->validated()) { + if (!getAccessManager()->validateAttempted()) { emit needLogin(); return; - } else if (getAccessManager()->loginWaiting()) { + } else if (getAccessManager()->validateWaiting()) { return; } } @@ -469,42 +471,51 @@ void NexusInterface::nextRequest() info.m_Timeout = new QTimer(this); info.m_Timeout->setInterval(60000); + QJsonObject postObject; + QJsonDocument postData(postObject); + QString url; if (!info.m_Reroute) { bool hasParams = false; switch (info.m_Type) { case NXMRequestInfo::TYPE_DESCRIPTION: { - url = QString("%1/Mods/%2/").arg(info.m_URL).arg(info.m_ModID); + url = QString("%1/games/%2/mods/%3").arg(info.m_URL).arg(info.m_GameName).arg(info.m_ModID); } break; case NXMRequestInfo::TYPE_FILES: { - url = QString("%1/Files/indexfrommod/%2/").arg(info.m_URL).arg(info.m_ModID); + url = QString("%1/games/%2/mods/%3/files").arg(info.m_URL).arg(info.m_GameName).arg(info.m_ModID); } break; case NXMRequestInfo::TYPE_FILEINFO: { - url = QString("%1/Files/%2/").arg(info.m_URL).arg(info.m_FileID); + url = QString("%1/games/%2/mods/%3/files/%4").arg(info.m_URL).arg(info.m_GameName).arg(info.m_ModID).arg(info.m_FileID); } break; case NXMRequestInfo::TYPE_DOWNLOADURL: { - url = QString("%1/Files/download/%2").arg(info.m_URL).arg(info.m_FileID); + url = QString("%1/games/%2/mods/%3/files/%4/download_link").arg(info.m_URL).arg(info.m_GameName).arg(info.m_ModID).arg(info.m_FileID); } break; case NXMRequestInfo::TYPE_TOGGLEENDORSEMENT: { - url = QString("%1/Mods/toggleendorsement/%2?lvote=%3").arg(info.m_URL).arg(info.m_ModID).arg(!info.m_Endorse); - hasParams = true; + QString endorse = info.m_Endorse ? "endorse" : "abstain"; + url = QString("%1/games/%2/mods/%3/%4").arg(info.m_URL).arg(info.m_GameName).arg(info.m_ModID).arg(endorse); + postObject.insert("Version", info.m_ModVersion); + postData.setObject(postObject); } break; case NXMRequestInfo::TYPE_GETUPDATES: { QString modIDList = VectorJoin(info.m_ModIDList, ","); modIDList = "[" + modIDList + "]"; url = QString("%1/Mods/GetUpdates?ModList=%2").arg(info.m_URL).arg(modIDList); - hasParams = true; } break; } - url.append(QString("%1game_id=%2").arg(hasParams ? '&' : '?').arg(info.m_NexusGameID)); } else { url = info.m_URL; } QNetworkRequest request(url); - request.setHeader(QNetworkRequest::ContentTypeHeader, "application/xml"); - request.setRawHeader("User-Agent", m_AccessManager->userAgent(info.m_SubModule).toUtf8()); + request.setRawHeader("apikey", m_AccessManager->apiKey().toUtf8()); + request.setHeader(QNetworkRequest::KnownHeaders::UserAgentHeader, m_AccessManager->userAgent(info.m_SubModule)); + request.setHeader(QNetworkRequest::KnownHeaders::ContentTypeHeader, "application/json"); + request.setRawHeader("Protocol-Version", "0.5.5"); + request.setRawHeader("Application-Version", QApplication::applicationVersion().toUtf8()); - info.m_Reply = m_AccessManager->get(request); + if (postData.object().isEmpty()) + info.m_Reply = m_AccessManager->get(request); + else + info.m_Reply = m_AccessManager->post(request, postData.toJson()); connect(info.m_Reply, SIGNAL(finished()), this, SLOT(requestFinished())); connect(info.m_Reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(requestError(QNetworkReply::NetworkError))); @@ -627,7 +638,7 @@ void NexusInterface::requestTimeout() namespace { QString get_management_url(MOBase::IPluginGame const *game) { - return "https://legacy-api.nexusmods.com/" + game->gameNexusName().toLower(); + return "https://api.nexusmods.com/v1"; } } @@ -638,6 +649,7 @@ NexusInterface::NXMRequestInfo::NXMRequestInfo(int modID , MOBase::IPluginGame const *game ) : m_ModID(modID) + , m_ModVersion("0") , m_FileID(0) , m_Reply(nullptr) , m_Type(type) @@ -648,7 +660,30 @@ NexusInterface::NXMRequestInfo::NXMRequestInfo(int modID , m_URL(get_management_url(game)) , m_SubModule(subModule) , m_NexusGameID(game->nexusGameID()) - , m_GameName(game->gameShortName()) + , m_GameName(game->gameNexusName()) + , m_Endorse(false) +{} + +NexusInterface::NXMRequestInfo::NXMRequestInfo(int modID + , QString modVersion + , NexusInterface::NXMRequestInfo::Type type + , QVariant userData + , const QString &subModule + , MOBase::IPluginGame const *game +) + : m_ModID(modID) + , m_ModVersion(modVersion) + , m_FileID(0) + , m_Reply(nullptr) + , m_Type(type) + , m_UserData(userData) + , m_Timeout(nullptr) + , m_Reroute(false) + , m_ID(s_NextID.fetchAndAddAcquire(1)) + , m_URL(get_management_url(game)) + , m_SubModule(subModule) + , m_NexusGameID(game->nexusGameID()) + , m_GameName(game->gameNexusName()) , m_Endorse(false) {} @@ -659,6 +694,7 @@ NexusInterface::NXMRequestInfo::NXMRequestInfo(std::vector modIDList , MOBase::IPluginGame const *game ) : m_ModID(-1) + , m_ModVersion("0") , m_ModIDList(modIDList) , m_FileID(0) , m_Reply(nullptr) @@ -670,18 +706,19 @@ NexusInterface::NXMRequestInfo::NXMRequestInfo(std::vector modIDList , m_URL(get_management_url(game)) , m_SubModule(subModule) , m_NexusGameID(game->nexusGameID()) - , m_GameName(game->gameShortName()) + , m_GameName(game->gameNexusName()) , m_Endorse(false) {} NexusInterface::NXMRequestInfo::NXMRequestInfo(int modID - , int fileID - , NexusInterface::NXMRequestInfo::Type type - , QVariant userData - , const QString &subModule - , MOBase::IPluginGame const *game - ) + , int fileID + , NexusInterface::NXMRequestInfo::Type type + , QVariant userData + , const QString &subModule + , MOBase::IPluginGame const *game +) : m_ModID(modID) + , m_ModVersion("0") , m_FileID(fileID) , m_Reply(nullptr) , m_Type(type) @@ -692,6 +729,6 @@ NexusInterface::NXMRequestInfo::NXMRequestInfo(int modID , m_URL(get_management_url(game)) , m_SubModule(subModule) , m_NexusGameID(game->nexusGameID()) - , m_GameName(game->gameShortName()) + , m_GameName(game->gameNexusName()) , m_Endorse(false) {} diff --git a/src/nexusinterface.h b/src/nexusinterface.h index defb370f..7b707711 100644 --- a/src/nexusinterface.h +++ b/src/nexusinterface.h @@ -96,7 +96,7 @@ public: * @param modID id of the mod caller is interested in * @param userData user data to be returned with the result */ - virtual void requestToggleEndorsement(QString gameName, int modID, bool endorse, QVariant userData); + virtual void requestToggleEndorsement(QString gameName, int modID, QString modVersion, bool endorse, QVariant userData); public slots: @@ -255,9 +255,9 @@ public: * @param userData user data to be returned with the result * @return int an id to identify the request */ - int requestToggleEndorsement(QString gameName, int modID, bool endorse, QObject *receiver, QVariant userData, const QString &subModule) + int requestToggleEndorsement(QString gameName, int modID, QString modVersion, bool endorse, QObject *receiver, QVariant userData, const QString &subModule) { - return requestToggleEndorsement(gameName, modID, endorse, receiver, userData, subModule, getGame(gameName)); + return requestToggleEndorsement(gameName, modID, modVersion, endorse, receiver, userData, subModule, getGame(gameName)); } /** @@ -269,7 +269,7 @@ public: * @param game the game with which the mods are associated * @return int an id to identify the request */ - int requestToggleEndorsement(QString gameName, int modID, bool endorse, QObject *receiver, QVariant userData, const QString &subModule, + int requestToggleEndorsement(QString gameName, int modID, QString modVersion, bool endorse, QObject *receiver, QVariant userData, const QString &subModule, MOBase::IPluginGame const *game); /** @@ -363,6 +363,7 @@ private: struct NXMRequestInfo { int m_ModID; + QString m_ModVersion; std::vector m_ModIDList; int m_FileID; QNetworkReply *m_Reply; @@ -385,6 +386,7 @@ private: int m_Endorse; NXMRequestInfo(int modID, Type type, QVariant userData, const QString &subModule, MOBase::IPluginGame const *game); + NXMRequestInfo(int modID, QString modVersion, Type type, QVariant userData, const QString &subModule, MOBase::IPluginGame const *game); NXMRequestInfo(std::vector modIDList, Type type, QVariant userData, const QString &subModule, MOBase::IPluginGame const *game); NXMRequestInfo(int modID, int fileID, Type type, QVariant userData, const QString &subModule, MOBase::IPluginGame const *game); diff --git a/src/nxmaccessmanager.cpp b/src/nxmaccessmanager.cpp index 912eab30..dc1eb2cb 100644 --- a/src/nxmaccessmanager.cpp +++ b/src/nxmaccessmanager.cpp @@ -1,351 +1,264 @@ -/* -Copyright (C) 2012 Sebastian Herbord. All rights reserved. - -This file is part of Mod Organizer. - -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 . -*/ - -#include "nxmaccessmanager.h" - -#include "iplugingame.h" -#include "nxmurl.h" -#include "report.h" -#include "utility.h" -#include "selfupdater.h" -#include "persistentcookiejar.h" -#include "settings.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace MOBase; - -namespace { - QString const Nexus_Management_URL("https://legacy-api.nexusmods.com"); -} - -// unfortunately Nexus doesn't seem to document these states, all I know is all these listed -// are considered premium (27 should be lifetime premium) -const std::set NXMAccessManager::s_PremiumAccountStates { 4, 6, 13, 27, 31, 32 }; - - -NXMAccessManager::NXMAccessManager(QObject *parent, const QString &moVersion) - : QNetworkAccessManager(parent) - , m_LoginReply(nullptr) - , m_MOVersion(moVersion) -{ - m_LoginTimeout.setSingleShot(true); - m_LoginTimeout.setInterval(30000); - setCookieJar(new PersistentCookieJar( - QDir::fromNativeSeparators(Settings::instance().getCacheDirectory() + "/nexus_cookies.dat"))); - - if (networkAccessible() == QNetworkAccessManager::UnknownAccessibility) { - // why is this necessary all of a sudden? - setNetworkAccessible(QNetworkAccessManager::Accessible); - } -} - -NXMAccessManager::~NXMAccessManager() -{ - if (m_LoginReply != nullptr) { - m_LoginReply->deleteLater(); - m_LoginReply = nullptr; - } -} - -void NXMAccessManager::setNMMVersion(const QString &nmmVersion) -{ - m_NMMVersion = nmmVersion; -} - -QNetworkReply *NXMAccessManager::createRequest( - QNetworkAccessManager::Operation operation, const QNetworkRequest &request, - QIODevice *device) -{ - if (request.url().scheme() != "nxm") { - return QNetworkAccessManager::createRequest(operation, request, device); - } - if (operation == GetOperation) { - emit requestNXMDownload(request.url().toString()); - - // eat the request, everything else will be done by the download manager - return QNetworkAccessManager::createRequest(QNetworkAccessManager::GetOperation, - QNetworkRequest(QUrl())); - } else if (operation == PostOperation) { - return QNetworkAccessManager::createRequest(operation, request, device);; - } else { - return QNetworkAccessManager::createRequest(operation, request, device); - } -} - - -void NXMAccessManager::showCookies() const -{ - QUrl url(Nexus_Management_URL + "/"); - for (const QNetworkCookie &cookie : cookieJar()->cookiesForUrl(url)) { - qDebug("%s - %s (expires: %s)", - cookie.name().constData(), cookie.value().constData(), - qUtf8Printable(cookie.expirationDate().toString())); - } -} - -void NXMAccessManager::clearCookies() -{ - PersistentCookieJar *jar = qobject_cast(cookieJar()); - if (jar != nullptr) { - jar->clear(); - } else { - qWarning("failed to clear cookies, invalid cookie jar"); - } -} - -void NXMAccessManager::startLoginCheck() -{ - if (hasLoginCookies()) { - qDebug("validating login cookies"); - QNetworkRequest request(Nexus_Management_URL + "/Sessions/?Validate"); - request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); - request.setRawHeader("User-Agent", userAgent().toUtf8()); - - m_LoginReply = get(request); - m_LoginTimeout.start(); - m_LoginState = LOGIN_CHECKING; - connect(m_LoginReply, SIGNAL(finished()), this, SLOT(loginChecked())); - connect(m_LoginReply, SIGNAL(error(QNetworkReply::NetworkError)), - this, SLOT(loginError(QNetworkReply::NetworkError))); - } -} - - -void NXMAccessManager::retrieveCredentials() -{ - qDebug("retrieving credentials"); - - QNetworkRequest request(Nexus_Management_URL + "/Core/Libs/Flamework/Entities/User?GetCredentials"); - request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); - request.setRawHeader("User-Agent", userAgent().toUtf8()); - - QNetworkReply *reply = get(request); - QTimer timeout; - connect(&timeout, &QTimer::timeout, [reply] () { - reply->deleteLater(); - }); - timeout.start(); - - connect(reply, &QNetworkReply::finished, [reply, this] () { - QJsonDocument jdoc = QJsonDocument::fromJson(reply->readAll()); - QJsonArray credentialsData = jdoc.array(); - emit credentialsReceived(credentialsData.at(2).toString(), - s_PremiumAccountStates.find(credentialsData.at(1).toInt()) - != s_PremiumAccountStates.end()); - reply->deleteLater(); - }); - - connect(reply, static_cast(&QNetworkReply::error), - [=] (QNetworkReply::NetworkError) { - qDebug("failed to retrieve account credentials: %s", qUtf8Printable(reply->errorString())); - reply->deleteLater(); - }); -} - - -bool NXMAccessManager::loggedIn() const -{ - if (m_LoginState == LOGIN_CHECKING) { - QProgressDialog progress; - progress.setLabelText(tr("Verifying Nexus login")); - progress.show(); - while (m_LoginState == LOGIN_CHECKING) { - QCoreApplication::processEvents(); - QThread::msleep(100); - } - progress.hide(); - } - - return m_LoginState == LOGIN_VALID; -} - - -void NXMAccessManager::refuseLogin() -{ - m_LoginState = LOGIN_REFUSED; -} - - -bool NXMAccessManager::loginAttempted() const -{ - return m_LoginState != LOGIN_NOT_CHECKED; -} - - -bool NXMAccessManager::loginWaiting() const -{ - return m_LoginReply != nullptr; -} - - -void NXMAccessManager::login(const QString &username, const QString &password) -{ - if (m_LoginReply != nullptr) { - return; - } - - if (m_LoginState == LOGIN_VALID) { - emit loginSuccessful(false); - return; - } - m_Username = username; - m_Password = password; - pageLogin(); -} - - -QString NXMAccessManager::userAgent(const QString &subModule) const -{ - QStringList comments; - comments << "Nexus Client v" + m_NMMVersion; - if (!subModule.isEmpty()) { - comments << "module: " + subModule; - } - - return QString("Mod Organizer/%1 (%2)").arg(m_MOVersion, comments.join("; ")); -} - - -void NXMAccessManager::pageLogin() -{ - qDebug("logging %s in on Nexus", qUtf8Printable(m_Username)); - QString requestString = (Nexus_Management_URL + "/Sessions/?Login&uri=%1") - .arg(QString(QUrl::toPercentEncoding(Nexus_Management_URL))); - - QNetworkRequest request(requestString); - request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); - - QByteArray postDataQuery; - QUrlQuery postData; - postData.addQueryItem("username", m_Username); - postData.addQueryItem("password", QUrl::toPercentEncoding(m_Password)); - postDataQuery = postData.query(QUrl::EncodeReserved).toUtf8(); - - request.setRawHeader("User-Agent", userAgent().toUtf8()); - - m_ProgressDialog = new QProgressDialog(nullptr); - m_ProgressDialog->setLabelText(tr("Logging into Nexus")); - QList buttons = m_ProgressDialog->findChildren(); - buttons.at(0)->setEnabled(false); - m_ProgressDialog->show(); - QCoreApplication::processEvents(); // for some reason the whole app hangs during the login. This way the user has at least a little feedback - - m_LoginReply = post(request, postDataQuery); - m_LoginTimeout.start(); - m_LoginState = LOGIN_CHECKING; - connect(m_LoginReply, SIGNAL(finished()), this, SLOT(loginFinished())); - connect(m_LoginReply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(loginError(QNetworkReply::NetworkError))); -} - - -void NXMAccessManager::loginTimeout() -{ - m_LoginReply->deleteLater(); - m_LoginReply = nullptr; - m_LoginAttempted = false; // this usually means we might have success later - m_Username.clear(); - m_Password.clear(); - m_LoginState = LOGIN_NOT_VALID; - - emit loginFailed(tr("timeout")); -} - - -void NXMAccessManager::loginError(QNetworkReply::NetworkError) -{ - qDebug("login error"); - if (m_ProgressDialog != nullptr) { - m_ProgressDialog->deleteLater(); - m_ProgressDialog = nullptr; - } - m_Username.clear(); - m_Password.clear(); - m_LoginState = LOGIN_NOT_VALID; - - if (m_LoginReply != nullptr) { - emit loginFailed(m_LoginReply->errorString()); - m_LoginReply->deleteLater(); - m_LoginReply = nullptr; - } else { - emit loginFailed(tr("Unknown error")); - } -} - - -bool NXMAccessManager::hasLoginCookies() const -{ - QUrl url(Nexus_Management_URL + "/"); - QList cookies = cookieJar()->cookiesForUrl(url); - for (const QNetworkCookie &cookie : cookies) { - if (cookie.name() == "sid") { - return true; - } - } - return false; -} - - -void NXMAccessManager::loginFinished() -{ - if (m_ProgressDialog != nullptr) { - m_ProgressDialog->deleteLater(); - m_ProgressDialog = nullptr; - } - - m_LoginReply->deleteLater(); - m_LoginReply = nullptr; - m_Username.clear(); - m_Password.clear(); - - if (hasLoginCookies()) { - m_LoginState = LOGIN_VALID; - retrieveCredentials(); - emit loginSuccessful(true); - } else { - m_LoginState = LOGIN_NOT_VALID; - emit loginFailed(tr("Please check your password")); - } -} - - -void NXMAccessManager::loginChecked() -{ - QNetworkReply *reply = static_cast(sender()); - QByteArray data = reply->readAll(); - m_LoginState = data == "null" ? LOGIN_NOT_VALID - : LOGIN_VALID; - if (m_LoginState == LOGIN_VALID) { - retrieveCredentials(); - } else { - qDebug("cookies seem to be invalid"); - } - m_LoginReply->deleteLater(); - m_LoginReply = nullptr; -} +/* +Copyright (C) 2012 Sebastian Herbord. All rights reserved. + +This file is part of Mod Organizer. + +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 . +*/ + +#include "nxmaccessmanager.h" + +#include "iplugingame.h" +#include "nxmurl.h" +#include "report.h" +#include "utility.h" +#include "selfupdater.h" +#include "persistentcookiejar.h" +#include "settings.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace MOBase; + +namespace { + QString const nexusBaseUrl("https://api.nexusmods.com/v1"); +} + +NXMAccessManager::NXMAccessManager(QObject *parent, const QString &moVersion) + : QNetworkAccessManager(parent) + , m_ValidateReply(nullptr) + , m_MOVersion(moVersion) +{ + m_ValidateTimeout.setSingleShot(true); + m_ValidateTimeout.setInterval(30000); + setCookieJar(new PersistentCookieJar( + QDir::fromNativeSeparators(Settings::instance().getCacheDirectory() + "/nexus_cookies.dat"))); + + if (networkAccessible() == QNetworkAccessManager::UnknownAccessibility) { + // why is this necessary all of a sudden? + setNetworkAccessible(QNetworkAccessManager::Accessible); + } +} + +NXMAccessManager::~NXMAccessManager() +{ + if (m_ValidateReply != nullptr) { + m_ValidateReply->deleteLater(); + m_ValidateReply = nullptr; + } +} + +void NXMAccessManager::setNMMVersion(const QString &nmmVersion) +{ + m_NMMVersion = nmmVersion; +} + +QNetworkReply *NXMAccessManager::createRequest( + QNetworkAccessManager::Operation operation, const QNetworkRequest &request, + QIODevice *device) +{ + if (request.url().scheme() != "nxm") { + return QNetworkAccessManager::createRequest(operation, request, device); + } + if (operation == GetOperation) { + emit requestNXMDownload(request.url().toString()); + + // eat the request, everything else will be done by the download manager + return QNetworkAccessManager::createRequest(QNetworkAccessManager::GetOperation, + QNetworkRequest(QUrl())); + } else if (operation == PostOperation) { + return QNetworkAccessManager::createRequest(operation, request, device);; + } else { + return QNetworkAccessManager::createRequest(operation, request, device); + } +} + + +void NXMAccessManager::showCookies() const +{ + QUrl url(nexusBaseUrl + "/"); + for (const QNetworkCookie &cookie : cookieJar()->cookiesForUrl(url)) { + qDebug("%s - %s (expires: %s)", + cookie.name().constData(), cookie.value().constData(), + qUtf8Printable(cookie.expirationDate().toString())); + } +} + +void NXMAccessManager::clearCookies() +{ + PersistentCookieJar *jar = qobject_cast(cookieJar()); + if (jar != nullptr) { + jar->clear(); + } else { + qWarning("failed to clear cookies, invalid cookie jar"); + } +} + +void NXMAccessManager::startValidationCheck() +{ + qDebug("Checking Nexus API Key..."); + QString requestString = nexusBaseUrl + "/users/validate"; + + QNetworkRequest request(requestString); + request.setRawHeader("APIKEY", m_ApiKey.toUtf8()); + request.setRawHeader("User-Agent", userAgent().toUtf8()); + + m_ProgressDialog = new QProgressDialog(nullptr); + m_ProgressDialog->setLabelText(tr("Validating Nexus Connection")); + QList buttons = m_ProgressDialog->findChildren(); + buttons.at(0)->setEnabled(false); + m_ProgressDialog->show(); + QCoreApplication::processEvents(); // for some reason the whole app hangs during the login. This way the user has at least a little feedback + + m_ValidateReply = get(request); + m_ValidateTimeout.start(); + m_ValidateState = VALIDATE_CHECKING; + connect(m_ValidateReply, SIGNAL(finished()), this, SLOT(validateFinished())); + connect(m_ValidateReply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(validateError(QNetworkReply::NetworkError))); +} + + +bool NXMAccessManager::validated() const +{ + if (m_ValidateState == VALIDATE_CHECKING) { + QProgressDialog progress; + progress.setLabelText(tr("Verifying Nexus login")); + progress.show(); + while (m_ValidateState == VALIDATE_CHECKING) { + QCoreApplication::processEvents(); + QThread::msleep(100); + } + progress.hide(); + } + + return m_ValidateState == VALIDATE_VALID; +} + + +void NXMAccessManager::refuseValidation() +{ + m_ValidateState = VALIDATE_REFUSED; +} + + +bool NXMAccessManager::validateAttempted() const +{ + return m_ValidateState != VALIDATE_NOT_CHECKED; +} + + +bool NXMAccessManager::validateWaiting() const +{ + return m_ValidateReply != nullptr; +} + + +void NXMAccessManager::apiCheck(const QString &apiKey) +{ + if (m_ValidateReply != nullptr) { + return; + } + + if (m_ValidateState == VALIDATE_VALID) { + emit validateSuccessful(false); + return; + } + m_ApiKey = apiKey; + startValidationCheck(); +} + + +QString NXMAccessManager::userAgent(const QString &subModule) const +{ + QStringList comments; + comments << "Nexus Client v" + m_NMMVersion; + if (!subModule.isEmpty()) { + comments << "module: " + subModule; + } + + return QString("Mod Organizer/%1 (%2)").arg(m_MOVersion, comments.join("; ")); +} + + +QString NXMAccessManager::apiKey() const +{ + return m_ApiKey; +} + + +void NXMAccessManager::validateTimeout() +{ + m_ValidateReply->deleteLater(); + m_ValidateReply = nullptr; + m_ValidateAttempted = false; // this usually means we might have success later + m_ApiKey.clear(); + m_ValidateState = VALIDATE_NOT_VALID; + + emit validateFailed(tr("timeout")); +} + + +void NXMAccessManager::validateError(QNetworkReply::NetworkError) +{ + qDebug("login error"); + if (m_ProgressDialog != nullptr) { + m_ProgressDialog->deleteLater(); + m_ProgressDialog = nullptr; + } + m_ApiKey.clear(); + m_ValidateState = VALIDATE_NOT_VALID; + + if (m_ValidateReply != nullptr) { + emit validateFailed(m_ValidateReply->errorString()); + m_ValidateReply->deleteLater(); + m_ValidateReply = nullptr; + } else { + emit validateFailed(tr("Unknown error")); + } +} + + +void NXMAccessManager::validateFinished() +{ + if (m_ProgressDialog != nullptr) { + m_ProgressDialog->deleteLater(); + m_ProgressDialog = nullptr; + } + + if (m_ValidateReply != nullptr) { + QJsonDocument jdoc = QJsonDocument::fromJson(m_ValidateReply->readAll()); + QJsonObject credentialsData = jdoc.object(); + QString test = jdoc.toJson(); + QString name = credentialsData.value("name").toString(); + bool premium = credentialsData.value("is_premium?").toBool(); + emit credentialsReceived(credentialsData.value("name").toString(), + credentialsData.value("is_premium?").toBool()); + + m_ValidateReply->deleteLater(); + m_ValidateReply = nullptr; + + m_ValidateState = VALIDATE_VALID; + emit validateSuccessful(true); + } +} diff --git a/src/nxmaccessmanager.h b/src/nxmaccessmanager.h index c58c4cc3..b316ef77 100644 --- a/src/nxmaccessmanager.h +++ b/src/nxmaccessmanager.h @@ -43,12 +43,12 @@ public: void setNMMVersion(const QString &nmmVersion); - bool loggedIn() const; + bool validated() const; - bool loginAttempted() const; - bool loginWaiting() const; + bool validateAttempted() const; + bool validateWaiting() const; - void login(const QString &username, const QString &password); + void apiCheck(const QString &apiKey); void showCookies() const; @@ -56,9 +56,11 @@ public: QString userAgent(const QString &subModule = QString()) const; - void startLoginCheck(); + QString apiKey() const; - void refuseLogin(); + void startValidationCheck(); + + void refuseValidation(); signals: @@ -74,18 +76,17 @@ signals: * * @param necessary true if a login was necessary and succeeded, false if the user is still logged in **/ - void loginSuccessful(bool necessary); + void validateSuccessful(bool necessary); - void loginFailed(const QString &message); + void validateFailed(const QString &message); void credentialsReceived(const QString &userName, bool premium); private slots: - void loginChecked(); - void loginFinished(); - void loginError(QNetworkReply::NetworkError errorCode); - void loginTimeout(); + void validateFinished(); + void validateError(QNetworkReply::NetworkError errorCode); + void validateTimeout(); protected: @@ -95,38 +96,24 @@ protected: private: - void pageLogin(); -// void dlLogin(); - - bool hasLoginCookies() const; - - void retrieveCredentials(); - -private: - - static const std::set s_PremiumAccountStates; - -private: - - QTimer m_LoginTimeout; - QNetworkReply *m_LoginReply; + QTimer m_ValidateTimeout; + QNetworkReply *m_ValidateReply; QProgressDialog *m_ProgressDialog { nullptr }; QString m_MOVersion; QString m_NMMVersion; - QString m_Username; - QString m_Password; + QString m_ApiKey; - bool m_LoginAttempted; + bool m_ValidateAttempted; enum { - LOGIN_NOT_CHECKED, - LOGIN_CHECKING, - LOGIN_NOT_VALID, - LOGIN_ATTEMPT_FAILED, - LOGIN_REFUSED, - LOGIN_VALID - } m_LoginState = LOGIN_NOT_CHECKED; + VALIDATE_NOT_CHECKED, + VALIDATE_CHECKING, + VALIDATE_NOT_VALID, + VALIDATE_ATTEMPT_FAILED, + VALIDATE_REFUSED, + VALIDATE_VALID + } m_ValidateState = VALIDATE_NOT_CHECKED; }; diff --git a/src/organizer_en.ts b/src/organizer_en.ts index 50301bfa..43c01310 100644 --- a/src/organizer_en.ts +++ b/src/organizer_en.ts @@ -26,7 +26,7 @@ - Lead Developers/ Maintainers + Current Maintainers @@ -35,92 +35,67 @@ - - Mo2 devs and Contributors + + Major Contributors - - Project579 - - - - - przester - - - - + Translators - + Cyb3r (Dutch) - + fruttyx (French) - + Yoplala (French) - + Faron (German) - + Mordan (Greek) - + Yoosk (Polish) - + Brgodfx (Portuguese) - - zDas (Portuguese) - - - - + Jax (Swedish) - - yohru (Japanese) - - - - + ...and all other Transifex contributors! - + Other Supporters && Contributors - - Tannin (Original Creator) - - - - + Close @@ -309,7 +284,7 @@ p, li { white-space: pre-wrap; } - + failed to read mod (%1): %2 @@ -317,251 +292,435 @@ p, li { white-space: pre-wrap; } DownloadList - + Name - - Size + + Filetime - - Status + + Size - - Filetime + + Done - - < game %1 mod %2 file %3 > + + Information missing, please select "Query Info" from the context menu to re-retrieve. - Unknown + pending download + + + DownloadListWidget - - Pending + + + Placeholder - - Started + + + + Done - Double Click to install - - Canceling + + + Paused - Double Click to resume - - Pausing + + + Installed - Double Click to re-install - - Canceled + + + Uninstalled - Double Click to re-install + + + DownloadListWidgetCompact - - Paused + + + Placeholder - - Error + + Done + + + DownloadListWidgetCompactDelegate - - Fetching Info 1 + + < game %1 mod %2 file %3 > - - Fetching Info 2 + + Pending - - Downloaded + + Paused - + + Fetching Info 1 + + + + + Fetching Info 2 + + + + Installed - + Uninstalled - - Pending download + + Done - - Information missing, please select "Query Info" from the context menu to re-retrieve. + + + + + + + + Are you sure? + + + + + This will permanently delete the selected download. + + + + + This will remove all finished downloads from this list and from disk. + + + + + This will remove all installed downloads from this list and from disk. + + + + + This will remove all uninstalled downloads from this list and from disk. - - - DownloadListWidget - + + This will permanently remove all finished downloads from this list (but NOT from disk). + + + + + This will permanently remove all installed downloads from this list (but NOT from disk). + + + + + This will permanently remove all uninstalled downloads from this list (but NOT from disk). + + + + Install - + Query Info - + Visit on Nexus - + Open File - - - + + + Show in Folder - - + Delete - + Un-Hide - + Hide - + Cancel - + Pause - + + Remove + + + + Resume - + Delete Installed... - + Delete Uninstalled... - + Delete All... - + Hide Installed... - + Hide Uninstalled... - + Hide All... - + Un-Hide All... + + + DownloadListWidgetDelegate - - - - + + < game %1 mod %2 file %3 > + + + + + Pending + + + + + Fetching Info 1 + + + + + Fetching Info 2 + + + + + + + Delete Files? - + This will permanently delete the selected download. - + This will remove all finished downloads from this list and from disk. - + This will remove all installed downloads from this list and from disk. - + This will remove all uninstalled downloads from this list and from disk. - - - + + + Are you sure? - + This will remove all finished downloads from this list (but NOT from disk). - + This will remove all installed downloads from this list (but NOT from disk). - + This will remove all uninstalled downloads from this list (but NOT from disk). + + + Install + + + + + Query Info + + + + + Visit on Nexus + + + + + Open File + + + + + + + Show in Folder + + + + + + Delete + + + + + Un-Hide + + + + + Hide + + + + + Cancel + + + + + Pause + + + + + Resume + + + + + Delete Installed... + + + + + Delete Uninstalled... + + + + + Delete All... + + + + + Hide Installed... + + + + + Hide Uninstalled... + + + + + Hide All... + + + + + Un-Hide All... + + DownloadManager @@ -587,7 +746,7 @@ p, li { white-space: pre-wrap; } - A file with the same name "%1" has already been downloaded. Do you want to download it again? The new file will receive a different name. + A file with the same name has already been downloaded. Do you want to download it again? The new file will receive a different name. @@ -618,7 +777,7 @@ p, li { white-space: pre-wrap; } - + remove: invalid download index %1 @@ -638,234 +797,234 @@ p, li { white-space: pre-wrap; } - + cancel: invalid download index %1 - + pause: invalid download index %1 - + resume: invalid download index %1 - + resume (int): invalid download index %1 - + No known download urls. Sorry, this download can't be resumed. - + query: invalid download index %1 - + Please enter the nexus mod id - + Mod ID: - + Please select the source game code for %1 - + VisitNexus: invalid download index %1 - + Nexus ID for this Mod is unknown - + OpenFile: invalid download index %1 - + OpenFileInDownloadsFolder: invalid download index %1 - + get pending: invalid download index %1 - + get path: invalid download index %1 - + Main - + Update - + Optional - + Old - + Misc - + Unknown - + display name: invalid download index %1 - + file name: invalid download index %1 - + file time: invalid download index %1 - + file size: invalid download index %1 - + progress: invalid download index %1 - + state: invalid download index %1 - + infocomplete: invalid download index %1 - - + + mod id: invalid download index %1 - + ishidden: invalid download index %1 - + file info: invalid download index %1 - + mark installed: invalid download index %1 - + mark uninstalled: invalid download index %1 - + Memory allocation error (in processing progress event). - + Memory allocation error (in processing downloaded data). - + Information updated - - + + No matching file found on Nexus! Maybe this file is no longer available or it was renamed? - + No file on Nexus matches the selected file by name. Please manually choose the correct one. - + No download server available. Please try again later. - + Failed to request file info from nexus: %1 - + Warning: Content type is: %1 - + Download header content length: %1 downloaded file size: %2 - + Download failed: %1 (%2) - + We were unable to download the file due to errors after four retries. There may be an issue with the Nexus servers. - + failed to re-open %1 - + Unable to write download to drive (return %1). Check the drive's available storage. @@ -984,107 +1143,92 @@ Right now the only case I know of where this needs to be overwritten is for the - - If this is enabled, the configured libraries will be automatically loaded when this executable is launched. - - - - - Force Load Libraries (*) - - - - - Configure Libraries - - - - + Use Application's Icon for shortcuts - + (*) This setting is profile-specific - - + + Add an executable - - + + Add - - + + Remove the selected executable - + Remove - + Close - + Select a binary - + Executable (%1) - + Java (32-bit) required - + MO requires 32-bit java to run this application. If you already have it installed, select javaw.exe from that installation as the binary. - + Select a directory - + Confirm - + Really remove "%1" from executables? - + Modify - - + + Save Changes? - - + + You made changes to the current executable, do you want to save them? @@ -1136,85 +1280,6 @@ Right now the only case I know of where this needs to be overwritten is for the - - ForcedLoadDialog - - - Forced Load Settings - - - - - - Adds a row to the table. - - - - - Add Row - - - - - - Deletes the selected row from the table. - - - - - Delete Row - - - - - ForcedLoadDialogWidget - - - - If checked, the specified library will be force loaded for the specified process. - - - - - - The name of the process that should be forced to load a library. - - - - - Process name - - - - - - Browse for a process. - - - - - - ... - - - - - - The path to the library to be loaded. This may be a path relative to the managed game's directory or may be an absolute path to somewhere else. - - - - - Library to load - - - - - - Browse for a library. - - - InstallDialog @@ -1280,116 +1345,103 @@ p, li { white-space: pre-wrap; } InstallationManager - + Password required - + Password - - + + Extracting files - + failed to create backup - + Mod Name - + Name - + Invalid name - + The name you entered is invalid, please enter a different one. - + File format "%1" not supported - + None of the available installer plugins were able to handle that archive. This is likely due to a corrupted or incompatible download or unrecognized archive format. - + no error - + 7z.dll not found - + 7z.dll isn't valid - + archive not found - + failed to open archive - + unsupported archive type - + internal library error - + archive invalid - + unknown archive error - - ListDialog - - - Select an item... - - - - - Filter - - - LockedDialog @@ -1447,17 +1499,17 @@ This is likely due to a corrupted or incompatible download or unrecognized archi - + failed to write to %1 - + file not found: %1 - + Save @@ -1482,47 +1534,47 @@ This is likely due to a corrupted or incompatible download or unrecognized archi MainWindow - + Categories - + Clear - + If checked, only mods that match all selected categories are displayed. - + And - + If checked, all mods that match at least one of the selected categories are displayed. - + Or - + Profile - + Pick a module collection - + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } @@ -1532,84 +1584,76 @@ p, li { white-space: pre-wrap; } - + Open list options... - + Refresh list. This is usually not necessary unless you modified data outside the program. - + Show Open Folders menu... - - + + Restore Backup... - - - + + Create Backup - - - Active: - - - - - This provides statistics about the mod list. The total number of active mod is normally displayed. Other statistics may be accessed with the tooltip of this counter. - - - - + List of available mods. - + This is a list of installed mods. Use the checkboxes to activate/deactivate mods and drag & drop mods to change their "installation" orders. - - - - + Filter - + Clear all Filters - + No groups - + Nexus IDs - + + + + Namefilter + + + + Pick a program to run. - + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } @@ -1619,12 +1663,12 @@ p, li { white-space: pre-wrap; } - + Run program - + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } @@ -1633,17 +1677,17 @@ p, li { white-space: pre-wrap; } - + Run - + Create a shortcut in your start menu or on the desktop to the specified program - + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } @@ -1652,32 +1696,27 @@ p, li { white-space: pre-wrap; } - + Shortcut - + Plugins - + Sort - This provides statistics about the plugin list. The total number of active plugins is normally displayed. Other statistics may be accessed with the tooltip of this counter. - - - - List of available esp/esm files - + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } @@ -1686,27 +1725,27 @@ p, li { white-space: pre-wrap; } - + Archives - + <html><head/><body><p>BSAs / BA2s are bundles of game assets (textures, scripts, etc.). By default, the engine loads these bundles in a separate step from loose files. <p>Their load order is specified by the priority of the corresponding plugin (right pane, plugins tab).</p><p>If there is a matching plugin, the game will load them no matter what.</p></body></html> - + <html><head/><body><p>Currently detected archives. (<a href="#"><span style=" text-decoration: underline; color:#0000ff;">What is an archive?</span></a>)</p></body></html> - + List of available BS Archives. Archives not checked here are not managed by MO and ignore installation order. - + BSA files are archives (comparable to .zip files) that contain data assets (meshes, textures, ...) to be used by the game. As such they "compete" with loose files in your data directory over which is loaded. By default, BSAs that share their base name with an enabled ESP (i.e. plugin.esp and plugin.bsa) are automatically loaded and will have precedence over all loose files, the installation order you set up to the left is then ignored! @@ -1714,1151 +1753,967 @@ p, li { white-space: pre-wrap; } - + Data - + refresh data-directory overview - + Refresh the overview. This may take a moment. - - - - + + + Refresh - + This is an overview of your data directory as visible to the game (and tools). - + File - + Mod - - - Filters the above list so that only conflicts are displayed. + + + Filter the above list so that only conflicts are displayed. - + Show only conflicts - - - Filters the above list so that files from archives are not shown - - - - - Show files from Archives - - - - + Saves - + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">This is a list of all save games for this game. Hover over a list entry to get detailed information about the save including a list of esps/esms that were used at the time this save was created but aren't active now.</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">This is a list of all savegames for this game. Hover over a list entry to get detailed information about the save including a list of esps/esms that were used at the time this save was created but aren't active now.</span></p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:8pt;"></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">If you click &quot;Fix Mods...&quot; in the context menu, MO will try to activate all mods and esps to fix those missing esps. It will not disable anything!</span></p></body></html> - + Downloads - - Refresh downloads view - - - - + This is a list of mods you downloaded from Nexus. Double click one to install it. You can also drag an archive into here. - + Show Hidden - + Tool Bar - + Install Mod - + Install &Mod - + Install a new mod from an archive - + Ctrl+M - + Profiles - + &Profiles - + Configure Profiles - + Ctrl+P - + Executables - + &Executables - + Configure the executables that can be started through Mod Organizer - + Ctrl+E - - + + Tools - + &Tools - + Ctrl+I - + Settings - + &Settings - + Configure settings and workarounds - + Ctrl+S - + Nexus - + Search nexus network for more mods - + Ctrl+N - - + + Update - + Mod Organizer is up-to-date - - - No Notifications + + + No Problems - - This button will be highlighted if MO discovered potential problems in your setup and provide tips on how to fix them. + + This button will be highlighted if MO discovered potential problems in your setup and provide tips on how to fix them. + +!Work in progress! +Right now this has very limited functionality - - + + Help - + Ctrl+H - + Endorse MO - - + + Endorse Mod Organizer - + Copy Log to Clipboard - + Change Game - + Open the Instance selection dialog to manage a different Game - + Toolbar - + Desktop - + Start Menu - + There is no supported sort mechanism for this game. You will probably have to use a third-party tool. - - Crash on exit + + Problems - - MO crashed while exiting. Some settings may not be saved. - -Error: %1 - - - - - Notifications - - - - - There are notifications to read - - - - - There are no notifications - - - - - - - Endorse + + There are potential problems with your setup - - Won't Endorse + + Everything seems to be in order - + Help on UI - - Documentation - - - - - Chat on Discord + + Documentation Wiki - + Report Issue - + Tutorials - + About - + About Qt - + Name - + Please enter a name for the new profile - + failed to create profile: %1 - + Show tutorial? - + You are starting Mod Organizer for the first time. Do you want to show a tutorial of its basic features? If you choose no you can always start the tutorial from the "Help"-menu. - + Downloads in progress - + There are still downloads in progress, do you really want to quit? - + Plugin "%1" failed: %2 - + Plugin "%1" failed - + Browse Mod Page - + Also in: <br> - + No conflict - + <Edit...> - + This bsa is enabled in the ini file so it may be required! - + Activating Network Proxy - - Notice: Your current MO version (%1) is lower than the previously used one (%2). The GUI may not downgrade gracefully, so you may experience oddities. However, there should be no serious issues. + + Notice: Your current MO version (%1) is lower than the previous version (%2).<br>The GUI may not downgrade gracefully, so you may experience oddities.<br>However, there should be no serious issues. - + Choose Mod - + Mod Archive - + Start Tutorial? - + You're about to start a tutorial. For technical reasons it's not possible to end the tutorial early. Continue? - + failed to spawn notepad.exe: %1 - + failed to change origin name: %1 - + failed to move "%1" from mod "%2" to "%3": %4 - + <Contains %1> - + <Checked> - + <Unchecked> - + <Update> - - <Mod Backup> - - - - + <Managed by MO> - + <Managed outside MO> - + <No category> - + <Conflicted> - + <Not Endorsed> - + failed to rename mod: %1 - + Overwrite? - + This will replace the existing mod "%1". Continue? - + failed to remove mod "%1" - - - + + + failed to rename "%1" to "%2" - - - - + + + + Confirm - + Remove the following mods?<br><ul>%1</ul> - + failed to remove mod: %1 - - - + + Failed - + Installation file no longer exists - + Mods installed with old versions of MO can't be reinstalled in this way. - - Failed to create backup. - - - - + You need to be logged in with Nexus to resume a download - - - - + + You need to be logged in with Nexus to endorse - - - Endorsing multiple mods will take a while. Please wait... - - - - - - Unendorsing multiple mods will take a while. Please wait... - - - - + Failed to display overwrite dialog: %1 - - Opening Nexus Links - - - - - You are trying to open %1 links to Nexus Mods. Are you sure you want to do this? - - - - + Nexus ID for this Mod is unknown - - Opening Web Pages - - - - - You are trying to open %1 Web Pages. Are you sure you want to do this? - - - - + Web page for this mod is unknown - - <table cellspacing="5"><tr><th>Type</th><th>All</th><th>Visible</th><tr><td>Enabled mods:&emsp;</td><td align=right>%1 / %2</td><td align=right>%3 / %4</td></tr><tr><td>Unmanaged/DLCs:&emsp;</td><td align=right>%5</td><td align=right>%6</td></tr><tr><td>Mod backups:&emsp;</td><td align=right>%7</td><td align=right>%8</td></tr><tr><td>Separators:&emsp;</td><td align=right>%9</td><td align=right>%10</td></tr></table> - - - - - <table cellspacing="6"><tr><th>Type</th><th>Active </th><th>Total</th></tr><tr><td>All plugins:</td><td align=right>%1 </td><td align=right>%2</td></tr><tr><td>ESMs:</td><td align=right>%3 </td><td align=right>%4</td></tr><tr><td>ESPs:</td><td align=right>%7 </td><td align=right>%8</td></tr><tr><td>ESMs+ESPs:</td><td align=right>%9 </td><td align=right>%10</td></tr><tr><td>ESLs:</td><td align=right>%5 </td><td align=right>%6</td></tr></table> - - - - - - + + + Create Mod... - + This will create an empty mod. Please enter a name: - - + + A mod with this name already exists - - Create Separator... - - - - - This will create a new separator. -Please enter a name: - - - - - A separator with this name already exists - - - - + This will move all files from overwrite into a new, regular mod. Please enter a name: - - Move successful. - - - - - + + Are you sure? - + About to recursively delete: - + Not logged in, endorsement information will be wrong - + Continue? - + The versioning scheme decides which version is considered newer than another. This function will guess the versioning scheme under the assumption that the installed version is outdated. - - + + Sorry - + I don't know a versioning scheme where %1 is newer than %2. - + Really enable all visible mods? - + Really disable all visible mods? - + Export to csv - + CSV (Comma Separated Values) is a format that can be imported in programs like Excel to create a spreadsheet. You can also use online editors and converters instead. - + Select what mods you want export: - + All installed mods - + Only active (checked) mods from your current profile - + All currently visible mods in the mod list - + Choose what Columns to export: - + Mod_Priority - + Mod_Name - - Notes_column - - - - + Mod_Status - + Primary_Category - + Nexus_ID - + Mod_Nexus_URL - + Mod_Version - + Install_Date - + Download_File_Name - + export failed: %1 - + Open Game folder - + Open MyGames folder - - Open INIs folder - - - - + Open Instance folder - + Open Mods folder - + Open Profile folder - + Open Downloads folder - + Open MO2 Install folder - + Open MO2 Plugins folder - + Open MO2 Logs folder - + Install Mod... - + Create empty mod - - Create Separator - - - - + Enable all visible - + Disable all visible - + Check all for update - + Export to csv... - - - Send to - - - - - - Top - - - - - - Bottom - - - - - - Priority... - - - - - Separator... - - - - + All Mods - + Sync to Mods... - - Move content to Mod... - - - - + Clear Overwrite... - - + + Open in Explorer - + Restore Backup - + Remove Backup... - - + Change Categories - - + Primary Category - - Rename Separator... - - - - - Remove Separator... - - - - - Select Color... - - - - - Reset Color - - - - + Change versioning scheme - + Un-ignore update - + Ignore update - - + + Enable selected - - + + Disable selected - + Rename Mod... - + Reinstall Mod - + Remove Mod... - + Un-Endorse - + + + Endorse + + + + Won't endorse - + Endorsement state unknown - + Ignore missing data - + Mark as converted/working - + Visit on Nexus - + Visit web page - + Information... - - + + Exception: - - + + Unknown exception - + <All> - + <Multiple> - + %1 more - + Are you sure you want to remove the following %n save(s)?<br><ul>%1</ul><br>Removed saves will be sent to the Recycle Bin. @@ -2866,12 +2721,12 @@ You can also use online editors and converters instead. - + Enable Mods... - + Delete %n save(s) @@ -2879,367 +2734,328 @@ You can also use online editors and converters instead. - + failed to remove %1 - + failed to create %1 - - Restarting MO - - - - - Changing the managed game directory requires restarting MO. -Any pending downloads will be paused. - -Click OK to restart MO now. - - - - + Can't change download directory while downloads are in progress! - + failed to write to file %1 - + %1 written - + Select binary - + Binary - + Enter Name - + Please enter a name for the executable - + Not an executable - + This is not a recognized executable. - - + + Replace file? - + There already is a hidden version of this file. Replace it? - - + + File operation failed - - + + Failed to remove "%1". Maybe you lack the required file permissions? - + There already is a visible version of this file. Replace it? - - - Set Priority - - - - - Set the priority of the selected plugins - - - - + file not found: %1 - + failed to generate preview for %1 - + Sorry, can't preview anything. This function currently does not support extracting from bsas. - + Update available - + Open/Execute - + Add as Executable - + Preview - + Un-Hide - + Hide - + Write To File... - + Do you want to endorse Mod Organizer on %1 now? - + Thank you! - + Thank you for your endorsement! - + Request to Nexus failed: %1 - - + + failed to read %1: %2 - - + + Error - + failed to extract %1 (errorcode %2) - + Extract BSA - + This archive contains invalid hashes. Some files may be broken. - + Extract... - + This will restart MO, continue? - + Edit Categories... - + Deselect filter - + Remove - + Enable all - + Disable all - + Unlock load order - + Lock load order - - Open Origin in Explorer - - - - - Open Origin Info... - - - - + depends on missing "%1" - + incompatible with "%1" - + Please wait while LOOT is running - + loot failed. Exit code was: %1 - + failed to start loot - + failed to run loot: %1 - + Errors occured - + Backup of load order created - + Choose backup to restore - + No Backups - + There are no backups to restore - - + + Restore failed - - + + Failed to restore the backup. Errorcode: %1 - + Backup of modlist created - + A file with the same name has already been downloaded. What would you like to do? - + Overwrite - + Rename new file - + Ignore file - - - Set the priority of the selected mods - - MessageDialog - - + + Placeholder @@ -3247,82 +3063,72 @@ Click OK to restart MO now. ModInfo - + Plugins - + Textures - + Meshes - + Bethesda Archive - + UI Changes - + Sound Effects - + Scripts - + Script Extender - - Script Extender Files - - - - + SkyProc Tools - + MCM Data - + INI files - - ModGroup files - - - - - invalid content type: %1 + + invalid content type %1 - - invalid mod index: %1 + + invalid mod index %1 - + remove: invalid mod index %1 @@ -3592,56 +3398,37 @@ p, li { white-space: pre-wrap; } - + about:blank - + Endorse - - Web page URL (only used if invalid NexusID) : - - - - + Notes - - - - Enter comments about the mod here. These are displayed in the notes column of the mod list. - - - - - - - Enter notes about the mod here. These can be viewed in the mod list by hovering over the notes column or the flags column. - - - - + Filetree - + Open Mod in Explorer - + A directory view of this mod - + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } @@ -3651,288 +3438,288 @@ p, li { white-space: pre-wrap; } - + Previous - + Next - + Close - + &Delete - + &Rename - + &Hide - + &Unhide - + &Open - + &New Folder - - + + Save changes? - - + + Save changes to "%1"? - + File Exists - + A file with that name exists, please enter a new one - + failed to move file - + failed to create directory "optional" - - + + Info requested, please wait - + Main - + Update - + Optional - + Old - + Misc - + Unknown - + Current Version: %1 - + No update available - + (description incomplete, please visit nexus) - + <a href="%1">Visit on Nexus</a> - + Failed to delete %1 - - - - + + + + Confirm - - + + Are sure you want to delete "%1"? - - + + Are sure you want to delete the selected files? - - + + New Folder - + Failed to create "%1" - - + + Replace file? - + There already is a hidden version of this file. Replace it? - - + + File operation failed - - + + Failed to remove "%1". Maybe you lack the required file permissions? - - + + failed to rename %1 to %2 - + There already is a visible version of this file. Replace it? - + Select binary - + Binary - + file not found: %1 - + failed to generate preview for %1 - + Sorry - + Sorry, can't preview anything. This function currently does not support extracting from bsas. - + Un-Hide - + Hide - - + + Open/Execute - - + + Preview - + Name - + Please enter a name - - + + Error - + Invalid name. Must be a valid file name - + A tweak by that name exists - + Create Tweak @@ -3971,328 +3758,300 @@ p, li { white-space: pre-wrap; } ModInfoRegular - - + + failed to write %1/meta.ini: error %2 - + %1 contains no esp/esm/esl and no asset (textures, meshes, interface, ...) directory - + Categories: <br> - - ModInfoSeparator - - - This is a Separator - - - ModList - + Game Plugins (ESP/ESM/ESL) - + Interface - + Meshes - + Bethesda Archive - + Scripts (Papyrus) - + Script Extender Plugin - + SkyProc Patcher - + Sound or Music - + Textures - + MCM Configuration - + INI files - - ModGroup files - - - - + This entry contains files that have been created inside the virtual data tree (i.e. by the construction kit) - + Backup - - Separator - - - - + No valid game data - + Not endorsed yet - + Overwrites loose files - + Overwritten loose files - + Loose files Overwrites & Overwritten - + Redundant - + Overwrites an archive with loose files - + Archive is overwritten by loose files - + Overwrites another archive file - + Overwritten by another archive file - + Archive files overwrites & overwritten - - <br>This mod is for a different game, make sure it's compatible or it could cause crashes. + + Alternate game source - + Non-MO - + invalid - + installed version: "%1", newest version: "%2" - + The newest version on Nexus seems to be older than the one you have installed. This could either mean the version you have has been withdrawn (i.e. due to a bug) or the author uses a non-standard versioning scheme and that newest version is actually newer. Either way you may want to "upgrade". - + Categories: <br> - + Invalid name - + Name is already in use by another mod - + drag&drop failed: %1 - + Confirm - + Are you sure you want to remove "%1"? - + Flags - + Content - + Mod Name - + Version - + Priority - + Category - + Source Game - + Nexus ID - + Installation - - Notes - - - - - + + unknown - + Name of your mods - + Version of the mod (if available) - + Installation priority of your mod. The higher, the more "important" it is and thus overwrites files from mods with lower priority. - + Category of the mod. - + The source game which was the origin of this mod. - + Id of the mod as used on Nexus. - + Emblemes to highlight things that might require attention. - - Depicts the content of the mod:<br><table cellspacing=7><tr><td><img src=":/MO/gui/content/plugin" width=32/></td><td>Game plugins (esp/esm/esl)</td></tr><tr><td><img src=":/MO/gui/content/interface" width=32/></td><td>Interface</td></tr><tr><td><img src=":/MO/gui/content/mesh" width=32/></td><td>Meshes</td></tr><tr><td><img src=":/MO/gui/content/bsa" width=32/></td><td>BSA</td></tr><tr><td><img src=":/MO/gui/content/texture" width=32/></td><td>Textures</td></tr><tr><td><img src=":/MO/gui/content/sound" width=32/></td><td>Sounds</td></tr><tr><td><img src=":/MO/gui/content/music" width=32/></td><td>Music</td></tr><tr><td><img src=":/MO/gui/content/string" width=32/></td><td>Strings</td></tr><tr><td><img src=":/MO/gui/content/script" width=32/></td><td>Scripts (Papyrus)</td></tr><tr><td><img src=":/MO/gui/content/skse" width=32/></td><td>Script Extender plugins</td></tr><tr><td><img src=":/MO/gui/content/skyproc" width=32/></td><td>SkyProc Patcher</td></tr><tr><td><img src=":/MO/gui/content/menu" width=32/></td><td>Mod Configuration Menu</td></tr><tr><td><img src=":/MO/gui/content/inifile" width=32/></td><td>INI files</td></tr><tr><td><img src=":/MO/gui/content/modgroup" width=32/></td><td>ModGroup files</td></tr></table> + + Depicts the content of the mod:<br><table cellspacing=7><tr><td><img src=":/MO/gui/content/plugin" width=32/></td><td>Game plugins (esp/esm/esl)</td></tr><tr><td><img src=":/MO/gui/content/interface" width=32/></td><td>Interface</td></tr><tr><td><img src=":/MO/gui/content/mesh" width=32/></td><td>Meshes</td></tr><tr><td><img src=":/MO/gui/content/bsa" width=32/></td><td>BSA</td></tr><tr><td><img src=":/MO/gui/content/texture" width=32/></td><td>Textures</td></tr><tr><td><img src=":/MO/gui/content/sound" width=32/></td><td>Sounds</td></tr><tr><td><img src=":/MO/gui/content/music" width=32/></td><td>Music</td></tr><tr><td><img src=":/MO/gui/content/string" width=32/></td><td>Strings</td></tr><tr><td><img src=":/MO/gui/content/script" width=32/></td><td>Scripts (Papyrus)</td></tr><tr><td><img src=":/MO/gui/content/skse" width=32/></td><td>Script Extender plugins</td></tr><tr><td><img src=":/MO/gui/content/skyproc" width=32/></td><td>SkyProc Patcher</td></tr><tr><td><img src=":/MO/gui/content/menu" width=32/></td><td>Mod Configuration Menu</td></tr><tr><td><img src=":/MO/gui/content/inifile" width=32/></td><td>INI files</td></tr></table> - + Time this mod was installed - - - User notes about the mod - - ModListSortProxy - + Drag&Drop is only supported when sorting by priority @@ -4326,30 +4085,25 @@ p, li { white-space: pre-wrap; } NXMAccessManager - - Verifying Nexus login + + Validating Nexus Connection - - Logging into Nexus + + Verifying Nexus login - + timeout - + Unknown error - - - Please check your password - - NXMUrl @@ -4362,17 +4116,17 @@ p, li { white-space: pre-wrap; } NexusInterface - + Failed to guess mod id for "%1", please pick the correct one - + empty response - + invalid response @@ -4380,222 +4134,201 @@ p, li { white-space: pre-wrap; } OrganizerCore - - + + Failed to write settings - + An error occured trying to update MO settings to %1: %2 - + File is write protected - + Invalid file format (probably a bug) - + Unknown error %1 - + An error occured trying to write back MO settings to %1: %2 - - + + Download started - + Download failed - - + + Installation successful - - + + Configure Mod - - + + This mod contains ini tweaks. Do you want to configure them now? - - - mod not found: %1 - - - - + - - - Installation cancelled + mod "%1" not found - - - Another installation is currently in progress. + + + Installation cancelled - - + + The mod was not installed completely. - - Executable not found: %1 + + Executable "%1" not found - + Start Steam? - + Steam is required to be running already to correctly start the game. Should MO try to start steam now? - - Error - - - - - Windows Event Log Error - - - - - The Windows Event Log service is disabled and/or not running. This prevents USVFS from running properly. Your mods may not be working in the executable that you are launching. Note that you may have to restart MO and/or your PC after the service is fixed. - -Continue launching %1? + + Error - - Blacklisted Executable + + Windows Event Log Error - - The executable you are attempted to launch is blacklisted in the virtual file system. This will likely prevent the executable, and any executables that are launched by this one, from seeing any mods. This could extend to INI files, save games and any other virtualized files. + + The Windows Event Log service is disabled and/or not running. This prevents USVFS from running properly. Your mods may not be working in the executable that you are launching. Note that you may have to restart MO and/or your PC after the service is fixed. Continue launching %1? - + No profile set - + Failed to refresh list of esps: %1 - + Multiple esps/esls activated, please check that they don't conflict. - + Download? - + A download has been started but no installed page plugin recognizes it. If you download anyway no information (i.e. version) will be associated with the download. Continue? - - + failed to update mod list: %1 - - + + login successful - + Login failed - + Login failed, try again? - + login failed: %1. Download will not be associated with an account - + login failed: %1 - + login failed: %1. You need to log-in with Nexus to update MO. - + MO1 "Script Extender" load mechanism has left hook.dll in your game folder - - + + Description missing - + <a href="%1">hook.dll</a> has been found in your game folder (right click to copy the full path). This is most likely a leftover of setting the ModOrganizer 1 load mechanism to "Script Extender", in which case you must remove this file either by changing the load mechanism in ModOrganizer 1 or manually removing the file, otherwise the game is likely to crash and burn. - + failed to save load order: %1 - + The designated write target "%1" is not enabled. @@ -4639,7 +4372,7 @@ Continue? - mod not found: %1 + %1 not found @@ -4701,135 +4434,135 @@ Continue? PluginList - + Name - + Priority - + Mod Index - + Flags - - + + unknown - + Name of your mods - + Load priority of your mod. The higher, the more "important" it is and thus overwrites data from plugins with lower priority. - + The modindex determines the formids of objects originating from this mods. - + failed to update esp info for file %1 (source id: %2), error: %3 - - Plugin not found: %1 + + esp not found: %1 - - + + Confirm - + Really enable all plugins? - + Really disable all plugins? - + The file containing locked plugin indices is broken - - + + <b>Origin</b>: %1 - + <br><b><i>This plugin can't be disabled (enforced by the game).</i></b> - + Author - + Description - + Missing Masters - + Enabled Masters - + Loads Archives - + There are Archives connected to this plugin. Their assets will be added to your game, overwriting in case of conflicts following the plugin order. Loose files will always overwrite assets from Archives. (This flag only checks for Archives from the same mod as the plugin) - + Loads INI settings - + There is an ini file connected to this plugin. Its settings will be added to your game settings, overwriting in case of conflicts. - + This ESP is flagged as an ESL. It will adhere to the ESP load order but the records will be loaded in ESL space. - + failed to restore load order for %1 @@ -4837,7 +4570,7 @@ Continue? PluginListSortProxy - + Drag&Drop is only supported when sorting by priority or mod index @@ -4859,7 +4592,7 @@ Continue? ProblemsDialog - Notifications + Problems @@ -4892,7 +4625,7 @@ p, li { white-space: pre-wrap; } Profile - invalid profile name: %1 + invalid profile name %1 @@ -4901,82 +4634,57 @@ p, li { white-space: pre-wrap; } - + failed to write mod list: %1 - + failed to update tweaked ini file, wrong settings may be used: %1 - + failed to create tweaked ini: %1 - + failed to open %1 - + "%1" is missing or inaccessible - - - - - - - - invalid mod index: %1 + + + + + + invalid index %1 - + Overwrite directory couldn't be parsed - + invalid priority %1 - - Delete profile-specific save games? - - - - - Do you want to delete the profile-specific save games? (If you select "No", the save games will show up again if you re-enable profile-specific save games) - - - - - Missing profile-specific game INI files! - - - - - Some of your profile-specific game INI files were missing. They will now be copied from the vanilla game folder. You might want double-check your settings. - -Missing files: - - - - - - Delete profile-specific game INI files? + + Delete savegames? - - Do you want to delete the profile-specific game INI files? (If you select "No", the INI files will be used again if you re-enable profile-specific game INI files.) + + Do you want to delete local savegames? (If you select "No", the save games will show up again if you re-enable local savegames) @@ -4994,17 +4702,17 @@ Missing files: - If checked, the new profile will use the default game INI settings. + If checked, the new profile will use the default game settings. - If checked, the new profile will use the default game INI settings instead of the "global" settings. Global settings are the settings you configure when running the game launcher directly, without MO. + If checked, the new profile will use the default game settings instead of the "global" settings. Global settings are the settings you configure when running the game launcher directly, without MO. - Default Game INI Settings + Default Game Settings @@ -5033,41 +4741,27 @@ p, li { white-space: pre-wrap; } - <html><head/><body><p>If checked, save games are stored locally to this profile and will not appear when starting with a different profile.</p></body></html> - - - - If checked, save games are local to this profile and will not appear when starting with a different profile. + If checked, savegames are local to this profile and will not appear when starting with a different profile. - Use profile-specific Save Games + Local Savegames - <html><head/><body><p>If checked MO2 will use his own profile-specific game INI files, so that the &quot;Global&quot; ones in MyGames can be left vanilla. This different set of INI files is then offered to the game instead of the default one.</p></body></html> - - - - - <html><head/><body><p>If checked, MO2 will use a local set of game INI files (configuration and settings files), different from the default ones found in MyGames. This way changes to the INI settings will only affect this profile and the Global INI files can remain vanilla. MO2 will then show the profile INI files to the game instead of the Global ones.</p></body></html> - - - - - Use profile-specific Game INI Files + Local Game Settings - + This ensures data files from mods are actually used. You want to enable this unless you use a different tool for Archive Invalidation. - + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } @@ -5079,65 +4773,65 @@ p, li { white-space: pre-wrap; } - + Automatic Archive Invalidation - - + + Create a new profile from scratch - + Create - + Clone the selected profile - + This creates a new profile with the same settings and active mods as the selected one. - + Copy - - + + Delete the selected Profile. This can not be un-done! - + Remove - + Rename - - + + Transfer save games to the selected profile. - + Transfer Saves - + Close @@ -5194,7 +4888,7 @@ p, li { white-space: pre-wrap; } - Are you sure you want to remove this profile (including profile-specific save games, if any)? + Are you sure you want to remove this profile (including local savegames if any)? @@ -5228,32 +4922,13 @@ p, li { white-space: pre-wrap; } - - QApplication - - - INI file is read-only - - - - - - Mod Organizer is attempting to write to "%1" which is currently set to read-only. Clear the read-only flag to allow the write? - - - - - File is read-only - - - QObject - + Error @@ -5299,12 +4974,12 @@ p, li { white-space: pre-wrap; } - invalid category index: %1 + invalid index %1 - invalid category id: %1 + invalid category id %1 @@ -5353,13 +5028,12 @@ p, li { white-space: pre-wrap; } - - + helper failed - + failed to determine account name @@ -5370,142 +5044,140 @@ p, li { white-space: pre-wrap; } - + archive.dll not loaded: "%1" - + Deleting folder - + I'm about to delete the following folder: "%1". Proceed? - + Choose Instance to Delete - + Be Carefull! Deleting an Instance will remove all your files for that Instance (mods, downloads, profiles, configuration, ...). Custom paths outside of the instance folder for downloads, mods, etc. will be left untoched. - + Are you sure? - + Are you really sure you want to delete the Instance "%1" with all its files? - + Failed to delete Instance - + Could not delete Instance "%1". If the folder was still in use, restart MO and try again. - + Enter a Name for the new Instance - - Enter a new name or select one from the suggested list: -(This is just a name for the Instance and can be whatever you wish, - the actual game selection will happen on the next screen regardless of chosen name) + + Enter a new name or select one from the suggested list: - - + + Canceled - + Invalid instance name - + The instance name "%1" is invalid. Use the name "%2" instead? - + The instance "%1" already exists. - + Please choose a different instance name, like: "%1 1" . - + Choose Instance - + Each Instance is a full set of MO data files (mods, downloads, profiles, configuration, ...). You can use multiple instances for different games. Instances are stored in Appdata and can be accessed by all MO installations. If your MO folder is writable, you can also store a single instance locally (called a Portable install, and all the MO data files will be inside the installation folder). - + New - + Create a new instance. - + Portable - + Use MO folder for data. - + Manage Instances - + Delete an Instance. - - + + failed to create %1 - + Data directory created - + New data directory created at %1. If you don't want to store a lot of data there, reconfigure the storage directories via settings. @@ -5517,7 +5189,7 @@ If the folder was still in use, restart MO and try again. - file not found: %1 + %1 not found @@ -5575,7 +5247,7 @@ If the folder was still in use, restart MO and try again. - + Failed to create "%1". Your user account probably lacks permission. @@ -5592,64 +5264,58 @@ If the folder was still in use, restart MO and try again. - Please select the game to manage - - Canceled finding game in "%1". - - - - - No game identified in "%1". The directory is required to contain the game binary. + + No game identified in "%1". The directory is required to contain the game binary and its launcher. - + Please select the game edition you have (MO can't start the game correctly if this is set incorrectly!) - + failed to start shortcut: %1 - + failed to start application: %1 - - + + Mod Organizer - + An instance of Mod Organizer is already running - + Failed to set up instance - + Please use "Help" from the toolbar to get usage instructions to all elements - - + + <Manage...> - + failed to parse profile %1: %2 @@ -5685,12 +5351,12 @@ If the folder was still in use, restart MO and try again. - + failed to access %1 - + failed to set file time %1 @@ -5700,39 +5366,37 @@ If the folder was still in use, restart MO and try again. - + Script Extender - + Proxy DLL - + failed to spawn "%1" - + Elevation required - + This process requires elevation to run. This is a potential security risk so I highly advice you to investigate if "%1" can be installed to work without elevation. -Restart Mod Organizer as an elevated process? -You will be asked if you want to allow helper.exe to make changes to the system. You will need to relaunch the process above manually. +Start elevated anyway? (you will be asked if you want to allow ModOrganizer.exe to make changes to the system) - - + failed to spawn "%1": %2 @@ -5898,12 +5562,12 @@ Select Show Details option to see the full change-log. - + Failed to start %1: %2 - + Error @@ -5911,42 +5575,31 @@ Select Show Details option to see the full change-log. Settings - + Failed - + Sorry, failed to start the helper application - - + + attempt to store setting for unknown plugin "%1" - + Error - + Failed to create "%1", you may not have the necessary permission. path remains unchanged. - - - Restart Mod Organizer? - - - - - In order to reset the window geometries, MO must be restarted. -Restart it now? - - SettingsDialog @@ -6020,188 +5673,136 @@ If you use pre-releases, never contact me directly by e-mail or via private mess - Colors - - - - - - When this is enabled, the color defined for a separator will be shown on the mod list scrollbar at the location of the separator. This can be useful for quick navigation between separator sections or to a specific separator section. - - - - - Show mod list separator colors on the scrollbar - - - - - Plugin is Contained in selected Mod - - - - - Is overwritten (loose files) - - - - - Is overwriting (loose files) - - - - - Reset Colors - - - - - Mod Contains selected Plugin - - - - - Is overwritten (archive files) + If checked, the download interface will be more compact. - - Is overwriting (archive files) + + Compact Download Interface - - - Modify the categories available to arrange your mods. + + If checked, the download list will display meta information instead of file names. - - Configure Mod Categories + + Download Meta Information - + Reset stored information from dialogs. - + This will make all dialogs show up again where you checked the "Remember selection"-box. - + Reset Dialogs - - If checked, the download interface will be more compact. - - - - - Compact Download Interface - - - - - If checked, the download list will display meta information instead of file names. + + + Modify the categories available to arrange your mods. - - Download Meta Information + + Configure Mod Categories - + Paths - - - - + + + ... - + Caches - + Overwrite - - + + Directory where downloads are stored. - + Downloads - + Profiles - + Directory where mods are stored. - + Directory where mods are stored. Please note that changing this will break all associations of profiles with mods that don't exist in the new location (with the same name). - + Mods - + Managed Game - + Base Directory - + Use %BASE_DIR% to refer to the Base Directory. - + Important: All directories have to be writeable! - - + + Nexus - + Allows automatic log-in when the Nexus-Page for the game is clicked. - + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } @@ -6210,149 +5811,137 @@ p, li { white-space: pre-wrap; } - - If checked and if correct credentials are entered below, log-in to Nexus (for browsing and downloading) is automatic. - - - - - Automatically Log-In to Nexus + + Connect to Nexus - - - Username - - - - - - Password - - - - + Remove cache and cookies. Forces a new login. - + Clear Cache - + Disable automatic internet features - + Disable automatic internet features. This does not affect features that are explicitly invoked by the user (like checking mods for updates, endorsing, opening the web browser) - + Offline Mode - + Use a proxy for network connections. - + Use a proxy for network connections. This uses the system-wide settings which can be configured in Internet Explorer. Please note that MO will start up a few seconds slower on some systems when using a proxy. - + Use HTTP Proxy (Uses System Settings) - - Endorsement Integration - - - - + Associate with "Download with manager" links - + Known Servers (updated on download) - + Preferred Servers (Drag & Drop) - + Steam - + + Username + + + + + Password + + + + If you save your steam user ID and password here, they will be used when logging into steam. Note, however, your password will be stored unencrypted, so make sure your computer is secure. - + Plugins - + Author: - + Version: - + Description: - + Key - + Value - + Blacklisted Plugins (use <del> to remove): - + Workarounds - + Steam App ID - + The Steam AppID for your game - + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } @@ -6368,17 +5957,17 @@ p, li { white-space: pre-wrap; } - + Load Mechanism - + Select loading mechanism. See help for details. - + Mod Organizer needs a dll to be injected into the game so all mods are visible to it. There are several means to do this: *Mod Organizer* (default) In this mode the Mod Organizer itself injects the dll. The disadvantage is that you always have to start the game through MO or a link created by it. @@ -6389,17 +5978,17 @@ If you use the Steam version of Oblivion the default will NOT work. In this case - + NMM Version - + The Version of Nexus Mod Manager to impersonate. - + Mod Organizer uses an API provided by the Nexus to provide features like checking for updates and downloading files. Unfortunately this API has not been made available officially to third party tools like MO so we have to impersonate the Nexus Mod Manager to be allowed in. On top of this Nexus has used the client identification to lock out outdated versions of NMM to force users to update. This means that MO also needs to impersonate the new version of NMM even if MO doesn't need an update. Therefore you can configure the version to identify as here. Please note that MO does identify itself as MO to the webserver, it's not lying about what it is. It is merely adding a "compatible" NMM version to the user agent. @@ -6408,178 +5997,127 @@ tl;dr-version: If Nexus-features don't work, insert the current version num - + Enforces that inactive ESPs and ESMs are never loaded. - + It seems that the Games occasionally load ESP or ESM files even if they haven't been activated as plugins. I don't yet know what the circumstances are, but user reports imply it is in some cases unwanted. If this is checked, ESPs and ESMs not checked in the List are invisible to the game and can not be loaded. - + Hide inactive ESPs/ESMs - - Disable this to no longer display mods installed outside MO in the mod list (left pane). Assets from those mods will then be treated as having lowest mod priority together with the original game content. - - - - - By default Mod Organizer will display esp+bsa bundles installed with foreign tools as mods (left pane). This allows you to control their priority in relation to other mods. This is particularly useful if you also use Steam Workshop to install mods. -However, if you installed loose file mods outside MO which conflict with BSAs also installed outside MO those conflicts can't be resolved correctly. - -If you disable this feature, MO will only display official DLCs this way. Please note that plugins (esps, esms, and esls) displayed in the right pane are completely unaffected by this feature. - - - - - Display mods installed outside MO - - - - + If checked, files (i.e. esps, esms and bsas) belonging to the core game can not be disabled in the UI. (default: on) - + If checked, files (i.e. esps, esms and bsas) belonging to the core game can not be disabled in the UI. (default: on) Uncheck this if you want to use Mod Organizer with total conversions (like Nehrim) but be aware that the game will crash if required files are not enabled. - + Force-enable game files - - - Disable this to prevent the GUI from being locked when running an executable. This may result in abnormal behavior. - - - - - Lock GUI when running executable - - - - - Enable parsing of Archives. This is an Experimental Feature. Has negative effects on performance and known incorrectness. + + Disable this to no longer display mods installed outside MO in the mod list (left pane). Assets from those mods will then be treated as having lowest mod priority together with the original game content. - - <html><head/><body><p>By default, MO will parse archive files (BSA, BA2) to calculate conflicts between the contents of the archive files and other loose files. This process has a noticeable cost in performance.</p><p>This feature should not be confused with the archive management feature offered by MO1. MO2 will only show conflicts with archives and will NOT load them into the game or program.</p><p>If you disable this feature, MO will only display conflicts between loose files.</p></body></html> + + By default Mod Organizer will display esp+bsa bundles installed with foreign tools as mods (left pane). This allows you to control their priority in relation to other mods. This is particularly useful if you also use Steam Workshop to install mods. +However, if you installed loose file mods outside MO which conflict with BSAs also installed outside MO those conflicts can't be resolved correctly. + +If you disable this feature, MO will only display official DLCs this way. Please note that plugins (esps, esms, and esls) displayed in the right pane are completely unaffected by this feature. - - Enable parsing of Archives (Experimental Feature) + + Display mods installed outside MO - - + + For Skyrim, this can be used instead of Archive Invalidation. It should make AI redundant for all Profiles. For the other games this is not a sufficient replacement for AI! - + Back-date BSAs - - Add executables to the blacklist to prevent them from -accessing the virtual file system. This is useful to prevent -unintended programs from being hooked. Hooking unintended -programs may affect the execution of these programs or the -programs you are intentionally running. - - - - - Add executables to the blacklist to prevent them from accessing the virtual file system. This is useful to prevent unintended programs from being hooked. Hooking unintended programs may affect the execution of these programs or the programs you are intentionally running. - - - - - Configure Executables Blacklist - - - - - - Resets the window geometries for all windows. This can be useful if a window becomes too small or too large, if a column becomes too thin or too wide, and in similar situations. + + These are workarounds for problems with Mod Organizer. Please make sure you read the help text before changing anything here. - - Reset Window Geometries + + Diagnostics - - These are workarounds for problems with Mod Organizer. Please make sure you read the help text before changing anything here. + + Log Level - - Diagnostics + + Decides the amount of data printed to "ModOrganizer.log" - - Max Dumps To Keep + + + Decides the amount of data printed to "ModOrganizer.log". + "Debug" produces very useful information for finding problems. There is usually no noteworthy performance impact but the file may become rather large. If this is a problem you may prefer the "Info" level for regluar use. On the "Error" level the log file usually remains empty. + - - Maximum number of crash dumps to keep on disk. Use 0 for unlimited. + + Debug - - - Maximum number of crash dumps to keep on disk. Use 0 for unlimited. - Set "Crash Dumps" above to None to disable crash dump collection. - + + Info (recommended) - - Hint: right click link and copy link location + + Warning - - - Logs and crash dumps are stored under your current instance in the <a href="LOGS_FULL_PATH">LOGS_DIR</a> - and <a href="DUMPS_FULL_PATH">DUMPS_DIR</a> folders. - Sending logs and/or crash dumps to the developers can help investigate issues. - It is recommended to compress large log and dmp files before sending. - + + Error - + Crash Dumps - + Decides which type of crash dumps are collected when injected processes crash. - + Decides which type of crash dumps are collected when injected processes crash. "None" Disables the generation of crash dumps by MO. @@ -6590,131 +6128,105 @@ programs you are intentionally running. - + None - + Mini (recommended) - + Data - + Full - - Log Level + + Max Dumps To Keep - - Decides the amount of data printed to "ModOrganizer.log" + + Maximum number of crash dumps to keep on disk. Use 0 for unlimited. - + - Decides the amount of data printed to "ModOrganizer.log". - "Debug" produces very useful information for finding problems. There is usually no noteworthy performance impact but the file may become rather large. If this is a problem you may prefer the "Info" level for regluar use. On the "Error" level the log file usually remains empty. + Maximum number of crash dumps to keep on disk. Use 0 for unlimited. + Set "Crash Dumps" above to None to disable crash dump collection. - - Debug - - - - - Info (recommended) - - - - - Warning + + Hint: right click link and copy link location - - Error + + + Logs and crash dumps are stored under your current instance in the <a href="LOGS_FULL_PATH">LOGS_DIR</a> + and <a href="DUMPS_FULL_PATH">DUMPS_DIR</a> folders. + Sending logs and/or crash dumps to the developers can help investigate issues. + It is recommended to compress large log and dmp files before sending. + - + Confirm - + Changing the mod directory affects all your profiles! Mods not present (or named differently) in the new location will be disabled in all profiles. There is no way to undo this unless you backed up your profiles manually. Proceed? - - Executables Blacklist - - - - - Enter one executable per line to be blacklisted from the virtual file system. -Mods and other virtualized files will not be visible to these executables and -any executables launched by them. - -Example: - Chrome.exe - Firefox.exe - - - - + Select base directory - + Select download directory - + Select mod directory - + Select cache directory - + Select profiles directory - + Select overwrite directory - - Select game executable - - - - + Confirm? - + This will make all dialogs show up again where you checked the "Remember selection"-box. Continue? @@ -6826,7 +6338,7 @@ Example: TransferSavesDialog - Transfer Save Games + Transfer Savegames @@ -6918,7 +6430,7 @@ On Windows XP: UsvfsConnector - + Preparing vfs diff --git a/src/organizercore.cpp b/src/organizercore.cpp index a668de6b..dca855c7 100644 --- a/src/organizercore.cpp +++ b/src/organizercore.cpp @@ -1,2485 +1,2461 @@ -#include "organizercore.h" - -#include "delayedfilewriter.h" -#include "guessedvalue.h" -#include "imodinterface.h" -#include "imoinfo.h" -#include "iplugingame.h" -#include "iuserinterface.h" -#include "loadmechanism.h" -#include "messagedialog.h" -#include "modlistsortproxy.h" -#include "modrepositoryfileinfo.h" -#include "nexusinterface.h" -#include "plugincontainer.h" -#include "pluginlistsortproxy.h" -#include "profile.h" -#include "logbuffer.h" -#include "credentialsdialog.h" -#include "filedialogmemory.h" -#include "modinfodialog.h" -#include "spawn.h" -#include "syncoverwritedialog.h" -#include "nxmaccessmanager.h" -#include -#include -#include -#include -#include -#include -#include -#include "appconfig.h" -#include -#include -#include "lockeddialog.h" -#include "instancemanager.h" -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include // for qUtf8Printable, etc - -#include -#include -#include -#include // for _tcsicmp - -#include -#include -#include // for memset, wcsrchr - -#include -#include -#include -#include -#include -#include //for wstring -#include -#include - - -using namespace MOShared; -using namespace MOBase; - -//static -CrashDumpsType OrganizerCore::m_globalCrashDumpsType = CrashDumpsType::None; - -static bool isOnline() -{ - QList interfaces = QNetworkInterface::allInterfaces(); - - bool connected = false; - for (auto iter = interfaces.begin(); iter != interfaces.end() && !connected; - ++iter) { - if ((iter->flags() & QNetworkInterface::IsUp) - && (iter->flags() & QNetworkInterface::IsRunning) - && !(iter->flags() & QNetworkInterface::IsLoopBack)) { - auto addresses = iter->addressEntries(); - if (addresses.count() == 0) { - continue; - } - qDebug("interface %s seems to be up (address: %s)", - qUtf8Printable(iter->humanReadableName()), - qUtf8Printable(addresses[0].ip().toString())); - connected = true; - } - } - - return connected; -} - -static bool renameFile(const QString &oldName, const QString &newName, - bool overwrite = true) -{ - if (overwrite && QFile::exists(newName)) { - QFile::remove(newName); - } - return QFile::rename(oldName, newName); -} - -static std::wstring getProcessName(HANDLE process) -{ - wchar_t buffer[MAX_PATH]; - wchar_t *fileName = L"unknown"; - - if (process == nullptr) return fileName; - - if (::GetProcessImageFileNameW(process, buffer, MAX_PATH) != 0) { - fileName = wcsrchr(buffer, L'\\'); - if (fileName == nullptr) { - fileName = buffer; - } - else { - fileName += 1; - } - } - - return fileName; -} - -// Get parent PID for the given process, return 0 on failure -static DWORD getProcessParentID(DWORD pid) -{ - HANDLE th = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); - PROCESSENTRY32 pe = { 0 }; - pe.dwSize = sizeof(PROCESSENTRY32); - - DWORD res = 0; - if (Process32First(th, &pe)) - do { - if (pe.th32ProcessID == pid) { - res = pe.th32ParentProcessID; - break; - } - } while (Process32Next(th, &pe)); - - CloseHandle(th); - - return res; -} - -static void startSteam(QWidget *widget) -{ - QSettings steamSettings("HKEY_CURRENT_USER\\Software\\Valve\\Steam", - QSettings::NativeFormat); - QString exe = steamSettings.value("SteamExe", "").toString(); - if (!exe.isEmpty()) { - exe = QString("\"%1\"").arg(exe); - // See if username and password supplied. If so, pass them into steam. - QStringList args; - QString username; - QString password; - if (Settings::instance().getSteamLogin(username, password)) { - args << "-login"; - args << username; - if (password != "") { - args << password; - } - } - if (!QProcess::startDetached(exe, args)) { - reportError(QObject::tr("Failed to start \"%1\"").arg(exe)); - } else { - QMessageBox::information( - widget, QObject::tr("Waiting"), - QObject::tr("Please press OK once you're logged into steam.")); - } - } -} - -template -QStringList toStringList(InputIterator current, InputIterator end) -{ - QStringList result; - for (; current != end; ++current) { - result.append(*current); - } - return result; -} - -bool checkService() -{ - SC_HANDLE serviceManagerHandle = NULL; - SC_HANDLE serviceHandle = NULL; - LPSERVICE_STATUS_PROCESS serviceStatus = NULL; - LPQUERY_SERVICE_CONFIG serviceConfig = NULL; - bool serviceRunning = true; - - DWORD bytesNeeded; - - try { - serviceManagerHandle = OpenSCManager(NULL, NULL, SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG); - if (!serviceManagerHandle) { - qWarning("failed to open service manager (query status) (error %d)", GetLastError()); - throw 1; - } - - serviceHandle = OpenService(serviceManagerHandle, L"EventLog", SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG); - if (!serviceHandle) { - qWarning("failed to open EventLog service (query status) (error %d)", GetLastError()); - throw 2; - } - - if (QueryServiceConfig(serviceHandle, NULL, 0, &bytesNeeded) - || (GetLastError() != ERROR_INSUFFICIENT_BUFFER)) { - qWarning("failed to get size of service config (error %d)", GetLastError()); - throw 3; - } - - DWORD serviceConfigSize = bytesNeeded; - serviceConfig = (LPQUERY_SERVICE_CONFIG)LocalAlloc(LMEM_FIXED, serviceConfigSize); - if (!QueryServiceConfig(serviceHandle, serviceConfig, serviceConfigSize, &bytesNeeded)) { - qWarning("failed to query service config (error %d)", GetLastError()); - throw 4; - } - - if (serviceConfig->dwStartType == SERVICE_DISABLED) { - qCritical("Windows Event Log service is disabled!"); - serviceRunning = false; - } - - if (QueryServiceStatusEx(serviceHandle, SC_STATUS_PROCESS_INFO, NULL, 0, &bytesNeeded) - || (GetLastError() != ERROR_INSUFFICIENT_BUFFER)) { - qWarning("failed to get size of service status (error %d)", GetLastError()); - throw 5; - } - - DWORD serviceStatusSize = bytesNeeded; - serviceStatus = (LPSERVICE_STATUS_PROCESS)LocalAlloc(LMEM_FIXED, serviceStatusSize); - if (!QueryServiceStatusEx(serviceHandle, SC_STATUS_PROCESS_INFO, (LPBYTE)serviceStatus, serviceStatusSize, &bytesNeeded)) { - qWarning("failed to query service status (error %d)", GetLastError()); - throw 6; - } - - if (serviceStatus->dwCurrentState != SERVICE_RUNNING) { - qCritical("Windows Event Log service is not running"); - serviceRunning = false; - } - } - catch (int e) { - UNUSED_VAR(e); - serviceRunning = false; - } - - if (serviceStatus) { - LocalFree(serviceStatus); - } - if (serviceConfig) { - LocalFree(serviceConfig); - } - if (serviceHandle) { - CloseServiceHandle(serviceHandle); - } - if (serviceManagerHandle) { - CloseServiceHandle(serviceManagerHandle); - } - - return serviceRunning; -} - -OrganizerCore::OrganizerCore(const QSettings &initSettings) - : m_UserInterface(nullptr) - , m_PluginContainer(nullptr) - , m_GameName() - , m_CurrentProfile(nullptr) - , m_Settings(initSettings) - , m_Updater(NexusInterface::instance(m_PluginContainer)) - , m_AboutToRun() - , m_FinishedRun() - , m_ModInstalled() - , m_ModList(m_PluginContainer, this) - , m_PluginList(this) - , m_DirectoryRefresher() - , m_DirectoryStructure(new DirectoryEntry(L"data", nullptr, 0)) - , m_DownloadManager(NexusInterface::instance(m_PluginContainer), this) - , m_InstallationManager() - , m_RefresherThread() - , m_AskForNexusPW(false) - , m_DirectoryUpdate(false) - , m_ArchivesInit(false) - , m_PluginListsWriter(std::bind(&OrganizerCore::savePluginList, this)) -{ - m_DownloadManager.setOutputDirectory(m_Settings.getDownloadDirectory()); - m_DownloadManager.setPreferredServers(m_Settings.getPreferredServers()); - - NexusInterface::instance(m_PluginContainer)->setCacheDirectory(m_Settings.getCacheDirectory()); - NexusInterface::instance(m_PluginContainer)->setNMMVersion(m_Settings.getNMMVersion()); - - MOBase::QuestionBoxMemory::init(initSettings.fileName()); - - m_InstallationManager.setModsDirectory(m_Settings.getModDirectory()); - m_InstallationManager.setDownloadDirectory(m_Settings.getDownloadDirectory()); - - connect(&m_DownloadManager, SIGNAL(downloadSpeed(QString, int)), this, - SLOT(downloadSpeed(QString, int))); - connect(&m_DirectoryRefresher, SIGNAL(refreshed()), this, - SLOT(directory_refreshed())); - - connect(&m_ModList, SIGNAL(removeOrigin(QString)), this, - SLOT(removeOrigin(QString))); - - connect(NexusInterface::instance(m_PluginContainer)->getAccessManager(), - SIGNAL(loginSuccessful(bool)), this, SLOT(loginSuccessful(bool))); - connect(NexusInterface::instance(m_PluginContainer)->getAccessManager(), - SIGNAL(loginFailed(QString)), this, SLOT(loginFailed(QString))); - - // This seems awfully imperative - connect(this, SIGNAL(managedGameChanged(MOBase::IPluginGame const *)), - &m_Settings, SLOT(managedGameChanged(MOBase::IPluginGame const *))); - connect(this, SIGNAL(managedGameChanged(MOBase::IPluginGame const *)), - &m_DownloadManager, - SLOT(managedGameChanged(MOBase::IPluginGame const *))); - connect(this, SIGNAL(managedGameChanged(MOBase::IPluginGame const *)), - &m_PluginList, SLOT(managedGameChanged(MOBase::IPluginGame const *))); - - connect(&m_PluginList, &PluginList::writePluginsList, &m_PluginListsWriter, - &DelayedFileWriterBase::write); - - // make directory refresher run in a separate thread - m_RefresherThread.start(); - m_DirectoryRefresher.moveToThread(&m_RefresherThread); - - m_AskForNexusPW = initSettings.value("ask_for_nexuspw", true).toBool(); -} - -OrganizerCore::~OrganizerCore() -{ - m_RefresherThread.exit(); - m_RefresherThread.wait(); - - prepareStart(); - - // profile has to be cleaned up before the modinfo-buffer is cleared - delete m_CurrentProfile; - m_CurrentProfile = nullptr; - - ModInfo::clear(); - LogBuffer::cleanQuit(); - m_ModList.setProfile(nullptr); - // NexusInterface::instance()->cleanup(); - - delete m_DirectoryStructure; -} - -QString OrganizerCore::commitSettings(const QString &iniFile) -{ - if (!shellRename(iniFile + ".new", iniFile, true, qApp->activeWindow())) { - DWORD err = ::GetLastError(); - // make a second attempt using qt functions but if that fails print the - // error from the first attempt - if (!renameFile(iniFile + ".new", iniFile)) { - return windowsErrorString(err); - } - } - return QString(); -} - -QSettings::Status OrganizerCore::storeSettings(const QString &fileName) -{ - QSettings settings(fileName, QSettings::IniFormat); - if (m_UserInterface != nullptr) { - m_UserInterface->storeSettings(settings); - } - if (m_CurrentProfile != nullptr) { - settings.setValue("selected_profile", - m_CurrentProfile->name().toUtf8().constData()); - } - settings.setValue("ask_for_nexuspw", m_AskForNexusPW); - - settings.remove("customExecutables"); - settings.beginWriteArray("customExecutables"); - std::vector::const_iterator current, end; - m_ExecutablesList.getExecutables(current, end); - int count = 0; - for (; current != end; ++current) { - const Executable &item = *current; - settings.setArrayIndex(count++); - settings.setValue("title", item.m_Title); - settings.setValue("custom", item.isCustom()); - settings.setValue("toolbar", item.isShownOnToolbar()); - settings.setValue("ownicon", item.usesOwnIcon()); - if (item.isCustom()) { - settings.setValue("binary", item.m_BinaryInfo.absoluteFilePath()); - settings.setValue("arguments", item.m_Arguments); - settings.setValue("workingDirectory", item.m_WorkingDirectory); - settings.setValue("steamAppID", item.m_SteamAppID); - } - } - settings.endArray(); - - FileDialogMemory::save(settings); - - settings.sync(); - return settings.status(); -} - -void OrganizerCore::storeSettings() -{ - QString iniFile = qApp->property("dataPath").toString() + "/" - + QString::fromStdWString(AppConfig::iniFileName()); - if (QFileInfo(iniFile).exists()) { - if (!shellCopy(iniFile, iniFile + ".new", true, qApp->activeWindow())) { - QMessageBox::critical( - qApp->activeWindow(), tr("Failed to write settings"), - tr("An error occured trying to update MO settings to %1: %2") - .arg(iniFile, windowsErrorString(::GetLastError()))); - return; - } - } - - QString writeTarget = iniFile + ".new"; - - QSettings::Status result = storeSettings(writeTarget); - - if (result == QSettings::NoError) { - QString errMsg = commitSettings(iniFile); - if (!errMsg.isEmpty()) { - qWarning("settings file not writable, may be locked by another " - "application, trying direct write"); - writeTarget = iniFile; - result = storeSettings(iniFile); - } - } - if (result != QSettings::NoError) { - QString reason = result == QSettings::AccessError - ? tr("File is write protected") - : result == QSettings::FormatError - ? tr("Invalid file format (probably a bug)") - : tr("Unknown error %1").arg(result); - QMessageBox::critical( - qApp->activeWindow(), tr("Failed to write settings"), - tr("An error occured trying to write back MO settings to %1: %2") - .arg(writeTarget, reason)); - } -} - -bool OrganizerCore::testForSteam() -{ - size_t currentSize = 1024; - std::unique_ptr processIDs; - DWORD bytesReturned; - bool success = false; - while (!success) { - processIDs.reset(new DWORD[currentSize]); - if (!::EnumProcesses(processIDs.get(), - static_cast(currentSize) * sizeof(DWORD), - &bytesReturned)) { - qWarning("failed to determine if steam is running"); - return true; - } - if (bytesReturned == (currentSize * sizeof(DWORD))) { - // maximum size used, list probably truncated - currentSize *= 2; - } else { - success = true; - } - } - TCHAR processName[MAX_PATH]; - for (unsigned int i = 0; i < bytesReturned / sizeof(DWORD); ++i) { - memset(processName, '\0', sizeof(TCHAR) * MAX_PATH); - if (processIDs[i] != 0) { - HANDLE process = ::OpenProcess( - PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processIDs[i]); - - if (process != nullptr) { - - ON_BLOCK_EXIT([&]() { - if (process != INVALID_HANDLE_VALUE) - ::CloseHandle(process); - }); - - HMODULE module; - DWORD ignore; - - // first module in a process is always the binary - if (EnumProcessModules(process, &module, sizeof(HMODULE) * 1, - &ignore)) { - ::GetModuleBaseName(process, module, processName, MAX_PATH); - if ((_tcsicmp(processName, TEXT("steam.exe")) == 0) - || (_tcsicmp(processName, TEXT("steamservice.exe")) == 0)) { - return true; - } - } - } - } - } - - return false; -} - -void OrganizerCore::updateExecutablesList(QSettings &settings) -{ - if (m_PluginContainer == nullptr) { - qCritical("can't update executables list now"); - return; - } - - m_ExecutablesList.init(managedGame()); - - qDebug("setting up configured executables"); - - int numCustomExecutables = settings.beginReadArray("customExecutables"); - for (int i = 0; i < numCustomExecutables; ++i) { - settings.setArrayIndex(i); - - Executable::Flags flags; - if (settings.value("custom", true).toBool()) - flags |= Executable::CustomExecutable; - if (settings.value("toolbar", false).toBool()) - flags |= Executable::ShowInToolbar; - if (settings.value("ownicon", false).toBool()) - flags |= Executable::UseApplicationIcon; - - m_ExecutablesList.addExecutable( - settings.value("title").toString(), settings.value("binary").toString(), - settings.value("arguments").toString(), - settings.value("workingDirectory", "").toString(), - settings.value("steamAppID", "").toString(), flags); - } - - settings.endArray(); - - // TODO this has nothing to do with executables list move to an appropriate - // function! - ModInfo::updateFromDisc(m_Settings.getModDirectory(), &m_DirectoryStructure, - m_PluginContainer, m_Settings.displayForeign(), managedGame()); -} - -void OrganizerCore::setUserInterface(IUserInterface *userInterface, - QWidget *widget) -{ - storeSettings(); - - m_UserInterface = userInterface; - - if (widget != nullptr) { - connect(&m_ModList, SIGNAL(modlistChanged(QModelIndex, int)), widget, - SLOT(modlistChanged(QModelIndex, int))); - connect(&m_ModList, SIGNAL(modlistChanged(QModelIndexList, int)), widget, - SLOT(modlistChanged(QModelIndexList, int))); - connect(&m_ModList, SIGNAL(showMessage(QString)), widget, - SLOT(showMessage(QString))); - connect(&m_ModList, SIGNAL(modRenamed(QString, QString)), widget, - SLOT(modRenamed(QString, QString))); - connect(&m_ModList, SIGNAL(modUninstalled(QString)), widget, - SLOT(modRemoved(QString))); - connect(&m_ModList, SIGNAL(removeSelectedMods()), widget, - SLOT(removeMod_clicked())); - connect(&m_ModList, SIGNAL(clearOverwrite()), widget, - SLOT(clearOverwrite())); - connect(&m_ModList, SIGNAL(requestColumnSelect(QPoint)), widget, - SLOT(displayColumnSelection(QPoint))); - connect(&m_ModList, SIGNAL(fileMoved(QString, QString, QString)), widget, - SLOT(fileMoved(QString, QString, QString))); - connect(&m_ModList, SIGNAL(modorder_changed()), widget, - SLOT(modorder_changed())); - connect(&m_PluginList, SIGNAL(writePluginsList()), widget, - SLOT(esplist_changed())); - connect(&m_PluginList, SIGNAL(esplist_changed()), widget, - SLOT(esplist_changed())); - connect(&m_DownloadManager, SIGNAL(showMessage(QString)), widget, - SLOT(showMessage(QString))); - } - - m_InstallationManager.setParentWidget(widget); - m_Updater.setUserInterface(widget); - - if (userInterface != nullptr) { - // this currently wouldn't work reliably if the ui isn't initialized yet to - // display the result - if (isOnline() && !m_Settings.offlineMode()) { - m_Updater.testForUpdate(); - } else { - qDebug("user doesn't seem to be connected to the internet"); - } - } -} - -void OrganizerCore::connectPlugins(PluginContainer *container) -{ - m_DownloadManager.setSupportedExtensions( - m_InstallationManager.getSupportedExtensions()); - m_PluginContainer = container; - m_Updater.setPluginContainer(m_PluginContainer); - m_DownloadManager.setPluginContainer(m_PluginContainer); - m_ModList.setPluginContainer(m_PluginContainer); - - if (!m_GameName.isEmpty()) { - m_GamePlugin = m_PluginContainer->managedGame(m_GameName); - emit managedGameChanged(m_GamePlugin); - } -} - -void OrganizerCore::disconnectPlugins() -{ - m_AboutToRun.disconnect_all_slots(); - m_FinishedRun.disconnect_all_slots(); - m_ModInstalled.disconnect_all_slots(); - m_ModList.disconnectSlots(); - m_PluginList.disconnectSlots(); - m_Updater.setPluginContainer(nullptr); - m_DownloadManager.setPluginContainer(nullptr); - m_ModList.setPluginContainer(nullptr); - - m_Settings.clearPlugins(); - m_GamePlugin = nullptr; - m_PluginContainer = nullptr; -} - -void OrganizerCore::setManagedGame(MOBase::IPluginGame *game) -{ - m_GameName = game->gameName(); - m_GamePlugin = game; - qApp->setProperty("managed_game", QVariant::fromValue(m_GamePlugin)); - emit managedGameChanged(m_GamePlugin); -} - -Settings &OrganizerCore::settings() -{ - return m_Settings; -} - -bool OrganizerCore::nexusLogin(bool retry) -{ - NXMAccessManager *accessManager - = NexusInterface::instance(m_PluginContainer)->getAccessManager(); - - if ((accessManager->loginAttempted() || accessManager->loggedIn()) - && !retry) { - // previous attempt, maybe even successful - return false; - } else { - QString username, password; - if ((!retry && m_Settings.getNexusLogin(username, password)) - || (m_AskForNexusPW && queryLogin(username, password))) { - // credentials stored or user entered them manually - qDebug("attempt login with username %s", qUtf8Printable(username)); - accessManager->login(username, password); - return true; - } else { - // no credentials stored and user didn't enter them - accessManager->refuseLogin(); - return false; - } - } -} - -bool OrganizerCore::queryLogin(QString &username, QString &password) -{ - CredentialsDialog dialog(qApp->activeWindow()); - int res = dialog.exec(); - if (dialog.neverAsk()) { - m_AskForNexusPW = false; - } - if (res == QDialog::Accepted) { - username = dialog.username(); - password = dialog.password(); - if (dialog.store()) { - m_Settings.setNexusLogin(username, password); - } - return true; - } else { - return false; - } -} - -void OrganizerCore::startMOUpdate() -{ - if (nexusLogin()) { - m_PostLoginTasks.append([&]() { m_Updater.startUpdate(); }); - } else { - m_Updater.startUpdate(); - } -} - -void OrganizerCore::downloadRequestedNXM(const QString &url) -{ - qDebug("download requested: %s", qUtf8Printable(url)); - if (nexusLogin()) { - m_PendingDownloads.append(url); - } else { - m_DownloadManager.addNXMDownload(url); - } -} - -void OrganizerCore::externalMessage(const QString &message) -{ - if (MOShortcut moshortcut{ message } ) { - if(moshortcut.hasExecutable()) - runShortcut(moshortcut); - } - else if (isNxmLink(message)) { - MessageDialog::showMessage(tr("Download started"), qApp->activeWindow()); - downloadRequestedNXM(message); - } -} - -void OrganizerCore::downloadRequested(QNetworkReply *reply, QString gameName, int modID, - const QString &fileName) -{ - try { - if (m_DownloadManager.addDownload(reply, QStringList(), fileName, gameName, modID, 0, - new ModRepositoryFileInfo(gameName, modID))) { - MessageDialog::showMessage(tr("Download started"), qApp->activeWindow()); - } - } catch (const std::exception &e) { - MessageDialog::showMessage(tr("Download failed"), qApp->activeWindow()); - qCritical("exception starting download: %s", e.what()); - } -} - -void OrganizerCore::removeOrigin(const QString &name) -{ - FilesOrigin &origin = m_DirectoryStructure->getOriginByName(ToWString(name)); - origin.enable(false); - refreshLists(); -} - -void OrganizerCore::downloadSpeed(const QString &serverName, int bytesPerSecond) -{ - m_Settings.setDownloadSpeed(serverName, bytesPerSecond); -} - -InstallationManager *OrganizerCore::installationManager() -{ - return &m_InstallationManager; -} - -bool OrganizerCore::createDirectory(const QString &path) { - if (!QDir(path).exists() && !QDir().mkpath(path)) { - QMessageBox::critical(nullptr, QObject::tr("Error"), - QObject::tr("Failed to create \"%1\". Your user " - "account probably lacks permission.") - .arg(QDir::toNativeSeparators(path))); - return false; - } else { - return true; - } -} - -bool OrganizerCore::bootstrap() { - return createDirectory(m_Settings.getProfileDirectory()) && - createDirectory(m_Settings.getModDirectory()) && - createDirectory(m_Settings.getDownloadDirectory()) && - createDirectory(m_Settings.getOverwriteDirectory()) && - createDirectory(QString::fromStdWString(crashDumpsPath())) && cycleDiagnostics(); -} - -void OrganizerCore::createDefaultProfile() -{ - QString profilesPath = settings().getProfileDirectory(); - if (QDir(profilesPath).entryList(QDir::AllDirs | QDir::NoDotAndDotDot).size() - == 0) { - Profile newProf("Default", managedGame(), false); - } -} - -void OrganizerCore::prepareVFS() -{ - m_USVFS.updateMapping(fileMapping(m_CurrentProfile->name(), QString())); -} - -void OrganizerCore::updateVFSParams(int logLevel, int crashDumpsType, QString executableBlacklist) { - setGlobalCrashDumpsType(crashDumpsType); - m_USVFS.updateParams(logLevel, crashDumpsType, executableBlacklist); -} - -bool OrganizerCore::cycleDiagnostics() { - if (int maxDumps = settings().crashDumpsMax()) - removeOldFiles(QString::fromStdWString(crashDumpsPath()), "*.dmp", maxDumps, QDir::Time|QDir::Reversed); - return true; -} - -//static -void OrganizerCore::setGlobalCrashDumpsType(int crashDumpsType) { - m_globalCrashDumpsType = ::crashDumpsType(crashDumpsType); -} - -//static -std::wstring OrganizerCore::crashDumpsPath() { - return ( - qApp->property("dataPath").toString() + "/" - + QString::fromStdWString(AppConfig::dumpsDir()) - ).toStdWString(); -} - -bool OrganizerCore::getArchiveParsing() const -{ - return m_ArchiveParsing; -} - -void OrganizerCore::setArchiveParsing(const bool archiveParsing) -{ - m_ArchiveParsing = archiveParsing; -} - -void OrganizerCore::setCurrentProfile(const QString &profileName) -{ - if ((m_CurrentProfile != nullptr) - && (profileName == m_CurrentProfile->name())) { - return; - } - - QDir profileBaseDir(settings().getProfileDirectory()); - QString profileDir = profileBaseDir.absoluteFilePath(profileName); - - if (!QDir(profileDir).exists()) { - // selected profile doesn't exist. Ensure there is at least one profile, - // then pick any one - createDefaultProfile(); - - profileDir = profileBaseDir.absoluteFilePath( - profileBaseDir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot).at(0)); - } - - Profile *newProfile = new Profile(QDir(profileDir), managedGame()); - - delete m_CurrentProfile; - m_CurrentProfile = newProfile; - m_ModList.setProfile(newProfile); - - if (m_CurrentProfile->invalidationActive(nullptr)) { - m_CurrentProfile->activateInvalidation(); - } else { - m_CurrentProfile->deactivateInvalidation(); - } - - connect(m_CurrentProfile, SIGNAL(modStatusChanged(uint)), this, SLOT(modStatusChanged(uint))); - connect(m_CurrentProfile, SIGNAL(modStatusChanged(QList)), this, SLOT(modStatusChanged(QList))); - refreshDirectoryStructure(); - - //This line is not actually needed and was only added to allow some - //outside detection of Mo2 profile change. (like BaobobMiller utility) - if (m_CurrentProfile != nullptr) { - settings().directInterface().setValue("selected_profile", - m_CurrentProfile->name().toUtf8().constData()); - } -} - -MOBase::IModRepositoryBridge *OrganizerCore::createNexusBridge() const -{ - return new NexusBridge(m_PluginContainer); -} - -QString OrganizerCore::profileName() const -{ - if (m_CurrentProfile != nullptr) { - return m_CurrentProfile->name(); - } else { - return ""; - } -} - -QString OrganizerCore::profilePath() const -{ - if (m_CurrentProfile != nullptr) { - return m_CurrentProfile->absolutePath(); - } else { - return ""; - } -} - -QString OrganizerCore::downloadsPath() const -{ - return QDir::fromNativeSeparators(m_Settings.getDownloadDirectory()); -} - -QString OrganizerCore::overwritePath() const -{ - return QDir::fromNativeSeparators(m_Settings.getOverwriteDirectory()); -} - -QString OrganizerCore::basePath() const -{ - return QDir::fromNativeSeparators(m_Settings.getBaseDirectory()); -} - -MOBase::VersionInfo OrganizerCore::appVersion() const -{ - return m_Updater.getVersion(); -} - -MOBase::IModInterface *OrganizerCore::getMod(const QString &name) const -{ - unsigned int index = ModInfo::getIndex(name); - return index == UINT_MAX ? nullptr : ModInfo::getByIndex(index).data(); -} - -MOBase::IPluginGame *OrganizerCore::getGame(const QString &name) const -{ - for (IPluginGame *game : m_PluginContainer->plugins()) { - if (game->gameShortName().compare(name, Qt::CaseInsensitive) == 0) - return game; - } - return nullptr; -} - -MOBase::IModInterface *OrganizerCore::createMod(GuessedValue &name) -{ - bool merge = false; - if (!m_InstallationManager.testOverwrite(name, &merge)) { - return nullptr; - } - - m_InstallationManager.setModsDirectory(m_Settings.getModDirectory()); - - QString targetDirectory - = QDir::fromNativeSeparators(m_Settings.getModDirectory()) - .append("/") - .append(name); - - QSettings settingsFile(targetDirectory + "/meta.ini", QSettings::IniFormat); - - if (!merge) { - settingsFile.setValue("modid", 0); - settingsFile.setValue("version", ""); - settingsFile.setValue("newestVersion", ""); - settingsFile.setValue("category", 0); - settingsFile.setValue("installationFile", ""); - - settingsFile.remove("installedFiles"); - settingsFile.beginWriteArray("installedFiles", 0); - settingsFile.endArray(); - } - - return ModInfo::createFrom(m_PluginContainer, m_GamePlugin, QDir(targetDirectory), &m_DirectoryStructure) - .data(); -} - -bool OrganizerCore::removeMod(MOBase::IModInterface *mod) -{ - unsigned int index = ModInfo::getIndex(mod->name()); - if (index == UINT_MAX) { - return mod->remove(); - } else { - return ModInfo::removeMod(index); - } -} - -void OrganizerCore::modDataChanged(MOBase::IModInterface *) -{ - refreshModList(false); -} - -QVariant OrganizerCore::pluginSetting(const QString &pluginName, - const QString &key) const -{ - return m_Settings.pluginSetting(pluginName, key); -} - -void OrganizerCore::setPluginSetting(const QString &pluginName, - const QString &key, const QVariant &value) -{ - m_Settings.setPluginSetting(pluginName, key, value); -} - -QVariant OrganizerCore::persistent(const QString &pluginName, - const QString &key, - const QVariant &def) const -{ - return m_Settings.pluginPersistent(pluginName, key, def); -} - -void OrganizerCore::setPersistent(const QString &pluginName, const QString &key, - const QVariant &value, bool sync) -{ - m_Settings.setPluginPersistent(pluginName, key, value, sync); -} - -QString OrganizerCore::pluginDataPath() const -{ - return qApp->applicationDirPath() + "/" + ToQString(AppConfig::pluginPath()) - + "/data"; -} - -MOBase::IModInterface *OrganizerCore::installMod(const QString &fileName, - const QString &initModName) -{ - if (m_CurrentProfile == nullptr) { - return nullptr; - } - - if (m_InstallationManager.isRunning()) { - QMessageBox::information( - qApp->activeWindow(), tr("Installation cancelled"), - tr("Another installation is currently in progress."), QMessageBox::Ok); - return nullptr; - } - - bool hasIniTweaks = false; - GuessedValue modName; - if (!initModName.isEmpty()) { - modName.update(initModName, GUESS_USER); - } - m_CurrentProfile->writeModlistNow(); - m_InstallationManager.setModsDirectory(m_Settings.getModDirectory()); - if (m_InstallationManager.install(fileName, modName, hasIniTweaks)) { - MessageDialog::showMessage(tr("Installation successful"), - qApp->activeWindow()); - refreshModList(); - - int modIndex = ModInfo::getIndex(modName); - if (modIndex != UINT_MAX) { - ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); - if (hasIniTweaks && (m_UserInterface != nullptr) - && (QMessageBox::question(qApp->activeWindow(), tr("Configure Mod"), - tr("This mod contains ini tweaks. Do you " - "want to configure them now?"), - QMessageBox::Yes | QMessageBox::No) - == QMessageBox::Yes)) { - m_UserInterface->displayModInformation(modInfo, modIndex, - ModInfoDialog::TAB_INIFILES); - } - m_ModInstalled(modName); - m_DownloadManager.markInstalled(fileName); - emit modInstalled(modName); - return modInfo.data(); - } else { - reportError(tr("mod not found: %1").arg(qUtf8Printable(modName))); - } - } else if (m_InstallationManager.wasCancelled()) { - QMessageBox::information(qApp->activeWindow(), tr("Installation cancelled"), - tr("The mod was not installed completely."), - QMessageBox::Ok); - } - return nullptr; -} - -void OrganizerCore::installDownload(int index) -{ - if (m_InstallationManager.isRunning()) { - QMessageBox::information( - qApp->activeWindow(), tr("Installation cancelled"), - tr("Another installation is currently in progress."), QMessageBox::Ok); - return; - } - - try { - QString fileName = m_DownloadManager.getFilePath(index); - QString gameName = m_DownloadManager.getGameName(index); - int modID = m_DownloadManager.getModID(index); - int fileID = m_DownloadManager.getFileInfo(index)->fileID; - GuessedValue modName; - - // see if there already are mods with the specified mod id - if (modID != 0) { - std::vector modInfo = ModInfo::getByModID(gameName, modID); - for (auto iter = modInfo.begin(); iter != modInfo.end(); ++iter) { - std::vector flags = (*iter)->getFlags(); - if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_BACKUP) - == flags.end()) { - modName.update((*iter)->name(), GUESS_PRESET); - (*iter)->saveMeta(); - } - } - } - - m_CurrentProfile->writeModlistNow(); - - bool hasIniTweaks = false; - m_InstallationManager.setModsDirectory(m_Settings.getModDirectory()); - if (m_InstallationManager.install(fileName, modName, hasIniTweaks)) { - MessageDialog::showMessage(tr("Installation successful"), - qApp->activeWindow()); - refreshModList(); - - int modIndex = ModInfo::getIndex(modName); - if (modIndex != UINT_MAX) { - ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); - modInfo->addInstalledFile(modID, fileID); - - if (hasIniTweaks && m_UserInterface != nullptr - && (QMessageBox::question(qApp->activeWindow(), tr("Configure Mod"), - tr("This mod contains ini tweaks. Do you " - "want to configure them now?"), - QMessageBox::Yes | QMessageBox::No) - == QMessageBox::Yes)) { - m_UserInterface->displayModInformation(modInfo, modIndex, - ModInfoDialog::TAB_INIFILES); - } - - m_ModInstalled(modName); - } else { - reportError(tr("mod not found: %1").arg(qUtf8Printable(modName))); - } - m_DownloadManager.markInstalled(index); - - emit modInstalled(modName); - } else if (m_InstallationManager.wasCancelled()) { - QMessageBox::information( - qApp->activeWindow(), tr("Installation cancelled"), - tr("The mod was not installed completely."), QMessageBox::Ok); - } - } catch (const std::exception &e) { - reportError(e.what()); - } -} - -QString OrganizerCore::resolvePath(const QString &fileName) const -{ - if (m_DirectoryStructure == nullptr) { - return QString(); - } - const FileEntry::Ptr file - = m_DirectoryStructure->searchFile(ToWString(fileName), nullptr); - if (file.get() != nullptr) { - return ToQString(file->getFullPath()); - } else { - return QString(); - } -} - -QStringList OrganizerCore::listDirectories(const QString &directoryName) const -{ - QStringList result; - DirectoryEntry *dir = m_DirectoryStructure; - if (!directoryName.isEmpty()) - dir = dir->findSubDirectoryRecursive(ToWString(directoryName)); - if (dir != nullptr) { - std::vector::iterator current, end; - dir->getSubDirectories(current, end); - for (; current != end; ++current) { - result.append(ToQString((*current)->getName())); - } - } - return result; -} - -QStringList OrganizerCore::findFiles( - const QString &path, - const std::function &filter) const -{ - QStringList result; - DirectoryEntry *dir = m_DirectoryStructure; - if (!path.isEmpty()) - dir = dir->findSubDirectoryRecursive(ToWString(path)); - if (dir != nullptr) { - std::vector files = dir->getFiles(); - foreach (FileEntry::Ptr file, files) { - if (filter(ToQString(file->getFullPath()))) { - result.append(ToQString(file->getFullPath())); - } - } - } else { - qWarning("directory not found: %1", qUtf8Printable(path)); - } - return result; -} - -QStringList OrganizerCore::getFileOrigins(const QString &fileName) const -{ - QStringList result; - const FileEntry::Ptr file = m_DirectoryStructure->searchFile( - ToWString(QFileInfo(fileName).fileName()), nullptr); - - if (file.get() != nullptr) { - result.append(ToQString( - m_DirectoryStructure->getOriginByID(file->getOrigin()).getName())); - foreach (auto i, file->getAlternatives()) { - result.append( - ToQString(m_DirectoryStructure->getOriginByID(i.first).getName())); - } - } else { - qWarning("file not found: %1", qUtf8Printable(fileName)); - } - return result; -} - -QList OrganizerCore::findFileInfos( - const QString &path, - const std::function &filter) - const -{ - QList result; - DirectoryEntry *dir = m_DirectoryStructure; - if (!path.isEmpty()) - dir = dir->findSubDirectoryRecursive(ToWString(path)); - if (dir != nullptr) { - std::vector files = dir->getFiles(); - foreach (FileEntry::Ptr file, files) { - IOrganizer::FileInfo info; - info.filePath = ToQString(file->getFullPath()); - bool fromArchive = false; - info.origins.append(ToQString( - m_DirectoryStructure->getOriginByID(file->getOrigin(fromArchive)) - .getName())); - info.archive = fromArchive ? ToQString(file->getArchive().first) : ""; - foreach (auto idx, file->getAlternatives()) { - info.origins.append( - ToQString(m_DirectoryStructure->getOriginByID(idx.first).getName())); - } - - if (filter(info)) { - result.append(info); - } - } - } - return result; -} - -DownloadManager *OrganizerCore::downloadManager() -{ - return &m_DownloadManager; -} - -PluginList *OrganizerCore::pluginList() -{ - return &m_PluginList; -} - -ModList *OrganizerCore::modList() -{ - return &m_ModList; -} - -QStringList OrganizerCore::modsSortedByProfilePriority() const -{ - QStringList res; - for (int i = currentProfile()->getPriorityMinimum(); - i < currentProfile()->getPriorityMinimum() + (int)currentProfile()->numRegularMods(); - ++i) { - int modIndex = currentProfile()->modIndexByPriority(i); - auto modInfo = ModInfo::getByIndex(modIndex); - if (!modInfo->hasFlag(ModInfo::FLAG_OVERWRITE) && - !modInfo->hasFlag(ModInfo::FLAG_BACKUP)) { - res.push_back(ModInfo::getByIndex(modIndex)->name()); - } - } - return res; -} - -void OrganizerCore::spawnBinary(const QFileInfo &binary, - const QString &arguments, - const QDir ¤tDirectory, - const QString &steamAppID, - const QString &customOverwrite, - const QList &forcedLibraries) -{ - DWORD processExitCode = 0; - HANDLE processHandle = spawnBinaryDirect(binary, arguments, m_CurrentProfile->name(), currentDirectory, steamAppID, customOverwrite, forcedLibraries, &processExitCode); - if (processHandle != INVALID_HANDLE_VALUE) { - refreshDirectoryStructure(); - // need to remove our stored load order because it may be outdated if a foreign tool changed the - // file time. After removing that file, refreshESPList will use the file time as the order - if (managedGame()->loadOrderMechanism() == IPluginGame::LoadOrderMechanism::FileTime) { - qDebug("removing loadorder.txt"); - QFile::remove(m_CurrentProfile->getLoadOrderFileName()); - } - refreshDirectoryStructure(); - - refreshESPList(true); - savePluginList(); - - //These callbacks should not fiddle with directoy structure and ESPs. - m_FinishedRun(binary.absoluteFilePath(), processExitCode); - } -} - -HANDLE OrganizerCore::spawnBinaryDirect(const QFileInfo &binary, - const QString &arguments, - const QString &profileName, - const QDir ¤tDirectory, - const QString &steamAppID, - const QString &customOverwrite, - const QList &forcedLibraries, - LPDWORD exitCode) -{ - HANDLE processHandle = spawnBinaryProcess(binary, arguments, profileName, currentDirectory, steamAppID, customOverwrite, forcedLibraries); - if (Settings::instance().lockGUI() && processHandle != INVALID_HANDLE_VALUE) { - std::unique_ptr dlg; - ILockedWaitingForProcess* uilock = nullptr; - - if (m_UserInterface != nullptr) { - uilock = m_UserInterface->lock(); - } - else { - // i.e. when running command line shortcuts there is no m_UserInterface - dlg.reset(new LockedDialog); - dlg->show(); - dlg->setEnabled(true); - uilock = dlg.get(); - } - - ON_BLOCK_EXIT([&]() { - if (m_UserInterface != nullptr) { - m_UserInterface->unlock(); - } }); - - DWORD ignoreExitCode; - waitForProcessCompletion(processHandle, exitCode ? exitCode : &ignoreExitCode, uilock); - cycleDiagnostics(); - } - - return processHandle; -} - - -HANDLE OrganizerCore::spawnBinaryProcess(const QFileInfo &binary, - const QString &arguments, - const QString &profileName, - const QDir ¤tDirectory, - const QString &steamAppID, - const QString &customOverwrite, - const QList &forcedLibraries) -{ - prepareStart(); - - if (!binary.exists()) { - reportError( - tr("Executable not found: %1").arg(qUtf8Printable(binary.absoluteFilePath()))); - return INVALID_HANDLE_VALUE; - } - - if (!steamAppID.isEmpty()) { - ::SetEnvironmentVariableW(L"SteamAPPId", ToWString(steamAppID).c_str()); - } else { - ::SetEnvironmentVariableW(L"SteamAPPId", - ToWString(m_Settings.getSteamAppID()).c_str()); - } - - QWidget *window = qApp->activeWindow(); - if ((window != nullptr) && (!window->isVisible())) { - window = nullptr; - } - - // This could possibly be extracted somewhere else but it's probably for when - // we have more than one provider of game registration. - if ((QFileInfo( - managedGame()->gameDirectory().absoluteFilePath("steam_api.dll")) - .exists() - || QFileInfo(managedGame()->gameDirectory().absoluteFilePath( - "steam_api64.dll")) - .exists()) - && (m_Settings.getLoadMechanism() == LoadMechanism::LOAD_MODORGANIZER)) { - if (!testForSteam()) { - QDialogButtonBox::StandardButton result; - result = QuestionBoxMemory::query(window, "steamQuery", binary.fileName(), - tr("Start Steam?"), - tr("Steam is required to be running already to correctly start the game. " - "Should MO try to start steam now?"), - QDialogButtonBox::Yes | QDialogButtonBox::No | QDialogButtonBox::Cancel); - if (result == QDialogButtonBox::Yes) { - startSteam(window); - } else if(result == QDialogButtonBox::Cancel) { - return INVALID_HANDLE_VALUE; - } - } - } - - while (m_DirectoryUpdate) { - ::Sleep(100); - QCoreApplication::processEvents(); - } - - // need to make sure all data is saved before we start the application - if (m_CurrentProfile != nullptr) { - m_CurrentProfile->writeModlistNow(true); - } - - // TODO: should also pass arguments - if (m_AboutToRun(binary.absoluteFilePath())) { - try { - m_USVFS.updateMapping(fileMapping(profileName, customOverwrite)); - m_USVFS.updateForcedLibraries(forcedLibraries); - - } catch (const UsvfsConnectorException &e) { - qDebug(e.what()); - return INVALID_HANDLE_VALUE; - } catch (const std::exception &e) { - QMessageBox::warning(window, tr("Error"), e.what()); - return INVALID_HANDLE_VALUE; - } - - // Check if the Windows Event Logging service is running. For some reason, this seems to be - // critical to the successful running of usvfs. - if (!checkService()) { - if (QuestionBoxMemory::query(window, QString("eventLogService"), binary.fileName(), - tr("Windows Event Log Error"), - tr("The Windows Event Log service is disabled and/or not running. This prevents" - " USVFS from running properly. Your mods may not be working in the executable" - " that you are launching. Note that you may have to restart MO and/or your PC" - " after the service is fixed.\n\nContinue launching %1?").arg(binary.fileName()), - QDialogButtonBox::Yes | QDialogButtonBox::No) == QDialogButtonBox::No) { - return INVALID_HANDLE_VALUE; - } - } - - for (auto exec : settings().executablesBlacklist().split(";")) { - if (exec.compare(binary.fileName(), Qt::CaseInsensitive) == 0) { - if (QuestionBoxMemory::query(window, QString("blacklistedExecutable"), binary.fileName(), - tr("Blacklisted Executable"), - tr("The executable you are attempted to launch is blacklisted in the virtual file" - " system. This will likely prevent the executable, and any executables that are" - " launched by this one, from seeing any mods. This could extend to INI files, save" - " games and any other virtualized files.\n\nContinue launching %1?").arg(binary.fileName()), - QDialogButtonBox::Yes | QDialogButtonBox::No) == QDialogButtonBox::No) { - return INVALID_HANDLE_VALUE; - } - } - } - - QString modsPath = settings().getModDirectory(); - - // Check if this a request with either an executable or a working directory under our mods folder - // then will start the process in a virtualized "environment" with the appropriate paths fixed: - // (i.e. mods\FNIS\path\exe => game\data\path\exe) - QString cwdPath = currentDirectory.absolutePath(); - bool virtualizedCwd = cwdPath.startsWith(modsPath, Qt::CaseInsensitive); - QString binPath = binary.absoluteFilePath(); - bool virtualizedBin = binPath.startsWith(modsPath, Qt::CaseInsensitive); - if (virtualizedCwd || virtualizedBin) { - if (virtualizedCwd) { - int cwdOffset = cwdPath.indexOf('/', modsPath.length() + 1); - QString adjustedCwd = cwdPath.mid(cwdOffset, -1); - cwdPath = m_GamePlugin->dataDirectory().absolutePath(); - if (cwdOffset >= 0) - cwdPath += adjustedCwd; - - } - - if (virtualizedBin) { - int binOffset = binPath.indexOf('/', modsPath.length() + 1); - QString adjustedBin = binPath.mid(binOffset, -1); - binPath = m_GamePlugin->dataDirectory().absolutePath(); - if (binOffset >= 0) - binPath += adjustedBin; - } - - QString cmdline - = QString("launch \"%1\" \"%2\" %3") - .arg(QDir::toNativeSeparators(cwdPath), - QDir::toNativeSeparators(binPath), arguments); - - qDebug() << "Spawning proxyed process <" << cmdline << ">"; - - return startBinary(QFileInfo(QCoreApplication::applicationFilePath()), - cmdline, QCoreApplication::applicationDirPath(), true); - } else { - qDebug() << "Spawning direct process <" << binPath << "," << arguments << "," << cwdPath << ">"; - return startBinary(binary, arguments, currentDirectory, true); - } - } else { - qDebug("start of \"%s\" canceled by plugin", - qUtf8Printable(binary.absoluteFilePath())); - return INVALID_HANDLE_VALUE; - } -} - -HANDLE OrganizerCore::runShortcut(const MOShortcut& shortcut) -{ - if (shortcut.hasInstance() && shortcut.instance() != InstanceManager::instance().currentInstance()) - throw std::runtime_error( - QString("Refusing to run executable from different instance %1:%2") - .arg(shortcut.instance(),shortcut.executable()) - .toLocal8Bit().constData()); - - Executable& exe = m_ExecutablesList.find(shortcut.executable()); - auto forcedLibaries = m_CurrentProfile->determineForcedLibraries(shortcut.executable()); - if (!m_CurrentProfile->forcedLibrariesEnabled(shortcut.executable())) { - forcedLibaries.clear(); - } - - return spawnBinaryDirect( - exe.m_BinaryInfo, exe.m_Arguments, - m_CurrentProfile->name(), - exe.m_WorkingDirectory.length() != 0 - ? exe.m_WorkingDirectory - : exe.m_BinaryInfo.absolutePath(), - exe.m_SteamAppID, - "", - forcedLibaries); -} - -HANDLE OrganizerCore::startApplication(const QString &executable, - const QStringList &args, - const QString &cwd, - const QString &profile) -{ - QFileInfo binary; - QString arguments = args.join(" "); - QString currentDirectory = cwd; - QString profileName = profile; - if (profile.length() == 0) { - if (m_CurrentProfile != nullptr) { - profileName = m_CurrentProfile->name(); - } else { - throw MyException(tr("No profile set")); - } - } - QString steamAppID; - QString customOverwrite; - QList forcedLibraries; - if (executable.contains('\\') || executable.contains('/')) { - // file path - - binary = QFileInfo(executable); - if (binary.isRelative()) { - // relative path, should be relative to game directory - binary = QFileInfo( - managedGame()->gameDirectory().absoluteFilePath(executable)); - } - if (cwd.length() == 0) { - currentDirectory = binary.absolutePath(); - } - try { - const Executable &exe = m_ExecutablesList.findByBinary(binary); - steamAppID = exe.m_SteamAppID; - customOverwrite - = m_CurrentProfile->setting("custom_overwrites", exe.m_Title) - .toString(); - if (m_CurrentProfile->forcedLibrariesEnabled(exe.m_Title)) { - forcedLibraries = m_CurrentProfile->determineForcedLibraries(exe.m_Title); - } - } catch (const std::runtime_error &) { - // nop - } - } else { - // only a file name, search executables list - try { - const Executable &exe = m_ExecutablesList.find(executable); - steamAppID = exe.m_SteamAppID; - customOverwrite - = m_CurrentProfile->setting("custom_overwrites", exe.m_Title) - .toString(); - if (m_CurrentProfile->forcedLibrariesEnabled(exe.m_Title)) { - forcedLibraries = m_CurrentProfile->determineForcedLibraries(exe.m_Title); - } - if (arguments == "") { - arguments = exe.m_Arguments; - } - binary = exe.m_BinaryInfo; - if (cwd.length() == 0) { - currentDirectory = exe.m_WorkingDirectory; - } - } catch (const std::runtime_error &) { - qWarning("\"%s\" not set up as executable", - qUtf8Printable(executable)); - binary = QFileInfo(executable); - } - } - - return spawnBinaryDirect(binary, arguments, profileName, currentDirectory, steamAppID, customOverwrite, forcedLibraries); -} - -bool OrganizerCore::waitForApplication(HANDLE handle, LPDWORD exitCode) -{ - if (!Settings::instance().lockGUI()) - return true; - - ILockedWaitingForProcess* uilock = nullptr; - if (m_UserInterface != nullptr) { - uilock = m_UserInterface->lock(); - } - - ON_BLOCK_EXIT([&] () { - if (m_UserInterface != nullptr) { - m_UserInterface->unlock(); - } }); - return waitForProcessCompletion(handle, exitCode, uilock); -} - -bool OrganizerCore::waitForProcessCompletion(HANDLE handle, LPDWORD exitCode, ILockedWaitingForProcess* uilock) -{ - bool originalHandle = true; - bool newHandle = true; - bool uiunlocked = false; - - DWORD currentPID = 0; - QString processName; - auto waitForChildUntil = GetTickCount64(); - if (handle != INVALID_HANDLE_VALUE) { - currentPID = GetProcessId(handle); - processName = QString::fromStdWString(getProcessName(handle)); - } - - // Certain process names we wish to "hide" for aesthetic reason: - bool waitingOnHidden = false; - std::vector hiddenList; - hiddenList.push_back(QFileInfo(QCoreApplication::applicationFilePath()).fileName()); - for (QString hide : hiddenList) - if (processName.contains(hide, Qt::CaseInsensitive)) - waitingOnHidden = true; - // The main reason for adding the hidden list is to hide the MO proxy we use to spawn virtualized processes. - // On the one hand we want to display the real executable without it feeling laggy, on the other we don't want - // to requery processes all the time if for some reason we are waiting on hidden processes and find no "unhidden" - // process. For this reason we use exponential backoff and also start with a delibrately low value to improve - // the responsiveness of the initial update - DWORD64 nextHiddenCheck = GetTickCount64(); - DWORD64 nextHiddenCheckDelay = 50; - - constexpr DWORD INPUT_EVENT = WAIT_OBJECT_0 + 1; - DWORD res = WAIT_TIMEOUT; - while (handle != INVALID_HANDLE_VALUE && (newHandle || res == WAIT_TIMEOUT || res == INPUT_EVENT)) - { - if (newHandle) { - processName += QString(" (%1)").arg(currentPID); - if (uilock) - uilock->setProcessName(processName); - qDebug() << "Waiting for" - << (originalHandle ? "spawned" : "usvfs") - << "process completion :" << qUtf8Printable(processName); - newHandle = false; - } - - // Wait for a an event on the handle, a key press, mouse click or timeout - res = MsgWaitForMultipleObjects(1, &handle, FALSE, 200, QS_KEY | QS_MOUSEBUTTON); - if (res == WAIT_FAILED) { - qWarning() << "Failed waiting for process completion : MsgWaitForMultipleObjects WAIT_FAILED" << GetLastError(); - break; - } - - // keep processing events so the app doesn't appear dead - QCoreApplication::sendPostedEvents(); - QCoreApplication::processEvents(); - - if (uilock && uilock->unlockForced()) { - uiunlocked = true; - break; - } - - if (res == WAIT_OBJECT_0) { - // process we were waiting on has completed - if (originalHandle && exitCode && !::GetExitCodeProcess(handle, exitCode)) - qWarning() << "Failed getting exit code of complete process :" << GetLastError(); - CloseHandle(handle); - handle = INVALID_HANDLE_VALUE; - originalHandle = false; - // if the previous process spawned a child process and immediately exits we may miss it if we check immediately - waitForChildUntil = GetTickCount64() + 800; - } - - // search for another process to wait on if either: - // 1. we just completed waiting for a process and need to find/wait for an inject child - // 2. we are currently waiting on a hidden process so periodically check if there is a non-hidden process to wait on - bool firstIteration = true; - while ((handle == INVALID_HANDLE_VALUE && GetTickCount64() <= waitForChildUntil) - || (waitingOnHidden && GetTickCount64() >= nextHiddenCheck)) - { - if (firstIteration) - firstIteration = false; - else { - QThread::msleep(200); - QCoreApplication::sendPostedEvents(); - QCoreApplication::processEvents(); - } - - // search if there is another usvfs process active - handle = findAndOpenAUSVFSProcess(hiddenList, currentPID); - waitingOnHidden = false; - newHandle = handle != INVALID_HANDLE_VALUE; - if (newHandle) { - currentPID = GetProcessId(handle); - processName = QString::fromStdWString(getProcessName(handle)); - for (QString hide : hiddenList) - if (processName.contains(hide, Qt::CaseInsensitive)) - waitingOnHidden = true; - } - if (waitingOnHidden) { - nextHiddenCheck = GetTickCount64() + nextHiddenCheckDelay; - nextHiddenCheckDelay = std::min(nextHiddenCheckDelay * 2, (DWORD64) 2000); - } - else { - nextHiddenCheck = GetTickCount64(); - nextHiddenCheckDelay = 200; - } - } - } - - if (res == WAIT_OBJECT_0) - qDebug() << "Waiting for process completion successfull"; - else if (uiunlocked) - qDebug() << "Waiting for process completion aborted by UI"; - else - qDebug() << "Waiting for process completion not successfull :" << res; - - if (handle != INVALID_HANDLE_VALUE) - ::CloseHandle(handle); - - return res == WAIT_OBJECT_0; -} - -HANDLE OrganizerCore::findAndOpenAUSVFSProcess(const std::vector& hiddenList, DWORD preferedParentPid) { - // for practical reasons a querySize of 1 is probably enough, we use a larger query as a heuristics - // to find a more "aesthetic injected processes (attempting to comply to hiddenList and preferedParentPid) - constexpr size_t querySize = 100; - DWORD pids[querySize]; - size_t found = querySize; - if (!::GetVFSProcessList(&found, pids)) { - qWarning() << "Failed seeking USVFS processes : GetVFSProcessList failed?!"; - return INVALID_HANDLE_VALUE; - } - - HANDLE best_match = INVALID_HANDLE_VALUE; - bool best_match_hidden = true; - for (size_t i = 0; i < found; ++i) { - if (pids[i] == GetCurrentProcessId()) - continue; // obviously don't wait for MO process - - HANDLE handle = ::OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, FALSE, pids[i]); - if (handle == INVALID_HANDLE_VALUE) { - qWarning() << "Failed openning USVFS process " << pids[i] << " : OpenProcess failed" << GetLastError(); - continue; - } - - QString pname = QString::fromStdWString(getProcessName(handle)); - bool phidden = false; - for (auto hide : hiddenList) - if (pname.contains(hide, Qt::CaseInsensitive)) - phidden = true; - - bool pprefered = preferedParentPid && getProcessParentID(pids[i]) == preferedParentPid; - - if (best_match == INVALID_HANDLE_VALUE || best_match_hidden || (!phidden && pprefered)) { - if (best_match != INVALID_HANDLE_VALUE) - CloseHandle(best_match); - best_match = handle; - best_match_hidden = phidden; - } - else - CloseHandle(handle); - - if (!phidden && pprefered) - return best_match; - } - - return best_match; -} - -bool OrganizerCore::onAboutToRun( - const std::function &func) -{ - auto conn = m_AboutToRun.connect(func); - return conn.connected(); -} - -bool OrganizerCore::onFinishedRun( - const std::function &func) -{ - auto conn = m_FinishedRun.connect(func); - return conn.connected(); -} - -bool OrganizerCore::onModInstalled( - const std::function &func) -{ - auto conn = m_ModInstalled.connect(func); - return conn.connected(); -} - -void OrganizerCore::refreshModList(bool saveChanges) -{ - // don't lose changes! - if (saveChanges) { - m_CurrentProfile->writeModlistNow(true); - } - ModInfo::updateFromDisc(m_Settings.getModDirectory(), &m_DirectoryStructure, - m_PluginContainer, m_Settings.displayForeign(), managedGame()); - - m_CurrentProfile->refreshModStatus(); - - m_ModList.notifyChange(-1); - - refreshDirectoryStructure(); -} - -void OrganizerCore::refreshESPList(bool force) -{ - if (m_DirectoryUpdate) { - // don't mess up the esp list if we're currently updating the directory - // structure - m_PostRefreshTasks.append([=]() { - this->refreshESPList(force); - }); - return; - } - m_CurrentProfile->writeModlist(); - - // clear list - try { - m_PluginList.refresh(m_CurrentProfile->name(), *m_DirectoryStructure, - m_CurrentProfile->getLockedOrderFileName(), force); - } catch (const std::exception &e) { - reportError(tr("Failed to refresh list of esps: %1").arg(e.what())); - } -} - -void OrganizerCore::refreshBSAList() -{ - DataArchives *archives = m_GamePlugin->feature(); - - if (archives != nullptr) { - m_ArchivesInit = false; - - // default archives are the ones enabled outside MO. if the list can't be - // found (which might - // happen if ini files are missing) use hard-coded defaults (preferrably the - // same the game would use) - m_DefaultArchives = archives->archives(m_CurrentProfile); - if (m_DefaultArchives.length() == 0) { - m_DefaultArchives = archives->vanillaArchives(); - } - - m_ActiveArchives.clear(); - - auto iter = enabledArchives(); - m_ActiveArchives = toStringList(iter.begin(), iter.end()); - if (m_ActiveArchives.isEmpty()) { - m_ActiveArchives = m_DefaultArchives; - } - - if (m_UserInterface != nullptr) { - m_UserInterface->updateBSAList(m_DefaultArchives, m_ActiveArchives); - } - - m_ArchivesInit = true; - } -} - -void OrganizerCore::refreshLists() -{ - if ((m_CurrentProfile != nullptr) && m_DirectoryStructure->isPopulated()) { - refreshESPList(true); - refreshBSAList(); - } // no point in refreshing lists if no files have been added to the directory - // tree -} - -void OrganizerCore::updateModActiveState(int index, bool active) -{ - QList modsToUpdate; - modsToUpdate.append(index); - updateModsActiveState(modsToUpdate, active); -} - -void OrganizerCore::updateModsActiveState(const QList &modIndices, bool active) -{ - int enabled = 0; - for (auto index : modIndices) { - ModInfo::Ptr modInfo = ModInfo::getByIndex(index); - QDir dir(modInfo->absolutePath()); - for (const QString &esm : - dir.entryList(QStringList() << "*.esm", QDir::Files)) { - const FileEntry::Ptr file = m_DirectoryStructure->findFile(ToWString(esm)); - if (file.get() == nullptr) { - qWarning("failed to activate %s", qUtf8Printable(esm)); - continue; - } - - if (active != m_PluginList.isEnabled(esm) - && file->getAlternatives().empty()) { - m_PluginList.blockSignals(true); - m_PluginList.enableESP(esm, active); - m_PluginList.blockSignals(false); - } - } - - for (const QString &esl : - dir.entryList(QStringList() << "*.esl", QDir::Files)) { - const FileEntry::Ptr file = m_DirectoryStructure->findFile(ToWString(esl)); - if (file.get() == nullptr) { - qWarning("failed to activate %s", qUtf8Printable(esl)); - continue; - } - - if (active != m_PluginList.isEnabled(esl) - && file->getAlternatives().empty()) { - m_PluginList.blockSignals(true); - m_PluginList.enableESP(esl, active); - m_PluginList.blockSignals(false); - ++enabled; - } - } - QStringList esps = dir.entryList(QStringList() << "*.esp", QDir::Files); - for (const QString &esp : esps) { - const FileEntry::Ptr file = m_DirectoryStructure->findFile(ToWString(esp)); - if (file.get() == nullptr) { - qWarning("failed to activate %s", qUtf8Printable(esp)); - continue; - } - - if (active != m_PluginList.isEnabled(esp) - && file->getAlternatives().empty()) { - m_PluginList.blockSignals(true); - m_PluginList.enableESP(esp, active); - m_PluginList.blockSignals(false); - ++enabled; - } - } - } - if (active && (enabled > 1)) { - MessageDialog::showMessage( - tr("Multiple esps/esls activated, please check that they don't conflict."), - qApp->activeWindow()); - } - m_PluginList.refreshLoadOrder(); - // immediately save affected lists - m_PluginListsWriter.writeImmediately(false); -} - -void OrganizerCore::updateModInDirectoryStructure(unsigned int index, - ModInfo::Ptr modInfo) -{ - QMap allModInfo; - allModInfo[index] = modInfo; - updateModsInDirectoryStructure(allModInfo); -} - -void OrganizerCore::updateModsInDirectoryStructure(QMap modInfo) -{ - for (auto idx : modInfo.keys()) { - // add files of the bsa to the directory structure - m_DirectoryRefresher.addModFilesToStructure( - m_DirectoryStructure, modInfo[idx]->name(), - m_CurrentProfile->getModPriority(idx), modInfo[idx]->absolutePath(), - modInfo[idx]->stealFiles()); - } - DirectoryRefresher::cleanStructure(m_DirectoryStructure); - // need to refresh plugin list now so we can activate esps - refreshESPList(true); - // activate all esps of the specified mod so the bsas get activated along with - // it - m_PluginList.blockSignals(true); - updateModsActiveState(modInfo.keys(), true); - m_PluginList.blockSignals(false); - // now we need to refresh the bsa list and save it so there is no confusion - // about what archives are avaiable and active - refreshBSAList(); - if (m_UserInterface != nullptr) { - m_UserInterface->archivesWriter().writeImmediately(false); - } - - std::vector archives = enabledArchives(); - m_DirectoryRefresher.setMods( - m_CurrentProfile->getActiveMods(), - std::set(archives.begin(), archives.end())); - - // finally also add files from bsas to the directory structure - for (auto idx : modInfo.keys()) { - m_DirectoryRefresher.addModBSAToStructure( - m_DirectoryStructure, modInfo[idx]->name(), - m_CurrentProfile->getModPriority(idx), modInfo[idx]->absolutePath(), - modInfo[idx]->archives()); - } -} - -void OrganizerCore::requestDownload(const QUrl &url, QNetworkReply *reply) -{ - if (m_PluginContainer != nullptr) { - for (IPluginModPage *modPage : - m_PluginContainer->plugins()) { - ModRepositoryFileInfo *fileInfo = new ModRepositoryFileInfo(); - if (modPage->handlesDownload(url, reply->url(), *fileInfo)) { - fileInfo->repository = modPage->name(); - m_DownloadManager.addDownload(reply, fileInfo); - return; - } - } - } - - // no mod found that could handle the download. Is it a nexus mod? - if (url.host() == "www.nexusmods.com") { - QString gameName = ""; - int modID = 0; - int fileID = 0; - QRegExp nameExp("www\\.nexusmods\\.com/(\\a+)/"); - if (nameExp.indexIn(url.toString()) != -1) { - gameName = nameExp.cap(1); - } - QRegExp modExp("mods/(\\d+)"); - if (modExp.indexIn(url.toString()) != -1) { - modID = modExp.cap(1).toInt(); - } - QRegExp fileExp("fid=(\\d+)"); - if (fileExp.indexIn(reply->url().toString()) != -1) { - fileID = fileExp.cap(1).toInt(); - } - m_DownloadManager.addDownload(reply, - new ModRepositoryFileInfo(gameName, modID, fileID)); - } else { - if (QMessageBox::question(qApp->activeWindow(), tr("Download?"), - tr("A download has been started but no installed " - "page plugin recognizes it.\n" - "If you download anyway no information (i.e. " - "version) will be associated with the " - "download.\n" - "Continue?"), - QMessageBox::Yes | QMessageBox::No) - == QMessageBox::Yes) { - m_DownloadManager.addDownload(reply, new ModRepositoryFileInfo()); - } - } -} - -ModListSortProxy *OrganizerCore::createModListProxyModel() -{ - ModListSortProxy *result = new ModListSortProxy(m_CurrentProfile, this); - result->setSourceModel(&m_ModList); - return result; -} - -PluginListSortProxy *OrganizerCore::createPluginListProxyModel() -{ - PluginListSortProxy *result = new PluginListSortProxy(this); - result->setSourceModel(&m_PluginList); - return result; -} - -IPluginGame const *OrganizerCore::managedGame() const -{ - return m_GamePlugin; -} - -std::vector OrganizerCore::enabledArchives() -{ - std::vector result; - if (m_ArchiveParsing) { - QFile archiveFile(m_CurrentProfile->getArchivesFileName()); - if (archiveFile.open(QIODevice::ReadOnly)) { - while (!archiveFile.atEnd()) { - result.push_back(QString::fromUtf8(archiveFile.readLine()).trimmed()); - } - archiveFile.close(); - } - } - return result; -} - -void OrganizerCore::refreshDirectoryStructure() -{ - if (!m_DirectoryUpdate) { - m_CurrentProfile->writeModlistNow(true); - - m_DirectoryUpdate = true; - std::vector> activeModList - = m_CurrentProfile->getActiveMods(); - auto archives = enabledArchives(); - m_DirectoryRefresher.setMods( - activeModList, std::set(archives.begin(), archives.end())); - - QTimer::singleShot(0, &m_DirectoryRefresher, SLOT(refresh())); - } -} - -void OrganizerCore::directory_refreshed() -{ - DirectoryEntry *newStructure = m_DirectoryRefresher.getDirectoryStructure(); - Q_ASSERT(newStructure != m_DirectoryStructure); - if (newStructure != nullptr) { - std::swap(m_DirectoryStructure, newStructure); - delete newStructure; - } else { - // TODO: don't know why this happens, this slot seems to get called twice - // with only one emit - return; - } - m_DirectoryUpdate = false; - - for (int i = 0; i < m_ModList.rowCount(); ++i) { - ModInfo::Ptr modInfo = ModInfo::getByIndex(i); - modInfo->clearCaches(); - } - for (auto task : m_PostRefreshTasks) { - task(); - } - m_PostRefreshTasks.clear(); - - if (m_CurrentProfile != nullptr) { - refreshLists(); - } -} - -void OrganizerCore::profileRefresh() -{ - // have to refresh mods twice (again in refreshModList), otherwise the refresh - // isn't complete. Not sure why - ModInfo::updateFromDisc(m_Settings.getModDirectory(), &m_DirectoryStructure, - m_PluginContainer, m_Settings.displayForeign(), managedGame()); - m_CurrentProfile->refreshModStatus(); - - refreshModList(); -} - -void OrganizerCore::modStatusChanged(unsigned int index) -{ - try { - ModInfo::Ptr modInfo = ModInfo::getByIndex(index); - if (m_CurrentProfile->modEnabled(index)) { - updateModInDirectoryStructure(index, modInfo); - } else { - updateModActiveState(index, false); - if (m_DirectoryStructure->originExists(ToWString(modInfo->name()))) { - FilesOrigin &origin - = m_DirectoryStructure->getOriginByName(ToWString(modInfo->name())); - origin.enable(false); - } - if (m_UserInterface != nullptr) { - m_UserInterface->archivesWriter().write(); - } - } - modInfo->clearCaches(); - - for (unsigned int i = 0; i < m_CurrentProfile->numMods(); ++i) { - ModInfo::Ptr modInfo = ModInfo::getByIndex(i); - int priority = m_CurrentProfile->getModPriority(i); - if (m_DirectoryStructure->originExists(ToWString(modInfo->name()))) { - // priorities in the directory structure are one higher because data is - // 0 - m_DirectoryStructure->getOriginByName(ToWString(modInfo->name())) - .setPriority(priority + 1); - } - } - m_DirectoryStructure->getFileRegister()->sortOrigins(); - - refreshLists(); - } catch (const std::exception &e) { - reportError(tr("failed to update mod list: %1").arg(e.what())); - } -} - -void OrganizerCore::modStatusChanged(QList index) { - try { - QMap modsToEnable; - QMap modsToDisable; - for (auto idx : index) { - if (m_CurrentProfile->modEnabled(idx)) { - modsToEnable[idx] = ModInfo::getByIndex(idx); - } else { - modsToDisable[idx] = ModInfo::getByIndex(idx); - } - } - if (!modsToEnable.isEmpty()) { - updateModsInDirectoryStructure(modsToEnable); - for (auto modInfo : modsToEnable.values()) { - modInfo->clearCaches(); - } - } - if (!modsToDisable.isEmpty()) { - updateModsActiveState(modsToDisable.keys(), false); - for (auto idx : modsToDisable.keys()) { - if (m_DirectoryStructure->originExists(ToWString(modsToDisable[idx]->name()))) { - FilesOrigin &origin - = m_DirectoryStructure->getOriginByName(ToWString(modsToDisable[idx]->name())); - origin.enable(false); - } - } - if (m_UserInterface != nullptr) { - m_UserInterface->archivesWriter().write(); - } - } - - for (unsigned int i = 0; i < m_CurrentProfile->numMods(); ++i) { - ModInfo::Ptr modInfo = ModInfo::getByIndex(i); - int priority = m_CurrentProfile->getModPriority(i); - if (m_DirectoryStructure->originExists(ToWString(modInfo->name()))) { - // priorities in the directory structure are one higher because data is - // 0 - m_DirectoryStructure->getOriginByName(ToWString(modInfo->name())) - .setPriority(priority + 1); - } - } - m_DirectoryStructure->getFileRegister()->sortOrigins(); - - refreshLists(); - } catch (const std::exception &e) { - reportError(tr("failed to update mod list: %1").arg(e.what())); - } -} - -void OrganizerCore::loginSuccessful(bool necessary) -{ - if (necessary) { - MessageDialog::showMessage(tr("login successful"), qApp->activeWindow()); - } - for (QString url : m_PendingDownloads) { - downloadRequestedNXM(url); - } - m_PendingDownloads.clear(); - for (auto task : m_PostLoginTasks) { - task(); - } - - m_PostLoginTasks.clear(); - NexusInterface::instance(m_PluginContainer)->loginCompleted(); -} - -void OrganizerCore::loginSuccessfulUpdate(bool necessary) -{ - if (necessary) { - MessageDialog::showMessage(tr("login successful"), qApp->activeWindow()); - } - m_Updater.startUpdate(); -} - -void OrganizerCore::loginFailed(const QString &message) -{ - if (QMessageBox::question(qApp->activeWindow(), tr("Login failed"), - tr("Login failed, try again?")) - == QMessageBox::Yes) { - if (nexusLogin(true)) { - return; - } - } - - if (!m_PendingDownloads.isEmpty()) { - MessageDialog::showMessage( - tr("login failed: %1. Download will not be associated with an account") - .arg(message), - qApp->activeWindow()); - for (QString url : m_PendingDownloads) { - downloadRequestedNXM(url); - } - m_PendingDownloads.clear(); - } else { - MessageDialog::showMessage(tr("login failed: %1").arg(message), - qApp->activeWindow()); - m_PostLoginTasks.clear(); - } - NexusInterface::instance(m_PluginContainer)->loginCompleted(); -} - -void OrganizerCore::loginFailedUpdate(const QString &message) -{ - MessageDialog::showMessage( - tr("login failed: %1. You need to log-in with Nexus to update MO.") - .arg(message), - qApp->activeWindow()); -} - -void OrganizerCore::syncOverwrite() -{ - unsigned int overwriteIndex = ModInfo::findMod([](ModInfo::Ptr mod) -> bool { - std::vector flags = mod->getFlags(); - return std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) - != flags.end(); - }); - - ModInfo::Ptr modInfo = ModInfo::getByIndex(overwriteIndex); - SyncOverwriteDialog syncDialog(modInfo->absolutePath(), m_DirectoryStructure, - qApp->activeWindow()); - if (syncDialog.exec() == QDialog::Accepted) { - syncDialog.apply(QDir::fromNativeSeparators(m_Settings.getModDirectory())); - modInfo->testValid(); - refreshDirectoryStructure(); - } -} - -QString OrganizerCore::oldMO1HookDll() const -{ - if (auto extender = managedGame()->feature()) { - QString hookdll = QDir::toNativeSeparators( - managedGame()->dataDirectory().absoluteFilePath(extender->PluginPath() + "/hook.dll")); - if (QFile(hookdll).exists()) - return hookdll; - } - return QString(); -} - -std::vector OrganizerCore::activeProblems() const -{ - std::vector problems; - const auto& hookdll = oldMO1HookDll(); - if (!hookdll.isEmpty()) { - // This warning will now be shown every time the problems are checked, which is a bit - // of a "log spam". But since this is a sevre error which will most likely make the - // game crash/freeze/etc. and is very hard to diagnose, this "log spam" will make it - // easier for the user to notice the warning. - qWarning("hook.dll found in game folder: %s", qUtf8Printable(hookdll)); - problems.push_back(PROBLEM_MO1SCRIPTEXTENDERWORKAROUND); - } - return problems; -} - -QString OrganizerCore::shortDescription(unsigned int key) const -{ - switch (key) { - case PROBLEM_MO1SCRIPTEXTENDERWORKAROUND: { - return tr("MO1 \"Script Extender\" load mechanism has left hook.dll in your game folder"); - } break; - default: { - return tr("Description missing"); - } break; - } -} - -QString OrganizerCore::fullDescription(unsigned int key) const -{ - switch (key) { - case PROBLEM_MO1SCRIPTEXTENDERWORKAROUND: { - return tr("hook.dll has been found in your game folder (right click to copy the full path). " - "This is most likely a leftover of setting the ModOrganizer 1 load mechanism to \"Script Extender\", " - "in which case you must remove this file either by changing the load mechanism in ModOrganizer 1 or " - "manually removing the file, otherwise the game is likely to crash and burn.").arg(oldMO1HookDll()); - break; - } - default: { - return tr("Description missing"); - } break; - } -} - -bool OrganizerCore::hasGuidedFix(unsigned int) const -{ - return false; -} - -void OrganizerCore::startGuidedFix(unsigned int) const -{ -} - -bool OrganizerCore::saveCurrentLists() -{ - if (m_DirectoryUpdate) { - qWarning("not saving lists during directory update"); - return false; - } - - try { - savePluginList(); - if (m_UserInterface != nullptr) { - m_UserInterface->archivesWriter().write(); - } - } catch (const std::exception &e) { - reportError(tr("failed to save load order: %1").arg(e.what())); - } - - return true; -} - -void OrganizerCore::savePluginList() -{ - if (m_DirectoryUpdate) { - // delay save till after directory update - m_PostRefreshTasks.append([this]() { - this->savePluginList(); - }); - return; - } - m_PluginList.saveTo(m_CurrentProfile->getLockedOrderFileName(), - m_CurrentProfile->getDeleterFileName(), - m_Settings.hideUncheckedPlugins()); - m_PluginList.saveLoadOrder(*m_DirectoryStructure); -} - -void OrganizerCore::prepareStart() -{ - if (m_CurrentProfile == nullptr) { - return; - } - m_CurrentProfile->writeModlist(); - m_CurrentProfile->createTweakedIniFile(); - saveCurrentLists(); - m_Settings.setupLoadMechanism(); - storeSettings(); -} - -std::vector OrganizerCore::fileMapping(const QString &profileName, - const QString &customOverwrite) -{ - // need to wait until directory structure - while (m_DirectoryUpdate) { - ::Sleep(100); - QCoreApplication::processEvents(); - } - - IPluginGame *game = qApp->property("managed_game").value(); - Profile profile(QDir(m_Settings.getProfileDirectory() + "/" + profileName), - game); - - MappingType result; - - QString dataPath - = QDir::toNativeSeparators(game->dataDirectory().absolutePath()); - - bool overwriteActive = false; - - for (auto mod : profile.getActiveMods()) { - if (std::get<0>(mod).compare("overwrite", Qt::CaseInsensitive) == 0) { - continue; - } - - unsigned int modIndex = ModInfo::getIndex(std::get<0>(mod)); - ModInfo::Ptr modPtr = ModInfo::getByIndex(modIndex); - - bool createTarget = customOverwrite == std::get<0>(mod); - - overwriteActive |= createTarget; - - if (modPtr->isRegular()) { - result.insert(result.end(), {QDir::toNativeSeparators(std::get<1>(mod)), - dataPath, true, createTarget}); - } - } - - if (!overwriteActive && !customOverwrite.isEmpty()) { - throw MyException(tr("The designated write target \"%1\" is not enabled.") - .arg(customOverwrite)); - } - - if (m_CurrentProfile->localSavesEnabled()) { - LocalSavegames *localSaves = game->feature(); - if (localSaves != nullptr) { - MappingType saveMap - = localSaves->mappings(currentProfile()->absolutePath() + "/saves"); - result.reserve(result.size() + saveMap.size()); - result.insert(result.end(), saveMap.begin(), saveMap.end()); - } else { - qWarning("local save games not supported by this game plugin"); - } - } - - result.insert(result.end(), { - QDir::toNativeSeparators(m_Settings.getOverwriteDirectory()), - dataPath, - true, - customOverwrite.isEmpty() - }); - - for (MOBase::IPluginFileMapper *mapper : - m_PluginContainer->plugins()) { - IPlugin *plugin = dynamic_cast(mapper); - if (plugin->isActive()) { - MappingType pluginMap = mapper->mappings(); - result.reserve(result.size() + pluginMap.size()); - result.insert(result.end(), pluginMap.begin(), pluginMap.end()); - } - } - - return result; -} - - -std::vector OrganizerCore::fileMapping( - const QString &dataPath, const QString &relPath, const DirectoryEntry *base, - const DirectoryEntry *directoryEntry, int createDestination) -{ - std::vector result; - - for (FileEntry::Ptr current : directoryEntry->getFiles()) { - bool isArchive = false; - int origin = current->getOrigin(isArchive); - if (isArchive || (origin == 0)) { - continue; - } - - QString originPath - = QString::fromStdWString(base->getOriginByID(origin).getPath()); - QString fileName = QString::fromStdWString(current->getName()); -// QString fileName = ToQString(current->getName()); - QString source = originPath + relPath + fileName; - QString target = dataPath + relPath + fileName; - if (source != target) { - result.push_back({source, target, false, false}); - } - } - - // recurse into subdirectories - std::vector::const_iterator current, end; - directoryEntry->getSubDirectories(current, end); - for (; current != end; ++current) { - int origin = (*current)->anyOrigin(); - - QString originPath - = QString::fromStdWString(base->getOriginByID(origin).getPath()); - QString dirName = QString::fromStdWString((*current)->getName()); - QString source = originPath + relPath + dirName; - QString target = dataPath + relPath + dirName; - - bool writeDestination - = (base == directoryEntry) && (origin == createDestination); - - result.push_back({source, target, true, writeDestination}); - std::vector subRes = fileMapping( - dataPath, relPath + dirName + "\\", base, *current, createDestination); - result.insert(result.end(), subRes.begin(), subRes.end()); - } - return result; -} +#include "organizercore.h" + +#include "delayedfilewriter.h" +#include "guessedvalue.h" +#include "imodinterface.h" +#include "imoinfo.h" +#include "iplugingame.h" +#include "iuserinterface.h" +#include "loadmechanism.h" +#include "messagedialog.h" +#include "modlistsortproxy.h" +#include "modrepositoryfileinfo.h" +#include "nexusinterface.h" +#include "plugincontainer.h" +#include "pluginlistsortproxy.h" +#include "profile.h" +#include "logbuffer.h" +#include "credentialsdialog.h" +#include "filedialogmemory.h" +#include "modinfodialog.h" +#include "spawn.h" +#include "syncoverwritedialog.h" +#include "nxmaccessmanager.h" +#include +#include +#include +#include +#include +#include +#include +#include "appconfig.h" +#include +#include +#include "lockeddialog.h" +#include "instancemanager.h" +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include // for qUtf8Printable, etc + +#include +#include +#include +#include // for _tcsicmp + +#include +#include +#include // for memset, wcsrchr + +#include +#include +#include +#include +#include +#include //for wstring +#include +#include + + +using namespace MOShared; +using namespace MOBase; + +//static +CrashDumpsType OrganizerCore::m_globalCrashDumpsType = CrashDumpsType::None; + +static bool isOnline() +{ + QList interfaces = QNetworkInterface::allInterfaces(); + + bool connected = false; + for (auto iter = interfaces.begin(); iter != interfaces.end() && !connected; + ++iter) { + if ((iter->flags() & QNetworkInterface::IsUp) + && (iter->flags() & QNetworkInterface::IsRunning) + && !(iter->flags() & QNetworkInterface::IsLoopBack)) { + auto addresses = iter->addressEntries(); + if (addresses.count() == 0) { + continue; + } + qDebug("interface %s seems to be up (address: %s)", + qUtf8Printable(iter->humanReadableName()), + qUtf8Printable(addresses[0].ip().toString())); + connected = true; + } + } + + return connected; +} + +static bool renameFile(const QString &oldName, const QString &newName, + bool overwrite = true) +{ + if (overwrite && QFile::exists(newName)) { + QFile::remove(newName); + } + return QFile::rename(oldName, newName); +} + +static std::wstring getProcessName(HANDLE process) +{ + wchar_t buffer[MAX_PATH]; + wchar_t *fileName = L"unknown"; + + if (process == nullptr) return fileName; + + if (::GetProcessImageFileNameW(process, buffer, MAX_PATH) != 0) { + fileName = wcsrchr(buffer, L'\\'); + if (fileName == nullptr) { + fileName = buffer; + } + else { + fileName += 1; + } + } + + return fileName; +} + +// Get parent PID for the given process, return 0 on failure +static DWORD getProcessParentID(DWORD pid) +{ + HANDLE th = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); + PROCESSENTRY32 pe = { 0 }; + pe.dwSize = sizeof(PROCESSENTRY32); + + DWORD res = 0; + if (Process32First(th, &pe)) + do { + if (pe.th32ProcessID == pid) { + res = pe.th32ParentProcessID; + break; + } + } while (Process32Next(th, &pe)); + + CloseHandle(th); + + return res; +} + +static void startSteam(QWidget *widget) +{ + QSettings steamSettings("HKEY_CURRENT_USER\\Software\\Valve\\Steam", + QSettings::NativeFormat); + QString exe = steamSettings.value("SteamExe", "").toString(); + if (!exe.isEmpty()) { + exe = QString("\"%1\"").arg(exe); + // See if username and password supplied. If so, pass them into steam. + QStringList args; + QString username; + QString password; + if (Settings::instance().getSteamLogin(username, password)) { + args << "-login"; + args << username; + if (password != "") { + args << password; + } + } + if (!QProcess::startDetached(exe, args)) { + reportError(QObject::tr("Failed to start \"%1\"").arg(exe)); + } else { + QMessageBox::information( + widget, QObject::tr("Waiting"), + QObject::tr("Please press OK once you're logged into steam.")); + } + } +} + +template +QStringList toStringList(InputIterator current, InputIterator end) +{ + QStringList result; + for (; current != end; ++current) { + result.append(*current); + } + return result; +} + +bool checkService() +{ + SC_HANDLE serviceManagerHandle = NULL; + SC_HANDLE serviceHandle = NULL; + LPSERVICE_STATUS_PROCESS serviceStatus = NULL; + LPQUERY_SERVICE_CONFIG serviceConfig = NULL; + bool serviceRunning = true; + + DWORD bytesNeeded; + + try { + serviceManagerHandle = OpenSCManager(NULL, NULL, SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG); + if (!serviceManagerHandle) { + qWarning("failed to open service manager (query status) (error %d)", GetLastError()); + throw 1; + } + + serviceHandle = OpenService(serviceManagerHandle, L"EventLog", SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG); + if (!serviceHandle) { + qWarning("failed to open EventLog service (query status) (error %d)", GetLastError()); + throw 2; + } + + if (QueryServiceConfig(serviceHandle, NULL, 0, &bytesNeeded) + || (GetLastError() != ERROR_INSUFFICIENT_BUFFER)) { + qWarning("failed to get size of service config (error %d)", GetLastError()); + throw 3; + } + + DWORD serviceConfigSize = bytesNeeded; + serviceConfig = (LPQUERY_SERVICE_CONFIG)LocalAlloc(LMEM_FIXED, serviceConfigSize); + if (!QueryServiceConfig(serviceHandle, serviceConfig, serviceConfigSize, &bytesNeeded)) { + qWarning("failed to query service config (error %d)", GetLastError()); + throw 4; + } + + if (serviceConfig->dwStartType == SERVICE_DISABLED) { + qCritical("Windows Event Log service is disabled!"); + serviceRunning = false; + } + + if (QueryServiceStatusEx(serviceHandle, SC_STATUS_PROCESS_INFO, NULL, 0, &bytesNeeded) + || (GetLastError() != ERROR_INSUFFICIENT_BUFFER)) { + qWarning("failed to get size of service status (error %d)", GetLastError()); + throw 5; + } + + DWORD serviceStatusSize = bytesNeeded; + serviceStatus = (LPSERVICE_STATUS_PROCESS)LocalAlloc(LMEM_FIXED, serviceStatusSize); + if (!QueryServiceStatusEx(serviceHandle, SC_STATUS_PROCESS_INFO, (LPBYTE)serviceStatus, serviceStatusSize, &bytesNeeded)) { + qWarning("failed to query service status (error %d)", GetLastError()); + throw 6; + } + + if (serviceStatus->dwCurrentState != SERVICE_RUNNING) { + qCritical("Windows Event Log service is not running"); + serviceRunning = false; + } + } + catch (int e) { + UNUSED_VAR(e); + serviceRunning = false; + } + + if (serviceStatus) { + LocalFree(serviceStatus); + } + if (serviceConfig) { + LocalFree(serviceConfig); + } + if (serviceHandle) { + CloseServiceHandle(serviceHandle); + } + if (serviceManagerHandle) { + CloseServiceHandle(serviceManagerHandle); + } + + return serviceRunning; +} + +OrganizerCore::OrganizerCore(const QSettings &initSettings) + : m_UserInterface(nullptr) + , m_PluginContainer(nullptr) + , m_GameName() + , m_CurrentProfile(nullptr) + , m_Settings(initSettings) + , m_Updater(NexusInterface::instance(m_PluginContainer)) + , m_AboutToRun() + , m_FinishedRun() + , m_ModInstalled() + , m_ModList(m_PluginContainer, this) + , m_PluginList(this) + , m_DirectoryRefresher() + , m_DirectoryStructure(new DirectoryEntry(L"data", nullptr, 0)) + , m_DownloadManager(NexusInterface::instance(m_PluginContainer), this) + , m_InstallationManager() + , m_RefresherThread() + , m_DirectoryUpdate(false) + , m_ArchivesInit(false) + , m_PluginListsWriter(std::bind(&OrganizerCore::savePluginList, this)) +{ + m_DownloadManager.setOutputDirectory(m_Settings.getDownloadDirectory()); + m_DownloadManager.setPreferredServers(m_Settings.getPreferredServers()); + + NexusInterface::instance(m_PluginContainer)->setCacheDirectory(m_Settings.getCacheDirectory()); + NexusInterface::instance(m_PluginContainer)->setNMMVersion(m_Settings.getNMMVersion()); + + MOBase::QuestionBoxMemory::init(initSettings.fileName()); + + m_InstallationManager.setModsDirectory(m_Settings.getModDirectory()); + m_InstallationManager.setDownloadDirectory(m_Settings.getDownloadDirectory()); + + connect(&m_DownloadManager, SIGNAL(downloadSpeed(QString, int)), this, + SLOT(downloadSpeed(QString, int))); + connect(&m_DirectoryRefresher, SIGNAL(refreshed()), this, + SLOT(directory_refreshed())); + + connect(&m_ModList, SIGNAL(removeOrigin(QString)), this, + SLOT(removeOrigin(QString))); + + connect(NexusInterface::instance(m_PluginContainer)->getAccessManager(), + SIGNAL(loginSuccessful(bool)), this, SLOT(loginSuccessful(bool))); + connect(NexusInterface::instance(m_PluginContainer)->getAccessManager(), + SIGNAL(loginFailed(QString)), this, SLOT(loginFailed(QString))); + + // This seems awfully imperative + connect(this, SIGNAL(managedGameChanged(MOBase::IPluginGame const *)), + &m_Settings, SLOT(managedGameChanged(MOBase::IPluginGame const *))); + connect(this, SIGNAL(managedGameChanged(MOBase::IPluginGame const *)), + &m_DownloadManager, + SLOT(managedGameChanged(MOBase::IPluginGame const *))); + connect(this, SIGNAL(managedGameChanged(MOBase::IPluginGame const *)), + &m_PluginList, SLOT(managedGameChanged(MOBase::IPluginGame const *))); + + connect(&m_PluginList, &PluginList::writePluginsList, &m_PluginListsWriter, + &DelayedFileWriterBase::write); + + // make directory refresher run in a separate thread + m_RefresherThread.start(); + m_DirectoryRefresher.moveToThread(&m_RefresherThread); +} + +OrganizerCore::~OrganizerCore() +{ + m_RefresherThread.exit(); + m_RefresherThread.wait(); + + prepareStart(); + + // profile has to be cleaned up before the modinfo-buffer is cleared + delete m_CurrentProfile; + m_CurrentProfile = nullptr; + + ModInfo::clear(); + LogBuffer::cleanQuit(); + m_ModList.setProfile(nullptr); + // NexusInterface::instance()->cleanup(); + + delete m_DirectoryStructure; +} + +QString OrganizerCore::commitSettings(const QString &iniFile) +{ + if (!shellRename(iniFile + ".new", iniFile, true, qApp->activeWindow())) { + DWORD err = ::GetLastError(); + // make a second attempt using qt functions but if that fails print the + // error from the first attempt + if (!renameFile(iniFile + ".new", iniFile)) { + return windowsErrorString(err); + } + } + return QString(); +} + +QSettings::Status OrganizerCore::storeSettings(const QString &fileName) +{ + QSettings settings(fileName, QSettings::IniFormat); + if (m_UserInterface != nullptr) { + m_UserInterface->storeSettings(settings); + } + if (m_CurrentProfile != nullptr) { + settings.setValue("selected_profile", + m_CurrentProfile->name().toUtf8().constData()); + } + + settings.remove("customExecutables"); + settings.beginWriteArray("customExecutables"); + std::vector::const_iterator current, end; + m_ExecutablesList.getExecutables(current, end); + int count = 0; + for (; current != end; ++current) { + const Executable &item = *current; + settings.setArrayIndex(count++); + settings.setValue("title", item.m_Title); + settings.setValue("custom", item.isCustom()); + settings.setValue("toolbar", item.isShownOnToolbar()); + settings.setValue("ownicon", item.usesOwnIcon()); + if (item.isCustom()) { + settings.setValue("binary", item.m_BinaryInfo.absoluteFilePath()); + settings.setValue("arguments", item.m_Arguments); + settings.setValue("workingDirectory", item.m_WorkingDirectory); + settings.setValue("steamAppID", item.m_SteamAppID); + } + } + settings.endArray(); + + FileDialogMemory::save(settings); + + settings.sync(); + return settings.status(); +} + +void OrganizerCore::storeSettings() +{ + QString iniFile = qApp->property("dataPath").toString() + "/" + + QString::fromStdWString(AppConfig::iniFileName()); + if (QFileInfo(iniFile).exists()) { + if (!shellCopy(iniFile, iniFile + ".new", true, qApp->activeWindow())) { + QMessageBox::critical( + qApp->activeWindow(), tr("Failed to write settings"), + tr("An error occured trying to update MO settings to %1: %2") + .arg(iniFile, windowsErrorString(::GetLastError()))); + return; + } + } + + QString writeTarget = iniFile + ".new"; + + QSettings::Status result = storeSettings(writeTarget); + + if (result == QSettings::NoError) { + QString errMsg = commitSettings(iniFile); + if (!errMsg.isEmpty()) { + qWarning("settings file not writable, may be locked by another " + "application, trying direct write"); + writeTarget = iniFile; + result = storeSettings(iniFile); + } + } + if (result != QSettings::NoError) { + QString reason = result == QSettings::AccessError + ? tr("File is write protected") + : result == QSettings::FormatError + ? tr("Invalid file format (probably a bug)") + : tr("Unknown error %1").arg(result); + QMessageBox::critical( + qApp->activeWindow(), tr("Failed to write settings"), + tr("An error occured trying to write back MO settings to %1: %2") + .arg(writeTarget, reason)); + } +} + +bool OrganizerCore::testForSteam() +{ + size_t currentSize = 1024; + std::unique_ptr processIDs; + DWORD bytesReturned; + bool success = false; + while (!success) { + processIDs.reset(new DWORD[currentSize]); + if (!::EnumProcesses(processIDs.get(), + static_cast(currentSize) * sizeof(DWORD), + &bytesReturned)) { + qWarning("failed to determine if steam is running"); + return true; + } + if (bytesReturned == (currentSize * sizeof(DWORD))) { + // maximum size used, list probably truncated + currentSize *= 2; + } else { + success = true; + } + } + TCHAR processName[MAX_PATH]; + for (unsigned int i = 0; i < bytesReturned / sizeof(DWORD); ++i) { + memset(processName, '\0', sizeof(TCHAR) * MAX_PATH); + if (processIDs[i] != 0) { + HANDLE process = ::OpenProcess( + PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processIDs[i]); + + if (process != nullptr) { + + ON_BLOCK_EXIT([&]() { + if (process != INVALID_HANDLE_VALUE) + ::CloseHandle(process); + }); + + HMODULE module; + DWORD ignore; + + // first module in a process is always the binary + if (EnumProcessModules(process, &module, sizeof(HMODULE) * 1, + &ignore)) { + ::GetModuleBaseName(process, module, processName, MAX_PATH); + if ((_tcsicmp(processName, TEXT("steam.exe")) == 0) + || (_tcsicmp(processName, TEXT("steamservice.exe")) == 0)) { + return true; + } + } + } + } + } + + return false; +} + +void OrganizerCore::updateExecutablesList(QSettings &settings) +{ + if (m_PluginContainer == nullptr) { + qCritical("can't update executables list now"); + return; + } + + m_ExecutablesList.init(managedGame()); + + qDebug("setting up configured executables"); + + int numCustomExecutables = settings.beginReadArray("customExecutables"); + for (int i = 0; i < numCustomExecutables; ++i) { + settings.setArrayIndex(i); + + Executable::Flags flags; + if (settings.value("custom", true).toBool()) + flags |= Executable::CustomExecutable; + if (settings.value("toolbar", false).toBool()) + flags |= Executable::ShowInToolbar; + if (settings.value("ownicon", false).toBool()) + flags |= Executable::UseApplicationIcon; + + m_ExecutablesList.addExecutable( + settings.value("title").toString(), settings.value("binary").toString(), + settings.value("arguments").toString(), + settings.value("workingDirectory", "").toString(), + settings.value("steamAppID", "").toString(), flags); + } + + settings.endArray(); + + // TODO this has nothing to do with executables list move to an appropriate + // function! + ModInfo::updateFromDisc(m_Settings.getModDirectory(), &m_DirectoryStructure, + m_PluginContainer, m_Settings.displayForeign(), managedGame()); +} + +void OrganizerCore::setUserInterface(IUserInterface *userInterface, + QWidget *widget) +{ + storeSettings(); + + m_UserInterface = userInterface; + + if (widget != nullptr) { + connect(&m_ModList, SIGNAL(modlistChanged(QModelIndex, int)), widget, + SLOT(modlistChanged(QModelIndex, int))); + connect(&m_ModList, SIGNAL(modlistChanged(QModelIndexList, int)), widget, + SLOT(modlistChanged(QModelIndexList, int))); + connect(&m_ModList, SIGNAL(showMessage(QString)), widget, + SLOT(showMessage(QString))); + connect(&m_ModList, SIGNAL(modRenamed(QString, QString)), widget, + SLOT(modRenamed(QString, QString))); + connect(&m_ModList, SIGNAL(modUninstalled(QString)), widget, + SLOT(modRemoved(QString))); + connect(&m_ModList, SIGNAL(removeSelectedMods()), widget, + SLOT(removeMod_clicked())); + connect(&m_ModList, SIGNAL(clearOverwrite()), widget, + SLOT(clearOverwrite())); + connect(&m_ModList, SIGNAL(requestColumnSelect(QPoint)), widget, + SLOT(displayColumnSelection(QPoint))); + connect(&m_ModList, SIGNAL(fileMoved(QString, QString, QString)), widget, + SLOT(fileMoved(QString, QString, QString))); + connect(&m_ModList, SIGNAL(modorder_changed()), widget, + SLOT(modorder_changed())); + connect(&m_PluginList, SIGNAL(writePluginsList()), widget, + SLOT(esplist_changed())); + connect(&m_PluginList, SIGNAL(esplist_changed()), widget, + SLOT(esplist_changed())); + connect(&m_DownloadManager, SIGNAL(showMessage(QString)), widget, + SLOT(showMessage(QString))); + } + + m_InstallationManager.setParentWidget(widget); + m_Updater.setUserInterface(widget); + + if (userInterface != nullptr) { + // this currently wouldn't work reliably if the ui isn't initialized yet to + // display the result + if (isOnline() && !m_Settings.offlineMode()) { + m_Updater.testForUpdate(); + } else { + qDebug("user doesn't seem to be connected to the internet"); + } + } +} + +void OrganizerCore::connectPlugins(PluginContainer *container) +{ + m_DownloadManager.setSupportedExtensions( + m_InstallationManager.getSupportedExtensions()); + m_PluginContainer = container; + m_Updater.setPluginContainer(m_PluginContainer); + m_DownloadManager.setPluginContainer(m_PluginContainer); + m_ModList.setPluginContainer(m_PluginContainer); + + if (!m_GameName.isEmpty()) { + m_GamePlugin = m_PluginContainer->managedGame(m_GameName); + emit managedGameChanged(m_GamePlugin); + } +} + +void OrganizerCore::disconnectPlugins() +{ + m_AboutToRun.disconnect_all_slots(); + m_FinishedRun.disconnect_all_slots(); + m_ModInstalled.disconnect_all_slots(); + m_ModList.disconnectSlots(); + m_PluginList.disconnectSlots(); + m_Updater.setPluginContainer(nullptr); + m_DownloadManager.setPluginContainer(nullptr); + m_ModList.setPluginContainer(nullptr); + + m_Settings.clearPlugins(); + m_GamePlugin = nullptr; + m_PluginContainer = nullptr; +} + +void OrganizerCore::setManagedGame(MOBase::IPluginGame *game) +{ + m_GameName = game->gameName(); + m_GamePlugin = game; + qApp->setProperty("managed_game", QVariant::fromValue(m_GamePlugin)); + emit managedGameChanged(m_GamePlugin); +} + +Settings &OrganizerCore::settings() +{ + return m_Settings; +} + +bool OrganizerCore::nexusApi(bool retry) +{ + NXMAccessManager *accessManager + = NexusInterface::instance(m_PluginContainer)->getAccessManager(); + + if ((accessManager->validateAttempted() || accessManager->validated()) + && !retry) { + // previous attempt, maybe even successful + return false; + } else { + QString apiKey; + if (!retry && m_Settings.getNexusApiKey(apiKey)) { + // credentials stored or user entered them manually + qDebug("attempt to verify nexus api key"); + accessManager->apiCheck(apiKey); + return true; + } else { + // no credentials stored and user didn't enter them + accessManager->refuseValidation(); + return false; + } + } +} + +void OrganizerCore::startMOUpdate() +{ + if (nexusApi()) { + m_PostLoginTasks.append([&]() { m_Updater.startUpdate(); }); + } else { + m_Updater.startUpdate(); + } +} + +void OrganizerCore::downloadRequestedNXM(const QString &url) +{ + qDebug("download requested: %s", qUtf8Printable(url)); + if (nexusApi()) { + m_PendingDownloads.append(url); + } else { + m_DownloadManager.addNXMDownload(url); + } +} + +void OrganizerCore::externalMessage(const QString &message) +{ + if (MOShortcut moshortcut{ message } ) { + if(moshortcut.hasExecutable()) + runShortcut(moshortcut); + } + else if (isNxmLink(message)) { + MessageDialog::showMessage(tr("Download started"), qApp->activeWindow()); + downloadRequestedNXM(message); + } +} + +void OrganizerCore::downloadRequested(QNetworkReply *reply, QString gameName, int modID, + const QString &fileName) +{ + try { + if (m_DownloadManager.addDownload(reply, QStringList(), fileName, gameName, modID, 0, + new ModRepositoryFileInfo(gameName, modID))) { + MessageDialog::showMessage(tr("Download started"), qApp->activeWindow()); + } + } catch (const std::exception &e) { + MessageDialog::showMessage(tr("Download failed"), qApp->activeWindow()); + qCritical("exception starting download: %s", e.what()); + } +} + +void OrganizerCore::removeOrigin(const QString &name) +{ + FilesOrigin &origin = m_DirectoryStructure->getOriginByName(ToWString(name)); + origin.enable(false); + refreshLists(); +} + +void OrganizerCore::downloadSpeed(const QString &serverName, int bytesPerSecond) +{ + m_Settings.setDownloadSpeed(serverName, bytesPerSecond); +} + +InstallationManager *OrganizerCore::installationManager() +{ + return &m_InstallationManager; +} + +bool OrganizerCore::createDirectory(const QString &path) { + if (!QDir(path).exists() && !QDir().mkpath(path)) { + QMessageBox::critical(nullptr, QObject::tr("Error"), + QObject::tr("Failed to create \"%1\". Your user " + "account probably lacks permission.") + .arg(QDir::toNativeSeparators(path))); + return false; + } else { + return true; + } +} + +bool OrganizerCore::bootstrap() { + return createDirectory(m_Settings.getProfileDirectory()) && + createDirectory(m_Settings.getModDirectory()) && + createDirectory(m_Settings.getDownloadDirectory()) && + createDirectory(m_Settings.getOverwriteDirectory()) && + createDirectory(QString::fromStdWString(crashDumpsPath())) && cycleDiagnostics(); +} + +void OrganizerCore::createDefaultProfile() +{ + QString profilesPath = settings().getProfileDirectory(); + if (QDir(profilesPath).entryList(QDir::AllDirs | QDir::NoDotAndDotDot).size() + == 0) { + Profile newProf("Default", managedGame(), false); + } +} + +void OrganizerCore::prepareVFS() +{ + m_USVFS.updateMapping(fileMapping(m_CurrentProfile->name(), QString())); +} + +void OrganizerCore::updateVFSParams(int logLevel, int crashDumpsType, QString executableBlacklist) { + setGlobalCrashDumpsType(crashDumpsType); + m_USVFS.updateParams(logLevel, crashDumpsType, executableBlacklist); +} + +bool OrganizerCore::cycleDiagnostics() { + if (int maxDumps = settings().crashDumpsMax()) + removeOldFiles(QString::fromStdWString(crashDumpsPath()), "*.dmp", maxDumps, QDir::Time|QDir::Reversed); + return true; +} + +//static +void OrganizerCore::setGlobalCrashDumpsType(int crashDumpsType) { + m_globalCrashDumpsType = ::crashDumpsType(crashDumpsType); +} + +//static +std::wstring OrganizerCore::crashDumpsPath() { + return ( + qApp->property("dataPath").toString() + "/" + + QString::fromStdWString(AppConfig::dumpsDir()) + ).toStdWString(); +} + +bool OrganizerCore::getArchiveParsing() const +{ + return m_ArchiveParsing; +} + +void OrganizerCore::setArchiveParsing(const bool archiveParsing) +{ + m_ArchiveParsing = archiveParsing; +} + +void OrganizerCore::setCurrentProfile(const QString &profileName) +{ + if ((m_CurrentProfile != nullptr) + && (profileName == m_CurrentProfile->name())) { + return; + } + + QDir profileBaseDir(settings().getProfileDirectory()); + QString profileDir = profileBaseDir.absoluteFilePath(profileName); + + if (!QDir(profileDir).exists()) { + // selected profile doesn't exist. Ensure there is at least one profile, + // then pick any one + createDefaultProfile(); + + profileDir = profileBaseDir.absoluteFilePath( + profileBaseDir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot).at(0)); + } + + Profile *newProfile = new Profile(QDir(profileDir), managedGame()); + + delete m_CurrentProfile; + m_CurrentProfile = newProfile; + m_ModList.setProfile(newProfile); + + if (m_CurrentProfile->invalidationActive(nullptr)) { + m_CurrentProfile->activateInvalidation(); + } else { + m_CurrentProfile->deactivateInvalidation(); + } + + connect(m_CurrentProfile, SIGNAL(modStatusChanged(uint)), this, SLOT(modStatusChanged(uint))); + connect(m_CurrentProfile, SIGNAL(modStatusChanged(QList)), this, SLOT(modStatusChanged(QList))); + refreshDirectoryStructure(); + + //This line is not actually needed and was only added to allow some + //outside detection of Mo2 profile change. (like BaobobMiller utility) + if (m_CurrentProfile != nullptr) { + settings().directInterface().setValue("selected_profile", + m_CurrentProfile->name().toUtf8().constData()); + } +} + +MOBase::IModRepositoryBridge *OrganizerCore::createNexusBridge() const +{ + return new NexusBridge(m_PluginContainer); +} + +QString OrganizerCore::profileName() const +{ + if (m_CurrentProfile != nullptr) { + return m_CurrentProfile->name(); + } else { + return ""; + } +} + +QString OrganizerCore::profilePath() const +{ + if (m_CurrentProfile != nullptr) { + return m_CurrentProfile->absolutePath(); + } else { + return ""; + } +} + +QString OrganizerCore::downloadsPath() const +{ + return QDir::fromNativeSeparators(m_Settings.getDownloadDirectory()); +} + +QString OrganizerCore::overwritePath() const +{ + return QDir::fromNativeSeparators(m_Settings.getOverwriteDirectory()); +} + +QString OrganizerCore::basePath() const +{ + return QDir::fromNativeSeparators(m_Settings.getBaseDirectory()); +} + +MOBase::VersionInfo OrganizerCore::appVersion() const +{ + return m_Updater.getVersion(); +} + +MOBase::IModInterface *OrganizerCore::getMod(const QString &name) const +{ + unsigned int index = ModInfo::getIndex(name); + return index == UINT_MAX ? nullptr : ModInfo::getByIndex(index).data(); +} + +MOBase::IPluginGame *OrganizerCore::getGame(const QString &name) const +{ + for (IPluginGame *game : m_PluginContainer->plugins()) { + if (game->gameShortName().compare(name, Qt::CaseInsensitive) == 0) + return game; + } + return nullptr; +} + +MOBase::IModInterface *OrganizerCore::createMod(GuessedValue &name) +{ + bool merge = false; + if (!m_InstallationManager.testOverwrite(name, &merge)) { + return nullptr; + } + + m_InstallationManager.setModsDirectory(m_Settings.getModDirectory()); + + QString targetDirectory + = QDir::fromNativeSeparators(m_Settings.getModDirectory()) + .append("/") + .append(name); + + QSettings settingsFile(targetDirectory + "/meta.ini", QSettings::IniFormat); + + if (!merge) { + settingsFile.setValue("modid", 0); + settingsFile.setValue("version", ""); + settingsFile.setValue("newestVersion", ""); + settingsFile.setValue("category", 0); + settingsFile.setValue("installationFile", ""); + + settingsFile.remove("installedFiles"); + settingsFile.beginWriteArray("installedFiles", 0); + settingsFile.endArray(); + } + + return ModInfo::createFrom(m_PluginContainer, m_GamePlugin, QDir(targetDirectory), &m_DirectoryStructure) + .data(); +} + +bool OrganizerCore::removeMod(MOBase::IModInterface *mod) +{ + unsigned int index = ModInfo::getIndex(mod->name()); + if (index == UINT_MAX) { + return mod->remove(); + } else { + return ModInfo::removeMod(index); + } +} + +void OrganizerCore::modDataChanged(MOBase::IModInterface *) +{ + refreshModList(false); +} + +QVariant OrganizerCore::pluginSetting(const QString &pluginName, + const QString &key) const +{ + return m_Settings.pluginSetting(pluginName, key); +} + +void OrganizerCore::setPluginSetting(const QString &pluginName, + const QString &key, const QVariant &value) +{ + m_Settings.setPluginSetting(pluginName, key, value); +} + +QVariant OrganizerCore::persistent(const QString &pluginName, + const QString &key, + const QVariant &def) const +{ + return m_Settings.pluginPersistent(pluginName, key, def); +} + +void OrganizerCore::setPersistent(const QString &pluginName, const QString &key, + const QVariant &value, bool sync) +{ + m_Settings.setPluginPersistent(pluginName, key, value, sync); +} + +QString OrganizerCore::pluginDataPath() const +{ + return qApp->applicationDirPath() + "/" + ToQString(AppConfig::pluginPath()) + + "/data"; +} + +MOBase::IModInterface *OrganizerCore::installMod(const QString &fileName, + const QString &initModName) +{ + if (m_CurrentProfile == nullptr) { + return nullptr; + } + + if (m_InstallationManager.isRunning()) { + QMessageBox::information( + qApp->activeWindow(), tr("Installation cancelled"), + tr("Another installation is currently in progress."), QMessageBox::Ok); + return nullptr; + } + + bool hasIniTweaks = false; + GuessedValue modName; + if (!initModName.isEmpty()) { + modName.update(initModName, GUESS_USER); + } + m_CurrentProfile->writeModlistNow(); + m_InstallationManager.setModsDirectory(m_Settings.getModDirectory()); + if (m_InstallationManager.install(fileName, modName, hasIniTweaks)) { + MessageDialog::showMessage(tr("Installation successful"), + qApp->activeWindow()); + refreshModList(); + + int modIndex = ModInfo::getIndex(modName); + if (modIndex != UINT_MAX) { + ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); + if (hasIniTweaks && (m_UserInterface != nullptr) + && (QMessageBox::question(qApp->activeWindow(), tr("Configure Mod"), + tr("This mod contains ini tweaks. Do you " + "want to configure them now?"), + QMessageBox::Yes | QMessageBox::No) + == QMessageBox::Yes)) { + m_UserInterface->displayModInformation(modInfo, modIndex, + ModInfoDialog::TAB_INIFILES); + } + m_ModInstalled(modName); + m_DownloadManager.markInstalled(fileName); + emit modInstalled(modName); + return modInfo.data(); + } else { + reportError(tr("mod not found: %1").arg(qUtf8Printable(modName))); + } + } else if (m_InstallationManager.wasCancelled()) { + QMessageBox::information(qApp->activeWindow(), tr("Installation cancelled"), + tr("The mod was not installed completely."), + QMessageBox::Ok); + } + return nullptr; +} + +void OrganizerCore::installDownload(int index) +{ + if (m_InstallationManager.isRunning()) { + QMessageBox::information( + qApp->activeWindow(), tr("Installation cancelled"), + tr("Another installation is currently in progress."), QMessageBox::Ok); + return; + } + + try { + QString fileName = m_DownloadManager.getFilePath(index); + QString gameName = m_DownloadManager.getGameName(index); + int modID = m_DownloadManager.getModID(index); + int fileID = m_DownloadManager.getFileInfo(index)->fileID; + GuessedValue modName; + + // see if there already are mods with the specified mod id + if (modID != 0) { + std::vector modInfo = ModInfo::getByModID(gameName, modID); + for (auto iter = modInfo.begin(); iter != modInfo.end(); ++iter) { + std::vector flags = (*iter)->getFlags(); + if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_BACKUP) + == flags.end()) { + modName.update((*iter)->name(), GUESS_PRESET); + (*iter)->saveMeta(); + } + } + } + + m_CurrentProfile->writeModlistNow(); + + bool hasIniTweaks = false; + m_InstallationManager.setModsDirectory(m_Settings.getModDirectory()); + if (m_InstallationManager.install(fileName, modName, hasIniTweaks)) { + MessageDialog::showMessage(tr("Installation successful"), + qApp->activeWindow()); + refreshModList(); + + int modIndex = ModInfo::getIndex(modName); + if (modIndex != UINT_MAX) { + ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); + modInfo->addInstalledFile(modID, fileID); + + if (hasIniTweaks && m_UserInterface != nullptr + && (QMessageBox::question(qApp->activeWindow(), tr("Configure Mod"), + tr("This mod contains ini tweaks. Do you " + "want to configure them now?"), + QMessageBox::Yes | QMessageBox::No) + == QMessageBox::Yes)) { + m_UserInterface->displayModInformation(modInfo, modIndex, + ModInfoDialog::TAB_INIFILES); + } + + m_ModInstalled(modName); + } else { + reportError(tr("mod not found: %1").arg(qUtf8Printable(modName))); + } + m_DownloadManager.markInstalled(index); + + emit modInstalled(modName); + } else if (m_InstallationManager.wasCancelled()) { + QMessageBox::information( + qApp->activeWindow(), tr("Installation cancelled"), + tr("The mod was not installed completely."), QMessageBox::Ok); + } + } catch (const std::exception &e) { + reportError(e.what()); + } +} + +QString OrganizerCore::resolvePath(const QString &fileName) const +{ + if (m_DirectoryStructure == nullptr) { + return QString(); + } + const FileEntry::Ptr file + = m_DirectoryStructure->searchFile(ToWString(fileName), nullptr); + if (file.get() != nullptr) { + return ToQString(file->getFullPath()); + } else { + return QString(); + } +} + +QStringList OrganizerCore::listDirectories(const QString &directoryName) const +{ + QStringList result; + DirectoryEntry *dir = m_DirectoryStructure; + if (!directoryName.isEmpty()) + dir = dir->findSubDirectoryRecursive(ToWString(directoryName)); + if (dir != nullptr) { + std::vector::iterator current, end; + dir->getSubDirectories(current, end); + for (; current != end; ++current) { + result.append(ToQString((*current)->getName())); + } + } + return result; +} + +QStringList OrganizerCore::findFiles( + const QString &path, + const std::function &filter) const +{ + QStringList result; + DirectoryEntry *dir = m_DirectoryStructure; + if (!path.isEmpty()) + dir = dir->findSubDirectoryRecursive(ToWString(path)); + if (dir != nullptr) { + std::vector files = dir->getFiles(); + foreach (FileEntry::Ptr file, files) { + if (filter(ToQString(file->getFullPath()))) { + result.append(ToQString(file->getFullPath())); + } + } + } else { + qWarning("directory not found: %1", qUtf8Printable(path)); + } + return result; +} + +QStringList OrganizerCore::getFileOrigins(const QString &fileName) const +{ + QStringList result; + const FileEntry::Ptr file = m_DirectoryStructure->searchFile( + ToWString(QFileInfo(fileName).fileName()), nullptr); + + if (file.get() != nullptr) { + result.append(ToQString( + m_DirectoryStructure->getOriginByID(file->getOrigin()).getName())); + foreach (auto i, file->getAlternatives()) { + result.append( + ToQString(m_DirectoryStructure->getOriginByID(i.first).getName())); + } + } else { + qWarning("file not found: %1", qUtf8Printable(fileName)); + } + return result; +} + +QList OrganizerCore::findFileInfos( + const QString &path, + const std::function &filter) + const +{ + QList result; + DirectoryEntry *dir = m_DirectoryStructure; + if (!path.isEmpty()) + dir = dir->findSubDirectoryRecursive(ToWString(path)); + if (dir != nullptr) { + std::vector files = dir->getFiles(); + foreach (FileEntry::Ptr file, files) { + IOrganizer::FileInfo info; + info.filePath = ToQString(file->getFullPath()); + bool fromArchive = false; + info.origins.append(ToQString( + m_DirectoryStructure->getOriginByID(file->getOrigin(fromArchive)) + .getName())); + info.archive = fromArchive ? ToQString(file->getArchive().first) : ""; + foreach (auto idx, file->getAlternatives()) { + info.origins.append( + ToQString(m_DirectoryStructure->getOriginByID(idx.first).getName())); + } + + if (filter(info)) { + result.append(info); + } + } + } + return result; +} + +DownloadManager *OrganizerCore::downloadManager() +{ + return &m_DownloadManager; +} + +PluginList *OrganizerCore::pluginList() +{ + return &m_PluginList; +} + +ModList *OrganizerCore::modList() +{ + return &m_ModList; +} + +QStringList OrganizerCore::modsSortedByProfilePriority() const +{ + QStringList res; + for (int i = currentProfile()->getPriorityMinimum(); + i < currentProfile()->getPriorityMinimum() + (int)currentProfile()->numRegularMods(); + ++i) { + int modIndex = currentProfile()->modIndexByPriority(i); + auto modInfo = ModInfo::getByIndex(modIndex); + if (!modInfo->hasFlag(ModInfo::FLAG_OVERWRITE) && + !modInfo->hasFlag(ModInfo::FLAG_BACKUP)) { + res.push_back(ModInfo::getByIndex(modIndex)->name()); + } + } + return res; +} + +void OrganizerCore::spawnBinary(const QFileInfo &binary, + const QString &arguments, + const QDir ¤tDirectory, + const QString &steamAppID, + const QString &customOverwrite, + const QList &forcedLibraries) +{ + DWORD processExitCode = 0; + HANDLE processHandle = spawnBinaryDirect(binary, arguments, m_CurrentProfile->name(), currentDirectory, steamAppID, customOverwrite, forcedLibraries, &processExitCode); + if (processHandle != INVALID_HANDLE_VALUE) { + refreshDirectoryStructure(); + // need to remove our stored load order because it may be outdated if a foreign tool changed the + // file time. After removing that file, refreshESPList will use the file time as the order + if (managedGame()->loadOrderMechanism() == IPluginGame::LoadOrderMechanism::FileTime) { + qDebug("removing loadorder.txt"); + QFile::remove(m_CurrentProfile->getLoadOrderFileName()); + } + refreshDirectoryStructure(); + + refreshESPList(true); + savePluginList(); + + //These callbacks should not fiddle with directoy structure and ESPs. + m_FinishedRun(binary.absoluteFilePath(), processExitCode); + } +} + +HANDLE OrganizerCore::spawnBinaryDirect(const QFileInfo &binary, + const QString &arguments, + const QString &profileName, + const QDir ¤tDirectory, + const QString &steamAppID, + const QString &customOverwrite, + const QList &forcedLibraries, + LPDWORD exitCode) +{ + HANDLE processHandle = spawnBinaryProcess(binary, arguments, profileName, currentDirectory, steamAppID, customOverwrite, forcedLibraries); + if (Settings::instance().lockGUI() && processHandle != INVALID_HANDLE_VALUE) { + std::unique_ptr dlg; + ILockedWaitingForProcess* uilock = nullptr; + + if (m_UserInterface != nullptr) { + uilock = m_UserInterface->lock(); + } + else { + // i.e. when running command line shortcuts there is no m_UserInterface + dlg.reset(new LockedDialog); + dlg->show(); + dlg->setEnabled(true); + uilock = dlg.get(); + } + + ON_BLOCK_EXIT([&]() { + if (m_UserInterface != nullptr) { + m_UserInterface->unlock(); + } }); + + DWORD ignoreExitCode; + waitForProcessCompletion(processHandle, exitCode ? exitCode : &ignoreExitCode, uilock); + cycleDiagnostics(); + } + + return processHandle; +} + + +HANDLE OrganizerCore::spawnBinaryProcess(const QFileInfo &binary, + const QString &arguments, + const QString &profileName, + const QDir ¤tDirectory, + const QString &steamAppID, + const QString &customOverwrite, + const QList &forcedLibraries) +{ + prepareStart(); + + if (!binary.exists()) { + reportError( + tr("Executable not found: %1").arg(qUtf8Printable(binary.absoluteFilePath()))); + return INVALID_HANDLE_VALUE; + } + + if (!steamAppID.isEmpty()) { + ::SetEnvironmentVariableW(L"SteamAPPId", ToWString(steamAppID).c_str()); + } else { + ::SetEnvironmentVariableW(L"SteamAPPId", + ToWString(m_Settings.getSteamAppID()).c_str()); + } + + QWidget *window = qApp->activeWindow(); + if ((window != nullptr) && (!window->isVisible())) { + window = nullptr; + } + + // This could possibly be extracted somewhere else but it's probably for when + // we have more than one provider of game registration. + if ((QFileInfo( + managedGame()->gameDirectory().absoluteFilePath("steam_api.dll")) + .exists() + || QFileInfo(managedGame()->gameDirectory().absoluteFilePath( + "steam_api64.dll")) + .exists()) + && (m_Settings.getLoadMechanism() == LoadMechanism::LOAD_MODORGANIZER)) { + if (!testForSteam()) { + QDialogButtonBox::StandardButton result; + result = QuestionBoxMemory::query(window, "steamQuery", binary.fileName(), + tr("Start Steam?"), + tr("Steam is required to be running already to correctly start the game. " + "Should MO try to start steam now?"), + QDialogButtonBox::Yes | QDialogButtonBox::No | QDialogButtonBox::Cancel); + if (result == QDialogButtonBox::Yes) { + startSteam(window); + } else if(result == QDialogButtonBox::Cancel) { + return INVALID_HANDLE_VALUE; + } + } + } + + while (m_DirectoryUpdate) { + ::Sleep(100); + QCoreApplication::processEvents(); + } + + // need to make sure all data is saved before we start the application + if (m_CurrentProfile != nullptr) { + m_CurrentProfile->writeModlistNow(true); + } + + // TODO: should also pass arguments + if (m_AboutToRun(binary.absoluteFilePath())) { + try { + m_USVFS.updateMapping(fileMapping(profileName, customOverwrite)); + m_USVFS.updateForcedLibraries(forcedLibraries); + + } catch (const UsvfsConnectorException &e) { + qDebug(e.what()); + return INVALID_HANDLE_VALUE; + } catch (const std::exception &e) { + QMessageBox::warning(window, tr("Error"), e.what()); + return INVALID_HANDLE_VALUE; + } + + // Check if the Windows Event Logging service is running. For some reason, this seems to be + // critical to the successful running of usvfs. + if (!checkService()) { + if (QuestionBoxMemory::query(window, QString("eventLogService"), binary.fileName(), + tr("Windows Event Log Error"), + tr("The Windows Event Log service is disabled and/or not running. This prevents" + " USVFS from running properly. Your mods may not be working in the executable" + " that you are launching. Note that you may have to restart MO and/or your PC" + " after the service is fixed.\n\nContinue launching %1?").arg(binary.fileName()), + QDialogButtonBox::Yes | QDialogButtonBox::No) == QDialogButtonBox::No) { + return INVALID_HANDLE_VALUE; + } + } + + for (auto exec : settings().executablesBlacklist().split(";")) { + if (exec.compare(binary.fileName(), Qt::CaseInsensitive) == 0) { + if (QuestionBoxMemory::query(window, QString("blacklistedExecutable"), binary.fileName(), + tr("Blacklisted Executable"), + tr("The executable you are attempted to launch is blacklisted in the virtual file" + " system. This will likely prevent the executable, and any executables that are" + " launched by this one, from seeing any mods. This could extend to INI files, save" + " games and any other virtualized files.\n\nContinue launching %1?").arg(binary.fileName()), + QDialogButtonBox::Yes | QDialogButtonBox::No) == QDialogButtonBox::No) { + return INVALID_HANDLE_VALUE; + } + } + } + + QString modsPath = settings().getModDirectory(); + + // Check if this a request with either an executable or a working directory under our mods folder + // then will start the process in a virtualized "environment" with the appropriate paths fixed: + // (i.e. mods\FNIS\path\exe => game\data\path\exe) + QString cwdPath = currentDirectory.absolutePath(); + bool virtualizedCwd = cwdPath.startsWith(modsPath, Qt::CaseInsensitive); + QString binPath = binary.absoluteFilePath(); + bool virtualizedBin = binPath.startsWith(modsPath, Qt::CaseInsensitive); + if (virtualizedCwd || virtualizedBin) { + if (virtualizedCwd) { + int cwdOffset = cwdPath.indexOf('/', modsPath.length() + 1); + QString adjustedCwd = cwdPath.mid(cwdOffset, -1); + cwdPath = m_GamePlugin->dataDirectory().absolutePath(); + if (cwdOffset >= 0) + cwdPath += adjustedCwd; + + } + + if (virtualizedBin) { + int binOffset = binPath.indexOf('/', modsPath.length() + 1); + QString adjustedBin = binPath.mid(binOffset, -1); + binPath = m_GamePlugin->dataDirectory().absolutePath(); + if (binOffset >= 0) + binPath += adjustedBin; + } + + QString cmdline + = QString("launch \"%1\" \"%2\" %3") + .arg(QDir::toNativeSeparators(cwdPath), + QDir::toNativeSeparators(binPath), arguments); + + qDebug() << "Spawning proxyed process <" << cmdline << ">"; + + return startBinary(QFileInfo(QCoreApplication::applicationFilePath()), + cmdline, QCoreApplication::applicationDirPath(), true); + } else { + qDebug() << "Spawning direct process <" << binPath << "," << arguments << "," << cwdPath << ">"; + return startBinary(binary, arguments, currentDirectory, true); + } + } else { + qDebug("start of \"%s\" canceled by plugin", + qUtf8Printable(binary.absoluteFilePath())); + return INVALID_HANDLE_VALUE; + } +} + +HANDLE OrganizerCore::runShortcut(const MOShortcut& shortcut) +{ + if (shortcut.hasInstance() && shortcut.instance() != InstanceManager::instance().currentInstance()) + throw std::runtime_error( + QString("Refusing to run executable from different instance %1:%2") + .arg(shortcut.instance(),shortcut.executable()) + .toLocal8Bit().constData()); + + Executable& exe = m_ExecutablesList.find(shortcut.executable()); + auto forcedLibaries = m_CurrentProfile->determineForcedLibraries(shortcut.executable()); + if (!m_CurrentProfile->forcedLibrariesEnabled(shortcut.executable())) { + forcedLibaries.clear(); + } + + return spawnBinaryDirect( + exe.m_BinaryInfo, exe.m_Arguments, + m_CurrentProfile->name(), + exe.m_WorkingDirectory.length() != 0 + ? exe.m_WorkingDirectory + : exe.m_BinaryInfo.absolutePath(), + exe.m_SteamAppID, + "", + forcedLibaries); +} + +HANDLE OrganizerCore::startApplication(const QString &executable, + const QStringList &args, + const QString &cwd, + const QString &profile) +{ + QFileInfo binary; + QString arguments = args.join(" "); + QString currentDirectory = cwd; + QString profileName = profile; + if (profile.length() == 0) { + if (m_CurrentProfile != nullptr) { + profileName = m_CurrentProfile->name(); + } else { + throw MyException(tr("No profile set")); + } + } + QString steamAppID; + QString customOverwrite; + QList forcedLibraries; + if (executable.contains('\\') || executable.contains('/')) { + // file path + + binary = QFileInfo(executable); + if (binary.isRelative()) { + // relative path, should be relative to game directory + binary = QFileInfo( + managedGame()->gameDirectory().absoluteFilePath(executable)); + } + if (cwd.length() == 0) { + currentDirectory = binary.absolutePath(); + } + try { + const Executable &exe = m_ExecutablesList.findByBinary(binary); + steamAppID = exe.m_SteamAppID; + customOverwrite + = m_CurrentProfile->setting("custom_overwrites", exe.m_Title) + .toString(); + if (m_CurrentProfile->forcedLibrariesEnabled(exe.m_Title)) { + forcedLibraries = m_CurrentProfile->determineForcedLibraries(exe.m_Title); + } + } catch (const std::runtime_error &) { + // nop + } + } else { + // only a file name, search executables list + try { + const Executable &exe = m_ExecutablesList.find(executable); + steamAppID = exe.m_SteamAppID; + customOverwrite + = m_CurrentProfile->setting("custom_overwrites", exe.m_Title) + .toString(); + if (m_CurrentProfile->forcedLibrariesEnabled(exe.m_Title)) { + forcedLibraries = m_CurrentProfile->determineForcedLibraries(exe.m_Title); + } + if (arguments == "") { + arguments = exe.m_Arguments; + } + binary = exe.m_BinaryInfo; + if (cwd.length() == 0) { + currentDirectory = exe.m_WorkingDirectory; + } + } catch (const std::runtime_error &) { + qWarning("\"%s\" not set up as executable", + qUtf8Printable(executable)); + binary = QFileInfo(executable); + } + } + + return spawnBinaryDirect(binary, arguments, profileName, currentDirectory, steamAppID, customOverwrite, forcedLibraries); +} + +bool OrganizerCore::waitForApplication(HANDLE handle, LPDWORD exitCode) +{ + if (!Settings::instance().lockGUI()) + return true; + + ILockedWaitingForProcess* uilock = nullptr; + if (m_UserInterface != nullptr) { + uilock = m_UserInterface->lock(); + } + + ON_BLOCK_EXIT([&] () { + if (m_UserInterface != nullptr) { + m_UserInterface->unlock(); + } }); + return waitForProcessCompletion(handle, exitCode, uilock); +} + +bool OrganizerCore::waitForProcessCompletion(HANDLE handle, LPDWORD exitCode, ILockedWaitingForProcess* uilock) +{ + bool originalHandle = true; + bool newHandle = true; + bool uiunlocked = false; + + DWORD currentPID = 0; + QString processName; + auto waitForChildUntil = GetTickCount64(); + if (handle != INVALID_HANDLE_VALUE) { + currentPID = GetProcessId(handle); + processName = QString::fromStdWString(getProcessName(handle)); + } + + // Certain process names we wish to "hide" for aesthetic reason: + bool waitingOnHidden = false; + std::vector hiddenList; + hiddenList.push_back(QFileInfo(QCoreApplication::applicationFilePath()).fileName()); + for (QString hide : hiddenList) + if (processName.contains(hide, Qt::CaseInsensitive)) + waitingOnHidden = true; + // The main reason for adding the hidden list is to hide the MO proxy we use to spawn virtualized processes. + // On the one hand we want to display the real executable without it feeling laggy, on the other we don't want + // to requery processes all the time if for some reason we are waiting on hidden processes and find no "unhidden" + // process. For this reason we use exponential backoff and also start with a delibrately low value to improve + // the responsiveness of the initial update + DWORD64 nextHiddenCheck = GetTickCount64(); + DWORD64 nextHiddenCheckDelay = 50; + + constexpr DWORD INPUT_EVENT = WAIT_OBJECT_0 + 1; + DWORD res = WAIT_TIMEOUT; + while (handle != INVALID_HANDLE_VALUE && (newHandle || res == WAIT_TIMEOUT || res == INPUT_EVENT)) + { + if (newHandle) { + processName += QString(" (%1)").arg(currentPID); + if (uilock) + uilock->setProcessName(processName); + qDebug() << "Waiting for" + << (originalHandle ? "spawned" : "usvfs") + << "process completion :" << qUtf8Printable(processName); + newHandle = false; + } + + // Wait for a an event on the handle, a key press, mouse click or timeout + res = MsgWaitForMultipleObjects(1, &handle, FALSE, 200, QS_KEY | QS_MOUSEBUTTON); + if (res == WAIT_FAILED) { + qWarning() << "Failed waiting for process completion : MsgWaitForMultipleObjects WAIT_FAILED" << GetLastError(); + break; + } + + // keep processing events so the app doesn't appear dead + QCoreApplication::sendPostedEvents(); + QCoreApplication::processEvents(); + + if (uilock && uilock->unlockForced()) { + uiunlocked = true; + break; + } + + if (res == WAIT_OBJECT_0) { + // process we were waiting on has completed + if (originalHandle && exitCode && !::GetExitCodeProcess(handle, exitCode)) + qWarning() << "Failed getting exit code of complete process :" << GetLastError(); + CloseHandle(handle); + handle = INVALID_HANDLE_VALUE; + originalHandle = false; + // if the previous process spawned a child process and immediately exits we may miss it if we check immediately + waitForChildUntil = GetTickCount64() + 800; + } + + // search for another process to wait on if either: + // 1. we just completed waiting for a process and need to find/wait for an inject child + // 2. we are currently waiting on a hidden process so periodically check if there is a non-hidden process to wait on + bool firstIteration = true; + while ((handle == INVALID_HANDLE_VALUE && GetTickCount64() <= waitForChildUntil) + || (waitingOnHidden && GetTickCount64() >= nextHiddenCheck)) + { + if (firstIteration) + firstIteration = false; + else { + QThread::msleep(200); + QCoreApplication::sendPostedEvents(); + QCoreApplication::processEvents(); + } + + // search if there is another usvfs process active + handle = findAndOpenAUSVFSProcess(hiddenList, currentPID); + waitingOnHidden = false; + newHandle = handle != INVALID_HANDLE_VALUE; + if (newHandle) { + currentPID = GetProcessId(handle); + processName = QString::fromStdWString(getProcessName(handle)); + for (QString hide : hiddenList) + if (processName.contains(hide, Qt::CaseInsensitive)) + waitingOnHidden = true; + } + if (waitingOnHidden) { + nextHiddenCheck = GetTickCount64() + nextHiddenCheckDelay; + nextHiddenCheckDelay = std::min(nextHiddenCheckDelay * 2, (DWORD64) 2000); + } + else { + nextHiddenCheck = GetTickCount64(); + nextHiddenCheckDelay = 200; + } + } + } + + if (res == WAIT_OBJECT_0) + qDebug() << "Waiting for process completion successfull"; + else if (uiunlocked) + qDebug() << "Waiting for process completion aborted by UI"; + else + qDebug() << "Waiting for process completion not successfull :" << res; + + if (handle != INVALID_HANDLE_VALUE) + ::CloseHandle(handle); + + return res == WAIT_OBJECT_0; +} + +HANDLE OrganizerCore::findAndOpenAUSVFSProcess(const std::vector& hiddenList, DWORD preferedParentPid) { + // for practical reasons a querySize of 1 is probably enough, we use a larger query as a heuristics + // to find a more "aesthetic injected processes (attempting to comply to hiddenList and preferedParentPid) + constexpr size_t querySize = 100; + DWORD pids[querySize]; + size_t found = querySize; + if (!::GetVFSProcessList(&found, pids)) { + qWarning() << "Failed seeking USVFS processes : GetVFSProcessList failed?!"; + return INVALID_HANDLE_VALUE; + } + + HANDLE best_match = INVALID_HANDLE_VALUE; + bool best_match_hidden = true; + for (size_t i = 0; i < found; ++i) { + if (pids[i] == GetCurrentProcessId()) + continue; // obviously don't wait for MO process + + HANDLE handle = ::OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, FALSE, pids[i]); + if (handle == INVALID_HANDLE_VALUE) { + qWarning() << "Failed openning USVFS process " << pids[i] << " : OpenProcess failed" << GetLastError(); + continue; + } + + QString pname = QString::fromStdWString(getProcessName(handle)); + bool phidden = false; + for (auto hide : hiddenList) + if (pname.contains(hide, Qt::CaseInsensitive)) + phidden = true; + + bool pprefered = preferedParentPid && getProcessParentID(pids[i]) == preferedParentPid; + + if (best_match == INVALID_HANDLE_VALUE || best_match_hidden || (!phidden && pprefered)) { + if (best_match != INVALID_HANDLE_VALUE) + CloseHandle(best_match); + best_match = handle; + best_match_hidden = phidden; + } + else + CloseHandle(handle); + + if (!phidden && pprefered) + return best_match; + } + + return best_match; +} + +bool OrganizerCore::onAboutToRun( + const std::function &func) +{ + auto conn = m_AboutToRun.connect(func); + return conn.connected(); +} + +bool OrganizerCore::onFinishedRun( + const std::function &func) +{ + auto conn = m_FinishedRun.connect(func); + return conn.connected(); +} + +bool OrganizerCore::onModInstalled( + const std::function &func) +{ + auto conn = m_ModInstalled.connect(func); + return conn.connected(); +} + +void OrganizerCore::refreshModList(bool saveChanges) +{ + // don't lose changes! + if (saveChanges) { + m_CurrentProfile->writeModlistNow(true); + } + ModInfo::updateFromDisc(m_Settings.getModDirectory(), &m_DirectoryStructure, + m_PluginContainer, m_Settings.displayForeign(), managedGame()); + + m_CurrentProfile->refreshModStatus(); + + m_ModList.notifyChange(-1); + + refreshDirectoryStructure(); +} + +void OrganizerCore::refreshESPList(bool force) +{ + if (m_DirectoryUpdate) { + // don't mess up the esp list if we're currently updating the directory + // structure + m_PostRefreshTasks.append([=]() { + this->refreshESPList(force); + }); + return; + } + m_CurrentProfile->writeModlist(); + + // clear list + try { + m_PluginList.refresh(m_CurrentProfile->name(), *m_DirectoryStructure, + m_CurrentProfile->getLockedOrderFileName(), force); + } catch (const std::exception &e) { + reportError(tr("Failed to refresh list of esps: %1").arg(e.what())); + } +} + +void OrganizerCore::refreshBSAList() +{ + DataArchives *archives = m_GamePlugin->feature(); + + if (archives != nullptr) { + m_ArchivesInit = false; + + // default archives are the ones enabled outside MO. if the list can't be + // found (which might + // happen if ini files are missing) use hard-coded defaults (preferrably the + // same the game would use) + m_DefaultArchives = archives->archives(m_CurrentProfile); + if (m_DefaultArchives.length() == 0) { + m_DefaultArchives = archives->vanillaArchives(); + } + + m_ActiveArchives.clear(); + + auto iter = enabledArchives(); + m_ActiveArchives = toStringList(iter.begin(), iter.end()); + if (m_ActiveArchives.isEmpty()) { + m_ActiveArchives = m_DefaultArchives; + } + + if (m_UserInterface != nullptr) { + m_UserInterface->updateBSAList(m_DefaultArchives, m_ActiveArchives); + } + + m_ArchivesInit = true; + } +} + +void OrganizerCore::refreshLists() +{ + if ((m_CurrentProfile != nullptr) && m_DirectoryStructure->isPopulated()) { + refreshESPList(true); + refreshBSAList(); + } // no point in refreshing lists if no files have been added to the directory + // tree +} + +void OrganizerCore::updateModActiveState(int index, bool active) +{ + QList modsToUpdate; + modsToUpdate.append(index); + updateModsActiveState(modsToUpdate, active); +} + +void OrganizerCore::updateModsActiveState(const QList &modIndices, bool active) +{ + int enabled = 0; + for (auto index : modIndices) { + ModInfo::Ptr modInfo = ModInfo::getByIndex(index); + QDir dir(modInfo->absolutePath()); + for (const QString &esm : + dir.entryList(QStringList() << "*.esm", QDir::Files)) { + const FileEntry::Ptr file = m_DirectoryStructure->findFile(ToWString(esm)); + if (file.get() == nullptr) { + qWarning("failed to activate %s", qUtf8Printable(esm)); + continue; + } + + if (active != m_PluginList.isEnabled(esm) + && file->getAlternatives().empty()) { + m_PluginList.blockSignals(true); + m_PluginList.enableESP(esm, active); + m_PluginList.blockSignals(false); + } + } + + for (const QString &esl : + dir.entryList(QStringList() << "*.esl", QDir::Files)) { + const FileEntry::Ptr file = m_DirectoryStructure->findFile(ToWString(esl)); + if (file.get() == nullptr) { + qWarning("failed to activate %s", qUtf8Printable(esl)); + continue; + } + + if (active != m_PluginList.isEnabled(esl) + && file->getAlternatives().empty()) { + m_PluginList.blockSignals(true); + m_PluginList.enableESP(esl, active); + m_PluginList.blockSignals(false); + ++enabled; + } + } + QStringList esps = dir.entryList(QStringList() << "*.esp", QDir::Files); + for (const QString &esp : esps) { + const FileEntry::Ptr file = m_DirectoryStructure->findFile(ToWString(esp)); + if (file.get() == nullptr) { + qWarning("failed to activate %s", qUtf8Printable(esp)); + continue; + } + + if (active != m_PluginList.isEnabled(esp) + && file->getAlternatives().empty()) { + m_PluginList.blockSignals(true); + m_PluginList.enableESP(esp, active); + m_PluginList.blockSignals(false); + ++enabled; + } + } + } + if (active && (enabled > 1)) { + MessageDialog::showMessage( + tr("Multiple esps/esls activated, please check that they don't conflict."), + qApp->activeWindow()); + } + m_PluginList.refreshLoadOrder(); + // immediately save affected lists + m_PluginListsWriter.writeImmediately(false); +} + +void OrganizerCore::updateModInDirectoryStructure(unsigned int index, + ModInfo::Ptr modInfo) +{ + QMap allModInfo; + allModInfo[index] = modInfo; + updateModsInDirectoryStructure(allModInfo); +} + +void OrganizerCore::updateModsInDirectoryStructure(QMap modInfo) +{ + for (auto idx : modInfo.keys()) { + // add files of the bsa to the directory structure + m_DirectoryRefresher.addModFilesToStructure( + m_DirectoryStructure, modInfo[idx]->name(), + m_CurrentProfile->getModPriority(idx), modInfo[idx]->absolutePath(), + modInfo[idx]->stealFiles()); + } + DirectoryRefresher::cleanStructure(m_DirectoryStructure); + // need to refresh plugin list now so we can activate esps + refreshESPList(true); + // activate all esps of the specified mod so the bsas get activated along with + // it + m_PluginList.blockSignals(true); + updateModsActiveState(modInfo.keys(), true); + m_PluginList.blockSignals(false); + // now we need to refresh the bsa list and save it so there is no confusion + // about what archives are avaiable and active + refreshBSAList(); + if (m_UserInterface != nullptr) { + m_UserInterface->archivesWriter().writeImmediately(false); + } + + std::vector archives = enabledArchives(); + m_DirectoryRefresher.setMods( + m_CurrentProfile->getActiveMods(), + std::set(archives.begin(), archives.end())); + + // finally also add files from bsas to the directory structure + for (auto idx : modInfo.keys()) { + m_DirectoryRefresher.addModBSAToStructure( + m_DirectoryStructure, modInfo[idx]->name(), + m_CurrentProfile->getModPriority(idx), modInfo[idx]->absolutePath(), + modInfo[idx]->archives()); + } +} + +void OrganizerCore::requestDownload(const QUrl &url, QNetworkReply *reply) +{ + if (m_PluginContainer != nullptr) { + for (IPluginModPage *modPage : + m_PluginContainer->plugins()) { + ModRepositoryFileInfo *fileInfo = new ModRepositoryFileInfo(); + if (modPage->handlesDownload(url, reply->url(), *fileInfo)) { + fileInfo->repository = modPage->name(); + m_DownloadManager.addDownload(reply, fileInfo); + return; + } + } + } + + // no mod found that could handle the download. Is it a nexus mod? + if (url.host() == "www.nexusmods.com") { + QString gameName = ""; + int modID = 0; + int fileID = 0; + QRegExp nameExp("www\\.nexusmods\\.com/(\\a+)/"); + if (nameExp.indexIn(url.toString()) != -1) { + gameName = nameExp.cap(1); + } + QRegExp modExp("mods/(\\d+)"); + if (modExp.indexIn(url.toString()) != -1) { + modID = modExp.cap(1).toInt(); + } + QRegExp fileExp("fid=(\\d+)"); + if (fileExp.indexIn(reply->url().toString()) != -1) { + fileID = fileExp.cap(1).toInt(); + } + m_DownloadManager.addDownload(reply, + new ModRepositoryFileInfo(gameName, modID, fileID)); + } else { + if (QMessageBox::question(qApp->activeWindow(), tr("Download?"), + tr("A download has been started but no installed " + "page plugin recognizes it.\n" + "If you download anyway no information (i.e. " + "version) will be associated with the " + "download.\n" + "Continue?"), + QMessageBox::Yes | QMessageBox::No) + == QMessageBox::Yes) { + m_DownloadManager.addDownload(reply, new ModRepositoryFileInfo()); + } + } +} + +ModListSortProxy *OrganizerCore::createModListProxyModel() +{ + ModListSortProxy *result = new ModListSortProxy(m_CurrentProfile, this); + result->setSourceModel(&m_ModList); + return result; +} + +PluginListSortProxy *OrganizerCore::createPluginListProxyModel() +{ + PluginListSortProxy *result = new PluginListSortProxy(this); + result->setSourceModel(&m_PluginList); + return result; +} + +IPluginGame const *OrganizerCore::managedGame() const +{ + return m_GamePlugin; +} + +std::vector OrganizerCore::enabledArchives() +{ + std::vector result; + if (m_ArchiveParsing) { + QFile archiveFile(m_CurrentProfile->getArchivesFileName()); + if (archiveFile.open(QIODevice::ReadOnly)) { + while (!archiveFile.atEnd()) { + result.push_back(QString::fromUtf8(archiveFile.readLine()).trimmed()); + } + archiveFile.close(); + } + } + return result; +} + +void OrganizerCore::refreshDirectoryStructure() +{ + if (!m_DirectoryUpdate) { + m_CurrentProfile->writeModlistNow(true); + + m_DirectoryUpdate = true; + std::vector> activeModList + = m_CurrentProfile->getActiveMods(); + auto archives = enabledArchives(); + m_DirectoryRefresher.setMods( + activeModList, std::set(archives.begin(), archives.end())); + + QTimer::singleShot(0, &m_DirectoryRefresher, SLOT(refresh())); + } +} + +void OrganizerCore::directory_refreshed() +{ + DirectoryEntry *newStructure = m_DirectoryRefresher.getDirectoryStructure(); + Q_ASSERT(newStructure != m_DirectoryStructure); + if (newStructure != nullptr) { + std::swap(m_DirectoryStructure, newStructure); + delete newStructure; + } else { + // TODO: don't know why this happens, this slot seems to get called twice + // with only one emit + return; + } + m_DirectoryUpdate = false; + + for (int i = 0; i < m_ModList.rowCount(); ++i) { + ModInfo::Ptr modInfo = ModInfo::getByIndex(i); + modInfo->clearCaches(); + } + for (auto task : m_PostRefreshTasks) { + task(); + } + m_PostRefreshTasks.clear(); + + if (m_CurrentProfile != nullptr) { + refreshLists(); + } +} + +void OrganizerCore::profileRefresh() +{ + // have to refresh mods twice (again in refreshModList), otherwise the refresh + // isn't complete. Not sure why + ModInfo::updateFromDisc(m_Settings.getModDirectory(), &m_DirectoryStructure, + m_PluginContainer, m_Settings.displayForeign(), managedGame()); + m_CurrentProfile->refreshModStatus(); + + refreshModList(); +} + +void OrganizerCore::modStatusChanged(unsigned int index) +{ + try { + ModInfo::Ptr modInfo = ModInfo::getByIndex(index); + if (m_CurrentProfile->modEnabled(index)) { + updateModInDirectoryStructure(index, modInfo); + } else { + updateModActiveState(index, false); + if (m_DirectoryStructure->originExists(ToWString(modInfo->name()))) { + FilesOrigin &origin + = m_DirectoryStructure->getOriginByName(ToWString(modInfo->name())); + origin.enable(false); + } + if (m_UserInterface != nullptr) { + m_UserInterface->archivesWriter().write(); + } + } + modInfo->clearCaches(); + + for (unsigned int i = 0; i < m_CurrentProfile->numMods(); ++i) { + ModInfo::Ptr modInfo = ModInfo::getByIndex(i); + int priority = m_CurrentProfile->getModPriority(i); + if (m_DirectoryStructure->originExists(ToWString(modInfo->name()))) { + // priorities in the directory structure are one higher because data is + // 0 + m_DirectoryStructure->getOriginByName(ToWString(modInfo->name())) + .setPriority(priority + 1); + } + } + m_DirectoryStructure->getFileRegister()->sortOrigins(); + + refreshLists(); + } catch (const std::exception &e) { + reportError(tr("failed to update mod list: %1").arg(e.what())); + } +} + +void OrganizerCore::modStatusChanged(QList index) { + try { + QMap modsToEnable; + QMap modsToDisable; + for (auto idx : index) { + if (m_CurrentProfile->modEnabled(idx)) { + modsToEnable[idx] = ModInfo::getByIndex(idx); + } else { + modsToDisable[idx] = ModInfo::getByIndex(idx); + } + } + if (!modsToEnable.isEmpty()) { + updateModsInDirectoryStructure(modsToEnable); + for (auto modInfo : modsToEnable.values()) { + modInfo->clearCaches(); + } + } + if (!modsToDisable.isEmpty()) { + updateModsActiveState(modsToDisable.keys(), false); + for (auto idx : modsToDisable.keys()) { + if (m_DirectoryStructure->originExists(ToWString(modsToDisable[idx]->name()))) { + FilesOrigin &origin + = m_DirectoryStructure->getOriginByName(ToWString(modsToDisable[idx]->name())); + origin.enable(false); + } + } + if (m_UserInterface != nullptr) { + m_UserInterface->archivesWriter().write(); + } + } + + for (unsigned int i = 0; i < m_CurrentProfile->numMods(); ++i) { + ModInfo::Ptr modInfo = ModInfo::getByIndex(i); + int priority = m_CurrentProfile->getModPriority(i); + if (m_DirectoryStructure->originExists(ToWString(modInfo->name()))) { + // priorities in the directory structure are one higher because data is + // 0 + m_DirectoryStructure->getOriginByName(ToWString(modInfo->name())) + .setPriority(priority + 1); + } + } + m_DirectoryStructure->getFileRegister()->sortOrigins(); + + refreshLists(); + } catch (const std::exception &e) { + reportError(tr("failed to update mod list: %1").arg(e.what())); + } +} + +void OrganizerCore::loginSuccessful(bool necessary) +{ + if (necessary) { + MessageDialog::showMessage(tr("login successful"), qApp->activeWindow()); + } + for (QString url : m_PendingDownloads) { + downloadRequestedNXM(url); + } + m_PendingDownloads.clear(); + for (auto task : m_PostLoginTasks) { + task(); + } + + m_PostLoginTasks.clear(); + NexusInterface::instance(m_PluginContainer)->loginCompleted(); +} + +void OrganizerCore::loginSuccessfulUpdate(bool necessary) +{ + if (necessary) { + MessageDialog::showMessage(tr("login successful"), qApp->activeWindow()); + } + m_Updater.startUpdate(); +} + +void OrganizerCore::loginFailed(const QString &message) +{ + if (QMessageBox::question(qApp->activeWindow(), tr("Login failed"), + tr("Login failed, try again?")) + == QMessageBox::Yes) { + if (nexusApi(true)) { + return; + } + } + + if (!m_PendingDownloads.isEmpty()) { + MessageDialog::showMessage( + tr("login failed: %1. Download will not be associated with an account") + .arg(message), + qApp->activeWindow()); + for (QString url : m_PendingDownloads) { + downloadRequestedNXM(url); + } + m_PendingDownloads.clear(); + } else { + MessageDialog::showMessage(tr("login failed: %1").arg(message), + qApp->activeWindow()); + m_PostLoginTasks.clear(); + } + NexusInterface::instance(m_PluginContainer)->loginCompleted(); +} + +void OrganizerCore::loginFailedUpdate(const QString &message) +{ + MessageDialog::showMessage( + tr("login failed: %1. You need to log-in with Nexus to update MO.") + .arg(message), + qApp->activeWindow()); +} + +void OrganizerCore::syncOverwrite() +{ + unsigned int overwriteIndex = ModInfo::findMod([](ModInfo::Ptr mod) -> bool { + std::vector flags = mod->getFlags(); + return std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) + != flags.end(); + }); + + ModInfo::Ptr modInfo = ModInfo::getByIndex(overwriteIndex); + SyncOverwriteDialog syncDialog(modInfo->absolutePath(), m_DirectoryStructure, + qApp->activeWindow()); + if (syncDialog.exec() == QDialog::Accepted) { + syncDialog.apply(QDir::fromNativeSeparators(m_Settings.getModDirectory())); + modInfo->testValid(); + refreshDirectoryStructure(); + } +} + +QString OrganizerCore::oldMO1HookDll() const +{ + if (auto extender = managedGame()->feature()) { + QString hookdll = QDir::toNativeSeparators( + managedGame()->dataDirectory().absoluteFilePath(extender->PluginPath() + "/hook.dll")); + if (QFile(hookdll).exists()) + return hookdll; + } + return QString(); +} + +std::vector OrganizerCore::activeProblems() const +{ + std::vector problems; + const auto& hookdll = oldMO1HookDll(); + if (!hookdll.isEmpty()) { + // This warning will now be shown every time the problems are checked, which is a bit + // of a "log spam". But since this is a sevre error which will most likely make the + // game crash/freeze/etc. and is very hard to diagnose, this "log spam" will make it + // easier for the user to notice the warning. + qWarning("hook.dll found in game folder: %s", qUtf8Printable(hookdll)); + problems.push_back(PROBLEM_MO1SCRIPTEXTENDERWORKAROUND); + } + return problems; +} + +QString OrganizerCore::shortDescription(unsigned int key) const +{ + switch (key) { + case PROBLEM_MO1SCRIPTEXTENDERWORKAROUND: { + return tr("MO1 \"Script Extender\" load mechanism has left hook.dll in your game folder"); + } break; + default: { + return tr("Description missing"); + } break; + } +} + +QString OrganizerCore::fullDescription(unsigned int key) const +{ + switch (key) { + case PROBLEM_MO1SCRIPTEXTENDERWORKAROUND: { + return tr("hook.dll has been found in your game folder (right click to copy the full path). " + "This is most likely a leftover of setting the ModOrganizer 1 load mechanism to \"Script Extender\", " + "in which case you must remove this file either by changing the load mechanism in ModOrganizer 1 or " + "manually removing the file, otherwise the game is likely to crash and burn.").arg(oldMO1HookDll()); + break; + } + default: { + return tr("Description missing"); + } break; + } +} + +bool OrganizerCore::hasGuidedFix(unsigned int) const +{ + return false; +} + +void OrganizerCore::startGuidedFix(unsigned int) const +{ +} + +bool OrganizerCore::saveCurrentLists() +{ + if (m_DirectoryUpdate) { + qWarning("not saving lists during directory update"); + return false; + } + + try { + savePluginList(); + if (m_UserInterface != nullptr) { + m_UserInterface->archivesWriter().write(); + } + } catch (const std::exception &e) { + reportError(tr("failed to save load order: %1").arg(e.what())); + } + + return true; +} + +void OrganizerCore::savePluginList() +{ + if (m_DirectoryUpdate) { + // delay save till after directory update + m_PostRefreshTasks.append([this]() { + this->savePluginList(); + }); + return; + } + m_PluginList.saveTo(m_CurrentProfile->getLockedOrderFileName(), + m_CurrentProfile->getDeleterFileName(), + m_Settings.hideUncheckedPlugins()); + m_PluginList.saveLoadOrder(*m_DirectoryStructure); +} + +void OrganizerCore::prepareStart() +{ + if (m_CurrentProfile == nullptr) { + return; + } + m_CurrentProfile->writeModlist(); + m_CurrentProfile->createTweakedIniFile(); + saveCurrentLists(); + m_Settings.setupLoadMechanism(); + storeSettings(); +} + +std::vector OrganizerCore::fileMapping(const QString &profileName, + const QString &customOverwrite) +{ + // need to wait until directory structure + while (m_DirectoryUpdate) { + ::Sleep(100); + QCoreApplication::processEvents(); + } + + IPluginGame *game = qApp->property("managed_game").value(); + Profile profile(QDir(m_Settings.getProfileDirectory() + "/" + profileName), + game); + + MappingType result; + + QString dataPath + = QDir::toNativeSeparators(game->dataDirectory().absolutePath()); + + bool overwriteActive = false; + + for (auto mod : profile.getActiveMods()) { + if (std::get<0>(mod).compare("overwrite", Qt::CaseInsensitive) == 0) { + continue; + } + + unsigned int modIndex = ModInfo::getIndex(std::get<0>(mod)); + ModInfo::Ptr modPtr = ModInfo::getByIndex(modIndex); + + bool createTarget = customOverwrite == std::get<0>(mod); + + overwriteActive |= createTarget; + + if (modPtr->isRegular()) { + result.insert(result.end(), {QDir::toNativeSeparators(std::get<1>(mod)), + dataPath, true, createTarget}); + } + } + + if (!overwriteActive && !customOverwrite.isEmpty()) { + throw MyException(tr("The designated write target \"%1\" is not enabled.") + .arg(customOverwrite)); + } + + if (m_CurrentProfile->localSavesEnabled()) { + LocalSavegames *localSaves = game->feature(); + if (localSaves != nullptr) { + MappingType saveMap + = localSaves->mappings(currentProfile()->absolutePath() + "/saves"); + result.reserve(result.size() + saveMap.size()); + result.insert(result.end(), saveMap.begin(), saveMap.end()); + } else { + qWarning("local save games not supported by this game plugin"); + } + } + + result.insert(result.end(), { + QDir::toNativeSeparators(m_Settings.getOverwriteDirectory()), + dataPath, + true, + customOverwrite.isEmpty() + }); + + for (MOBase::IPluginFileMapper *mapper : + m_PluginContainer->plugins()) { + IPlugin *plugin = dynamic_cast(mapper); + if (plugin->isActive()) { + MappingType pluginMap = mapper->mappings(); + result.reserve(result.size() + pluginMap.size()); + result.insert(result.end(), pluginMap.begin(), pluginMap.end()); + } + } + + return result; +} + + +std::vector OrganizerCore::fileMapping( + const QString &dataPath, const QString &relPath, const DirectoryEntry *base, + const DirectoryEntry *directoryEntry, int createDestination) +{ + std::vector result; + + for (FileEntry::Ptr current : directoryEntry->getFiles()) { + bool isArchive = false; + int origin = current->getOrigin(isArchive); + if (isArchive || (origin == 0)) { + continue; + } + + QString originPath + = QString::fromStdWString(base->getOriginByID(origin).getPath()); + QString fileName = QString::fromStdWString(current->getName()); +// QString fileName = ToQString(current->getName()); + QString source = originPath + relPath + fileName; + QString target = dataPath + relPath + fileName; + if (source != target) { + result.push_back({source, target, false, false}); + } + } + + // recurse into subdirectories + std::vector::const_iterator current, end; + directoryEntry->getSubDirectories(current, end); + for (; current != end; ++current) { + int origin = (*current)->anyOrigin(); + + QString originPath + = QString::fromStdWString(base->getOriginByID(origin).getPath()); + QString dirName = QString::fromStdWString((*current)->getName()); + QString source = originPath + relPath + dirName; + QString target = dataPath + relPath + dirName; + + bool writeDestination + = (base == directoryEntry) && (origin == createDestination); + + result.push_back({source, target, true, writeDestination}); + std::vector subRes = fileMapping( + dataPath, relPath + dirName + "\\", base, *current, createDestination); + result.insert(result.end(), subRes.begin(), subRes.end()); + } + return result; +} diff --git a/src/organizercore.h b/src/organizercore.h index 68d4e7e4..0a4cff6c 100644 --- a/src/organizercore.h +++ b/src/organizercore.h @@ -245,7 +245,7 @@ public slots: void requestDownload(const QUrl &url, QNetworkReply *reply); void downloadRequestedNXM(const QString &url); - bool nexusLogin(bool retry = false); + bool nexusApi(bool retry = false); signals: @@ -267,7 +267,7 @@ private: QString commitSettings(const QString &iniFile); - bool queryLogin(QString &username, QString &password); + bool queryApi(QString &apiKey); void updateModActiveState(int index, bool active); void updateModsActiveState(const QList &modIndices, bool active); @@ -341,7 +341,6 @@ private: QThread m_RefresherThread; - bool m_AskForNexusPW; bool m_DirectoryUpdate; bool m_ArchivesInit; bool m_ArchiveParsing{ m_Settings.archiveParsing() }; diff --git a/src/settings.cpp b/src/settings.cpp index 0ce647fd..7a1d6737 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -332,15 +332,12 @@ QString Settings::getNMMVersion() const return result; } -bool Settings::getNexusLogin(QString &username, QString &password) const +bool Settings::getNexusApiKey(QString &apiKey) const { - if (m_Settings.value("Settings/nexus_login", false).toBool()) { - username = m_Settings.value("Settings/nexus_username", "").toString(); - password = deObfuscate(m_Settings.value("Settings/nexus_password", "").toString()); - return true; - } else { + if (m_Settings.value("Settings/nexus_api_key", "").toString().isEmpty()) return false; - } + apiKey = deObfuscate(m_Settings.value("Settings/nexus_api_key", "").toString()); + return true; } bool Settings::getSteamLogin(QString &username, QString &password) const @@ -431,11 +428,9 @@ QString Settings::executablesBlacklist() const ).toString(); } -void Settings::setNexusLogin(QString username, QString password) +void Settings::setNexusApiKey(QString apiKey) { - m_Settings.setValue("Settings/nexus_login", true); - m_Settings.setValue("Settings/nexus_username", username); - m_Settings.setValue("Settings/nexus_password", obfuscate(password)); + m_Settings.setValue("Settings/nexus_api_key", obfuscate(apiKey)); } void Settings::setSteamLogin(QString username, QString password) @@ -674,11 +669,29 @@ void Settings::resetDialogs() QuestionBoxMemory::resetDialogs(); } +void Settings::processApiKey(const QString &apiKey) +{ + m_Settings.setValue("Settings/nexus_api_key", obfuscate(apiKey)); +} + +void Settings::checkApiKey(QPushButton *nexusButton) +{ + if (m_Settings.value("Settings/nexus_api_key", "").toString().isEmpty()) { + nexusButton->setEnabled(true); + nexusButton->setText("Connect to Nexus"); + QMessageBox::warning(qApp->activeWindow(), tr("Error"), + tr("Failed to retrieve a Nexus API key! Please try again." + "A browser window should open asking you to authorize.")); + } +} + void Settings::query(PluginContainer *pluginContainer, QWidget *parent) { SettingsDialog dialog(pluginContainer, parent); connect(&dialog, SIGNAL(resetDialogs()), this, SLOT(resetDialogs())); + connect(&dialog, SIGNAL(processApiKey(const QString &)), this, SLOT(processApiKey(const QString &))); + connect(&dialog, SIGNAL(closeApiConnection(QPushButton *)), this, SLOT(checkApiKey(QPushButton *))); std::vector> tabs; @@ -960,9 +973,7 @@ void Settings::DiagnosticsTab::update() Settings::NexusTab::NexusTab(Settings *parent, SettingsDialog &dialog) : Settings::SettingsTab(parent, dialog) - , m_loginCheckBox(dialog.findChild("loginCheckBox")) - , m_usernameEdit(dialog.findChild("usernameEdit")) - , m_passwordEdit(dialog.findChild("passwordEdit")) + , m_nexusConnect(dialog.findChild("nexusConnect")) , m_offlineBox(dialog.findChild("offlineBox")) , m_proxyBox(dialog.findChild("proxyBox")) , m_knownServersList(dialog.findChild("knownServersList")) @@ -970,10 +981,9 @@ Settings::NexusTab::NexusTab(Settings *parent, SettingsDialog &dialog) dialog.findChild("preferredServersList")) , m_endorsementBox(dialog.findChild("endorsementBox")) { - if (parent->automaticLoginEnabled()) { - m_loginCheckBox->setChecked(true); - m_usernameEdit->setText(m_Settings.value("Settings/nexus_username", "").toString()); - m_passwordEdit->setText(deObfuscate(m_Settings.value("Settings/nexus_password", "").toString())); + if (!m_Settings.value("Settings/nexus_api_key", "").toString().isEmpty()) { + m_nexusConnect->setText("Nexus API Key Stored"); + m_nexusConnect->setDisabled(true); } m_offlineBox->setChecked(parent->offlineMode()); @@ -1009,6 +1019,7 @@ Settings::NexusTab::NexusTab(Settings *parent, SettingsDialog &dialog) void Settings::NexusTab::update() { + /* if (m_loginCheckBox->isChecked()) { m_Settings.setValue("Settings/nexus_login", true); m_Settings.setValue("Settings/nexus_username", m_usernameEdit->text()); @@ -1018,6 +1029,7 @@ void Settings::NexusTab::update() m_Settings.remove("Settings/nexus_username"); m_Settings.remove("Settings/nexus_password"); } + */ m_Settings.setValue("Settings/offline_mode", m_offlineBox->isChecked()); m_Settings.setValue("Settings/use_proxy", m_proxyBox->isChecked()); m_Settings.setValue("Settings/endorsement_integration", m_endorsementBox->isChecked()); diff --git a/src/settings.h b/src/settings.h index 0286d4db..49e5a5b6 100644 --- a/src/settings.h +++ b/src/settings.h @@ -25,6 +25,7 @@ along with Mod Organizer. If not, see . #include #include #include +#include #include #include #include @@ -188,7 +189,7 @@ public: * @param password (out) received the password for nexus * @return true if automatic login is active, false otherwise **/ - bool getNexusLogin(QString &username, QString &password) const; + bool getNexusApiKey(QString &apiKey) const; /** * @brief retrieve the login information for steam @@ -249,7 +250,7 @@ public: * @param username username * @param password password */ - void setNexusLogin(QString username, QString password); + void setNexusApiKey(QString apiKey); /** * @brief set the steam login information @@ -475,13 +476,10 @@ private: { public: NexusTab(Settings *m_parent, SettingsDialog &m_dialog); - void update(); private: - QCheckBox *m_loginCheckBox; - QLineEdit *m_usernameEdit; - QLineEdit *m_passwordEdit; + QPushButton *m_nexusConnect; QCheckBox *m_offlineBox; QCheckBox *m_proxyBox; QListWidget *m_knownServersList; @@ -537,6 +535,8 @@ private: private slots: void resetDialogs(); + void processApiKey(const QString &); + void checkApiKey(QPushButton *nexusButton); signals: diff --git a/src/settingsdialog.cpp b/src/settingsdialog.cpp index 1bbc256f..4843dea5 100644 --- a/src/settingsdialog.cpp +++ b/src/settingsdialog.cpp @@ -29,12 +29,17 @@ along with Mod Organizer. If not, see . #include "nexusinterface.h" #include "plugincontainer.h" +#include +#include + #include #include #include #include #include #include +#include +#include #define WIN32_LEAN_AND_MEAN #include @@ -46,6 +51,7 @@ SettingsDialog::SettingsDialog(PluginContainer *pluginContainer, QWidget *parent : TutorableDialog("SettingsDialog", parent) , ui(new Ui::SettingsDialog) , m_PluginContainer(pluginContainer) + , m_nexusLogin(new QWebSocket) { ui->setupUi(this); ui->pluginSettingsList->setStyleSheet("QTreeWidget::item {padding-right: 10px;}"); @@ -53,6 +59,9 @@ SettingsDialog::SettingsDialog(PluginContainer *pluginContainer, QWidget *parent QShortcut *delShortcut = new QShortcut(QKeySequence(Qt::Key_Delete), ui->pluginBlacklist); connect(delShortcut, SIGNAL(activated()), this, SLOT(deleteBlacklistItem())); + connect(m_nexusLogin, SIGNAL(connected()), this, SLOT(dispatchLogin())); + connect(m_nexusLogin, SIGNAL(textMessageReceived(const QString &)), this, SLOT(receiveApiKey(const QString &))); + connect(m_nexusLogin, SIGNAL(disconnected()), this, SLOT(completeApiConnection())); } SettingsDialog::~SettingsDialog() @@ -326,6 +335,39 @@ void SettingsDialog::on_resetDialogsButton_clicked() } } +void SettingsDialog::on_nexusConnect_clicked() +{ + ui->nexusConnect->setText("Connecting the API..."); + ui->nexusConnect->setDisabled(true); + QUrl url = QUrl("wss://sso.nexusmods.com:8443"); + m_nexusLogin->open(url); +} + +void SettingsDialog::dispatchLogin() +{ + QJsonObject login; + boost::uuids::random_generator generator; + boost::uuids::uuid sessionId = generator(); + login.insert(QString("id"), QJsonValue(QString(boost::uuids::to_string(sessionId).c_str()))); + login.insert(QString("appid"), QJsonValue(QString("MO2"))); + QJsonDocument loginDoc(login); + QString finalMessage(loginDoc.toJson()); + m_nexusLogin->sendTextMessage(finalMessage); + QDesktopServices::openUrl(QUrl(QString("https://www.nexusmods.com/sso?id=") + QString(boost::uuids::to_string(sessionId).c_str()))); +} + +void SettingsDialog::receiveApiKey(const QString &apiKey) +{ + emit processApiKey(apiKey); + m_nexusLogin->close(); + ui->nexusConnect->setText("Nexus API Key Stored"); +} + +void SettingsDialog::completeApiConnection() +{ + emit closeApiConnection(ui->nexusConnect); +} + void SettingsDialog::storeSettings(QListWidgetItem *pluginItem) { if (pluginItem != nullptr) { diff --git a/src/settingsdialog.h b/src/settingsdialog.h index 6357f064..90b60c91 100644 --- a/src/settingsdialog.h +++ b/src/settingsdialog.h @@ -1,163 +1,177 @@ -/* -Copyright (C) 2012 Sebastian Herbord. All rights reserved. - -This file is part of Mod Organizer. - -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 . -*/ - -#ifndef SETTINGSDIALOG_H -#define SETTINGSDIALOG_H - -#include "tutorabledialog.h" -#include -#include -#include - -class PluginContainer; - -namespace Ui { - class SettingsDialog; -} - -/** - * dialog used to change settings for Mod Organizer. On top of the - * settings managed by the "Settings" class, this offers a button to open the - * CategoriesDialog - **/ -class SettingsDialog : public MOBase::TutorableDialog -{ - Q_OBJECT - -public: - explicit SettingsDialog(PluginContainer *pluginContainer, QWidget *parent = 0); - ~SettingsDialog(); - - /** - * @brief get stylesheet of settings buttons with colored background - * @return string of stylesheet - */ - QString getColoredButtonStyleSheet() const; - - void setButtonColor(QPushButton *button, QColor &color); - -public slots: - - virtual void accept(); - -signals: - - void resetDialogs(); - -private: - - void storeSettings(QListWidgetItem *pluginItem); - void normalizePath(QLineEdit *lineEdit); - -public: - - QColor getOverwritingColor() { return m_OverwritingColor; } - QColor getOverwrittenColor() { return m_OverwrittenColor; } - QColor getOverwritingArchiveColor() { return m_OverwritingArchiveColor; } - QColor getOverwrittenArchiveColor() { return m_OverwrittenArchiveColor; } - QColor getContainsColor() { return m_ContainsColor; } - QColor getContainedColor() { return m_ContainedColor; } - QString getExecutableBlacklist() { return m_ExecutableBlacklist; } - bool getResetGeometries(); - - void setOverwritingColor(QColor col) { m_OverwritingColor = col; } - void setOverwrittenColor(QColor col) { m_OverwrittenColor = col; } - void setOverwritingArchiveColor(QColor col) { m_OverwritingArchiveColor = col; } - void setOverwrittenArchiveColor(QColor col) { m_OverwrittenArchiveColor = col; } - void setContainsColor(QColor col) { m_ContainsColor = col; } - void setContainedColor(QColor col) { m_ContainedColor = col; } - void setExecutableBlacklist(QString blacklist) { m_ExecutableBlacklist = blacklist; } - - -private slots: - void on_loginCheckBox_toggled(bool checked); - - void on_categoriesBtn_clicked(); - - void on_execBlacklistBtn_clicked(); - - void on_bsaDateBtn_clicked(); - - void on_browseDownloadDirBtn_clicked(); - - void on_browseModDirBtn_clicked(); - - void on_browseCacheDirBtn_clicked(); - - void on_resetDialogsButton_clicked(); - - void on_pluginsList_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous); - - void deleteBlacklistItem(); - - void on_associateButton_clicked(); - - void on_clearCacheButton_clicked(); - - void on_browseBaseDirBtn_clicked(); - - void on_browseOverwriteDirBtn_clicked(); - - void on_browseProfilesDirBtn_clicked(); - - void on_browseGameDirBtn_clicked(); - - void on_overwritingBtn_clicked(); - - void on_overwrittenBtn_clicked(); - - void on_overwritingArchiveBtn_clicked(); - - void on_overwrittenArchiveBtn_clicked(); - - void on_containsBtn_clicked(); - - void on_containedBtn_clicked(); - - void on_resetColorsBtn_clicked(); - - void on_baseDirEdit_editingFinished(); - - void on_downloadDirEdit_editingFinished(); - - void on_modDirEdit_editingFinished(); - - void on_cacheDirEdit_editingFinished(); - - void on_profilesDirEdit_editingFinished(); - - void on_overwriteDirEdit_editingFinished(); - -private: - Ui::SettingsDialog *ui; - PluginContainer *m_PluginContainer; - - QColor m_OverwritingColor; - QColor m_OverwrittenColor; - QColor m_OverwritingArchiveColor; - QColor m_OverwrittenArchiveColor; - QColor m_ContainsColor; - QColor m_ContainedColor; - - QString m_ExecutableBlacklist; -}; - - - -#endif // SETTINGSDIALOG_H +/* +Copyright (C) 2012 Sebastian Herbord. All rights reserved. + +This file is part of Mod Organizer. + +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 . +*/ + +#ifndef SETTINGSDIALOG_H +#define SETTINGSDIALOG_H + +#include "tutorabledialog.h" +#include +#include +#include +#include +#include + +class PluginContainer; + +namespace Ui { + class SettingsDialog; +} + +/** + * dialog used to change settings for Mod Organizer. On top of the + * settings managed by the "Settings" class, this offers a button to open the + * CategoriesDialog + **/ +class SettingsDialog : public MOBase::TutorableDialog +{ + Q_OBJECT + +public: + explicit SettingsDialog(PluginContainer *pluginContainer, QWidget *parent = 0); + ~SettingsDialog(); + + /** + * @brief get stylesheet of settings buttons with colored background + * @return string of stylesheet + */ + QString getColoredButtonStyleSheet() const; + + void setButtonColor(QPushButton *button, QColor &color); + +public slots: + + virtual void accept(); + +signals: + + void resetDialogs(); + void processApiKey(const QString &); + void closeApiConnection(QPushButton *); + +private: + + void storeSettings(QListWidgetItem *pluginItem); + void normalizePath(QLineEdit *lineEdit); + +public: + + QColor getOverwritingColor() { return m_OverwritingColor; } + QColor getOverwrittenColor() { return m_OverwrittenColor; } + QColor getOverwritingArchiveColor() { return m_OverwritingArchiveColor; } + QColor getOverwrittenArchiveColor() { return m_OverwrittenArchiveColor; } + QColor getContainsColor() { return m_ContainsColor; } + QColor getContainedColor() { return m_ContainedColor; } + QString getExecutableBlacklist() { return m_ExecutableBlacklist; } + bool getResetGeometries(); + + void setOverwritingColor(QColor col) { m_OverwritingColor = col; } + void setOverwrittenColor(QColor col) { m_OverwrittenColor = col; } + void setOverwritingArchiveColor(QColor col) { m_OverwritingArchiveColor = col; } + void setOverwrittenArchiveColor(QColor col) { m_OverwrittenArchiveColor = col; } + void setContainsColor(QColor col) { m_ContainsColor = col; } + void setContainedColor(QColor col) { m_ContainedColor = col; } + void setExecutableBlacklist(QString blacklist) { m_ExecutableBlacklist = blacklist; } + + +private slots: + void on_loginCheckBox_toggled(bool checked); + + void on_categoriesBtn_clicked(); + + void on_execBlacklistBtn_clicked(); + + void on_bsaDateBtn_clicked(); + + void on_browseDownloadDirBtn_clicked(); + + void on_browseModDirBtn_clicked(); + + void on_browseCacheDirBtn_clicked(); + + void on_resetDialogsButton_clicked(); + + void on_pluginsList_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous); + + void deleteBlacklistItem(); + + void on_associateButton_clicked(); + + void on_clearCacheButton_clicked(); + + void on_browseBaseDirBtn_clicked(); + + void on_browseOverwriteDirBtn_clicked(); + + void on_browseProfilesDirBtn_clicked(); + + void on_browseGameDirBtn_clicked(); + + void on_overwritingBtn_clicked(); + + void on_overwrittenBtn_clicked(); + + void on_overwritingArchiveBtn_clicked(); + + void on_overwrittenArchiveBtn_clicked(); + + void on_containsBtn_clicked(); + + void on_containedBtn_clicked(); + + void on_resetColorsBtn_clicked(); + + void on_baseDirEdit_editingFinished(); + + void on_downloadDirEdit_editingFinished(); + + void on_modDirEdit_editingFinished(); + + void on_cacheDirEdit_editingFinished(); + + void on_profilesDirEdit_editingFinished(); + + void on_overwriteDirEdit_editingFinished(); + + void on_nexusConnect_clicked(); + + void dispatchLogin(); + + void receiveApiKey(const QString &apiKey); + + void completeApiConnection(); + +private: + Ui::SettingsDialog *ui; + PluginContainer *m_PluginContainer; + + QColor m_OverwritingColor; + QColor m_OverwrittenColor; + QColor m_OverwritingArchiveColor; + QColor m_OverwrittenArchiveColor; + QColor m_ContainsColor; + QColor m_ContainedColor; + + QString m_ExecutableBlacklist; + + QWebSocket *m_nexusLogin; +}; + + + +#endif // SETTINGSDIALOG_H diff --git a/src/settingsdialog.ui b/src/settingsdialog.ui index c865744e..d3628ab3 100644 --- a/src/settingsdialog.ui +++ b/src/settingsdialog.ui @@ -468,49 +468,12 @@ p, li { white-space: pre-wrap; } Nexus
    - - - - - - - If checked and if correct credentials are entered below, log-in to Nexus (for browsing and downloading) is automatic. - - - Automatically Log-In to Nexus - - - - + - Username - - - - - - - false - - - - - - - Password - - - - - - - false - - - QLineEdit::Password + Connect to Nexus @@ -1387,9 +1350,6 @@ programs you are intentionally running. browseProfilesDirBtn overwriteDirEdit browseOverwriteDirBtn - loginCheckBox - usernameEdit - passwordEdit clearCacheButton associateButton knownServersList -- cgit v1.3.1 From 7de78b6697b60ac20add32b5b9140b04da973be8 Mon Sep 17 00:00:00 2001 From: Silarn Date: Sun, 27 Jan 2019 03:43:18 -0600 Subject: Several Nexus API-related changes * Added 30-second ping so Nexus doesn't close our connection * Set an overall 5 minute timeout before we give up listening for auth * Fixed some old signal and slot connections * Added a button to revoke the current API authorization * Updated bulk endorsement function with new API changes --- src/main.cpp | 1480 ++++++++++++------------ src/mainwindow.cpp | 37 +- src/mainwindow.h | 1316 ++++++++++----------- src/nxmaccessmanager.cpp | 2 +- src/organizer_en.ts | 2819 ++++++++++++++++++++++++++------------------- src/organizercore.cpp | 4 +- src/settings.cpp | 8 + src/settings.h | 1 + src/settingsdialog.cpp | 48 +- src/settingsdialog.h | 10 +- src/settingsdialog.ui | 2837 +++++++++++++++++++++++----------------------- 11 files changed, 4554 insertions(+), 4008 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/main.cpp b/src/main.cpp index 631ec5b5..a8942b1a 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,740 +1,740 @@ -/* -Copyright (C) 2012 Sebastian Herbord. All rights reserved. - -This file is part of Mod Organizer. - -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 . -*/ - - -#ifdef LEAK_CHECK_WITH_VLD -#include -#include -#endif // LEAK_CHECK_WITH_VLD - -#define WIN32_LEAN_AND_MEAN -#include -#include - -#include -#include -#include -#include "mainwindow.h" -#include -#include "modlist.h" -#include "profile.h" -#include "spawn.h" -#include "executableslist.h" -#include "singleinstance.h" -#include "utility.h" -#include "helper.h" -#include "logbuffer.h" -#include "selectiondialog.h" -#include "moapplication.h" -#include "tutorialmanager.h" -#include "nxmaccessmanager.h" -#include "instancemanager.h" -#include "moshortcut.h" -#include "organizercore.h" - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include - -#include -#include -#include -#include - - -#pragma comment(linker, "/manifestDependency:\"name='dlls' processorArchitecture='x86' version='1.0.0.0' type='win32' \"") - - -using namespace MOBase; -using namespace MOShared; - -bool createAndMakeWritable(const std::wstring &subPath) { - QString const dataPath = qApp->property("dataPath").toString(); - QString fullPath = dataPath + "/" + QString::fromStdWString(subPath); - - if (!QDir(fullPath).exists() && !QDir().mkdir(fullPath)) { - QMessageBox::critical(nullptr, QObject::tr("Error"), - QObject::tr("Failed to create \"%1\". Your user " - "account probably lacks permission.") - .arg(fullPath)); - return false; - } else { - return true; - } -} - -bool bootstrap() -{ - // remove the temporary backup directory in case we're restarting after an update - QString backupDirectory = qApp->applicationDirPath() + "/update_backup"; - if (QDir(backupDirectory).exists()) { - shellDelete(QStringList(backupDirectory)); - } - - // cycle logfile - removeOldFiles(qApp->property("dataPath").toString() + "/" + QString::fromStdWString(AppConfig::logPath()), - "usvfs*.log", 5, QDir::Name); - - if (!createAndMakeWritable(AppConfig::logPath())) { - return false; - } - - return true; -} - -LPTOP_LEVEL_EXCEPTION_FILTER prevUnhandledExceptionFilter = nullptr; - -static LONG WINAPI MyUnhandledExceptionFilter(struct _EXCEPTION_POINTERS *exceptionPtrs) -{ - const std::wstring& dumpPath = OrganizerCore::crashDumpsPath(); - int dumpRes = - CreateMiniDump(exceptionPtrs, OrganizerCore::getGlobalCrashDumpsType(), dumpPath.c_str()); - if (!dumpRes) - qCritical("ModOrganizer has crashed, crash dump created."); - else - qCritical("ModOrganizer has crashed, CreateMiniDump failed (%d, error %lu).", dumpRes, GetLastError()); - - if (prevUnhandledExceptionFilter) - return prevUnhandledExceptionFilter(exceptionPtrs); - else - return EXCEPTION_CONTINUE_SEARCH; -} - -// Parses the first parseArgCount arguments of the current process command line and returns -// them in parsedArgs, the rest of the command line is returned untouched. -LPCWSTR UntouchedCommandLineArguments(int parseArgCount, std::vector& parsedArgs) -{ - LPCWSTR cmd = GetCommandLineW(); - LPCWSTR arg = nullptr; // to skip executable name - for (; parseArgCount >= 0 && *cmd; ++cmd) - { - if (*cmd == '"') { - int escaped = 0; - for (++cmd; *cmd && (*cmd != '"' || escaped % 2 != 0); ++cmd) - escaped = *cmd == '\\' ? escaped + 1 : 0; - } - if (*cmd == ' ') { - if (arg) - if (cmd-1 > arg && *arg == '"' && *(cmd-1) == '"') - parsedArgs.push_back(std::wstring(arg+1, cmd-1)); - else - parsedArgs.push_back(std::wstring(arg, cmd)); - arg = cmd + 1; - --parseArgCount; - } - } - return cmd; -} - -static int SpawnWaitProcess(LPCWSTR workingDirectory, LPCWSTR commandLine) { - PROCESS_INFORMATION pi{ 0 }; - STARTUPINFO si{ 0 }; - si.cb = sizeof(si); - std::wstring commandLineCopy = commandLine; - - if (!CreateProcessW(NULL, &commandLineCopy[0], NULL, NULL, FALSE, 0, NULL, workingDirectory, &si, &pi)) { - // A bit of a problem where to log the error message here, at least this way you can get the message - // using a either DebugView or a live debugger: - std::wostringstream ost; - ost << L"CreateProcess failed: " << commandLine << ", " << GetLastError(); - OutputDebugStringW(ost.str().c_str()); - return -1; - } - - WaitForSingleObject(pi.hProcess, INFINITE); - - DWORD exitCode = (DWORD)-1; - ::GetExitCodeProcess(pi.hProcess, &exitCode); - CloseHandle(pi.hThread); - CloseHandle(pi.hProcess); - return static_cast(exitCode); -} - -static DWORD WaitForProcess() { - -} - -static bool HaveWriteAccess(const std::wstring &path) -{ - bool writable = false; - - const static SECURITY_INFORMATION requestedFileInformation = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION; - - DWORD length = 0; - if (!::GetFileSecurityW(path.c_str(), requestedFileInformation, nullptr, 0UL, &length) - && (::GetLastError() == ERROR_INSUFFICIENT_BUFFER)) { - std::string tempBuffer; - tempBuffer.reserve(length); - PSECURITY_DESCRIPTOR security = (PSECURITY_DESCRIPTOR)tempBuffer.data(); - if (security - && ::GetFileSecurity(path.c_str(), requestedFileInformation, security, length, &length)) { - HANDLE token = nullptr; - const static DWORD tokenDesiredAccess = TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_DUPLICATE | STANDARD_RIGHTS_READ; - if (!::OpenThreadToken(::GetCurrentThread(), tokenDesiredAccess, TRUE, &token)) { - if (!::OpenProcessToken(::GetCurrentProcess(), tokenDesiredAccess, &token)) { - throw std::runtime_error("Unable to get any thread or process token"); - } - } - - HANDLE impersonatedToken = nullptr; - if (::DuplicateToken(token, SecurityImpersonation, &impersonatedToken)) { - GENERIC_MAPPING mapping = { 0xFFFFFFFF }; - mapping.GenericRead = FILE_GENERIC_READ; - mapping.GenericWrite = FILE_GENERIC_WRITE; - mapping.GenericExecute = FILE_GENERIC_EXECUTE; - mapping.GenericAll = FILE_ALL_ACCESS; - - DWORD genericAccessRights = FILE_GENERIC_WRITE; - ::MapGenericMask(&genericAccessRights, &mapping); - - PRIVILEGE_SET privileges = { 0 }; - DWORD grantedAccess = 0; - DWORD privilegesLength = sizeof(privileges); - BOOL result = 0; - if (::AccessCheck(security, impersonatedToken, genericAccessRights, &mapping, &privileges, &privilegesLength, &grantedAccess, &result)) { - writable = result != 0; - } - ::CloseHandle(impersonatedToken); - } - - ::CloseHandle(token); - } - } - return writable; -} - - -QString determineProfile(QStringList &arguments, const QSettings &settings) -{ - QString selectedProfileName = QString::fromUtf8(settings.value("selected_profile", "").toByteArray()); - { // see if there is a profile on the command line - int profileIndex = arguments.indexOf("-p", 1); - if ((profileIndex != -1) && (profileIndex < arguments.size() - 1)) { - qDebug("profile overwritten on command line"); - selectedProfileName = arguments.at(profileIndex + 1); - } - arguments.removeAt(profileIndex); - arguments.removeAt(profileIndex); - } - if (selectedProfileName.isEmpty()) { - qDebug("no configured profile"); - selectedProfileName = "Default"; - } else { - qDebug("configured profile: %s", qUtf8Printable(selectedProfileName)); - } - - return selectedProfileName; -} - -MOBase::IPluginGame *selectGame(QSettings &settings, QDir const &gamePath, MOBase::IPluginGame *game) -{ - settings.setValue("gameName", game->gameName()); - //Sadly, hookdll needs gamePath in order to run. So following code block is - //commented out - /*if (gamePath == game->gameDirectory()) { - settings.remove("gamePath"); - } else*/ { - QString gameDir = gamePath.absolutePath(); - game->setGamePath(gameDir); - settings.setValue("gamePath", QDir::toNativeSeparators(gameDir).toUtf8().constData()); - } - return game; //Woot -} - - -MOBase::IPluginGame *determineCurrentGame(QString const &moPath, QSettings &settings, PluginContainer const &plugins) -{ - //Determine what game we are running where. Be very paranoid in case the - //user has done something odd. - //If the game name has been set up, use that. - QString gameName = settings.value("gameName", "").toString(); - if (!gameName.isEmpty()) { - MOBase::IPluginGame *game = plugins.managedGame(gameName); - if (game == nullptr) { - reportError(QObject::tr("Plugin to handle %1 no longer installed").arg(gameName)); - return nullptr; - } - QString gamePath = QString::fromUtf8(settings.value("gamePath", "").toByteArray()); - if (gamePath == "") { - gamePath = game->gameDirectory().absolutePath(); - } - QDir gameDir(gamePath); - if (game->looksValid(gameDir)) { - return selectGame(settings, gameDir, game); - } - } - - //gameName wasn't set, or otherwise can't be found. Try looking through all - //the plugins using the gamePath - QString gamePath = QString::fromUtf8(settings.value("gamePath", "").toByteArray()); - if (!gamePath.isEmpty()) { - QDir gameDir(gamePath); - //Look to see if one of the installed games binary file exists in the current - //game directory. - for (IPluginGame * const game : plugins.plugins()) { - if (game->looksValid(gameDir)) { - return selectGame(settings, gameDir, game); - } - } - } - - //The following code would try to determine the right game to mange but it would usually find the wrong one - //so it was commented out. - /* - //OK, we are in a new setup or existing info is useless. - //See if MO has been installed inside a game directory - for (IPluginGame * const game : plugins.plugins()) { - if (game->isInstalled() && moPath.startsWith(game->gameDirectory().absolutePath())) { - //Found it. - return selectGame(settings, game->gameDirectory(), game); - } - } - - //Try walking up the directory tree to see if MO has been installed inside a game - { - QDir gameDir(moPath); - do { - //Look to see if one of the installed games binary file exists in the current - //directory. - for (IPluginGame * const game : plugins.plugins()) { - if (game->looksValid(gameDir)) { - return selectGame(settings, gameDir, game); - } - } - //OK, chop off the last directory and try again - } while (gameDir.cdUp()); - } - */ - - //Then try a selection dialogue. - if (!gamePath.isEmpty() || !gameName.isEmpty()) { - reportError(QObject::tr("Could not use configuration settings for game \"%1\", path \"%2\"."). - arg(gameName).arg(gamePath)); - } - - SelectionDialog selection(QObject::tr("Please select the game to manage"), nullptr, QSize(32, 32)); - - for (IPluginGame *game : plugins.plugins()) { - if (game->isInstalled()) { - QString path = game->gameDirectory().absolutePath(); - selection.addChoice(game->gameIcon(), game->gameName(), path, QVariant::fromValue(game)); - } - } - - selection.addChoice(QString("Browse..."), QString(), QVariant::fromValue(static_cast(nullptr))); - - while (selection.exec() != QDialog::Rejected) { - IPluginGame * game = selection.getChoiceData().value(); - if (game != nullptr) { - return selectGame(settings, game->gameDirectory(), game); - } - - gamePath = QFileDialog::getExistingDirectory( - nullptr, QObject::tr("Please select the game to manage"), QString(), - QFileDialog::ShowDirsOnly); - - if (!gamePath.isEmpty()) { - QDir gameDir(gamePath); - QList possibleGames; - for (IPluginGame * const game : plugins.plugins()) { - if (game->looksValid(gameDir)) { - possibleGames.append(game); - //return selectGame(settings, gameDir, game); - } - } - if (possibleGames.count() > 1) { - SelectionDialog browseSelection(QObject::tr("Please select the game to manage"), nullptr, QSize(32, 32)); - for (IPluginGame *game : possibleGames) { - QString path = game->gameDirectory().absolutePath(); - browseSelection.addChoice(game->gameIcon(), game->gameName(), path, QVariant::fromValue(game)); - } - if (browseSelection.exec() == QDialog::Accepted) { - return selectGame(settings, gameDir, browseSelection.getChoiceData().value()); - } else { - reportError(QObject::tr("Canceled finding game in \"%1\".").arg(gamePath)); - } - } else if(possibleGames.count() == 1) { - return selectGame(settings, gameDir, possibleGames[0]); - } else { - reportError(QObject::tr("No game identified in \"%1\". The directory is required to contain " - "the game binary.").arg(gamePath)); - } - } - } - - return nullptr; -} - - -// extend path to include dll directory so plugins don't need a manifest -// (using AddDllDirectory would be an alternative to this but it seems fairly -// complicated esp. -// since it isn't easily accessible on Windows < 8 -// SetDllDirectory replaces other search directories and this seems to -// propagate to child processes) -void setupPath() -{ - static const int BUFSIZE = 4096; - - qDebug("MO at: %s", qUtf8Printable(QDir::toNativeSeparators( - QCoreApplication::applicationDirPath()))); - - QCoreApplication::setLibraryPaths(QStringList(QCoreApplication::applicationDirPath() + "/dlls") + QCoreApplication::libraryPaths()); - - boost::scoped_array oldPath(new TCHAR[BUFSIZE]); - DWORD offset = ::GetEnvironmentVariable(TEXT("PATH"), oldPath.get(), BUFSIZE); - if (offset > BUFSIZE) { - oldPath.reset(new TCHAR[offset]); - ::GetEnvironmentVariable(TEXT("PATH"), oldPath.get(), offset); - } - - std::wstring newPath(ToWString(QDir::toNativeSeparators( - QCoreApplication::applicationDirPath())) + L"\\dlls"); - newPath += L";"; - newPath += oldPath.get(); - - ::SetEnvironmentVariableW(L"PATH", newPath.c_str()); -} - -static void preloadSsl() -{ - QString appPath = QDir::toNativeSeparators(QCoreApplication::applicationDirPath()); - if (GetModuleHandleA("libeay32.dll")) - qWarning("libeay32.dll already loaded?!"); - else { - QString libeay32 = appPath + "\\libeay32.dll"; - if (!QFile::exists(libeay32)) - qWarning("libeay32.dll not found: %s", qUtf8Printable(libeay32)); - else if (!LoadLibraryW(libeay32.toStdWString().c_str())) - qWarning("failed to load: %s, %d", qUtf8Printable(libeay32), GetLastError()); - } - if (GetModuleHandleA("ssleay32.dll")) - qWarning("ssleay32.dll already loaded?!"); - else { - QString ssleay32 = appPath + "\\ssleay32.dll"; - if (!QFile::exists(ssleay32)) - qWarning("ssleay32.dll not found: %s", qUtf8Printable(ssleay32)); - else if (!LoadLibraryW(ssleay32.toStdWString().c_str())) - qWarning("failed to load: %s, %d", qUtf8Printable(ssleay32), GetLastError()); - } -} - -static QString getVersionDisplayString() -{ - return createVersionInfo().displayString(3); -} - -int runApplication(MOApplication &application, SingleInstance &instance, - const QString &splashPath) -{ - - qDebug("Starting Mod Organizer version %s revision %s", qUtf8Printable(getVersionDisplayString()), -#if defined(HGID) - HGID -#elif defined(GITID) - GITID -#else - "unknown" -#endif - ); - -#if !defined(QT_NO_SSL) - preloadSsl(); - qDebug("ssl support: %d", QSslSocket::supportsSsl()); -#else - qDebug("non-ssl build"); -#endif - - QString dataPath = application.property("dataPath").toString(); - qDebug("data path: %s", qUtf8Printable(dataPath)); - - if (!bootstrap()) { - reportError("failed to set up data paths"); - return 1; - } - - QWindowsWindowFunctions::setWindowActivationBehavior(QWindowsWindowFunctions::AlwaysActivateWindow); - - QStringList arguments = application.arguments(); - - try { - qDebug("Working directory: %s", qUtf8Printable(QDir::toNativeSeparators(QDir::currentPath()))); - - QSettings settings(dataPath + "/" - + QString::fromStdWString(AppConfig::iniFileName()), - QSettings::IniFormat); - - // global crashDumpType sits in OrganizerCore to make a bit less ugly to update it when the settings are changed during runtime - OrganizerCore::setGlobalCrashDumpsType(settings.value("Settings/crash_dumps_type", static_cast(CrashDumpsType::Mini)).toInt()); - - qDebug("Loaded settings:"); - settings.beginGroup("Settings"); - for (auto k : settings.allKeys()) - if (!k.contains("username") && !k.contains("password")) - qDebug(" %s=%s", k.toUtf8().data(), settings.value(k).toString().toUtf8().data()); - settings.endGroup(); - - - qDebug("initializing core"); - OrganizerCore organizer(settings); - if (!organizer.bootstrap()) { - reportError("failed to set up data paths"); - return 1; - } - qDebug("initialize plugins"); - PluginContainer pluginContainer(&organizer); - pluginContainer.loadPlugins(); - - MOBase::IPluginGame *game = determineCurrentGame( - application.applicationDirPath(), settings, pluginContainer); - if (game == nullptr) { - return 1; - } - if (splashPath.startsWith(':')) { - // currently using MO splash, see if the plugin contains one - QString pluginSplash - = QString(":/%1/splash").arg(game->gameShortName()); - QImage image(pluginSplash); - if (!image.isNull()) { - image.save(dataPath + "/splash.png"); - } else { - qDebug("no plugin splash"); - } - } - - organizer.setManagedGame(game); - organizer.createDefaultProfile(); - - if (!settings.contains("game_edition")) { - QStringList editions = game->gameVariants(); - if (editions.size() > 1) { - SelectionDialog selection( - QObject::tr("Please select the game edition you have (MO can't " - "start the game correctly if this is set " - "incorrectly!)"), - nullptr); - selection.setWindowFlag(Qt::WindowStaysOnTopHint, true); - int index = 0; - for (const QString &edition : editions) { - selection.addChoice(edition, "", index++); - } - if (selection.exec() == QDialog::Rejected) { - return 1; - } else { - settings.setValue("game_edition", selection.getChoiceString()); - } - } - } - game->setGameVariant(settings.value("game_edition").toString()); - - qDebug("managing game at %s", qUtf8Printable(QDir::toNativeSeparators( - game->gameDirectory().absolutePath()))); - - organizer.updateExecutablesList(settings); - - QString selectedProfileName = determineProfile(arguments, settings); - organizer.setCurrentProfile(selectedProfileName); - - // if we have a command line parameter, it is either a nxm link or - // a binary to start - if (arguments.size() > 1) { - if (MOShortcut shortcut{ arguments.at(1) }) { - if (shortcut.hasExecutable()) { - try { - organizer.runShortcut(shortcut); - return 0; - } - catch (const std::exception &e) { - reportError( - QObject::tr("failed to start shortcut: %1").arg(e.what())); - return 1; - } - } - } - else if (OrganizerCore::isNxmLink(arguments.at(1))) { - qDebug("starting download from command line: %s", - qUtf8Printable(arguments.at(1))); - organizer.externalMessage(arguments.at(1)); - } - else { - QString exeName = arguments.at(1); - qDebug("starting %s from command line", qUtf8Printable(exeName)); - arguments.removeFirst(); // remove application name (ModOrganizer.exe) - arguments.removeFirst(); // remove binary name - // pass the remaining parameters to the binary - try { - organizer.startApplication(exeName, arguments, QString(), QString()); - return 0; - } - catch (const std::exception &e) { - reportError( - QObject::tr("failed to start application: %1").arg(e.what())); - return 1; - } - } - } - - QPixmap pixmap(splashPath); - QSplashScreen splash(pixmap); - splash.show(); - splash.activateWindow(); - - QString apiKey; - if (organizer.settings().getNexusApiKey(apiKey)) { - NexusInterface::instance(&pluginContainer)->getAccessManager()->apiCheck(apiKey); - } - - qDebug("initializing tutorials"); - TutorialManager::init( - qApp->applicationDirPath() + "/" - + QString::fromStdWString(AppConfig::tutorialsPath()) + "/", - &organizer); - - if (!application.setStyleFile(settings.value("Settings/style", "").toString())) { - // disable invalid stylesheet - settings.setValue("Settings/style", ""); - } - - int res = 1; - { // scope to control lifetime of mainwindow - // set up main window and its data structures - MainWindow mainWindow(settings, organizer, pluginContainer); - - QObject::connect(&mainWindow, SIGNAL(styleChanged(QString)), &application, - SLOT(setStyleFile(QString))); - QObject::connect(&instance, SIGNAL(messageSent(QString)), &organizer, - SLOT(externalMessage(QString))); - - mainWindow.processUpdates(); - mainWindow.readSettings(); - - qDebug("displaying main window"); - mainWindow.show(); - mainWindow.activateWindow(); - - splash.finish(&mainWindow); - return application.exec(); - } - } catch (const std::exception &e) { - reportError(e.what()); - return 1; - } -} - - -int main(int argc, char *argv[]) -{ - //Should allow for better scaling of ui with higher resolution displays - QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); - - if (argc >= 4) { - std::vector arg; - auto args = UntouchedCommandLineArguments(2, arg); - if (arg[0] == L"launch") - return SpawnWaitProcess(arg[1].c_str(), args); - } - - MOApplication application(argc, argv); - QStringList arguments = application.arguments(); - - setupPath(); - - bool forcePrimary = false; - if (arguments.contains("update")) { - arguments.removeAll("update"); - forcePrimary = true; - } - - MOShortcut moshortcut{ arguments.size() > 1 ? arguments.at(1) : "" }; - - SingleInstance instance(forcePrimary); - if (!instance.primaryInstance()) { - if (moshortcut || - arguments.size() > 1 && OrganizerCore::isNxmLink(arguments.at(1))) - { - qDebug("not primary instance, sending shortcut/download message"); - instance.sendMessage(arguments.at(1)); - return 0; - } else if (arguments.size() == 1) { - QMessageBox::information( - nullptr, QObject::tr("Mod Organizer"), - QObject::tr("An instance of Mod Organizer is already running")); - return 0; - } - } // we continue for the primary instance OR if MO was called with parameters - - do { - QString dataPath; - - try { - InstanceManager& instanceManager = InstanceManager::instance(); - if (moshortcut && moshortcut.hasInstance()) - instanceManager.overrideInstance(moshortcut.instance()); - dataPath = instanceManager.determineDataPath(); - } catch (const std::exception &e) { - if (strcmp(e.what(),"Canceled")) - QMessageBox::critical(nullptr, QObject::tr("Failed to set up instance"), e.what()); - return 1; - } - application.setProperty("dataPath", dataPath); - - // initialize dump collection only after "dataPath" since the crashes are stored under it - prevUnhandledExceptionFilter = SetUnhandledExceptionFilter(MyUnhandledExceptionFilter); - - LogBuffer::init(1000, QtDebugMsg, qApp->property("dataPath").toString() + "/logs/mo_interface.log"); - - QString splash = dataPath + "/splash.png"; - if (!QFile::exists(dataPath + "/splash.png")) { - splash = ":/MO/gui/splash"; - } - - int result = runApplication(application, instance, splash); - if (result != INT_MAX) { - return result; - } - argc = 1; - moshortcut = MOShortcut(""); - } while (true); -} +/* +Copyright (C) 2012 Sebastian Herbord. All rights reserved. + +This file is part of Mod Organizer. + +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 . +*/ + + +#ifdef LEAK_CHECK_WITH_VLD +#include +#include +#endif // LEAK_CHECK_WITH_VLD + +#define WIN32_LEAN_AND_MEAN +#include +#include + +#include +#include +#include +#include "mainwindow.h" +#include +#include "modlist.h" +#include "profile.h" +#include "spawn.h" +#include "executableslist.h" +#include "singleinstance.h" +#include "utility.h" +#include "helper.h" +#include "logbuffer.h" +#include "selectiondialog.h" +#include "moapplication.h" +#include "tutorialmanager.h" +#include "nxmaccessmanager.h" +#include "instancemanager.h" +#include "moshortcut.h" +#include "organizercore.h" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +#include +#include +#include +#include + + +#pragma comment(linker, "/manifestDependency:\"name='dlls' processorArchitecture='x86' version='1.0.0.0' type='win32' \"") + + +using namespace MOBase; +using namespace MOShared; + +bool createAndMakeWritable(const std::wstring &subPath) { + QString const dataPath = qApp->property("dataPath").toString(); + QString fullPath = dataPath + "/" + QString::fromStdWString(subPath); + + if (!QDir(fullPath).exists() && !QDir().mkdir(fullPath)) { + QMessageBox::critical(nullptr, QObject::tr("Error"), + QObject::tr("Failed to create \"%1\". Your user " + "account probably lacks permission.") + .arg(fullPath)); + return false; + } else { + return true; + } +} + +bool bootstrap() +{ + // remove the temporary backup directory in case we're restarting after an update + QString backupDirectory = qApp->applicationDirPath() + "/update_backup"; + if (QDir(backupDirectory).exists()) { + shellDelete(QStringList(backupDirectory)); + } + + // cycle logfile + removeOldFiles(qApp->property("dataPath").toString() + "/" + QString::fromStdWString(AppConfig::logPath()), + "usvfs*.log", 5, QDir::Name); + + if (!createAndMakeWritable(AppConfig::logPath())) { + return false; + } + + return true; +} + +LPTOP_LEVEL_EXCEPTION_FILTER prevUnhandledExceptionFilter = nullptr; + +static LONG WINAPI MyUnhandledExceptionFilter(struct _EXCEPTION_POINTERS *exceptionPtrs) +{ + const std::wstring& dumpPath = OrganizerCore::crashDumpsPath(); + int dumpRes = + CreateMiniDump(exceptionPtrs, OrganizerCore::getGlobalCrashDumpsType(), dumpPath.c_str()); + if (!dumpRes) + qCritical("ModOrganizer has crashed, crash dump created."); + else + qCritical("ModOrganizer has crashed, CreateMiniDump failed (%d, error %lu).", dumpRes, GetLastError()); + + if (prevUnhandledExceptionFilter) + return prevUnhandledExceptionFilter(exceptionPtrs); + else + return EXCEPTION_CONTINUE_SEARCH; +} + +// Parses the first parseArgCount arguments of the current process command line and returns +// them in parsedArgs, the rest of the command line is returned untouched. +LPCWSTR UntouchedCommandLineArguments(int parseArgCount, std::vector& parsedArgs) +{ + LPCWSTR cmd = GetCommandLineW(); + LPCWSTR arg = nullptr; // to skip executable name + for (; parseArgCount >= 0 && *cmd; ++cmd) + { + if (*cmd == '"') { + int escaped = 0; + for (++cmd; *cmd && (*cmd != '"' || escaped % 2 != 0); ++cmd) + escaped = *cmd == '\\' ? escaped + 1 : 0; + } + if (*cmd == ' ') { + if (arg) + if (cmd-1 > arg && *arg == '"' && *(cmd-1) == '"') + parsedArgs.push_back(std::wstring(arg+1, cmd-1)); + else + parsedArgs.push_back(std::wstring(arg, cmd)); + arg = cmd + 1; + --parseArgCount; + } + } + return cmd; +} + +static int SpawnWaitProcess(LPCWSTR workingDirectory, LPCWSTR commandLine) { + PROCESS_INFORMATION pi{ 0 }; + STARTUPINFO si{ 0 }; + si.cb = sizeof(si); + std::wstring commandLineCopy = commandLine; + + if (!CreateProcessW(NULL, &commandLineCopy[0], NULL, NULL, FALSE, 0, NULL, workingDirectory, &si, &pi)) { + // A bit of a problem where to log the error message here, at least this way you can get the message + // using a either DebugView or a live debugger: + std::wostringstream ost; + ost << L"CreateProcess failed: " << commandLine << ", " << GetLastError(); + OutputDebugStringW(ost.str().c_str()); + return -1; + } + + WaitForSingleObject(pi.hProcess, INFINITE); + + DWORD exitCode = (DWORD)-1; + ::GetExitCodeProcess(pi.hProcess, &exitCode); + CloseHandle(pi.hThread); + CloseHandle(pi.hProcess); + return static_cast(exitCode); +} + +static DWORD WaitForProcess() { + +} + +static bool HaveWriteAccess(const std::wstring &path) +{ + bool writable = false; + + const static SECURITY_INFORMATION requestedFileInformation = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION; + + DWORD length = 0; + if (!::GetFileSecurityW(path.c_str(), requestedFileInformation, nullptr, 0UL, &length) + && (::GetLastError() == ERROR_INSUFFICIENT_BUFFER)) { + std::string tempBuffer; + tempBuffer.reserve(length); + PSECURITY_DESCRIPTOR security = (PSECURITY_DESCRIPTOR)tempBuffer.data(); + if (security + && ::GetFileSecurity(path.c_str(), requestedFileInformation, security, length, &length)) { + HANDLE token = nullptr; + const static DWORD tokenDesiredAccess = TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_DUPLICATE | STANDARD_RIGHTS_READ; + if (!::OpenThreadToken(::GetCurrentThread(), tokenDesiredAccess, TRUE, &token)) { + if (!::OpenProcessToken(::GetCurrentProcess(), tokenDesiredAccess, &token)) { + throw std::runtime_error("Unable to get any thread or process token"); + } + } + + HANDLE impersonatedToken = nullptr; + if (::DuplicateToken(token, SecurityImpersonation, &impersonatedToken)) { + GENERIC_MAPPING mapping = { 0xFFFFFFFF }; + mapping.GenericRead = FILE_GENERIC_READ; + mapping.GenericWrite = FILE_GENERIC_WRITE; + mapping.GenericExecute = FILE_GENERIC_EXECUTE; + mapping.GenericAll = FILE_ALL_ACCESS; + + DWORD genericAccessRights = FILE_GENERIC_WRITE; + ::MapGenericMask(&genericAccessRights, &mapping); + + PRIVILEGE_SET privileges = { 0 }; + DWORD grantedAccess = 0; + DWORD privilegesLength = sizeof(privileges); + BOOL result = 0; + if (::AccessCheck(security, impersonatedToken, genericAccessRights, &mapping, &privileges, &privilegesLength, &grantedAccess, &result)) { + writable = result != 0; + } + ::CloseHandle(impersonatedToken); + } + + ::CloseHandle(token); + } + } + return writable; +} + + +QString determineProfile(QStringList &arguments, const QSettings &settings) +{ + QString selectedProfileName = QString::fromUtf8(settings.value("selected_profile", "").toByteArray()); + { // see if there is a profile on the command line + int profileIndex = arguments.indexOf("-p", 1); + if ((profileIndex != -1) && (profileIndex < arguments.size() - 1)) { + qDebug("profile overwritten on command line"); + selectedProfileName = arguments.at(profileIndex + 1); + } + arguments.removeAt(profileIndex); + arguments.removeAt(profileIndex); + } + if (selectedProfileName.isEmpty()) { + qDebug("no configured profile"); + selectedProfileName = "Default"; + } else { + qDebug("configured profile: %s", qUtf8Printable(selectedProfileName)); + } + + return selectedProfileName; +} + +MOBase::IPluginGame *selectGame(QSettings &settings, QDir const &gamePath, MOBase::IPluginGame *game) +{ + settings.setValue("gameName", game->gameName()); + //Sadly, hookdll needs gamePath in order to run. So following code block is + //commented out + /*if (gamePath == game->gameDirectory()) { + settings.remove("gamePath"); + } else*/ { + QString gameDir = gamePath.absolutePath(); + game->setGamePath(gameDir); + settings.setValue("gamePath", QDir::toNativeSeparators(gameDir).toUtf8().constData()); + } + return game; //Woot +} + + +MOBase::IPluginGame *determineCurrentGame(QString const &moPath, QSettings &settings, PluginContainer const &plugins) +{ + //Determine what game we are running where. Be very paranoid in case the + //user has done something odd. + //If the game name has been set up, use that. + QString gameName = settings.value("gameName", "").toString(); + if (!gameName.isEmpty()) { + MOBase::IPluginGame *game = plugins.managedGame(gameName); + if (game == nullptr) { + reportError(QObject::tr("Plugin to handle %1 no longer installed").arg(gameName)); + return nullptr; + } + QString gamePath = QString::fromUtf8(settings.value("gamePath", "").toByteArray()); + if (gamePath == "") { + gamePath = game->gameDirectory().absolutePath(); + } + QDir gameDir(gamePath); + if (game->looksValid(gameDir)) { + return selectGame(settings, gameDir, game); + } + } + + //gameName wasn't set, or otherwise can't be found. Try looking through all + //the plugins using the gamePath + QString gamePath = QString::fromUtf8(settings.value("gamePath", "").toByteArray()); + if (!gamePath.isEmpty()) { + QDir gameDir(gamePath); + //Look to see if one of the installed games binary file exists in the current + //game directory. + for (IPluginGame * const game : plugins.plugins()) { + if (game->looksValid(gameDir)) { + return selectGame(settings, gameDir, game); + } + } + } + + //The following code would try to determine the right game to mange but it would usually find the wrong one + //so it was commented out. + /* + //OK, we are in a new setup or existing info is useless. + //See if MO has been installed inside a game directory + for (IPluginGame * const game : plugins.plugins()) { + if (game->isInstalled() && moPath.startsWith(game->gameDirectory().absolutePath())) { + //Found it. + return selectGame(settings, game->gameDirectory(), game); + } + } + + //Try walking up the directory tree to see if MO has been installed inside a game + { + QDir gameDir(moPath); + do { + //Look to see if one of the installed games binary file exists in the current + //directory. + for (IPluginGame * const game : plugins.plugins()) { + if (game->looksValid(gameDir)) { + return selectGame(settings, gameDir, game); + } + } + //OK, chop off the last directory and try again + } while (gameDir.cdUp()); + } + */ + + //Then try a selection dialogue. + if (!gamePath.isEmpty() || !gameName.isEmpty()) { + reportError(QObject::tr("Could not use configuration settings for game \"%1\", path \"%2\"."). + arg(gameName).arg(gamePath)); + } + + SelectionDialog selection(QObject::tr("Please select the game to manage"), nullptr, QSize(32, 32)); + + for (IPluginGame *game : plugins.plugins()) { + if (game->isInstalled()) { + QString path = game->gameDirectory().absolutePath(); + selection.addChoice(game->gameIcon(), game->gameName(), path, QVariant::fromValue(game)); + } + } + + selection.addChoice(QString("Browse..."), QString(), QVariant::fromValue(static_cast(nullptr))); + + while (selection.exec() != QDialog::Rejected) { + IPluginGame * game = selection.getChoiceData().value(); + if (game != nullptr) { + return selectGame(settings, game->gameDirectory(), game); + } + + gamePath = QFileDialog::getExistingDirectory( + nullptr, QObject::tr("Please select the game to manage"), QString(), + QFileDialog::ShowDirsOnly); + + if (!gamePath.isEmpty()) { + QDir gameDir(gamePath); + QList possibleGames; + for (IPluginGame * const game : plugins.plugins()) { + if (game->looksValid(gameDir)) { + possibleGames.append(game); + //return selectGame(settings, gameDir, game); + } + } + if (possibleGames.count() > 1) { + SelectionDialog browseSelection(QObject::tr("Please select the game to manage"), nullptr, QSize(32, 32)); + for (IPluginGame *game : possibleGames) { + QString path = game->gameDirectory().absolutePath(); + browseSelection.addChoice(game->gameIcon(), game->gameName(), path, QVariant::fromValue(game)); + } + if (browseSelection.exec() == QDialog::Accepted) { + return selectGame(settings, gameDir, browseSelection.getChoiceData().value()); + } else { + reportError(QObject::tr("Canceled finding game in \"%1\".").arg(gamePath)); + } + } else if(possibleGames.count() == 1) { + return selectGame(settings, gameDir, possibleGames[0]); + } else { + reportError(QObject::tr("No game identified in \"%1\". The directory is required to contain " + "the game binary.").arg(gamePath)); + } + } + } + + return nullptr; +} + + +// extend path to include dll directory so plugins don't need a manifest +// (using AddDllDirectory would be an alternative to this but it seems fairly +// complicated esp. +// since it isn't easily accessible on Windows < 8 +// SetDllDirectory replaces other search directories and this seems to +// propagate to child processes) +void setupPath() +{ + static const int BUFSIZE = 4096; + + qDebug("MO at: %s", qUtf8Printable(QDir::toNativeSeparators( + QCoreApplication::applicationDirPath()))); + + QCoreApplication::setLibraryPaths(QStringList(QCoreApplication::applicationDirPath() + "/dlls") + QCoreApplication::libraryPaths()); + + boost::scoped_array oldPath(new TCHAR[BUFSIZE]); + DWORD offset = ::GetEnvironmentVariable(TEXT("PATH"), oldPath.get(), BUFSIZE); + if (offset > BUFSIZE) { + oldPath.reset(new TCHAR[offset]); + ::GetEnvironmentVariable(TEXT("PATH"), oldPath.get(), offset); + } + + std::wstring newPath(ToWString(QDir::toNativeSeparators( + QCoreApplication::applicationDirPath())) + L"\\dlls"); + newPath += L";"; + newPath += oldPath.get(); + + ::SetEnvironmentVariableW(L"PATH", newPath.c_str()); +} + +static void preloadSsl() +{ + QString appPath = QDir::toNativeSeparators(QCoreApplication::applicationDirPath()); + if (GetModuleHandleA("libeay32.dll")) + qWarning("libeay32.dll already loaded?!"); + else { + QString libeay32 = appPath + "\\libeay32.dll"; + if (!QFile::exists(libeay32)) + qWarning("libeay32.dll not found: %s", qUtf8Printable(libeay32)); + else if (!LoadLibraryW(libeay32.toStdWString().c_str())) + qWarning("failed to load: %s, %d", qUtf8Printable(libeay32), GetLastError()); + } + if (GetModuleHandleA("ssleay32.dll")) + qWarning("ssleay32.dll already loaded?!"); + else { + QString ssleay32 = appPath + "\\ssleay32.dll"; + if (!QFile::exists(ssleay32)) + qWarning("ssleay32.dll not found: %s", qUtf8Printable(ssleay32)); + else if (!LoadLibraryW(ssleay32.toStdWString().c_str())) + qWarning("failed to load: %s, %d", qUtf8Printable(ssleay32), GetLastError()); + } +} + +static QString getVersionDisplayString() +{ + return createVersionInfo().displayString(3); +} + +int runApplication(MOApplication &application, SingleInstance &instance, + const QString &splashPath) +{ + + qDebug("Starting Mod Organizer version %s revision %s", qUtf8Printable(getVersionDisplayString()), +#if defined(HGID) + HGID +#elif defined(GITID) + GITID +#else + "unknown" +#endif + ); + +#if !defined(QT_NO_SSL) + preloadSsl(); + qDebug("ssl support: %d", QSslSocket::supportsSsl()); +#else + qDebug("non-ssl build"); +#endif + + QString dataPath = application.property("dataPath").toString(); + qDebug("data path: %s", qUtf8Printable(dataPath)); + + if (!bootstrap()) { + reportError("failed to set up data paths"); + return 1; + } + + QWindowsWindowFunctions::setWindowActivationBehavior(QWindowsWindowFunctions::AlwaysActivateWindow); + + QStringList arguments = application.arguments(); + + try { + qDebug("Working directory: %s", qUtf8Printable(QDir::toNativeSeparators(QDir::currentPath()))); + + QSettings settings(dataPath + "/" + + QString::fromStdWString(AppConfig::iniFileName()), + QSettings::IniFormat); + + // global crashDumpType sits in OrganizerCore to make a bit less ugly to update it when the settings are changed during runtime + OrganizerCore::setGlobalCrashDumpsType(settings.value("Settings/crash_dumps_type", static_cast(CrashDumpsType::Mini)).toInt()); + + qDebug("Loaded settings:"); + settings.beginGroup("Settings"); + for (auto k : settings.allKeys()) + if (!k.contains("username") && !k.contains("password") && !k.contains("nexus_api_key")) + qDebug(" %s=%s", k.toUtf8().data(), settings.value(k).toString().toUtf8().data()); + settings.endGroup(); + + + qDebug("initializing core"); + OrganizerCore organizer(settings); + if (!organizer.bootstrap()) { + reportError("failed to set up data paths"); + return 1; + } + qDebug("initialize plugins"); + PluginContainer pluginContainer(&organizer); + pluginContainer.loadPlugins(); + + MOBase::IPluginGame *game = determineCurrentGame( + application.applicationDirPath(), settings, pluginContainer); + if (game == nullptr) { + return 1; + } + if (splashPath.startsWith(':')) { + // currently using MO splash, see if the plugin contains one + QString pluginSplash + = QString(":/%1/splash").arg(game->gameShortName()); + QImage image(pluginSplash); + if (!image.isNull()) { + image.save(dataPath + "/splash.png"); + } else { + qDebug("no plugin splash"); + } + } + + organizer.setManagedGame(game); + organizer.createDefaultProfile(); + + if (!settings.contains("game_edition")) { + QStringList editions = game->gameVariants(); + if (editions.size() > 1) { + SelectionDialog selection( + QObject::tr("Please select the game edition you have (MO can't " + "start the game correctly if this is set " + "incorrectly!)"), + nullptr); + selection.setWindowFlag(Qt::WindowStaysOnTopHint, true); + int index = 0; + for (const QString &edition : editions) { + selection.addChoice(edition, "", index++); + } + if (selection.exec() == QDialog::Rejected) { + return 1; + } else { + settings.setValue("game_edition", selection.getChoiceString()); + } + } + } + game->setGameVariant(settings.value("game_edition").toString()); + + qDebug("managing game at %s", qUtf8Printable(QDir::toNativeSeparators( + game->gameDirectory().absolutePath()))); + + organizer.updateExecutablesList(settings); + + QString selectedProfileName = determineProfile(arguments, settings); + organizer.setCurrentProfile(selectedProfileName); + + // if we have a command line parameter, it is either a nxm link or + // a binary to start + if (arguments.size() > 1) { + if (MOShortcut shortcut{ arguments.at(1) }) { + if (shortcut.hasExecutable()) { + try { + organizer.runShortcut(shortcut); + return 0; + } + catch (const std::exception &e) { + reportError( + QObject::tr("failed to start shortcut: %1").arg(e.what())); + return 1; + } + } + } + else if (OrganizerCore::isNxmLink(arguments.at(1))) { + qDebug("starting download from command line: %s", + qUtf8Printable(arguments.at(1))); + organizer.externalMessage(arguments.at(1)); + } + else { + QString exeName = arguments.at(1); + qDebug("starting %s from command line", qUtf8Printable(exeName)); + arguments.removeFirst(); // remove application name (ModOrganizer.exe) + arguments.removeFirst(); // remove binary name + // pass the remaining parameters to the binary + try { + organizer.startApplication(exeName, arguments, QString(), QString()); + return 0; + } + catch (const std::exception &e) { + reportError( + QObject::tr("failed to start application: %1").arg(e.what())); + return 1; + } + } + } + + QPixmap pixmap(splashPath); + QSplashScreen splash(pixmap); + splash.show(); + splash.activateWindow(); + + QString apiKey; + if (organizer.settings().getNexusApiKey(apiKey)) { + NexusInterface::instance(&pluginContainer)->getAccessManager()->apiCheck(apiKey); + } + + qDebug("initializing tutorials"); + TutorialManager::init( + qApp->applicationDirPath() + "/" + + QString::fromStdWString(AppConfig::tutorialsPath()) + "/", + &organizer); + + if (!application.setStyleFile(settings.value("Settings/style", "").toString())) { + // disable invalid stylesheet + settings.setValue("Settings/style", ""); + } + + int res = 1; + { // scope to control lifetime of mainwindow + // set up main window and its data structures + MainWindow mainWindow(settings, organizer, pluginContainer); + + QObject::connect(&mainWindow, SIGNAL(styleChanged(QString)), &application, + SLOT(setStyleFile(QString))); + QObject::connect(&instance, SIGNAL(messageSent(QString)), &organizer, + SLOT(externalMessage(QString))); + + mainWindow.processUpdates(); + mainWindow.readSettings(); + + qDebug("displaying main window"); + mainWindow.show(); + mainWindow.activateWindow(); + + splash.finish(&mainWindow); + return application.exec(); + } + } catch (const std::exception &e) { + reportError(e.what()); + return 1; + } +} + + +int main(int argc, char *argv[]) +{ + //Should allow for better scaling of ui with higher resolution displays + QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); + + if (argc >= 4) { + std::vector arg; + auto args = UntouchedCommandLineArguments(2, arg); + if (arg[0] == L"launch") + return SpawnWaitProcess(arg[1].c_str(), args); + } + + MOApplication application(argc, argv); + QStringList arguments = application.arguments(); + + setupPath(); + + bool forcePrimary = false; + if (arguments.contains("update")) { + arguments.removeAll("update"); + forcePrimary = true; + } + + MOShortcut moshortcut{ arguments.size() > 1 ? arguments.at(1) : "" }; + + SingleInstance instance(forcePrimary); + if (!instance.primaryInstance()) { + if (moshortcut || + arguments.size() > 1 && OrganizerCore::isNxmLink(arguments.at(1))) + { + qDebug("not primary instance, sending shortcut/download message"); + instance.sendMessage(arguments.at(1)); + return 0; + } else if (arguments.size() == 1) { + QMessageBox::information( + nullptr, QObject::tr("Mod Organizer"), + QObject::tr("An instance of Mod Organizer is already running")); + return 0; + } + } // we continue for the primary instance OR if MO was called with parameters + + do { + QString dataPath; + + try { + InstanceManager& instanceManager = InstanceManager::instance(); + if (moshortcut && moshortcut.hasInstance()) + instanceManager.overrideInstance(moshortcut.instance()); + dataPath = instanceManager.determineDataPath(); + } catch (const std::exception &e) { + if (strcmp(e.what(),"Canceled")) + QMessageBox::critical(nullptr, QObject::tr("Failed to set up instance"), e.what()); + return 1; + } + application.setProperty("dataPath", dataPath); + + // initialize dump collection only after "dataPath" since the crashes are stored under it + prevUnhandledExceptionFilter = SetUnhandledExceptionFilter(MyUnhandledExceptionFilter); + + LogBuffer::init(1000, QtDebugMsg, qApp->property("dataPath").toString() + "/logs/mo_interface.log"); + + QString splash = dataPath + "/splash.png"; + if (!QFile::exists(dataPath + "/splash.png")) { + splash = ":/MO/gui/splash"; + } + + int result = runApplication(application, instance, splash); + if (result != INT_MAX) { + return result; + } + argc = 1; + moshortcut = MOShortcut(""); + } while (true); +} diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index add1ef7f..9003d6b2 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -392,8 +392,8 @@ MainWindow::MainWindow(QSettings &initSettings connect(NexusInterface::instance(&pluginContainer), SIGNAL(requestNXMDownload(QString)), &m_OrganizerCore, SLOT(downloadRequestedNXM(QString))); connect(NexusInterface::instance(&pluginContainer), SIGNAL(nxmDownloadURLsAvailable(QString,int,int,QVariant,QVariant,int)), this, SLOT(nxmDownloadURLs(QString,int,int,QVariant,QVariant,int))); - connect(NexusInterface::instance(&pluginContainer), SIGNAL(needLogin()), &m_OrganizerCore, SLOT(nexusLogin())); - connect(NexusInterface::instance(&pluginContainer)->getAccessManager(), SIGNAL(loginFailed(QString)), this, SLOT(loginFailed(QString))); + connect(NexusInterface::instance(&pluginContainer), SIGNAL(needLogin()), &m_OrganizerCore, SLOT(nexusApi())); + connect(NexusInterface::instance(&pluginContainer)->getAccessManager(), SIGNAL(validateFailed(QString)), this, SLOT(validationFailed(QString))); connect(NexusInterface::instance(&pluginContainer)->getAccessManager(), SIGNAL(credentialsReceived(const QString&, bool)), this, SLOT(updateWindowTitle(const QString&, bool))); @@ -2695,7 +2695,7 @@ void MainWindow::endorseMod(ModInfo::Ptr mod) } else { QString apiKey; if (m_OrganizerCore.settings().getNexusApiKey(apiKey)) { - m_OrganizerCore.doAfterLogin(boost::bind(&MainWindow::endorseMod, this, mod)); + m_OrganizerCore.doAfterLogin([&]() { this->endorseMod(mod); }); NexusInterface::instance(&m_PluginContainer)->getAccessManager()->apiCheck(apiKey); } else { MessageDialog::showMessage(tr("You need to be logged in with Nexus to endorse"), this); @@ -2708,21 +2708,21 @@ void MainWindow::endorse_clicked() { QItemSelectionModel *selection = ui->modList->selectionModel(); if (selection->hasSelection() && selection->selectedRows().count() > 1) { - if (NexusInterface::instance(&m_PluginContainer)->getAccessManager()->loggedIn()) { + if (NexusInterface::instance(&m_PluginContainer)->getAccessManager()->validated()) { MessageDialog::showMessage(tr("Endorsing multiple mods will take a while. Please wait..."), this); for (QModelIndex idx : selection->selectedRows()) { ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt())->endorse(true); } } else { - QString username, password; - if (m_OrganizerCore.settings().getNexusLogin(username, password)) { + QString apiKey; + if (m_OrganizerCore.settings().getNexusApiKey(apiKey)) { MessageDialog::showMessage(tr("Endorsing multiple mods will take a while. Please wait..."), this); for (QModelIndex idx : selection->selectedRows()) { ModInfo::Ptr modInfo = ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt()); - m_OrganizerCore.doAfterLogin(boost::bind(&MainWindow::endorseMod, this, modInfo)); + m_OrganizerCore.doAfterLogin([&]() { this->endorseMod(modInfo); }); } - NexusInterface::instance(&m_PluginContainer)->getAccessManager()->login(username, password); + NexusInterface::instance(&m_PluginContainer)->getAccessManager()->apiCheck(apiKey); } else { MessageDialog::showMessage(tr("You need to be logged in with Nexus to endorse"), this); return; @@ -2750,12 +2750,12 @@ void MainWindow::dontendorse_clicked() void MainWindow::unendorseMod(ModInfo::Ptr mod) { - QString apiKey; if (NexusInterface::instance(&m_PluginContainer)->getAccessManager()->validated()) { ModInfo::getByIndex(m_ContextRow)->endorse(false); } else { + QString apiKey; if (m_OrganizerCore.settings().getNexusApiKey(apiKey)) { - m_OrganizerCore.doAfterLogin([this] () { this->unendorse_clicked(); }); + m_OrganizerCore.doAfterLogin([&]() { this->unendorseMod(mod); }); NexusInterface::instance(&m_PluginContainer)->getAccessManager()->apiCheck(apiKey); } else { MessageDialog::showMessage(tr("You need to be logged in with Nexus to endorse"), this); @@ -2768,21 +2768,20 @@ void MainWindow::unendorse_clicked() { QItemSelectionModel *selection = ui->modList->selectionModel(); if (selection->hasSelection() && selection->selectedRows().count() > 1) { - if (NexusInterface::instance(&m_PluginContainer)->getAccessManager()->loggedIn()) { + if (NexusInterface::instance(&m_PluginContainer)->getAccessManager()->validated()) { MessageDialog::showMessage(tr("Unendorsing multiple mods will take a while. Please wait..."), this); for (QModelIndex idx : selection->selectedRows()) { ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt())->endorse(false); } - } - else { - QString username, password; - if (m_OrganizerCore.settings().getNexusLogin(username, password)) { + } else { + QString apiKey; + if (m_OrganizerCore.settings().getNexusApiKey(apiKey)) { MessageDialog::showMessage(tr("Unendorsing multiple mods will take a while. Please wait..."), this); for (QModelIndex idx : selection->selectedRows()) { ModInfo::Ptr modInfo = ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt()); - m_OrganizerCore.doAfterLogin(boost::bind(&MainWindow::unendorseMod, this, modInfo)); + m_OrganizerCore.doAfterLogin([&]() { this->unendorseMod(modInfo); }); } - NexusInterface::instance(&m_PluginContainer)->getAccessManager()->login(username, password); + NexusInterface::instance(&m_PluginContainer)->getAccessManager()->apiCheck(apiKey); } else { MessageDialog::showMessage(tr("You need to be logged in with Nexus to endorse"), this); return; @@ -2794,9 +2793,9 @@ void MainWindow::unendorse_clicked() } } -void MainWindow::loginFailed(const QString &error) +void MainWindow::validationFailed(const QString &error) { - qDebug("login failed: %s", qUtf8Printable(error)); + qDebug("Nexus API validation failed: %s", qUtf8Printable(error)); statusBar()->hide(); } diff --git a/src/mainwindow.h b/src/mainwindow.h index 0e39c613..caf94c0e 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -1,658 +1,658 @@ -/* -Copyright (C) 2012 Sebastian Herbord. All rights reserved. - -This file is part of Mod Organizer. - -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 . -*/ - -#ifndef MAINWINDOW_H -#define MAINWINDOW_H - -#include "bsafolder.h" -#include "browserdialog.h" -#include "delayedfilewriter.h" -#include "errorcodes.h" -#include "imoinfo.h" -#include "iuserinterface.h" -#include "modinfo.h" -#include "modlistsortproxy.h" -#include "savegameinfo.h" -#include "tutorialcontrol.h" - -//Note the commented headers here can be replaced with forward references, -//when I get round to cleaning up main.cpp -struct Executable; -class CategoryFactory; -class LockedDialogBase; -class OrganizerCore; -#include "plugincontainer.h" //class PluginContainer; -class PluginListSortProxy; -namespace BSA { class Archive; } -#include "iplugingame.h" //namespace MOBase { class IPluginGame; } -namespace MOBase { class IPluginModPage; } -namespace MOBase { class IPluginTool; } -namespace MOBase { class ISaveGame; } - -namespace MOShared { class DirectoryEntry; } - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -class QAction; -class QAbstractItemModel; -class QDateTime; -class QEvent; -class QFile; -class QListWidgetItem; -class QMenu; -class QModelIndex; -class QPoint; -class QProgressBar; -class QProgressDialog; -class QTranslator; -class QTreeWidgetItem; -class QUrl; -class QSettings; -class QWidget; - -#ifndef Q_MOC_RUN -#include -#endif - -//Sigh - just for HANDLE -#define WIN32_LEAN_AND_MEAN -#include - -#include -#include -#include -#include - -namespace Ui { - class MainWindow; -} - - - -class MainWindow : public QMainWindow, public IUserInterface -{ - Q_OBJECT - - friend class OrganizerProxy; - -public: - - explicit MainWindow(QSettings &initSettings, - OrganizerCore &organizerCore, PluginContainer &pluginContainer, - QWidget *parent = 0); - ~MainWindow(); - - void storeSettings(QSettings &settings) override; - void readSettings(); - void processUpdates(); - - virtual ILockedWaitingForProcess* lock() override; - virtual void unlock() override; - - bool addProfile(); - void updateBSAList(const QStringList &defaultArchives, const QStringList &activeArchives); - void refreshDataTree(); - void refreshDataTreeKeepExpandedNodes(); - void refreshSaveList(); - - void setModListSorting(int index); - void setESPListSorting(int index); - - void saveArchiveList(); - - void registerPluginTool(MOBase::IPluginTool *tool, QString name = QString(), QMenu *menu = nullptr); - void registerPluginTools(std::vector toolPlugins); - void registerModPage(MOBase::IPluginModPage *modPage); - - void addPrimaryCategoryCandidates(QMenu *primaryCategoryMenu, ModInfo::Ptr info); - - void createStdoutPipe(HANDLE *stdOutRead, HANDLE *stdOutWrite); - std::string readFromPipe(HANDLE stdOutRead); - void processLOOTOut(const std::string &lootOut, std::string &errorMessages, QProgressDialog &dialog); - - void updateModInDirectoryStructure(unsigned int index, ModInfo::Ptr modInfo); - - QString getOriginDisplayName(int originID); - - void installTranslator(const QString &name); - - virtual void disconnectPlugins(); - - void displayModInformation(ModInfo::Ptr modInfo, unsigned int index, int tab); - - virtual bool closeWindow(); - virtual void setWindowEnabled(bool enabled); - - virtual MOBase::DelayedFileWriterBase &archivesWriter() override { return m_ArchiveListWriter; } - -public slots: - - void displayColumnSelection(const QPoint &pos); - - void modorder_changed(); - void esplist_changed(); - void refresher_progress(int percent); - void directory_refreshed(); - - void toolPluginInvoke(); - void modPagePluginInvoke(); - -signals: - - /** - * @brief emitted after the information dialog has been closed - */ - void modInfoDisplayed(); - - /** - * @brief emitted when the selected style changes - */ - void styleChanged(const QString &styleFile); - - - void modListDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight); - -protected: - - virtual void showEvent(QShowEvent *event); - virtual void closeEvent(QCloseEvent *event); - virtual bool eventFilter(QObject *obj, QEvent *event); - virtual void resizeEvent(QResizeEvent *event); - virtual void dragEnterEvent(QDragEnterEvent *event); - virtual void dropEvent(QDropEvent *event); - -private slots: - void on_actionChange_Game_triggered(); - -private slots: - void on_clickBlankButton_clicked(); - -private: - - void cleanup(); - - void actionToToolButton(QAction *&sourceAction); - - void updateToolBar(); - void activateSelectedProfile(); - - void setExecutableIndex(int index); - - void startSteam(); - - void updateTo(QTreeWidgetItem *subTree, const std::wstring &directorySoFar, const MOShared::DirectoryEntry &directoryEntry, bool conflictsOnly, QIcon *fileIcon, QIcon *folderIcon); - bool refreshProfiles(bool selectProfile = true); - void refreshExecutablesList(); - void installMod(QString fileName = ""); - - QList findFileInfos(const QString &path, const std::function &filter) const; - - bool modifyExecutablesDialog(); - void displayModInformation(int row, int tab = -1); - void testExtractBSA(int modIndex); - - void writeDataToFile(QFile &file, const QString &directory, const MOShared::DirectoryEntry &directoryEntry); - - void refreshFilters(); - - /** - * Sets category selections from menu; for multiple mods, this will only apply - * the changes made in the menu (which is the delta between the current menu selection and the reference mod) - * @param menu the menu after editing by the user - * @param modRow index of the mod to edit - * @param referenceRow row of the reference mod - */ - void addRemoveCategoriesFromMenu(QMenu *menu, int modRow, int referenceRow); - - /** - * Sets category selections from menu; for multiple mods, this will completely - * replace the current set of categories on each selected with those selected in the menu - * @param menu the menu after editing by the user - * @param modRow index of the mod to edit - */ - void replaceCategoriesFromMenu(QMenu *menu, int modRow); - - bool populateMenuCategories(QMenu *menu, int targetID); - - void initDownloadView(); - void updateDownloadView(); - - // remove invalid category-references from mods - void fixCategories(); - - void createEndorseWidget(); - void createHelpWidget(); - - bool extractProgress(QProgressDialog &extractProgress, int percentage, std::string fileName); - - size_t checkForProblems(); - - int getBinaryExecuteInfo(const QFileInfo &targetInfo, QFileInfo &binaryInfo, QString &arguments); - QTreeWidgetItem *addFilterItem(QTreeWidgetItem *root, const QString &name, int categoryID, ModListSortProxy::FilterType type); - void addContentFilters(); - void addCategoryFilters(QTreeWidgetItem *root, const std::set &categoriesUsed, int targetID); - - void setCategoryListVisible(bool visible); - - void displaySaveGameInfo(QListWidgetItem *newItem); - - HANDLE nextChildProcess(); - - bool errorReported(QString &logFile); - - void updateESPLock(bool locked); - - static void setupNetworkProxy(bool activate); - void activateProxy(bool activate); - void setBrowserGeometry(const QByteArray &geometry); - - bool createBackup(const QString &filePath, const QDateTime &time); - QString queryRestore(const QString &filePath); - - void initModListContextMenu(QMenu *menu); - void addModSendToContextMenu(QMenu *menu); - void addPluginSendToContextMenu(QMenu *menu); - - QMenu *openFolderMenu(); - - std::set enabledArchives(); - - void scheduleUpdateButton(); - - QDir currentSavesDir() const; - - void startMonitorSaves(); - void stopMonitorSaves(); - - void dropLocalFile(const QUrl &url, const QString &outputDir, bool move); - - bool registerWidgetState(const QString &name, QHeaderView *view, const char *oldSettingName = nullptr); - - void sendSelectedModsToPriority(int newPriority); - void sendSelectedPluginsToPriority(int newPriority); - -private: - - static const char *PATTERN_BACKUP_GLOB; - static const char *PATTERN_BACKUP_REGEX; - static const char *PATTERN_BACKUP_DATE; - -private: - - Ui::MainWindow *ui; - - QAction *m_Sep; // Executable Shortcuts are added after this. Non owning. - - bool m_WasVisible; - - MOBase::TutorialControl m_Tutorial; - - int m_OldProfileIndex; - - std::vector m_ModNameList; // the mod-list to go with the directory structure - QProgressBar *m_RefreshProgress; - bool m_Refreshing; - - QStringList m_DefaultArchives; - - QAbstractItemModel *m_ModListGroupingProxy; - ModListSortProxy *m_ModListSortProxy; - - PluginListSortProxy *m_PluginListSortProxy; - - int m_OldExecutableIndex; - - int m_ContextRow; - QPersistentModelIndex m_ContextIdx; - QTreeWidgetItem *m_ContextItem; - QAction *m_ContextAction; - - CategoryFactory &m_CategoryFactory; - - int m_ModsToUpdate; - - bool m_LoginAttempted; - - QTimer m_CheckBSATimer; - QTimer m_SaveMetaTimer; - QTimer m_UpdateProblemsTimer; - - QFuture m_MetaSave; - - QTime m_StartTime; - //SaveGameInfoWidget *m_CurrentSaveView; - MOBase::ISaveGameInfoWidget *m_CurrentSaveView; - - OrganizerCore &m_OrganizerCore; - PluginContainer &m_PluginContainer; - - QString m_CurrentLanguage; - std::vector m_Translators; - - BrowserDialog m_IntegratedBrowser; - - QFileSystemWatcher m_SavesWatcher; - - std::vector m_RemoveWidget; - - QByteArray m_ArchiveListHash; - - bool m_DidUpdateMasterList; - - LockedDialogBase *m_LockDialog { nullptr }; - uint64_t m_LockCount { 0 }; - - bool m_closing{ false }; - - bool m_showArchiveData{ true }; - - std::vector> m_PersistedGeometry; - - MOBase::DelayedFileWriter m_ArchiveListWriter; - - enum class ShortcutType { - Toolbar, - Desktop, - StartMenu - }; - - void addWindowsLink(ShortcutType const); - - Executable const &getSelectedExecutable() const; - Executable &getSelectedExecutable(); - -private slots: - - void updateWindowTitle(const QString &accountName, bool premium); - - void showMessage(const QString &message); - void showError(const QString &message); - - - // main window actions - void helpTriggered(); - void issueTriggered(); - void wikiTriggered(); - void discordTriggered(); - void tutorialTriggered(); - void extractBSATriggered(); - - //modlist shortcuts - void openExplorer_activated(); - void refreshProfile_activated(); - - // modlist context menu - void installMod_clicked(); - void createEmptyMod_clicked(); - void createSeparator_clicked(); - void restoreBackup_clicked(); - void renameMod_clicked(); - void removeMod_clicked(); - void setColor_clicked(); - void resetColor_clicked(); - void backupMod_clicked(); - void reinstallMod_clicked(); - void endorse_clicked(); - void dontendorse_clicked(); - void unendorse_clicked(); - void ignoreMissingData_clicked(); - void markConverted_clicked(); - void visitOnNexus_clicked(); - void visitWebPage_clicked(); - void openExplorer_clicked(); - void openOriginExplorer_clicked(); - void openOriginInformation_clicked(); - void information_clicked(); - void enableSelectedMods_clicked(); - void disableSelectedMods_clicked(); - void sendSelectedModsToTop_clicked(); - void sendSelectedModsToBottom_clicked(); - void sendSelectedModsToPriority_clicked(); - void sendSelectedModsToSeparator_clicked(); - // savegame context menu - void deleteSavegame_clicked(); - void fixMods_clicked(SaveGameInfo::MissingAssets const &missingAssets); - // data-tree context menu - void writeDataToFile(); - void openDataFile(); - void addAsExecutable(); - void previewDataFile(); - void hideFile(); - void unhideFile(); - - // pluginlist context menu - void enableSelectedPlugins_clicked(); - void disableSelectedPlugins_clicked(); - void sendSelectedPluginsToTop_clicked(); - void sendSelectedPluginsToBottom_clicked(); - void sendSelectedPluginsToPriority_clicked(); - - void linkToolbar(); - void linkDesktop(); - void linkMenu(); - - void languageChange(const QString &newLanguage); - void saveSelectionChanged(QListWidgetItem *newItem); - - void windowTutorialFinished(const QString &windowName); - - BSA::EErrorCode extractBSA(BSA::Archive &archive, BSA::Folder::Ptr folder, const QString &destination, QProgressDialog &extractProgress); - - void createModFromOverwrite(); - /** - * @brief sends the content of the overwrite folder to an already existing mod - */ - void moveOverwriteContentToExistingMod(); - /** - * @brief actually sends the content of the overwrite folder to specified mod - */ - void doMoveOverwriteContentToMod(const QString &modAbsolutePath); - void clearOverwrite(); - - void procError(QProcess::ProcessError error); - void procFinished(int exitCode, QProcess::ExitStatus exitStatus); - - // nexus related - void checkModsForUpdates(); - - void loginFailed(const QString &message); - - void linkClicked(const QString &url); - - void updateAvailable(); - - void motdReceived(const QString &motd); - void notEndorsedYet(); - void wontEndorse(); - - void originModified(int originID); - - void addRemoveCategories_MenuHandler(); - void replaceCategories_MenuHandler(); - - void addPrimaryCategoryCandidates(); - - void modDetailsUpdated(bool success); - - void modInstalled(const QString &modName); - - void nxmUpdatesAvailable(const std::vector &modIDs, QVariant userData, QVariant resultData, int requestID); - void nxmEndorsementToggled(QString, int, QVariant, QVariant resultData, int); - void nxmDownloadURLs(QString, int modID, int fileID, QVariant userData, QVariant resultData, int requestID); - void nxmRequestFailed(QString, int modID, int fileID, QVariant userData, int requestID, const QString &errorString); - - void editCategories(); - void deselectFilters(); - - void displayModInformation(const QString &modName, int tab); - void modOpenNext(int tab=-1); - void modOpenPrev(int tab=-1); - - void modRenamed(const QString &oldName, const QString &newName); - void modRemoved(const QString &fileName); - - void hideSaveGameInfo(); - - void hookUpWindowTutorials(); - - void resumeDownload(int downloadIndex); - void endorseMod(ModInfo::Ptr mod); - void unendorseMod(ModInfo::Ptr mod); - void cancelModListEditor(); - - void lockESPIndex(); - void unlockESPIndex(); - - void enableVisibleMods(); - void disableVisibleMods(); - void exportModListCSV(); - void openInstanceFolder(); - void openLogsFolder(); - void openInstallFolder(); - void openPluginsFolder(); - void openDownloadsFolder(); - void openModsFolder(); - void openProfileFolder(); - void openIniFolder(); - void openGameFolder(); - void openMyGamesFolder(); - void startExeAction(); - - void checkBSAList(); - - void updateProblemsButton(); - - void saveModMetas(); - - void updateStyle(const QString &style); - - void modlistChanged(const QModelIndex &index, int role); - void modlistChanged(const QModelIndexList &indicies, int role); - void fileMoved(const QString &filePath, const QString &oldOriginName, const QString &newOriginName); - - - void modFilterActive(bool active); - void espFilterChanged(const QString &filter); - void downloadFilterChanged(const QString &filter); - - void expandModList(const QModelIndex &index); - - /** - * @brief resize columns in mod list and plugin list to content - */ - void resizeLists(bool modListCustom, bool pluginListCustom); - - /** - * @brief allow columns in mod list and plugin list to be resized - */ - void allowListResize(); - - void toolBar_customContextMenuRequested(const QPoint &point); - void removeFromToolbar(); - void overwriteClosed(int); - - void changeVersioningScheme(); - void ignoreUpdate(); - void unignoreUpdate(); - - void refreshSavesIfOpen(); - void expandDataTreeItem(QTreeWidgetItem *item); - void about(); - void delayedRemove(); - - void modlistSelectionChanged(const QModelIndex ¤t, const QModelIndex &previous); - void modListSortIndicatorChanged(int column, Qt::SortOrder order); - void modListSectionResized(int logicalIndex, int oldSize, int newSize); - - void modlistSelectionsChanged(const QItemSelection ¤t); - void esplistSelectionsChanged(const QItemSelection ¤t); - - void search_activated(); - void searchClear_activated(); - - void updateModCount(); - void updatePluginCount(); - -private slots: // ui slots - // actions - void on_actionAdd_Profile_triggered(); - void on_actionInstallMod_triggered(); - void on_actionModify_Executables_triggered(); - void on_actionNexus_triggered(); - void on_actionNotifications_triggered(); - void on_actionSettings_triggered(); - void on_actionUpdate_triggered(); - void on_actionEndorseMO_triggered(); - - void on_bsaList_customContextMenuRequested(const QPoint &pos); - void on_clearFiltersButton_clicked(); - void on_btnRefreshData_clicked(); - void on_btnRefreshDownloads_clicked(); - void on_categoriesList_customContextMenuRequested(const QPoint &pos); - void on_conflictsCheckBox_toggled(bool checked); - void on_showArchiveDataCheckBox_toggled(bool checked); - void on_dataTree_customContextMenuRequested(const QPoint &pos); - void on_executablesListBox_currentIndexChanged(int index); - void on_modList_customContextMenuRequested(const QPoint &pos); - void on_modList_doubleClicked(const QModelIndex &index); - void on_listOptionsBtn_pressed(); - void on_espList_doubleClicked(const QModelIndex &index); - void on_profileBox_currentIndexChanged(int index); - void on_savegameList_customContextMenuRequested(const QPoint &pos); - void on_startButton_clicked(); - void on_tabWidget_currentChanged(int index); - - void on_espList_customContextMenuRequested(const QPoint &pos); - void on_displayCategoriesBtn_toggled(bool checked); - void on_groupCombo_currentIndexChanged(int index); - void on_categoriesList_itemSelectionChanged(); - void on_linkButton_pressed(); - void on_showHiddenBox_toggled(bool checked); - void on_bsaList_itemChanged(QTreeWidgetItem *item, int column); - void on_bossButton_clicked(); - - void on_saveButton_clicked(); - void on_restoreButton_clicked(); - void on_restoreModsButton_clicked(); - void on_saveModsButton_clicked(); - void on_actionCopy_Log_to_Clipboard_triggered(); - void on_categoriesAndBtn_toggled(bool checked); - void on_categoriesOrBtn_toggled(bool checked); - void on_managedArchiveLabel_linkHovered(const QString &link); -}; - - - -#endif // MAINWINDOW_H +/* +Copyright (C) 2012 Sebastian Herbord. All rights reserved. + +This file is part of Mod Organizer. + +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 . +*/ + +#ifndef MAINWINDOW_H +#define MAINWINDOW_H + +#include "bsafolder.h" +#include "browserdialog.h" +#include "delayedfilewriter.h" +#include "errorcodes.h" +#include "imoinfo.h" +#include "iuserinterface.h" +#include "modinfo.h" +#include "modlistsortproxy.h" +#include "savegameinfo.h" +#include "tutorialcontrol.h" + +//Note the commented headers here can be replaced with forward references, +//when I get round to cleaning up main.cpp +struct Executable; +class CategoryFactory; +class LockedDialogBase; +class OrganizerCore; +#include "plugincontainer.h" //class PluginContainer; +class PluginListSortProxy; +namespace BSA { class Archive; } +#include "iplugingame.h" //namespace MOBase { class IPluginGame; } +namespace MOBase { class IPluginModPage; } +namespace MOBase { class IPluginTool; } +namespace MOBase { class ISaveGame; } + +namespace MOShared { class DirectoryEntry; } + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class QAction; +class QAbstractItemModel; +class QDateTime; +class QEvent; +class QFile; +class QListWidgetItem; +class QMenu; +class QModelIndex; +class QPoint; +class QProgressBar; +class QProgressDialog; +class QTranslator; +class QTreeWidgetItem; +class QUrl; +class QSettings; +class QWidget; + +#ifndef Q_MOC_RUN +#include +#endif + +//Sigh - just for HANDLE +#define WIN32_LEAN_AND_MEAN +#include + +#include +#include +#include +#include + +namespace Ui { + class MainWindow; +} + + + +class MainWindow : public QMainWindow, public IUserInterface +{ + Q_OBJECT + + friend class OrganizerProxy; + +public: + + explicit MainWindow(QSettings &initSettings, + OrganizerCore &organizerCore, PluginContainer &pluginContainer, + QWidget *parent = 0); + ~MainWindow(); + + void storeSettings(QSettings &settings) override; + void readSettings(); + void processUpdates(); + + virtual ILockedWaitingForProcess* lock() override; + virtual void unlock() override; + + bool addProfile(); + void updateBSAList(const QStringList &defaultArchives, const QStringList &activeArchives); + void refreshDataTree(); + void refreshDataTreeKeepExpandedNodes(); + void refreshSaveList(); + + void setModListSorting(int index); + void setESPListSorting(int index); + + void saveArchiveList(); + + void registerPluginTool(MOBase::IPluginTool *tool, QString name = QString(), QMenu *menu = nullptr); + void registerPluginTools(std::vector toolPlugins); + void registerModPage(MOBase::IPluginModPage *modPage); + + void addPrimaryCategoryCandidates(QMenu *primaryCategoryMenu, ModInfo::Ptr info); + + void createStdoutPipe(HANDLE *stdOutRead, HANDLE *stdOutWrite); + std::string readFromPipe(HANDLE stdOutRead); + void processLOOTOut(const std::string &lootOut, std::string &errorMessages, QProgressDialog &dialog); + + void updateModInDirectoryStructure(unsigned int index, ModInfo::Ptr modInfo); + + QString getOriginDisplayName(int originID); + + void installTranslator(const QString &name); + + virtual void disconnectPlugins(); + + void displayModInformation(ModInfo::Ptr modInfo, unsigned int index, int tab); + + virtual bool closeWindow(); + virtual void setWindowEnabled(bool enabled); + + virtual MOBase::DelayedFileWriterBase &archivesWriter() override { return m_ArchiveListWriter; } + +public slots: + + void displayColumnSelection(const QPoint &pos); + + void modorder_changed(); + void esplist_changed(); + void refresher_progress(int percent); + void directory_refreshed(); + + void toolPluginInvoke(); + void modPagePluginInvoke(); + +signals: + + /** + * @brief emitted after the information dialog has been closed + */ + void modInfoDisplayed(); + + /** + * @brief emitted when the selected style changes + */ + void styleChanged(const QString &styleFile); + + + void modListDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight); + +protected: + + virtual void showEvent(QShowEvent *event); + virtual void closeEvent(QCloseEvent *event); + virtual bool eventFilter(QObject *obj, QEvent *event); + virtual void resizeEvent(QResizeEvent *event); + virtual void dragEnterEvent(QDragEnterEvent *event); + virtual void dropEvent(QDropEvent *event); + +private slots: + void on_actionChange_Game_triggered(); + +private slots: + void on_clickBlankButton_clicked(); + +private: + + void cleanup(); + + void actionToToolButton(QAction *&sourceAction); + + void updateToolBar(); + void activateSelectedProfile(); + + void setExecutableIndex(int index); + + void startSteam(); + + void updateTo(QTreeWidgetItem *subTree, const std::wstring &directorySoFar, const MOShared::DirectoryEntry &directoryEntry, bool conflictsOnly, QIcon *fileIcon, QIcon *folderIcon); + bool refreshProfiles(bool selectProfile = true); + void refreshExecutablesList(); + void installMod(QString fileName = ""); + + QList findFileInfos(const QString &path, const std::function &filter) const; + + bool modifyExecutablesDialog(); + void displayModInformation(int row, int tab = -1); + void testExtractBSA(int modIndex); + + void writeDataToFile(QFile &file, const QString &directory, const MOShared::DirectoryEntry &directoryEntry); + + void refreshFilters(); + + /** + * Sets category selections from menu; for multiple mods, this will only apply + * the changes made in the menu (which is the delta between the current menu selection and the reference mod) + * @param menu the menu after editing by the user + * @param modRow index of the mod to edit + * @param referenceRow row of the reference mod + */ + void addRemoveCategoriesFromMenu(QMenu *menu, int modRow, int referenceRow); + + /** + * Sets category selections from menu; for multiple mods, this will completely + * replace the current set of categories on each selected with those selected in the menu + * @param menu the menu after editing by the user + * @param modRow index of the mod to edit + */ + void replaceCategoriesFromMenu(QMenu *menu, int modRow); + + bool populateMenuCategories(QMenu *menu, int targetID); + + void initDownloadView(); + void updateDownloadView(); + + // remove invalid category-references from mods + void fixCategories(); + + void createEndorseWidget(); + void createHelpWidget(); + + bool extractProgress(QProgressDialog &extractProgress, int percentage, std::string fileName); + + size_t checkForProblems(); + + int getBinaryExecuteInfo(const QFileInfo &targetInfo, QFileInfo &binaryInfo, QString &arguments); + QTreeWidgetItem *addFilterItem(QTreeWidgetItem *root, const QString &name, int categoryID, ModListSortProxy::FilterType type); + void addContentFilters(); + void addCategoryFilters(QTreeWidgetItem *root, const std::set &categoriesUsed, int targetID); + + void setCategoryListVisible(bool visible); + + void displaySaveGameInfo(QListWidgetItem *newItem); + + HANDLE nextChildProcess(); + + bool errorReported(QString &logFile); + + void updateESPLock(bool locked); + + static void setupNetworkProxy(bool activate); + void activateProxy(bool activate); + void setBrowserGeometry(const QByteArray &geometry); + + bool createBackup(const QString &filePath, const QDateTime &time); + QString queryRestore(const QString &filePath); + + void initModListContextMenu(QMenu *menu); + void addModSendToContextMenu(QMenu *menu); + void addPluginSendToContextMenu(QMenu *menu); + + QMenu *openFolderMenu(); + + std::set enabledArchives(); + + void scheduleUpdateButton(); + + QDir currentSavesDir() const; + + void startMonitorSaves(); + void stopMonitorSaves(); + + void dropLocalFile(const QUrl &url, const QString &outputDir, bool move); + + bool registerWidgetState(const QString &name, QHeaderView *view, const char *oldSettingName = nullptr); + + void sendSelectedModsToPriority(int newPriority); + void sendSelectedPluginsToPriority(int newPriority); + +private: + + static const char *PATTERN_BACKUP_GLOB; + static const char *PATTERN_BACKUP_REGEX; + static const char *PATTERN_BACKUP_DATE; + +private: + + Ui::MainWindow *ui; + + QAction *m_Sep; // Executable Shortcuts are added after this. Non owning. + + bool m_WasVisible; + + MOBase::TutorialControl m_Tutorial; + + int m_OldProfileIndex; + + std::vector m_ModNameList; // the mod-list to go with the directory structure + QProgressBar *m_RefreshProgress; + bool m_Refreshing; + + QStringList m_DefaultArchives; + + QAbstractItemModel *m_ModListGroupingProxy; + ModListSortProxy *m_ModListSortProxy; + + PluginListSortProxy *m_PluginListSortProxy; + + int m_OldExecutableIndex; + + int m_ContextRow; + QPersistentModelIndex m_ContextIdx; + QTreeWidgetItem *m_ContextItem; + QAction *m_ContextAction; + + CategoryFactory &m_CategoryFactory; + + int m_ModsToUpdate; + + bool m_LoginAttempted; + + QTimer m_CheckBSATimer; + QTimer m_SaveMetaTimer; + QTimer m_UpdateProblemsTimer; + + QFuture m_MetaSave; + + QTime m_StartTime; + //SaveGameInfoWidget *m_CurrentSaveView; + MOBase::ISaveGameInfoWidget *m_CurrentSaveView; + + OrganizerCore &m_OrganizerCore; + PluginContainer &m_PluginContainer; + + QString m_CurrentLanguage; + std::vector m_Translators; + + BrowserDialog m_IntegratedBrowser; + + QFileSystemWatcher m_SavesWatcher; + + std::vector m_RemoveWidget; + + QByteArray m_ArchiveListHash; + + bool m_DidUpdateMasterList; + + LockedDialogBase *m_LockDialog { nullptr }; + uint64_t m_LockCount { 0 }; + + bool m_closing{ false }; + + bool m_showArchiveData{ true }; + + std::vector> m_PersistedGeometry; + + MOBase::DelayedFileWriter m_ArchiveListWriter; + + enum class ShortcutType { + Toolbar, + Desktop, + StartMenu + }; + + void addWindowsLink(ShortcutType const); + + Executable const &getSelectedExecutable() const; + Executable &getSelectedExecutable(); + +private slots: + + void updateWindowTitle(const QString &accountName, bool premium); + + void showMessage(const QString &message); + void showError(const QString &message); + + + // main window actions + void helpTriggered(); + void issueTriggered(); + void wikiTriggered(); + void discordTriggered(); + void tutorialTriggered(); + void extractBSATriggered(); + + //modlist shortcuts + void openExplorer_activated(); + void refreshProfile_activated(); + + // modlist context menu + void installMod_clicked(); + void createEmptyMod_clicked(); + void createSeparator_clicked(); + void restoreBackup_clicked(); + void renameMod_clicked(); + void removeMod_clicked(); + void setColor_clicked(); + void resetColor_clicked(); + void backupMod_clicked(); + void reinstallMod_clicked(); + void endorse_clicked(); + void dontendorse_clicked(); + void unendorse_clicked(); + void ignoreMissingData_clicked(); + void markConverted_clicked(); + void visitOnNexus_clicked(); + void visitWebPage_clicked(); + void openExplorer_clicked(); + void openOriginExplorer_clicked(); + void openOriginInformation_clicked(); + void information_clicked(); + void enableSelectedMods_clicked(); + void disableSelectedMods_clicked(); + void sendSelectedModsToTop_clicked(); + void sendSelectedModsToBottom_clicked(); + void sendSelectedModsToPriority_clicked(); + void sendSelectedModsToSeparator_clicked(); + // savegame context menu + void deleteSavegame_clicked(); + void fixMods_clicked(SaveGameInfo::MissingAssets const &missingAssets); + // data-tree context menu + void writeDataToFile(); + void openDataFile(); + void addAsExecutable(); + void previewDataFile(); + void hideFile(); + void unhideFile(); + + // pluginlist context menu + void enableSelectedPlugins_clicked(); + void disableSelectedPlugins_clicked(); + void sendSelectedPluginsToTop_clicked(); + void sendSelectedPluginsToBottom_clicked(); + void sendSelectedPluginsToPriority_clicked(); + + void linkToolbar(); + void linkDesktop(); + void linkMenu(); + + void languageChange(const QString &newLanguage); + void saveSelectionChanged(QListWidgetItem *newItem); + + void windowTutorialFinished(const QString &windowName); + + BSA::EErrorCode extractBSA(BSA::Archive &archive, BSA::Folder::Ptr folder, const QString &destination, QProgressDialog &extractProgress); + + void createModFromOverwrite(); + /** + * @brief sends the content of the overwrite folder to an already existing mod + */ + void moveOverwriteContentToExistingMod(); + /** + * @brief actually sends the content of the overwrite folder to specified mod + */ + void doMoveOverwriteContentToMod(const QString &modAbsolutePath); + void clearOverwrite(); + + void procError(QProcess::ProcessError error); + void procFinished(int exitCode, QProcess::ExitStatus exitStatus); + + // nexus related + void checkModsForUpdates(); + + void validationFailed(const QString &message); + + void linkClicked(const QString &url); + + void updateAvailable(); + + void motdReceived(const QString &motd); + void notEndorsedYet(); + void wontEndorse(); + + void originModified(int originID); + + void addRemoveCategories_MenuHandler(); + void replaceCategories_MenuHandler(); + + void addPrimaryCategoryCandidates(); + + void modDetailsUpdated(bool success); + + void modInstalled(const QString &modName); + + void nxmUpdatesAvailable(const std::vector &modIDs, QVariant userData, QVariant resultData, int requestID); + void nxmEndorsementToggled(QString, int, QVariant, QVariant resultData, int); + void nxmDownloadURLs(QString, int modID, int fileID, QVariant userData, QVariant resultData, int requestID); + void nxmRequestFailed(QString, int modID, int fileID, QVariant userData, int requestID, const QString &errorString); + + void editCategories(); + void deselectFilters(); + + void displayModInformation(const QString &modName, int tab); + void modOpenNext(int tab=-1); + void modOpenPrev(int tab=-1); + + void modRenamed(const QString &oldName, const QString &newName); + void modRemoved(const QString &fileName); + + void hideSaveGameInfo(); + + void hookUpWindowTutorials(); + + void resumeDownload(int downloadIndex); + void endorseMod(ModInfo::Ptr mod); + void unendorseMod(ModInfo::Ptr mod); + void cancelModListEditor(); + + void lockESPIndex(); + void unlockESPIndex(); + + void enableVisibleMods(); + void disableVisibleMods(); + void exportModListCSV(); + void openInstanceFolder(); + void openLogsFolder(); + void openInstallFolder(); + void openPluginsFolder(); + void openDownloadsFolder(); + void openModsFolder(); + void openProfileFolder(); + void openIniFolder(); + void openGameFolder(); + void openMyGamesFolder(); + void startExeAction(); + + void checkBSAList(); + + void updateProblemsButton(); + + void saveModMetas(); + + void updateStyle(const QString &style); + + void modlistChanged(const QModelIndex &index, int role); + void modlistChanged(const QModelIndexList &indicies, int role); + void fileMoved(const QString &filePath, const QString &oldOriginName, const QString &newOriginName); + + + void modFilterActive(bool active); + void espFilterChanged(const QString &filter); + void downloadFilterChanged(const QString &filter); + + void expandModList(const QModelIndex &index); + + /** + * @brief resize columns in mod list and plugin list to content + */ + void resizeLists(bool modListCustom, bool pluginListCustom); + + /** + * @brief allow columns in mod list and plugin list to be resized + */ + void allowListResize(); + + void toolBar_customContextMenuRequested(const QPoint &point); + void removeFromToolbar(); + void overwriteClosed(int); + + void changeVersioningScheme(); + void ignoreUpdate(); + void unignoreUpdate(); + + void refreshSavesIfOpen(); + void expandDataTreeItem(QTreeWidgetItem *item); + void about(); + void delayedRemove(); + + void modlistSelectionChanged(const QModelIndex ¤t, const QModelIndex &previous); + void modListSortIndicatorChanged(int column, Qt::SortOrder order); + void modListSectionResized(int logicalIndex, int oldSize, int newSize); + + void modlistSelectionsChanged(const QItemSelection ¤t); + void esplistSelectionsChanged(const QItemSelection ¤t); + + void search_activated(); + void searchClear_activated(); + + void updateModCount(); + void updatePluginCount(); + +private slots: // ui slots + // actions + void on_actionAdd_Profile_triggered(); + void on_actionInstallMod_triggered(); + void on_actionModify_Executables_triggered(); + void on_actionNexus_triggered(); + void on_actionNotifications_triggered(); + void on_actionSettings_triggered(); + void on_actionUpdate_triggered(); + void on_actionEndorseMO_triggered(); + + void on_bsaList_customContextMenuRequested(const QPoint &pos); + void on_clearFiltersButton_clicked(); + void on_btnRefreshData_clicked(); + void on_btnRefreshDownloads_clicked(); + void on_categoriesList_customContextMenuRequested(const QPoint &pos); + void on_conflictsCheckBox_toggled(bool checked); + void on_showArchiveDataCheckBox_toggled(bool checked); + void on_dataTree_customContextMenuRequested(const QPoint &pos); + void on_executablesListBox_currentIndexChanged(int index); + void on_modList_customContextMenuRequested(const QPoint &pos); + void on_modList_doubleClicked(const QModelIndex &index); + void on_listOptionsBtn_pressed(); + void on_espList_doubleClicked(const QModelIndex &index); + void on_profileBox_currentIndexChanged(int index); + void on_savegameList_customContextMenuRequested(const QPoint &pos); + void on_startButton_clicked(); + void on_tabWidget_currentChanged(int index); + + void on_espList_customContextMenuRequested(const QPoint &pos); + void on_displayCategoriesBtn_toggled(bool checked); + void on_groupCombo_currentIndexChanged(int index); + void on_categoriesList_itemSelectionChanged(); + void on_linkButton_pressed(); + void on_showHiddenBox_toggled(bool checked); + void on_bsaList_itemChanged(QTreeWidgetItem *item, int column); + void on_bossButton_clicked(); + + void on_saveButton_clicked(); + void on_restoreButton_clicked(); + void on_restoreModsButton_clicked(); + void on_saveModsButton_clicked(); + void on_actionCopy_Log_to_Clipboard_triggered(); + void on_categoriesAndBtn_toggled(bool checked); + void on_categoriesOrBtn_toggled(bool checked); + void on_managedArchiveLabel_linkHovered(const QString &link); +}; + + + +#endif // MAINWINDOW_H diff --git a/src/nxmaccessmanager.cpp b/src/nxmaccessmanager.cpp index dc1eb2cb..5da7b6a3 100644 --- a/src/nxmaccessmanager.cpp +++ b/src/nxmaccessmanager.cpp @@ -215,7 +215,7 @@ void NXMAccessManager::validateTimeout() m_ApiKey.clear(); m_ValidateState = VALIDATE_NOT_VALID; - emit validateFailed(tr("timeout")); + emit validateFailed(tr("There was a timeout during the request")); } diff --git a/src/organizer_en.ts b/src/organizer_en.ts index 43c01310..bcdbd069 100644 --- a/src/organizer_en.ts +++ b/src/organizer_en.ts @@ -26,7 +26,7 @@ - Current Maintainers + Lead Developers/ Maintainers @@ -35,67 +35,92 @@ - - Major Contributors + + Mo2 devs and Contributors - + + Project579 + + + + + przester + + + + Translators - + Cyb3r (Dutch) - + fruttyx (French) - + Yoplala (French) - + Faron (German) - + Mordan (Greek) - + Yoosk (Polish) - + Brgodfx (Portuguese) - + + zDas (Portuguese) + + + + Jax (Swedish) - + + yohru (Japanese) + + + + ...and all other Transifex contributors! - + Other Supporters && Contributors - + + Tannin (Original Creator) + + + + Close @@ -279,12 +304,12 @@ p, li { white-space: pre-wrap; } DirectoryRefresher - + failed to parse bsa %1: %2 - + failed to read mod (%1): %2 @@ -292,435 +317,251 @@ p, li { white-space: pre-wrap; } DownloadList - + Name - - Filetime - - - - + Size - - Done + + Status - - Information missing, please select "Query Info" from the context menu to re-retrieve. - - - - - pending download - - - - - DownloadListWidget - - - - Placeholder + + Filetime - - - - Done - Double Click to install + + < game %1 mod %2 file %3 > - - - Paused - Double Click to resume + + Unknown - - - Installed - Double Click to re-install + + Pending - - - Uninstalled - Double Click to re-install + + Started - - - DownloadListWidgetCompact - - - Placeholder + + Canceling - - Done + + Pausing - - - DownloadListWidgetCompactDelegate - - < game %1 mod %2 file %3 > + + Canceled - - Pending + + Paused - - Paused + + Error - + Fetching Info 1 - + Fetching Info 2 - - Installed - - - - - Uninstalled - - - - - Done - - - - - - - - - - - Are you sure? + + Downloaded - - This will permanently delete the selected download. - - - - - This will remove all finished downloads from this list and from disk. - - - - - This will remove all installed downloads from this list and from disk. - - - - - This will remove all uninstalled downloads from this list and from disk. + + Installed - - This will permanently remove all finished downloads from this list (but NOT from disk). + + Uninstalled - - This will permanently remove all installed downloads from this list (but NOT from disk). + + Pending download - - This will permanently remove all uninstalled downloads from this list (but NOT from disk). + + Information missing, please select "Query Info" from the context menu to re-retrieve. + + + DownloadListWidget - + Install - + Query Info - + Visit on Nexus - + Open File - - - + + + Show in Folder - + + Delete - + Un-Hide - + Hide - + Cancel - + Pause - - Remove - - - - + Resume - + Delete Installed... - + Delete Uninstalled... - + Delete All... - + Hide Installed... - + Hide Uninstalled... - + Hide All... - + Un-Hide All... - - - DownloadListWidgetDelegate - - - < game %1 mod %2 file %3 > - - - - - Pending - - - - - Fetching Info 1 - - - - Fetching Info 2 - - - - - - - + + + + Delete Files? - + This will permanently delete the selected download. - + This will remove all finished downloads from this list and from disk. - + This will remove all installed downloads from this list and from disk. - + This will remove all uninstalled downloads from this list and from disk. - - - + + + Are you sure? - + This will remove all finished downloads from this list (but NOT from disk). - + This will remove all installed downloads from this list (but NOT from disk). - + This will remove all uninstalled downloads from this list (but NOT from disk). - - - Install - - - - - Query Info - - - - - Visit on Nexus - - - - - Open File - - - - - - - Show in Folder - - - - - - Delete - - - - - Un-Hide - - - - - Hide - - - - - Cancel - - - - - Pause - - - - - Resume - - - - - Delete Installed... - - - - - Delete Uninstalled... - - - - - Delete All... - - - - - Hide Installed... - - - - - Hide Uninstalled... - - - - - Hide All... - - - - - Un-Hide All... - - DownloadManager @@ -746,7 +587,7 @@ p, li { white-space: pre-wrap; } - A file with the same name has already been downloaded. Do you want to download it again? The new file will receive a different name. + A file with the same name "%1" has already been downloaded. Do you want to download it again? The new file will receive a different name. @@ -777,7 +618,7 @@ p, li { white-space: pre-wrap; } - + remove: invalid download index %1 @@ -797,234 +638,234 @@ p, li { white-space: pre-wrap; } - + cancel: invalid download index %1 - + pause: invalid download index %1 - + resume: invalid download index %1 - + resume (int): invalid download index %1 - + No known download urls. Sorry, this download can't be resumed. - + query: invalid download index %1 - + Please enter the nexus mod id - + Mod ID: - + Please select the source game code for %1 - + VisitNexus: invalid download index %1 - + Nexus ID for this Mod is unknown - + OpenFile: invalid download index %1 - + OpenFileInDownloadsFolder: invalid download index %1 - + get pending: invalid download index %1 - + get path: invalid download index %1 - + Main - + Update - + Optional - + Old - + Misc - + Unknown - + display name: invalid download index %1 - + file name: invalid download index %1 - + file time: invalid download index %1 - + file size: invalid download index %1 - + progress: invalid download index %1 - + state: invalid download index %1 - + infocomplete: invalid download index %1 - - + + mod id: invalid download index %1 - + ishidden: invalid download index %1 - + file info: invalid download index %1 - + mark installed: invalid download index %1 - + mark uninstalled: invalid download index %1 - + Memory allocation error (in processing progress event). - + Memory allocation error (in processing downloaded data). - + Information updated - - + + No matching file found on Nexus! Maybe this file is no longer available or it was renamed? - + No file on Nexus matches the selected file by name. Please manually choose the correct one. - + No download server available. Please try again later. - + Failed to request file info from nexus: %1 - + Warning: Content type is: %1 - + Download header content length: %1 downloaded file size: %2 - + Download failed: %1 (%2) - + We were unable to download the file due to errors after four retries. There may be an issue with the Nexus servers. - + failed to re-open %1 - + Unable to write download to drive (return %1). Check the drive's available storage. @@ -1143,92 +984,107 @@ Right now the only case I know of where this needs to be overwritten is for the - + + If this is enabled, the configured libraries will be automatically loaded when this executable is launched. + + + + + Force Load Libraries (*) + + + + + Configure Libraries + + + + Use Application's Icon for shortcuts - + (*) This setting is profile-specific - - + + Add an executable - - + + Add - - + + Remove the selected executable - + Remove - + Close - + Select a binary - + Executable (%1) - + Java (32-bit) required - + MO requires 32-bit java to run this application. If you already have it installed, select javaw.exe from that installation as the binary. - + Select a directory - + Confirm - + Really remove "%1" from executables? - + Modify - - + + Save Changes? - - + + You made changes to the current executable, do you want to save them? @@ -1280,6 +1136,85 @@ Right now the only case I know of where this needs to be overwritten is for the + + ForcedLoadDialog + + + Forced Load Settings + + + + + + Adds a row to the table. + + + + + Add Row + + + + + + Deletes the selected row from the table. + + + + + Delete Row + + + + + ForcedLoadDialogWidget + + + + If checked, the specified library will be force loaded for the specified process. + + + + + + The name of the process that should be forced to load a library. + + + + + Process name + + + + + + Browse for a process. + + + + + + ... + + + + + + The path to the library to be loaded. This may be a path relative to the managed game's directory or may be an absolute path to somewhere else. + + + + + Library to load + + + + + + Browse for a library. + + + InstallDialog @@ -1386,59 +1321,72 @@ p, li { white-space: pre-wrap; } - + File format "%1" not supported - + None of the available installer plugins were able to handle that archive. This is likely due to a corrupted or incompatible download or unrecognized archive format. - + no error - + 7z.dll not found - + 7z.dll isn't valid - + archive not found - + failed to open archive - + unsupported archive type - + internal library error - + archive invalid - - unknown archive error + + unknown archive error + + + + + ListDialog + + + Select an item... + + + + + Filter @@ -1499,17 +1447,17 @@ This is likely due to a corrupted or incompatible download or unrecognized archi - + failed to write to %1 - + file not found: %1 - + Save @@ -1534,47 +1482,47 @@ This is likely due to a corrupted or incompatible download or unrecognized archi MainWindow - + Categories - + Clear - + If checked, only mods that match all selected categories are displayed. - + And - + If checked, all mods that match at least one of the selected categories are displayed. - + Or - + Profile - + Pick a module collection - + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } @@ -1584,76 +1532,84 @@ p, li { white-space: pre-wrap; } - + Open list options... - + Refresh list. This is usually not necessary unless you modified data outside the program. - + Show Open Folders menu... - - + + Restore Backup... - - + + + Create Backup - + + + Active: + + + + + This provides statistics about the mod list. The total number of active mod is normally displayed. Other statistics may be accessed with the tooltip of this counter. + + + + List of available mods. - + This is a list of installed mods. Use the checkboxes to activate/deactivate mods and drag & drop mods to change their "installation" orders. - + + + + Filter - + Clear all Filters - + No groups - + Nexus IDs - - - - Namefilter - - - - + Pick a program to run. - + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } @@ -1663,12 +1619,12 @@ p, li { white-space: pre-wrap; } - + Run program - + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } @@ -1677,17 +1633,17 @@ p, li { white-space: pre-wrap; } - + Run - + Create a shortcut in your start menu or on the desktop to the specified program - + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } @@ -1696,27 +1652,32 @@ p, li { white-space: pre-wrap; } - + Shortcut - + Plugins - + Sort + This provides statistics about the plugin list. The total number of active plugins is normally displayed. Other statistics may be accessed with the tooltip of this counter. + + + + List of available esp/esm files - + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } @@ -1725,27 +1686,27 @@ p, li { white-space: pre-wrap; } - + Archives - + <html><head/><body><p>BSAs / BA2s are bundles of game assets (textures, scripts, etc.). By default, the engine loads these bundles in a separate step from loose files. <p>Their load order is specified by the priority of the corresponding plugin (right pane, plugins tab).</p><p>If there is a matching plugin, the game will load them no matter what.</p></body></html> - + <html><head/><body><p>Currently detected archives. (<a href="#"><span style=" text-decoration: underline; color:#0000ff;">What is an archive?</span></a>)</p></body></html> - + List of available BS Archives. Archives not checked here are not managed by MO and ignore installation order. - + BSA files are archives (comparable to .zip files) that contain data assets (meshes, textures, ...) to be used by the game. As such they "compete" with loose files in your data directory over which is loaded. By default, BSAs that share their base name with an enabled ESP (i.e. plugin.esp and plugin.bsa) are automatically loaded and will have precedence over all loose files, the installation order you set up to the left is then ignored! @@ -1753,219 +1714,236 @@ p, li { white-space: pre-wrap; } - + Data - + refresh data-directory overview - + Refresh the overview. This may take a moment. - - - + + + + Refresh - + This is an overview of your data directory as visible to the game (and tools). - + File - + Mod - - - Filter the above list so that only conflicts are displayed. + + + Filters the above list so that only conflicts are displayed. - + Show only conflicts - + + + Filters the above list so that files from archives are not shown + + + + + Show files from Archives + + + + Saves - + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">This is a list of all savegames for this game. Hover over a list entry to get detailed information about the save including a list of esps/esms that were used at the time this save was created but aren't active now.</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">This is a list of all save games for this game. Hover over a list entry to get detailed information about the save including a list of esps/esms that were used at the time this save was created but aren't active now.</span></p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:8pt;"></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">If you click &quot;Fix Mods...&quot; in the context menu, MO will try to activate all mods and esps to fix those missing esps. It will not disable anything!</span></p></body></html> - + Downloads - + + Refresh downloads view + + + + This is a list of mods you downloaded from Nexus. Double click one to install it. You can also drag an archive into here. - + Show Hidden - + Tool Bar - + Install Mod - + Install &Mod - + Install a new mod from an archive - + Ctrl+M - + Profiles - + &Profiles - + Configure Profiles - + Ctrl+P - + Executables - + &Executables - + Configure the executables that can be started through Mod Organizer - + Ctrl+E - - + + Tools - + &Tools - + Ctrl+I - + Settings - + &Settings - + Configure settings and workarounds - + Ctrl+S - + Nexus - + Search nexus network for more mods - + Ctrl+N - - + + Update - + Mod Organizer is up-to-date - - + + No Problems - + This button will be highlighted if MO discovered potential problems in your setup and provide tips on how to fix them. !Work in progress! @@ -1973,747 +1951,917 @@ Right now this has very limited functionality - - + + Help - + Ctrl+H - + Endorse MO - - + + Endorse Mod Organizer - + Copy Log to Clipboard - + Change Game - + Open the Instance selection dialog to manage a different Game - + Toolbar - + Desktop - + Start Menu - + There is no supported sort mechanism for this game. You will probably have to use a third-party tool. - + + Crash on exit + + + + + MO crashed while exiting. Some settings may not be saved. + +Error: %1 + + + + Problems - + There are potential problems with your setup - + Everything seems to be in order - + + + + Endorse + + + + + Won't Endorse + + + + Help on UI - - Documentation Wiki + + Documentation - + + Chat on Discord + + + + Report Issue - + Tutorials - + About - + About Qt - + Name - + Please enter a name for the new profile - + failed to create profile: %1 - + Show tutorial? - + You are starting Mod Organizer for the first time. Do you want to show a tutorial of its basic features? If you choose no you can always start the tutorial from the "Help"-menu. - + Downloads in progress - + There are still downloads in progress, do you really want to quit? - + Plugin "%1" failed: %2 - + Plugin "%1" failed - + Browse Mod Page - + Also in: <br> - + No conflict - + <Edit...> - + This bsa is enabled in the ini file so it may be required! - + Activating Network Proxy - - Notice: Your current MO version (%1) is lower than the previous version (%2).<br>The GUI may not downgrade gracefully, so you may experience oddities.<br>However, there should be no serious issues. + + Notice: Your current MO version (%1) is lower than the previously used one (%2). The GUI may not downgrade gracefully, so you may experience oddities. However, there should be no serious issues. - + Choose Mod - + Mod Archive - + Start Tutorial? - + You're about to start a tutorial. For technical reasons it's not possible to end the tutorial early. Continue? - + failed to spawn notepad.exe: %1 - + failed to change origin name: %1 - + failed to move "%1" from mod "%2" to "%3": %4 - + <Contains %1> - + <Checked> - + <Unchecked> - + <Update> - + + <Mod Backup> + + + + <Managed by MO> - + <Managed outside MO> - + <No category> - + <Conflicted> - + <Not Endorsed> - + failed to rename mod: %1 - + Overwrite? - + This will replace the existing mod "%1". Continue? - + failed to remove mod "%1" - - - + + + failed to rename "%1" to "%2" - - - - + + + + Confirm - + Remove the following mods?<br><ul>%1</ul> - + failed to remove mod: %1 - - + + + Failed - + Installation file no longer exists - + Mods installed with old versions of MO can't be reinstalled in this way. - + + Failed to create backup. + + + + You need to be logged in with Nexus to resume a download - - + + + + You need to be logged in with Nexus to endorse - + + + Endorsing multiple mods will take a while. Please wait... + + + + + + Unendorsing multiple mods will take a while. Please wait... + + + + Failed to display overwrite dialog: %1 - + + Opening Nexus Links + + + + + You are trying to open %1 links to Nexus Mods. Are you sure you want to do this? + + + + Nexus ID for this Mod is unknown - + + Opening Web Pages + + + + + You are trying to open %1 Web Pages. Are you sure you want to do this? + + + + Web page for this mod is unknown - - - + + <table cellspacing="5"><tr><th>Type</th><th>All</th><th>Visible</th><tr><td>Enabled mods:&emsp;</td><td align=right>%1 / %2</td><td align=right>%3 / %4</td></tr><tr><td>Unmanaged/DLCs:&emsp;</td><td align=right>%5</td><td align=right>%6</td></tr><tr><td>Mod backups:&emsp;</td><td align=right>%7</td><td align=right>%8</td></tr><tr><td>Separators:&emsp;</td><td align=right>%9</td><td align=right>%10</td></tr></table> + + + + + <table cellspacing="6"><tr><th>Type</th><th>Active </th><th>Total</th></tr><tr><td>All plugins:</td><td align=right>%1 </td><td align=right>%2</td></tr><tr><td>ESMs:</td><td align=right>%3 </td><td align=right>%4</td></tr><tr><td>ESPs:</td><td align=right>%7 </td><td align=right>%8</td></tr><tr><td>ESMs+ESPs:</td><td align=right>%9 </td><td align=right>%10</td></tr><tr><td>ESLs:</td><td align=right>%5 </td><td align=right>%6</td></tr></table> + + + + + + Create Mod... - + This will create an empty mod. Please enter a name: - - + + A mod with this name already exists - + + Create Separator... + + + + + This will create a new separator. +Please enter a name: + + + + + A separator with this name already exists + + + + This will move all files from overwrite into a new, regular mod. Please enter a name: - - + + Move successful. + + + + + Are you sure? - + About to recursively delete: - + Not logged in, endorsement information will be wrong - + Continue? - + The versioning scheme decides which version is considered newer than another. This function will guess the versioning scheme under the assumption that the installed version is outdated. - - + + Sorry - + I don't know a versioning scheme where %1 is newer than %2. - + Really enable all visible mods? - + Really disable all visible mods? - + Export to csv - + CSV (Comma Separated Values) is a format that can be imported in programs like Excel to create a spreadsheet. You can also use online editors and converters instead. - + Select what mods you want export: - + All installed mods - + Only active (checked) mods from your current profile - + All currently visible mods in the mod list - + Choose what Columns to export: - + Mod_Priority - + Mod_Name - + + Notes_column + + + + Mod_Status - + Primary_Category - + Nexus_ID - + Mod_Nexus_URL - + Mod_Version - + Install_Date - + Download_File_Name - + export failed: %1 - + Open Game folder - + Open MyGames folder - + + Open INIs folder + + + + Open Instance folder - + Open Mods folder - + Open Profile folder - + Open Downloads folder - + Open MO2 Install folder - + Open MO2 Plugins folder - + Open MO2 Logs folder - + Install Mod... - + Create empty mod - + + Create Separator + + + + Enable all visible - + Disable all visible - + Check all for update - + Export to csv... - + + + Send to + + + + + + Top + + + + + + Bottom + + + + + + Priority... + + + + + Separator... + + + + All Mods - + Sync to Mods... - + + Move content to Mod... + + + + Clear Overwrite... - - + + Open in Explorer - + Restore Backup - + Remove Backup... - + + Change Categories - + + Primary Category - + + Rename Separator... + + + + + Remove Separator... + + + + + Select Color... + + + + + Reset Color + + + + Change versioning scheme - + Un-ignore update - + Ignore update - - + + Enable selected - - + + Disable selected - + Rename Mod... - + Reinstall Mod - + Remove Mod... - + Un-Endorse - - - Endorse - - - - + Won't endorse - + Endorsement state unknown - + Ignore missing data - + Mark as converted/working - + Visit on Nexus - + Visit web page - + Information... - - + + Exception: - - + + Unknown exception - + <All> - + <Multiple> - + %1 more - + Are you sure you want to remove the following %n save(s)?<br><ul>%1</ul><br>Removed saves will be sent to the Recycle Bin. @@ -2721,12 +2869,12 @@ You can also use online editors and converters instead. - + Enable Mods... - + Delete %n save(s) @@ -2734,322 +2882,371 @@ You can also use online editors and converters instead. - + failed to remove %1 - + failed to create %1 - + + Restarting MO + + + + + Changing the managed game directory requires restarting MO. +Any pending downloads will be paused. + +Click OK to restart MO now. + + + + Can't change download directory while downloads are in progress! - + failed to write to file %1 - + %1 written - + Select binary - + Binary - + Enter Name - + Please enter a name for the executable - + Not an executable - + This is not a recognized executable. - - + + Replace file? - + There already is a hidden version of this file. Replace it? - - + + File operation failed - - + + Failed to remove "%1". Maybe you lack the required file permissions? - + There already is a visible version of this file. Replace it? - + + + Set Priority + + + + + Set the priority of the selected plugins + + + + file not found: %1 - + failed to generate preview for %1 - + Sorry, can't preview anything. This function currently does not support extracting from bsas. - + Update available - + Open/Execute - + Add as Executable - + Preview - + Un-Hide - + Hide - + Write To File... - + Do you want to endorse Mod Organizer on %1 now? - + Thank you! - + Thank you for your endorsement! - + + Okay. + + + + + This mod will not be endorsed and will no longer ask you to endorse. + + + + Request to Nexus failed: %1 - - + + failed to read %1: %2 - - + + Error - + failed to extract %1 (errorcode %2) - + Extract BSA - + This archive contains invalid hashes. Some files may be broken. - + Extract... - + This will restart MO, continue? - + Edit Categories... - + Deselect filter - + Remove - + Enable all - + Disable all - + Unlock load order - + Lock load order - + + Open Origin in Explorer + + + + + Open Origin Info... + + + + depends on missing "%1" - + incompatible with "%1" - + Please wait while LOOT is running - + loot failed. Exit code was: %1 - + failed to start loot - + failed to run loot: %1 - + Errors occured - + Backup of load order created - + Choose backup to restore - + No Backups - + There are no backups to restore - - + + Restore failed - - + + Failed to restore the backup. Errorcode: %1 - + Backup of modlist created - + A file with the same name has already been downloaded. What would you like to do? - + Overwrite - + Rename new file - + Ignore file + + + Set the priority of the selected mods + + MessageDialog @@ -3063,72 +3260,82 @@ You can also use online editors and converters instead. ModInfo - + Plugins - + Textures - + Meshes - + Bethesda Archive - + UI Changes - + Sound Effects - + Scripts - + Script Extender - + + Script Extender Files + + + + SkyProc Tools - + MCM Data - + INI files - + + ModGroup files + + + + invalid content type %1 - + invalid mod index %1 - + remove: invalid mod index %1 @@ -3398,37 +3605,56 @@ p, li { white-space: pre-wrap; } - + about:blank - + Endorse - + + Web page URL (only used if invalid NexusID) : + + + + Notes - + + + + Enter comments about the mod here. These are displayed in the notes column of the mod list. + + + + + + + Enter notes about the mod here. These can be viewed in the mod list by hovering over the notes column or the flags column. + + + + Filetree - + Open Mod in Explorer - + A directory view of this mod - + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } @@ -3438,288 +3664,288 @@ p, li { white-space: pre-wrap; } - + Previous - + Next - + Close - + &Delete - + &Rename - + &Hide - + &Unhide - + &Open - + &New Folder - - + + Save changes? - - + + Save changes to "%1"? - + File Exists - + A file with that name exists, please enter a new one - + failed to move file - + failed to create directory "optional" - - + + Info requested, please wait - + Main - + Update - + Optional - + Old - + Misc - + Unknown - + Current Version: %1 - + No update available - + (description incomplete, please visit nexus) - + <a href="%1">Visit on Nexus</a> - + Failed to delete %1 - - - - + + + + Confirm - - + + Are sure you want to delete "%1"? - - + + Are sure you want to delete the selected files? - - + + New Folder - + Failed to create "%1" - - + + Replace file? - + There already is a hidden version of this file. Replace it? - - + + File operation failed - - + + Failed to remove "%1". Maybe you lack the required file permissions? - - + + failed to rename %1 to %2 - + There already is a visible version of this file. Replace it? - + Select binary - + Binary - + file not found: %1 - + failed to generate preview for %1 - + Sorry - + Sorry, can't preview anything. This function currently does not support extracting from bsas. - + Un-Hide - + Hide - - + + Open/Execute - - + + Preview - + Name - + Please enter a name - - + + Error - + Invalid name. Must be a valid file name - + A tweak by that name exists - + Create Tweak @@ -3758,300 +3984,328 @@ p, li { white-space: pre-wrap; } ModInfoRegular - - + + failed to write %1/meta.ini: error %2 - + %1 contains no esp/esm/esl and no asset (textures, meshes, interface, ...) directory - + Categories: <br> + + ModInfoSeparator + + + This is a Separator + + + ModList - + Game Plugins (ESP/ESM/ESL) - + Interface - + Meshes - + Bethesda Archive - + Scripts (Papyrus) - + Script Extender Plugin - + SkyProc Patcher - + Sound or Music - + Textures - + MCM Configuration - + INI files - + + ModGroup files + + + + This entry contains files that have been created inside the virtual data tree (i.e. by the construction kit) - + Backup - + + Separator + + + + No valid game data - + Not endorsed yet - + Overwrites loose files - + Overwritten loose files - + Loose files Overwrites & Overwritten - + Redundant - + Overwrites an archive with loose files - + Archive is overwritten by loose files - + Overwrites another archive file - + Overwritten by another archive file - + Archive files overwrites & overwritten - - Alternate game source + + <br>This mod is for a different game, make sure it's compatible or it could cause crashes. - + Non-MO - + invalid - + installed version: "%1", newest version: "%2" - + The newest version on Nexus seems to be older than the one you have installed. This could either mean the version you have has been withdrawn (i.e. due to a bug) or the author uses a non-standard versioning scheme and that newest version is actually newer. Either way you may want to "upgrade". - + Categories: <br> - + Invalid name - + Name is already in use by another mod - + drag&drop failed: %1 - + Confirm - + Are you sure you want to remove "%1"? - + Flags - + Content - + Mod Name - + Version - + Priority - + Category - + Source Game - + Nexus ID - + Installation - - + + Notes + + + + + unknown - + Name of your mods - + Version of the mod (if available) - + Installation priority of your mod. The higher, the more "important" it is and thus overwrites files from mods with lower priority. - + Category of the mod. - + The source game which was the origin of this mod. - + Id of the mod as used on Nexus. - + Emblemes to highlight things that might require attention. - - Depicts the content of the mod:<br><table cellspacing=7><tr><td><img src=":/MO/gui/content/plugin" width=32/></td><td>Game plugins (esp/esm/esl)</td></tr><tr><td><img src=":/MO/gui/content/interface" width=32/></td><td>Interface</td></tr><tr><td><img src=":/MO/gui/content/mesh" width=32/></td><td>Meshes</td></tr><tr><td><img src=":/MO/gui/content/bsa" width=32/></td><td>BSA</td></tr><tr><td><img src=":/MO/gui/content/texture" width=32/></td><td>Textures</td></tr><tr><td><img src=":/MO/gui/content/sound" width=32/></td><td>Sounds</td></tr><tr><td><img src=":/MO/gui/content/music" width=32/></td><td>Music</td></tr><tr><td><img src=":/MO/gui/content/string" width=32/></td><td>Strings</td></tr><tr><td><img src=":/MO/gui/content/script" width=32/></td><td>Scripts (Papyrus)</td></tr><tr><td><img src=":/MO/gui/content/skse" width=32/></td><td>Script Extender plugins</td></tr><tr><td><img src=":/MO/gui/content/skyproc" width=32/></td><td>SkyProc Patcher</td></tr><tr><td><img src=":/MO/gui/content/menu" width=32/></td><td>Mod Configuration Menu</td></tr><tr><td><img src=":/MO/gui/content/inifile" width=32/></td><td>INI files</td></tr></table> + + Depicts the content of the mod:<br><table cellspacing=7><tr><td><img src=":/MO/gui/content/plugin" width=32/></td><td>Game plugins (esp/esm/esl)</td></tr><tr><td><img src=":/MO/gui/content/interface" width=32/></td><td>Interface</td></tr><tr><td><img src=":/MO/gui/content/mesh" width=32/></td><td>Meshes</td></tr><tr><td><img src=":/MO/gui/content/bsa" width=32/></td><td>BSA</td></tr><tr><td><img src=":/MO/gui/content/texture" width=32/></td><td>Textures</td></tr><tr><td><img src=":/MO/gui/content/sound" width=32/></td><td>Sounds</td></tr><tr><td><img src=":/MO/gui/content/music" width=32/></td><td>Music</td></tr><tr><td><img src=":/MO/gui/content/string" width=32/></td><td>Strings</td></tr><tr><td><img src=":/MO/gui/content/script" width=32/></td><td>Scripts (Papyrus)</td></tr><tr><td><img src=":/MO/gui/content/skse" width=32/></td><td>Script Extender plugins</td></tr><tr><td><img src=":/MO/gui/content/skyproc" width=32/></td><td>SkyProc Patcher</td></tr><tr><td><img src=":/MO/gui/content/menu" width=32/></td><td>Mod Configuration Menu</td></tr><tr><td><img src=":/MO/gui/content/inifile" width=32/></td><td>INI files</td></tr><tr><td><img src=":/MO/gui/content/modgroup" width=32/></td><td>ModGroup files</td></tr></table> - + Time this mod was installed + + + User notes about the mod + + ModListSortProxy - + Drag&Drop is only supported when sorting by priority @@ -4085,22 +4339,22 @@ p, li { white-space: pre-wrap; } NXMAccessManager - + Validating Nexus Connection - + Verifying Nexus login - + timeout - + Unknown error @@ -4116,17 +4370,17 @@ p, li { white-space: pre-wrap; } NexusInterface - + Failed to guess mod id for "%1", please pick the correct one - + empty response - + invalid response @@ -4165,170 +4419,183 @@ p, li { white-space: pre-wrap; } - - + + Download started - + Download failed - - + + Installation successful - - + + Configure Mod - - + + This mod contains ini tweaks. Do you want to configure them now? - - + + mod "%1" not found - - + + Installation cancelled - - + + The mod was not installed completely. - + Executable "%1" not found - + Start Steam? - + Steam is required to be running already to correctly start the game. Should MO try to start steam now? - + Error - + Windows Event Log Error - + The Windows Event Log service is disabled and/or not running. This prevents USVFS from running properly. Your mods may not be working in the executable that you are launching. Note that you may have to restart MO and/or your PC after the service is fixed. Continue launching %1? - + + Blacklisted Executable + + + + + The executable you are attempted to launch is blacklisted in the virtual file system. This will likely prevent the executable, and any executables that are launched by this one, from seeing any mods. This could extend to INI files, save games and any other virtualized files. + +Continue launching %1? + + + + No profile set - + Failed to refresh list of esps: %1 - + Multiple esps/esls activated, please check that they don't conflict. - + Download? - + A download has been started but no installed page plugin recognizes it. If you download anyway no information (i.e. version) will be associated with the download. Continue? - + + failed to update mod list: %1 - - + + login successful - + Login failed - + Login failed, try again? - + login failed: %1. Download will not be associated with an account - + login failed: %1 - + login failed: %1. You need to log-in with Nexus to update MO. - + MO1 "Script Extender" load mechanism has left hook.dll in your game folder - - + + Description missing - + <a href="%1">hook.dll</a> has been found in your game folder (right click to copy the full path). This is most likely a leftover of setting the ModOrganizer 1 load mechanism to "Script Extender", in which case you must remove this file either by changing the load mechanism in ModOrganizer 1 or manually removing the file, otherwise the game is likely to crash and burn. - + failed to save load order: %1 - + The designated write target "%1" is not enabled. @@ -4434,135 +4701,135 @@ Continue? PluginList - + Name - + Priority - + Mod Index - + Flags - - + + unknown - + Name of your mods - + Load priority of your mod. The higher, the more "important" it is and thus overwrites data from plugins with lower priority. - + The modindex determines the formids of objects originating from this mods. - + failed to update esp info for file %1 (source id: %2), error: %3 - + esp not found: %1 - - + + Confirm - + Really enable all plugins? - + Really disable all plugins? - + The file containing locked plugin indices is broken - - + + <b>Origin</b>: %1 - + <br><b><i>This plugin can't be disabled (enforced by the game).</i></b> - + Author - + Description - + Missing Masters - + Enabled Masters - + Loads Archives - + There are Archives connected to this plugin. Their assets will be added to your game, overwriting in case of conflicts following the plugin order. Loose files will always overwrite assets from Archives. (This flag only checks for Archives from the same mod as the plugin) - + Loads INI settings - + There is an ini file connected to this plugin. Its settings will be added to your game settings, overwriting in case of conflicts. - + This ESP is flagged as an ESL. It will adhere to the ESP load order but the records will be loaded in ESL space. - + failed to restore load order for %1 @@ -4570,7 +4837,7 @@ Continue? PluginListSortProxy - + Drag&Drop is only supported when sorting by priority or mod index @@ -4634,57 +4901,82 @@ p, li { white-space: pre-wrap; } - + failed to write mod list: %1 - + failed to update tweaked ini file, wrong settings may be used: %1 - + failed to create tweaked ini: %1 - + failed to open %1 - + "%1" is missing or inaccessible - - - - - + + + + + + + invalid index %1 - + Overwrite directory couldn't be parsed - + invalid priority %1 - - Delete savegames? + + Delete profile-specific save games? - - Do you want to delete local savegames? (If you select "No", the save games will show up again if you re-enable local savegames) + + Do you want to delete the profile-specific save games? (If you select "No", the save games will show up again if you re-enable profile-specific save games) + + + + + Missing profile-specific game INI files! + + + + + Some of your profile-specific game INI files were missing. They will now be copied from the vanilla game folder. You might want double-check your settings. + +Missing files: + + + + + + Delete profile-specific game INI files? + + + + + Do you want to delete the profile-specific game INI files? (If you select "No", the INI files will be used again if you re-enable profile-specific game INI files.) @@ -4702,17 +4994,17 @@ p, li { white-space: pre-wrap; } - If checked, the new profile will use the default game settings. + If checked, the new profile will use the default game INI settings. - If checked, the new profile will use the default game settings instead of the "global" settings. Global settings are the settings you configure when running the game launcher directly, without MO. + If checked, the new profile will use the default game INI settings instead of the "global" settings. Global settings are the settings you configure when running the game launcher directly, without MO. - Default Game Settings + Default Game INI Settings @@ -4741,27 +5033,41 @@ p, li { white-space: pre-wrap; } + <html><head/><body><p>If checked, save games are stored locally to this profile and will not appear when starting with a different profile.</p></body></html> + + + - If checked, savegames are local to this profile and will not appear when starting with a different profile. + If checked, save games are local to this profile and will not appear when starting with a different profile. - Local Savegames + Use profile-specific Save Games - Local Game Settings + <html><head/><body><p>If checked MO2 will use his own profile-specific game INI files, so that the &quot;Global&quot; ones in MyGames can be left vanilla. This different set of INI files is then offered to the game instead of the default one.</p></body></html> + + + + + <html><head/><body><p>If checked, MO2 will use a local set of game INI files (configuration and settings files), different from the default ones found in MyGames. This way changes to the INI settings will only affect this profile and the Global INI files can remain vanilla. MO2 will then show the profile INI files to the game instead of the Global ones.</p></body></html> - + + Use profile-specific Game INI Files + + + + This ensures data files from mods are actually used. You want to enable this unless you use a different tool for Archive Invalidation. - + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } @@ -4773,65 +5079,65 @@ p, li { white-space: pre-wrap; } - + Automatic Archive Invalidation - - + + Create a new profile from scratch - + Create - + Clone the selected profile - + This creates a new profile with the same settings and active mods as the selected one. - + Copy - - + + Delete the selected Profile. This can not be un-done! - + Remove - + Rename - - + + Transfer save games to the selected profile. - + Transfer Saves - + Close @@ -4888,7 +5194,7 @@ p, li { white-space: pre-wrap; } - Are you sure you want to remove this profile (including local savegames if any)? + Are you sure you want to remove this profile (including profile-specific save games, if any)? @@ -4922,13 +5228,32 @@ p, li { white-space: pre-wrap; } + + QApplication + + + INI file is read-only + + + + + + Mod Organizer is attempting to write to "%1" which is currently set to read-only. Clear the read-only flag to allow the write? + + + + + File is read-only + + + QObject - + Error @@ -5028,12 +5353,13 @@ p, li { white-space: pre-wrap; } - + + helper failed - + failed to determine account name @@ -5049,135 +5375,137 @@ p, li { white-space: pre-wrap; } - + Deleting folder - + I'm about to delete the following folder: "%1". Proceed? - + Choose Instance to Delete - + Be Carefull! Deleting an Instance will remove all your files for that Instance (mods, downloads, profiles, configuration, ...). Custom paths outside of the instance folder for downloads, mods, etc. will be left untoched. - + Are you sure? - + Are you really sure you want to delete the Instance "%1" with all its files? - + Failed to delete Instance - + Could not delete Instance "%1". If the folder was still in use, restart MO and try again. - + Enter a Name for the new Instance - - Enter a new name or select one from the suggested list: + + Enter a new name or select one from the suggested list: +(This is just a name for the Instance and can be whatever you wish, + the actual game selection will happen on the next screen regardless of chosen name) - - + + Canceled - + Invalid instance name - + The instance name "%1" is invalid. Use the name "%2" instead? - + The instance "%1" already exists. - + Please choose a different instance name, like: "%1 1" . - + Choose Instance - + Each Instance is a full set of MO data files (mods, downloads, profiles, configuration, ...). You can use multiple instances for different games. Instances are stored in Appdata and can be accessed by all MO installations. If your MO folder is writable, you can also store a single instance locally (called a Portable install, and all the MO data files will be inside the installation folder). - + New - + Create a new instance. - + Portable - + Use MO folder for data. - + Manage Instances - + Delete an Instance. - - + + failed to create %1 - + Data directory created - + New data directory created at %1. If you don't want to store a lot of data there, reconfigure the storage directories via settings. @@ -5247,7 +5575,7 @@ If the folder was still in use, restart MO and try again. - + Failed to create "%1". Your user account probably lacks permission. @@ -5269,7 +5597,7 @@ If the folder was still in use, restart MO and try again. - No game identified in "%1". The directory is required to contain the game binary and its launcher. + No game identified in "%1". The directory is required to contain the game binary. @@ -5288,34 +5616,34 @@ If the folder was still in use, restart MO and try again. - - + + Mod Organizer - + An instance of Mod Organizer is already running - + Failed to set up instance - + Please use "Help" from the toolbar to get usage instructions to all elements - - + + <Manage...> - + failed to parse profile %1: %2 @@ -5351,12 +5679,12 @@ If the folder was still in use, restart MO and try again. - + failed to access %1 - + failed to set file time %1 @@ -5366,37 +5694,39 @@ If the folder was still in use, restart MO and try again. - + Script Extender - + Proxy DLL - + failed to spawn "%1" - + Elevation required - + This process requires elevation to run. This is a potential security risk so I highly advice you to investigate if "%1" can be installed to work without elevation. -Start elevated anyway? (you will be asked if you want to allow ModOrganizer.exe to make changes to the system) +Restart Mod Organizer as an elevated process? +You will be asked if you want to allow helper.exe to make changes to the system. You will need to relaunch the process above manually. - + + failed to spawn "%1": %2 @@ -5562,12 +5892,12 @@ Select Show Details option to see the full change-log. - + Failed to start %1: %2 - + Error @@ -5575,31 +5905,48 @@ Select Show Details option to see the full change-log. Settings - + Failed - + Sorry, failed to start the helper application - - + + attempt to store setting for unknown plugin "%1" - + + Error - + + Failed to retrieve a Nexus API key! Please try again.A browser window should open asking you to authorize. + + + + Failed to create "%1", you may not have the necessary permission. path remains unchanged. + + + Restart Mod Organizer? + + + + + In order to reset the window geometries, MO must be restarted. +Restart it now? + + SettingsDialog @@ -5673,136 +6020,188 @@ If you use pre-releases, never contact me directly by e-mail or via private mess - If checked, the download interface will be more compact. + Colors - - Compact Download Interface + + + When this is enabled, the color defined for a separator will be shown on the mod list scrollbar at the location of the separator. This can be useful for quick navigation between separator sections or to a specific separator section. - - If checked, the download list will display meta information instead of file names. + + Show mod list separator colors on the scrollbar - - Download Meta Information + + Plugin is Contained in selected Mod + + + + + Is overwritten (loose files) + + + + + Is overwriting (loose files) + + + + + Reset Colors + + + + + Mod Contains selected Plugin - + + Is overwritten (archive files) + + + + + Is overwriting (archive files) + + + + + + Modify the categories available to arrange your mods. + + + + + Configure Mod Categories + + + + Reset stored information from dialogs. - + This will make all dialogs show up again where you checked the "Remember selection"-box. - + Reset Dialogs - - - Modify the categories available to arrange your mods. + + If checked, the download interface will be more compact. - - Configure Mod Categories + + Compact Download Interface + + + + + If checked, the download list will display meta information instead of file names. - + + Download Meta Information + + + + Paths - - - + + + + ... - + Caches - + Overwrite - - + + Directory where downloads are stored. - + Downloads - + Profiles - + Directory where mods are stored. - + Directory where mods are stored. Please note that changing this will break all associations of profiles with mods that don't exist in the new location (with the same name). - + Mods - + Managed Game - + Base Directory - + Use %BASE_DIR% to refer to the Base Directory. - + Important: All directories have to be writeable! - - + + Nexus - + Allows automatic log-in when the Nexus-Page for the game is clicked. - + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } @@ -5811,137 +6210,142 @@ p, li { white-space: pre-wrap; } - + Connect to Nexus - + Remove cache and cookies. Forces a new login. - + Clear Cache - + Disable automatic internet features - + Disable automatic internet features. This does not affect features that are explicitly invoked by the user (like checking mods for updates, endorsing, opening the web browser) - + Offline Mode - + Use a proxy for network connections. - + Use a proxy for network connections. This uses the system-wide settings which can be configured in Internet Explorer. Please note that MO will start up a few seconds slower on some systems when using a proxy. - + Use HTTP Proxy (Uses System Settings) - + + Endorsement Integration + + + + Associate with "Download with manager" links - + Known Servers (updated on download) - + Preferred Servers (Drag & Drop) - + Steam - + Username - + Password - + If you save your steam user ID and password here, they will be used when logging into steam. Note, however, your password will be stored unencrypted, so make sure your computer is secure. - + Plugins - + Author: - + Version: - + Description: - + Key - + Value - + Blacklisted Plugins (use <del> to remove): - + Workarounds - + Steam App ID - + The Steam AppID for your game - + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } @@ -5957,17 +6361,17 @@ p, li { white-space: pre-wrap; } - + Load Mechanism - + Select loading mechanism. See help for details. - + Mod Organizer needs a dll to be injected into the game so all mods are visible to it. There are several means to do this: *Mod Organizer* (default) In this mode the Mod Organizer itself injects the dll. The disadvantage is that you always have to start the game through MO or a link created by it. @@ -5978,17 +6382,17 @@ If you use the Steam version of Oblivion the default will NOT work. In this case - + NMM Version - + The Version of Nexus Mod Manager to impersonate. - + Mod Organizer uses an API provided by the Nexus to provide features like checking for updates and downloading files. Unfortunately this API has not been made available officially to third party tools like MO so we have to impersonate the Nexus Mod Manager to be allowed in. On top of this Nexus has used the client identification to lock out outdated versions of NMM to force users to update. This means that MO also needs to impersonate the new version of NMM even if MO doesn't need an update. Therefore you can configure the version to identify as here. Please note that MO does identify itself as MO to the webserver, it's not lying about what it is. It is merely adding a "compatible" NMM version to the user agent. @@ -5997,127 +6401,178 @@ tl;dr-version: If Nexus-features don't work, insert the current version num - + Enforces that inactive ESPs and ESMs are never loaded. - + It seems that the Games occasionally load ESP or ESM files even if they haven't been activated as plugins. I don't yet know what the circumstances are, but user reports imply it is in some cases unwanted. If this is checked, ESPs and ESMs not checked in the List are invisible to the game and can not be loaded. - + Hide inactive ESPs/ESMs - + + Disable this to no longer display mods installed outside MO in the mod list (left pane). Assets from those mods will then be treated as having lowest mod priority together with the original game content. + + + + + By default Mod Organizer will display esp+bsa bundles installed with foreign tools as mods (left pane). This allows you to control their priority in relation to other mods. This is particularly useful if you also use Steam Workshop to install mods. +However, if you installed loose file mods outside MO which conflict with BSAs also installed outside MO those conflicts can't be resolved correctly. + +If you disable this feature, MO will only display official DLCs this way. Please note that plugins (esps, esms, and esls) displayed in the right pane are completely unaffected by this feature. + + + + + Display mods installed outside MO + + + + If checked, files (i.e. esps, esms and bsas) belonging to the core game can not be disabled in the UI. (default: on) - + If checked, files (i.e. esps, esms and bsas) belonging to the core game can not be disabled in the UI. (default: on) Uncheck this if you want to use Mod Organizer with total conversions (like Nehrim) but be aware that the game will crash if required files are not enabled. - + Force-enable game files - - Disable this to no longer display mods installed outside MO in the mod list (left pane). Assets from those mods will then be treated as having lowest mod priority together with the original game content. + + + Disable this to prevent the GUI from being locked when running an executable. This may result in abnormal behavior. - - By default Mod Organizer will display esp+bsa bundles installed with foreign tools as mods (left pane). This allows you to control their priority in relation to other mods. This is particularly useful if you also use Steam Workshop to install mods. -However, if you installed loose file mods outside MO which conflict with BSAs also installed outside MO those conflicts can't be resolved correctly. - -If you disable this feature, MO will only display official DLCs this way. Please note that plugins (esps, esms, and esls) displayed in the right pane are completely unaffected by this feature. + + Lock GUI when running executable - - Display mods installed outside MO + + Enable parsing of Archives. Has negative effects on performance. - - + + <html><head/><body><p>By default, MO will parse archive files (BSA, BA2) to calculate conflicts between the contents of the archive files and other loose files. This process has a noticeable cost in performance.</p><p>This feature should not be confused with the archive management feature offered by MO1. MO2 will only show conflicts with archives and will NOT load them into the game or program.</p><p>If you disable this feature, MO will only display conflicts between loose files.</p></body></html> + + + + + Enable parsing of Archives + + + + + For Skyrim, this can be used instead of Archive Invalidation. It should make AI redundant for all Profiles. For the other games this is not a sufficient replacement for AI! - + Back-date BSAs - - These are workarounds for problems with Mod Organizer. Please make sure you read the help text before changing anything here. + + Add executables to the blacklist to prevent them from +accessing the virtual file system. This is useful to prevent +unintended programs from being hooked. Hooking unintended +programs may affect the execution of these programs or the +programs you are intentionally running. - - Diagnostics + + Add executables to the blacklist to prevent them from accessing the virtual file system. This is useful to prevent unintended programs from being hooked. Hooking unintended programs may affect the execution of these programs or the programs you are intentionally running. - - Log Level + + Configure Executables Blacklist - - Decides the amount of data printed to "ModOrganizer.log" + + + Resets the window geometries for all windows. This can be useful if a window becomes too small or too large, if a column becomes too thin or too wide, and in similar situations. - - - Decides the amount of data printed to "ModOrganizer.log". - "Debug" produces very useful information for finding problems. There is usually no noteworthy performance impact but the file may become rather large. If this is a problem you may prefer the "Info" level for regluar use. On the "Error" level the log file usually remains empty. - + + Reset Window Geometries - - Debug + + These are workarounds for problems with Mod Organizer. Please make sure you read the help text before changing anything here. - - Info (recommended) + + Diagnostics - - Warning + + Max Dumps To Keep - - Error + + Maximum number of crash dumps to keep on disk. Use 0 for unlimited. + + + + + + Maximum number of crash dumps to keep on disk. Use 0 for unlimited. + Set "Crash Dumps" above to None to disable crash dump collection. + + + + + + Hint: right click link and copy link location + + + + + + Logs and crash dumps are stored under your current instance in the <a href="LOGS_FULL_PATH">LOGS_DIR</a> + and <a href="DUMPS_FULL_PATH">DUMPS_DIR</a> folders. + Sending logs and/or crash dumps to the developers can help investigate issues. + It is recommended to compress large log and dmp files before sending. + - + Crash Dumps - + Decides which type of crash dumps are collected when injected processes crash. - + Decides which type of crash dumps are collected when injected processes crash. "None" Disables the generation of crash dumps by MO. @@ -6128,105 +6583,131 @@ For the other games this is not a sufficient replacement for AI! - + None - + Mini (recommended) - + Data - + Full - - Max Dumps To Keep + + Log Level - - Maximum number of crash dumps to keep on disk. Use 0 for unlimited. + + Decides the amount of data printed to "ModOrganizer.log" - + - Maximum number of crash dumps to keep on disk. Use 0 for unlimited. - Set "Crash Dumps" above to None to disable crash dump collection. + Decides the amount of data printed to "ModOrganizer.log". + "Debug" produces very useful information for finding problems. There is usually no noteworthy performance impact but the file may become rather large. If this is a problem you may prefer the "Info" level for regluar use. On the "Error" level the log file usually remains empty. - - Hint: right click link and copy link location + + Debug - - - Logs and crash dumps are stored under your current instance in the <a href="LOGS_FULL_PATH">LOGS_DIR</a> - and <a href="DUMPS_FULL_PATH">DUMPS_DIR</a> folders. - Sending logs and/or crash dumps to the developers can help investigate issues. - It is recommended to compress large log and dmp files before sending. - + + Info (recommended) + + + + + Warning - + + Error + + + + Confirm - + Changing the mod directory affects all your profiles! Mods not present (or named differently) in the new location will be disabled in all profiles. There is no way to undo this unless you backed up your profiles manually. Proceed? - + + Executables Blacklist + + + + + Enter one executable per line to be blacklisted from the virtual file system. +Mods and other virtualized files will not be visible to these executables and +any executables launched by them. + +Example: + Chrome.exe + Firefox.exe + + + + Select base directory - + Select download directory - + Select mod directory - + Select cache directory - + Select profiles directory - + Select overwrite directory - + + Select game executable + + + + Confirm? - + This will make all dialogs show up again where you checked the "Remember selection"-box. Continue? @@ -6338,7 +6819,7 @@ For the other games this is not a sufficient replacement for AI! TransferSavesDialog - Transfer Savegames + Transfer Save Games @@ -6430,7 +6911,7 @@ On Windows XP: UsvfsConnector - + Preparing vfs diff --git a/src/organizercore.cpp b/src/organizercore.cpp index dca855c7..bfe36b24 100644 --- a/src/organizercore.cpp +++ b/src/organizercore.cpp @@ -307,9 +307,9 @@ OrganizerCore::OrganizerCore(const QSettings &initSettings) SLOT(removeOrigin(QString))); connect(NexusInterface::instance(m_PluginContainer)->getAccessManager(), - SIGNAL(loginSuccessful(bool)), this, SLOT(loginSuccessful(bool))); + SIGNAL(validateSuccessful(bool)), this, SLOT(loginSuccessful(bool))); connect(NexusInterface::instance(m_PluginContainer)->getAccessManager(), - SIGNAL(loginFailed(QString)), this, SLOT(loginFailed(QString))); + SIGNAL(validateFailed(QString)), this, SLOT(loginFailed(QString))); // This seems awfully imperative connect(this, SIGNAL(managedGameChanged(MOBase::IPluginGame const *)), diff --git a/src/settings.cpp b/src/settings.cpp index 7a1d6737..fdc767bf 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -674,6 +674,13 @@ void Settings::processApiKey(const QString &apiKey) m_Settings.setValue("Settings/nexus_api_key", obfuscate(apiKey)); } +void Settings::clearApiKey(QPushButton *nexusButton) +{ + m_Settings.remove("Settings/nexus_api_key"); + nexusButton->setEnabled(true); + nexusButton->setText("Connect to Nexus"); +} + void Settings::checkApiKey(QPushButton *nexusButton) { if (m_Settings.value("Settings/nexus_api_key", "").toString().isEmpty()) { @@ -692,6 +699,7 @@ void Settings::query(PluginContainer *pluginContainer, QWidget *parent) connect(&dialog, SIGNAL(resetDialogs()), this, SLOT(resetDialogs())); connect(&dialog, SIGNAL(processApiKey(const QString &)), this, SLOT(processApiKey(const QString &))); connect(&dialog, SIGNAL(closeApiConnection(QPushButton *)), this, SLOT(checkApiKey(QPushButton *))); + connect(&dialog, SIGNAL(revokeApiKey(QPushButton *)), this, SLOT(clearApiKey(QPushButton *))); std::vector> tabs; diff --git a/src/settings.h b/src/settings.h index 49e5a5b6..d692497e 100644 --- a/src/settings.h +++ b/src/settings.h @@ -536,6 +536,7 @@ private slots: void resetDialogs(); void processApiKey(const QString &); + void clearApiKey(QPushButton *nexusButton); void checkApiKey(QPushButton *nexusButton); signals: diff --git a/src/settingsdialog.cpp b/src/settingsdialog.cpp index 4843dea5..f63b1a10 100644 --- a/src/settingsdialog.cpp +++ b/src/settingsdialog.cpp @@ -62,6 +62,7 @@ SettingsDialog::SettingsDialog(PluginContainer *pluginContainer, QWidget *parent connect(m_nexusLogin, SIGNAL(connected()), this, SLOT(dispatchLogin())); connect(m_nexusLogin, SIGNAL(textMessageReceived(const QString &)), this, SLOT(receiveApiKey(const QString &))); connect(m_nexusLogin, SIGNAL(disconnected()), this, SLOT(completeApiConnection())); + m_loginTimer.callOnTimeout(this, &SettingsDialog::loginPing); } SettingsDialog::~SettingsDialog() @@ -124,18 +125,18 @@ bool SettingsDialog::getResetGeometries() return ui->resetGeometryBtn->isChecked(); } -void SettingsDialog::on_loginCheckBox_toggled(bool checked) -{ - QLineEdit *usernameEdit = findChild("usernameEdit"); - QLineEdit *passwordEdit = findChild("passwordEdit"); - if (checked) { - passwordEdit->setEnabled(true); - usernameEdit->setEnabled(true); - } else { - passwordEdit->setEnabled(false); - usernameEdit->setEnabled(false); - } -} +//void SettingsDialog::on_loginCheckBox_toggled(bool checked) +//{ +// QLineEdit *usernameEdit = findChild("usernameEdit"); +// QLineEdit *passwordEdit = findChild("passwordEdit"); +// if (checked) { +// passwordEdit->setEnabled(true); +// usernameEdit->setEnabled(true); +// } else { +// passwordEdit->setEnabled(false); +// usernameEdit->setEnabled(false); +// } +//} void SettingsDialog::on_categoriesBtn_clicked() { @@ -337,7 +338,7 @@ void SettingsDialog::on_resetDialogsButton_clicked() void SettingsDialog::on_nexusConnect_clicked() { - ui->nexusConnect->setText("Connecting the API..."); + ui->nexusConnect->setText("Connecting the API. Please login within the browser and accept the request. This will time out after 5 minutes."); ui->nexusConnect->setDisabled(true); QUrl url = QUrl("wss://sso.nexusmods.com:8443"); m_nexusLogin->open(url); @@ -354,6 +355,20 @@ void SettingsDialog::dispatchLogin() QString finalMessage(loginDoc.toJson()); m_nexusLogin->sendTextMessage(finalMessage); QDesktopServices::openUrl(QUrl(QString("https://www.nexusmods.com/sso?id=") + QString(boost::uuids::to_string(sessionId).c_str()))); + m_loginTimer.start(30000); +} + +void SettingsDialog::loginPing() +{ + if (m_nexusLogin->isValid()) { + m_nexusLogin->ping(); + m_totalPings++; + } + if (m_totalPings >= 10) { + m_loginTimer.stop(); + m_totalPings = 0; + m_nexusLogin->close(QWebSocketProtocol::CloseCodeGoingAway, "Timeout: No response received after five minutes. Cancelling request."); + } } void SettingsDialog::receiveApiKey(const QString &apiKey) @@ -361,6 +376,8 @@ void SettingsDialog::receiveApiKey(const QString &apiKey) emit processApiKey(apiKey); m_nexusLogin->close(); ui->nexusConnect->setText("Nexus API Key Stored"); + m_loginTimer.stop(); + m_totalPings = 0; } void SettingsDialog::completeApiConnection() @@ -435,6 +452,11 @@ void SettingsDialog::on_clearCacheButton_clicked() NexusInterface::instance(m_PluginContainer)->clearCache(); } +void SettingsDialog::on_revokeNexusAuthButton_clicked() +{ + emit revokeApiKey(ui->nexusConnect); +} + void SettingsDialog::normalizePath(QLineEdit *lineEdit) { QString text = lineEdit->text(); diff --git a/src/settingsdialog.h b/src/settingsdialog.h index 90b60c91..d0f6a36c 100644 --- a/src/settingsdialog.h +++ b/src/settingsdialog.h @@ -26,6 +26,7 @@ along with Mod Organizer. If not, see . #include #include #include +#include class PluginContainer; @@ -63,6 +64,7 @@ signals: void resetDialogs(); void processApiKey(const QString &); void closeApiConnection(QPushButton *); + void revokeApiKey(QPushButton *); private: @@ -90,7 +92,7 @@ public: private slots: - void on_loginCheckBox_toggled(bool checked); + //void on_loginCheckBox_toggled(bool checked); void on_categoriesBtn_clicked(); @@ -114,6 +116,8 @@ private slots: void on_clearCacheButton_clicked(); + void on_revokeNexusAuthButton_clicked(); + void on_browseBaseDirBtn_clicked(); void on_browseOverwriteDirBtn_clicked(); @@ -152,6 +156,8 @@ private slots: void dispatchLogin(); + void loginPing(); + void receiveApiKey(const QString &apiKey); void completeApiConnection(); @@ -170,6 +176,8 @@ private: QString m_ExecutableBlacklist; QWebSocket *m_nexusLogin; + QTimer m_loginTimer; + int m_totalPings = 0; }; diff --git a/src/settingsdialog.ui b/src/settingsdialog.ui index d3628ab3..127c94c7 100644 --- a/src/settingsdialog.ui +++ b/src/settingsdialog.ui @@ -1,1405 +1,1432 @@ - - - SettingsDialog - - - - 0 - 0 - 586 - 486 - - - - Settings - - - - - - 0 - - - - General - - - - - - - - Language - - - - - - - The display language - - - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> -<html><head><meta name="qrichtext" content="1" /><style type="text/css"> -p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">The display language. This will only displaye languages for which you have a translation installed.</span></p></body></html> - - - - - - - - - - - Style - - - - - - - graphical style - - - graphical style of the MO user interface - - - - - - - - - Update to non-stable releases. - - - If this is enabled, the integrated update mechanism will notify of all releases, including pre-releases (alphas, betas). - -Please use this only if you're sufficiently tech-savvy to investigate issues, look for known problems in the issue tracker and create meaningful reports. - -If you use pre-releases, never contact me directly by e-mail or via private messages! - - - Install Pre-releases (Betas) - - - - - - - User interface - - - - - - Colors - - - - - - When this is enabled, the color defined for a separator will be shown on the mod list scrollbar at the location of the separator. This can be useful for quick navigation between separator sections or to a specific separator section. - - - When this is enabled, the color defined for a separator will be shown on the mod list scrollbar at the location of the separator. This can be useful for quick navigation between separator sections or to a specific separator section. - - - Show mod list separator colors on the scrollbar - - - true - - - - - - - Plugin is Contained in selected Mod - - - - - - - Is overwritten (loose files) - - - - - - - Is overwriting (loose files) - - - - - - - Reset Colors - - - - - - - Mod Contains selected Plugin - - - - - - - Is overwritten (archive files) - - - - - - - Is overwriting (archive files) - - - - - - - - - - Modify the categories available to arrange your mods. - - - Modify the categories available to arrange your mods. - - - Configure Mod Categories - - - - - - - - 16777215 - 16777215 - - - - Reset stored information from dialogs. - - - This will make all dialogs show up again where you checked the "Remember selection"-box. - - - Reset Dialogs - - - - - - - If checked, the download interface will be more compact. - - - Compact Download Interface - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - If checked, the download list will display meta information instead of file names. - - - Download Meta Information - - - - - - - - - - - Paths - - - - - - - - ... - - - - - - - ... - - - - - - - - - - ... - - - - - - - - - - Caches - - - - - - - Overwrite - - - - - - - Directory where downloads are stored. - - - Directory where downloads are stored. - - - - - - - - - - ... - - - - - - - Downloads - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - Profiles - - - - - - - - 0 - 0 - - - - ... - - - - - - - - - - Directory where mods are stored. - - - Directory where mods are stored. Please note that changing this will break all associations of profiles with mods that don't exist in the new location (with the same name). - - - - - - - ... - - - - - - - false - - - true - - - - - - - Mods - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - Managed Game - - - - - - - Base Directory - - - - - - - Use %BASE_DIR% to refer to the Base Directory. - - - - - - - ... - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - Important: All directories have to be writeable! - - - - - - - - Nexus - - - - - - Allows automatic log-in when the Nexus-Page for the game is clicked. - - - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> -<html><head><meta name="qrichtext" content="1" /><style type="text/css"> -p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Allows automatic log-in when the Nexus-Page for the game is clicked. Please note that the obfuscation with which the password is stored in modorganizer.ini is not very strong. If you're worried someone might steal your password, don't store it here.</span></p></body></html> - - - Nexus - - - - - - - - Connect to Nexus - - - - - - - - - - - Remove cache and cookies. Forces a new login. - - - Clear Cache - - - - :/MO/gui/edit_clear:/MO/gui/edit_clear - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - - - - - Disable automatic internet features - - - Disable automatic internet features. This does not affect features that are explicitly invoked by the user (like checking mods for updates, endorsing, opening the web browser) - - - Offline Mode - - - - - - - Use a proxy for network connections. - - - Use a proxy for network connections. This uses the system-wide settings which can be configured in Internet Explorer. Please note that MO will start up a few seconds slower on some systems when using a proxy. - - - Use HTTP Proxy (Uses System Settings) - - - - - - - Endorsement Integration - - - true - - - - - - - - - - - Associate with "Download with manager" links - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - 4 - - - - - - - Known Servers (updated on download) - - - - - - - QAbstractItemView::DragDrop - - - Qt::MoveAction - - - - - - - - - - - Preferred Servers (Drag & Drop) - - - - - - - QAbstractItemView::DragDrop - - - Qt::MoveAction - - - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - Steam - - - - - - Username - - - - - - - - - - Password - - - - - - - QLineEdit::Password - - - - - - - Qt::Vertical - - - QSizePolicy::Minimum - - - - 20 - 40 - - - - - - - - If you save your steam user ID and password here, they will be used when logging into steam. Note, however, your password will be stored unencrypted, so make sure your computer is secure. - - - true - - - - - - - Qt::Vertical - - - QSizePolicy::Expanding - - - - 20 - 232 - - - - - - - - - Plugins - - - - - - - - - 0 - 0 - - - - true - - - - - - - - - - - Author: - - - - - - - - - - - - - - Version: - - - - - - - - - - - - - - Description: - - - - - - - - - - true - - - - - - - - - 0 - - - false - - - false - - - false - - - false - - - 170 - - - - Key - - - - - Value - - - - - - - - - - - - Blacklisted Plugins (use <del> to remove): - - - - - - - - - - - Workarounds - - - - - - - - Steam App ID - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - The Steam AppID for your game - - - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> -<html><head><meta name="qrichtext" content="1" /><style type="text/css"> -p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">The Steam App ID is required to directly start some games. For Skyrim, if this is not set or wrong, the &quot;Mod Organizer&quot; load mechanism may not work properly.</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">The preset for this is the App ID of the &quot;regular&quot; version so in most cases, you should be set.</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">If you think you have a different version (GotY or something), follow these steps to get to the id:</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">1. Navigate to the game library in steam</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">2. right-click on the game you need the id for and choose </span><span style=" font-size:8pt; font-weight:600;">Create desktop shortcut</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">3. right-click on the newly created shortcut on your desktop and select </span><span style=" font-size:8pt; font-weight:600;">Properties</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">4. in the URL-field you should see something like this: </span><span style=" font-size:8pt; font-style:italic;">steam://rungameid/22380</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">22380 is the id you're looking for.</span></p></body></html> - - - - - - - - - 7 - - - - - - 16777215 - 16777215 - - - - Load Mechanism - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Select loading mechanism. See help for details. - - - Mod Organizer needs a dll to be injected into the game so all mods are visible to it. -There are several means to do this: -*Mod Organizer* (default) In this mode the Mod Organizer itself injects the dll. The disadvantage is that you always have to start the game through MO or a link created by it. -*Script Extender* In this mode, MO is installed as a Script Extender (obse, fose, nvse, skse) plugin. -*Proxy DLL* In this mode, MO replaces one of the game's dlls with one that loads MO (and the original dll of course). This will ONLY work with Steam games and it has only been tested with Skyrim. Please use this only if the other mechanisms don't work. - -If you use the Steam version of Oblivion the default will NOT work. In this case, please install obse and use "Script Extender" as the load mechanism. Also you can then not start Oblivion from MO. Instead, use MO only to set up your mods, then quit and start Oblivion through Steam. - - - - - - - - - - - NMM Version - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - The Version of Nexus Mod Manager to impersonate. - - - Mod Organizer uses an API provided by the Nexus to provide features like checking for updates and downloading files. Unfortunately this API has not been made available officially to third party tools like MO so we have to impersonate the Nexus Mod Manager to be allowed in. -On top of this Nexus has used the client identification to lock out outdated versions of NMM to force users to update. This means that MO also needs to impersonate the new version of NMM even if MO doesn't need an update. Therefore you can configure the version to identify as here. -Please note that MO does identify itself as MO to the webserver, it's not lying about what it is. It is merely adding a "compatible" NMM version to the user agent. - -tl;dr-version: If Nexus-features don't work, insert the current version number of NMM here and try again. - - - 009.009.009 - - - Qt::AlignCenter - - - - - - - - - - - - - - false - - - Enforces that inactive ESPs and ESMs are never loaded. - - - It seems that the Games occasionally load ESP or ESM files even if they haven't been activated as plugins. -I don't yet know what the circumstances are, but user reports imply it is in some cases unwanted. If this is checked, ESPs and ESMs not checked in the List are invisible to the game and can not be loaded. - - - Hide inactive ESPs/ESMs - - - - - - - Disable this to no longer display mods installed outside MO in the mod list (left pane). Assets from those mods will then be treated as having lowest mod priority together with the original game content. - - - By default Mod Organizer will display esp+bsa bundles installed with foreign tools as mods (left pane). This allows you to control their priority in relation to other mods. This is particularly useful if you also use Steam Workshop to install mods. -However, if you installed loose file mods outside MO which conflict with BSAs also installed outside MO those conflicts can't be resolved correctly. - -If you disable this feature, MO will only display official DLCs this way. Please note that plugins (esps, esms, and esls) displayed in the right pane are completely unaffected by this feature. - - - Display mods installed outside MO - - - true - - - - - - - If checked, files (i.e. esps, esms and bsas) belonging to the core game can not be disabled in the UI. (default: on) - - - If checked, files (i.e. esps, esms and bsas) belonging to the core game can not be disabled in the UI. (default: on) -Uncheck this if you want to use Mod Organizer with total conversions (like Nehrim) but be aware that the game will crash if required files are not enabled. - - - Force-enable game files - - - true - - - - - - - Disable this to prevent the GUI from being locked when running an executable. This may result in abnormal behavior. - - - Disable this to prevent the GUI from being locked when running an executable. This may result in abnormal behavior. - - - Lock GUI when running executable - - - true - - - - - - - Enable parsing of Archives. This is an Experimental Feature. Has negative effects on performance and known incorrectness. - - - <html><head/><body><p>By default, MO will parse archive files (BSA, BA2) to calculate conflicts between the contents of the archive files and other loose files. This process has a noticeable cost in performance.</p><p>This feature should not be confused with the archive management feature offered by MO1. MO2 will only show conflicts with archives and will NOT load them into the game or program.</p><p>If you disable this feature, MO will only display conflicts between loose files.</p></body></html> - - - Enable parsing of Archives (Experimental Feature) - - - true - - - - - - - - - For Skyrim, this can be used instead of Archive Invalidation. It should make AI redundant for all Profiles. -For the other games this is not a sufficient replacement for AI! - - - For Skyrim, this can be used instead of Archive Invalidation. It should make AI redundant for all Profiles. -For the other games this is not a sufficient replacement for AI! - - - Back-date BSAs - - - - :/MO/gui/resources/emblem-readonly.png:/MO/gui/resources/emblem-readonly.png - - - - - - - Add executables to the blacklist to prevent them from -accessing the virtual file system. This is useful to prevent -unintended programs from being hooked. Hooking unintended -programs may affect the execution of these programs or the -programs you are intentionally running. - - - Add executables to the blacklist to prevent them from accessing the virtual file system. This is useful to prevent unintended programs from being hooked. Hooking unintended programs may affect the execution of these programs or the programs you are intentionally running. - - - Configure Executables Blacklist - - - false - - - - - - - Resets the window geometries for all windows. This can be useful if a window becomes too small or too large, if a column becomes too thin or too wide, and in similar situations. - - - Resets the window geometries for all windows. This can be useful if a window becomes too small or too large, if a column becomes too thin or too wide, and in similar situations. - - - Reset Window Geometries - - - true - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - These are workarounds for problems with Mod Organizer. Please make sure you read the help text before changing anything here. - - - true - - - - - - - - Diagnostics - - - - - - - - Max Dumps To Keep - - - - - - - Qt::Horizontal - - - - 60 - 20 - - - - - - - - Maximum number of crash dumps to keep on disk. Use 0 for unlimited. - - - - Maximum number of crash dumps to keep on disk. Use 0 for unlimited. - Set "Crash Dumps" above to None to disable crash dump collection. - - - - - - - - - - Hint: right click link and copy link location - - - - Logs and crash dumps are stored under your current instance in the <a href="LOGS_FULL_PATH">LOGS_DIR</a> - and <a href="DUMPS_FULL_PATH">DUMPS_DIR</a> folders. - Sending logs and/or crash dumps to the developers can help investigate issues. - It is recommended to compress large log and dmp files before sending. - - - - true - - - - - - - - - Crash Dumps - - - - - - - Decides which type of crash dumps are collected when injected processes crash. - - - - Decides which type of crash dumps are collected when injected processes crash. - "None" Disables the generation of crash dumps by MO. - "Mini" Default level which generates small dumps (only stack traces). - "Data" Much larger dumps with additional information which may be need (also data segments). - "Full" Even larger dumps with a full memory dump of the process. - - - - - None - - - - - Mini (recommended) - - - - - Data - - - - - Full - - - - - - - - - - Qt::Vertical - - - QSizePolicy::Expanding - - - - 20 - 232 - - - - - - - - - - Log Level - - - - - - - Decides the amount of data printed to "ModOrganizer.log" - - - - Decides the amount of data printed to "ModOrganizer.log". - "Debug" produces very useful information for finding problems. There is usually no noteworthy performance impact but the file may become rather large. If this is a problem you may prefer the "Info" level for regluar use. On the "Error" level the log file usually remains empty. - - - - - Debug - - - - - Info (recommended) - - - - - Warning - - - - - Error - - - - - - - - - - - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - languageBox - styleBox - logLevelBox - usePrereleaseBox - compactBox - categoriesBtn - baseDirEdit - browseBaseDirBtn - downloadDirEdit - browseDownloadDirBtn - modDirEdit - browseModDirBtn - cacheDirEdit - browseCacheDirBtn - profilesDirEdit - browseProfilesDirBtn - overwriteDirEdit - browseOverwriteDirBtn - clearCacheButton - associateButton - knownServersList - preferredServersList - steamUserEdit - steamPassEdit - pluginsList - pluginSettingsList - pluginBlacklist - appIDEdit - mechanismBox - nmmVersionEdit - bsaDateBtn - tabWidget - - - - - - - buttonBox - accepted() - SettingsDialog - accept() - - - 248 - 254 - - - 157 - 274 - - - - - buttonBox - rejected() - SettingsDialog - reject() - - - 316 - 260 - - - 286 - 274 - - - - - + + + SettingsDialog + + + + 0 + 0 + 586 + 486 + + + + Settings + + + + + + 0 + + + + General + + + + + + + + Language + + + + + + + The display language + + + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">The display language. This will only displaye languages for which you have a translation installed.</span></p></body></html> + + + + + + + + + + + Style + + + + + + + graphical style + + + graphical style of the MO user interface + + + + + + + + + Update to non-stable releases. + + + If this is enabled, the integrated update mechanism will notify of all releases, including pre-releases (alphas, betas). + +Please use this only if you're sufficiently tech-savvy to investigate issues, look for known problems in the issue tracker and create meaningful reports. + +If you use pre-releases, never contact me directly by e-mail or via private messages! + + + Install Pre-releases (Betas) + + + + + + + User interface + + + + + + Colors + + + + + + When this is enabled, the color defined for a separator will be shown on the mod list scrollbar at the location of the separator. This can be useful for quick navigation between separator sections or to a specific separator section. + + + When this is enabled, the color defined for a separator will be shown on the mod list scrollbar at the location of the separator. This can be useful for quick navigation between separator sections or to a specific separator section. + + + Show mod list separator colors on the scrollbar + + + true + + + + + + + Plugin is Contained in selected Mod + + + + + + + Is overwritten (loose files) + + + + + + + Is overwriting (loose files) + + + + + + + Reset Colors + + + + + + + Mod Contains selected Plugin + + + + + + + Is overwritten (archive files) + + + + + + + Is overwriting (archive files) + + + + + + + + + + Modify the categories available to arrange your mods. + + + Modify the categories available to arrange your mods. + + + Configure Mod Categories + + + + + + + + 16777215 + 16777215 + + + + Reset stored information from dialogs. + + + This will make all dialogs show up again where you checked the "Remember selection"-box. + + + Reset Dialogs + + + + + + + If checked, the download interface will be more compact. + + + Compact Download Interface + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + If checked, the download list will display meta information instead of file names. + + + Download Meta Information + + + + + + + + + + + Paths + + + + + + + + ... + + + + + + + ... + + + + + + + + + + ... + + + + + + + + + + Caches + + + + + + + Overwrite + + + + + + + Directory where downloads are stored. + + + Directory where downloads are stored. + + + + + + + + + + ... + + + + + + + Downloads + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + Profiles + + + + + + + + 0 + 0 + + + + ... + + + + + + + + + + Directory where mods are stored. + + + Directory where mods are stored. Please note that changing this will break all associations of profiles with mods that don't exist in the new location (with the same name). + + + + + + + ... + + + + + + + false + + + true + + + + + + + Mods + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + Managed Game + + + + + + + Base Directory + + + + + + + Use %BASE_DIR% to refer to the Base Directory. + + + + + + + ... + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + Important: All directories have to be writeable! + + + + + + + + Nexus + + + + + + Allows automatic log-in when the Nexus-Page for the game is clicked. + + + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Allows automatic log-in when the Nexus-Page for the game is clicked. Please note that the obfuscation with which the password is stored in modorganizer.ini is not very strong. If you're worried someone might steal your password, don't store it here.</span></p></body></html> + + + Nexus + + + + + + + + Connect to Nexus + + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Clear the stored Nexus API key and force reauthorization. + + + Revoke Nexus Authorization + + + + :/MO/gui/edit_clear:/MO/gui/edit_clear + + + + + + + Remove cache and cookies. + + + Clear Cache + + + + :/MO/gui/edit_clear:/MO/gui/edit_clear + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + + + + Disable automatic internet features + + + Disable automatic internet features. This does not affect features that are explicitly invoked by the user (like checking mods for updates, endorsing, opening the web browser) + + + Offline Mode + + + + + + + Use a proxy for network connections. + + + Use a proxy for network connections. This uses the system-wide settings which can be configured in Internet Explorer. Please note that MO will start up a few seconds slower on some systems when using a proxy. + + + Use HTTP Proxy (Uses System Settings) + + + + + + + Endorsement Integration + + + true + + + + + + + + + + + Associate with "Download with manager" links + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + 4 + + + + + + + Known Servers (updated on download) + + + + + + + QAbstractItemView::DragDrop + + + Qt::MoveAction + + + + + + + + + + + Preferred Servers (Drag & Drop) + + + + + + + QAbstractItemView::DragDrop + + + Qt::MoveAction + + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + Steam + + + + + + Username + + + + + + + + + + Password + + + + + + + QLineEdit::Password + + + + + + + Qt::Vertical + + + QSizePolicy::Minimum + + + + 20 + 40 + + + + + + + + If you save your steam user ID and password here, they will be used when logging into steam. Note, however, your password will be stored unencrypted, so make sure your computer is secure. + + + true + + + + + + + Qt::Vertical + + + QSizePolicy::Expanding + + + + 20 + 232 + + + + + + + + + Plugins + + + + + + + + + 0 + 0 + + + + true + + + + + + + + + + + Author: + + + + + + + + + + + + + + Version: + + + + + + + + + + + + + + Description: + + + + + + + + + + true + + + + + + + + + 0 + + + false + + + false + + + false + + + false + + + 170 + + + + Key + + + + + Value + + + + + + + + + + + + Blacklisted Plugins (use <del> to remove): + + + + + + + + + + + Workarounds + + + + + + + + Steam App ID + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + The Steam AppID for your game + + + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">The Steam App ID is required to directly start some games. For Skyrim, if this is not set or wrong, the &quot;Mod Organizer&quot; load mechanism may not work properly.</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">The preset for this is the App ID of the &quot;regular&quot; version so in most cases, you should be set.</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">If you think you have a different version (GotY or something), follow these steps to get to the id:</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">1. Navigate to the game library in steam</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">2. right-click on the game you need the id for and choose </span><span style=" font-size:8pt; font-weight:600;">Create desktop shortcut</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">3. right-click on the newly created shortcut on your desktop and select </span><span style=" font-size:8pt; font-weight:600;">Properties</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">4. in the URL-field you should see something like this: </span><span style=" font-size:8pt; font-style:italic;">steam://rungameid/22380</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">22380 is the id you're looking for.</span></p></body></html> + + + + + + + + + 7 + + + + + + 16777215 + 16777215 + + + + Load Mechanism + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Select loading mechanism. See help for details. + + + Mod Organizer needs a dll to be injected into the game so all mods are visible to it. +There are several means to do this: +*Mod Organizer* (default) In this mode the Mod Organizer itself injects the dll. The disadvantage is that you always have to start the game through MO or a link created by it. +*Script Extender* In this mode, MO is installed as a Script Extender (obse, fose, nvse, skse) plugin. +*Proxy DLL* In this mode, MO replaces one of the game's dlls with one that loads MO (and the original dll of course). This will ONLY work with Steam games and it has only been tested with Skyrim. Please use this only if the other mechanisms don't work. + +If you use the Steam version of Oblivion the default will NOT work. In this case, please install obse and use "Script Extender" as the load mechanism. Also you can then not start Oblivion from MO. Instead, use MO only to set up your mods, then quit and start Oblivion through Steam. + + + + + + + + + + + NMM Version + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + The Version of Nexus Mod Manager to impersonate. + + + Mod Organizer uses an API provided by the Nexus to provide features like checking for updates and downloading files. Unfortunately this API has not been made available officially to third party tools like MO so we have to impersonate the Nexus Mod Manager to be allowed in. +On top of this Nexus has used the client identification to lock out outdated versions of NMM to force users to update. This means that MO also needs to impersonate the new version of NMM even if MO doesn't need an update. Therefore you can configure the version to identify as here. +Please note that MO does identify itself as MO to the webserver, it's not lying about what it is. It is merely adding a "compatible" NMM version to the user agent. + +tl;dr-version: If Nexus-features don't work, insert the current version number of NMM here and try again. + + + 009.009.009 + + + Qt::AlignCenter + + + + + + + + + + + + + + false + + + Enforces that inactive ESPs and ESMs are never loaded. + + + It seems that the Games occasionally load ESP or ESM files even if they haven't been activated as plugins. +I don't yet know what the circumstances are, but user reports imply it is in some cases unwanted. If this is checked, ESPs and ESMs not checked in the List are invisible to the game and can not be loaded. + + + Hide inactive ESPs/ESMs + + + + + + + Disable this to no longer display mods installed outside MO in the mod list (left pane). Assets from those mods will then be treated as having lowest mod priority together with the original game content. + + + By default Mod Organizer will display esp+bsa bundles installed with foreign tools as mods (left pane). This allows you to control their priority in relation to other mods. This is particularly useful if you also use Steam Workshop to install mods. +However, if you installed loose file mods outside MO which conflict with BSAs also installed outside MO those conflicts can't be resolved correctly. + +If you disable this feature, MO will only display official DLCs this way. Please note that plugins (esps, esms, and esls) displayed in the right pane are completely unaffected by this feature. + + + Display mods installed outside MO + + + true + + + + + + + If checked, files (i.e. esps, esms and bsas) belonging to the core game can not be disabled in the UI. (default: on) + + + If checked, files (i.e. esps, esms and bsas) belonging to the core game can not be disabled in the UI. (default: on) +Uncheck this if you want to use Mod Organizer with total conversions (like Nehrim) but be aware that the game will crash if required files are not enabled. + + + Force-enable game files + + + true + + + + + + + Disable this to prevent the GUI from being locked when running an executable. This may result in abnormal behavior. + + + Disable this to prevent the GUI from being locked when running an executable. This may result in abnormal behavior. + + + Lock GUI when running executable + + + true + + + + + + + Enable parsing of Archives. This is an Experimental Feature. Has negative effects on performance and known incorrectness. + + + <html><head/><body><p>By default, MO will parse archive files (BSA, BA2) to calculate conflicts between the contents of the archive files and other loose files. This process has a noticeable cost in performance.</p><p>This feature should not be confused with the archive management feature offered by MO1. MO2 will only show conflicts with archives and will NOT load them into the game or program.</p><p>If you disable this feature, MO will only display conflicts between loose files.</p></body></html> + + + Enable parsing of Archives (Experimental Feature) + + + true + + + + + + + + + For Skyrim, this can be used instead of Archive Invalidation. It should make AI redundant for all Profiles. +For the other games this is not a sufficient replacement for AI! + + + For Skyrim, this can be used instead of Archive Invalidation. It should make AI redundant for all Profiles. +For the other games this is not a sufficient replacement for AI! + + + Back-date BSAs + + + + :/MO/gui/resources/emblem-readonly.png:/MO/gui/resources/emblem-readonly.png + + + + + + + Add executables to the blacklist to prevent them from +accessing the virtual file system. This is useful to prevent +unintended programs from being hooked. Hooking unintended +programs may affect the execution of these programs or the +programs you are intentionally running. + + + Add executables to the blacklist to prevent them from accessing the virtual file system. This is useful to prevent unintended programs from being hooked. Hooking unintended programs may affect the execution of these programs or the programs you are intentionally running. + + + Configure Executables Blacklist + + + false + + + + + + + Resets the window geometries for all windows. This can be useful if a window becomes too small or too large, if a column becomes too thin or too wide, and in similar situations. + + + Resets the window geometries for all windows. This can be useful if a window becomes too small or too large, if a column becomes too thin or too wide, and in similar situations. + + + Reset Window Geometries + + + true + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + These are workarounds for problems with Mod Organizer. Please make sure you read the help text before changing anything here. + + + true + + + + + + + + Diagnostics + + + + + + + + Max Dumps To Keep + + + + + + + Qt::Horizontal + + + + 60 + 20 + + + + + + + + Maximum number of crash dumps to keep on disk. Use 0 for unlimited. + + + + Maximum number of crash dumps to keep on disk. Use 0 for unlimited. + Set "Crash Dumps" above to None to disable crash dump collection. + + + + + + + + + + Hint: right click link and copy link location + + + + Logs and crash dumps are stored under your current instance in the <a href="LOGS_FULL_PATH">LOGS_DIR</a> + and <a href="DUMPS_FULL_PATH">DUMPS_DIR</a> folders. + Sending logs and/or crash dumps to the developers can help investigate issues. + It is recommended to compress large log and dmp files before sending. + + + + true + + + + + + + + + Crash Dumps + + + + + + + Decides which type of crash dumps are collected when injected processes crash. + + + + Decides which type of crash dumps are collected when injected processes crash. + "None" Disables the generation of crash dumps by MO. + "Mini" Default level which generates small dumps (only stack traces). + "Data" Much larger dumps with additional information which may be need (also data segments). + "Full" Even larger dumps with a full memory dump of the process. + + + + + None + + + + + Mini (recommended) + + + + + Data + + + + + Full + + + + + + + + + + Qt::Vertical + + + QSizePolicy::Expanding + + + + 20 + 232 + + + + + + + + + + Log Level + + + + + + + Decides the amount of data printed to "ModOrganizer.log" + + + + Decides the amount of data printed to "ModOrganizer.log". + "Debug" produces very useful information for finding problems. There is usually no noteworthy performance impact but the file may become rather large. If this is a problem you may prefer the "Info" level for regluar use. On the "Error" level the log file usually remains empty. + + + + + Debug + + + + + Info (recommended) + + + + + Warning + + + + + Error + + + + + + + + + + + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + languageBox + styleBox + logLevelBox + usePrereleaseBox + compactBox + categoriesBtn + baseDirEdit + browseBaseDirBtn + downloadDirEdit + browseDownloadDirBtn + modDirEdit + browseModDirBtn + cacheDirEdit + browseCacheDirBtn + profilesDirEdit + browseProfilesDirBtn + overwriteDirEdit + browseOverwriteDirBtn + clearCacheButton + associateButton + knownServersList + preferredServersList + steamUserEdit + steamPassEdit + pluginsList + pluginSettingsList + pluginBlacklist + appIDEdit + mechanismBox + nmmVersionEdit + bsaDateBtn + tabWidget + + + + + + + buttonBox + accepted() + SettingsDialog + accept() + + + 248 + 254 + + + 157 + 274 + + + + + buttonBox + rejected() + SettingsDialog + reject() + + + 316 + 260 + + + 286 + 274 + + + + + -- cgit v1.3.1 From b751b070e5d7d55ceaea7439e041468bab553b92 Mon Sep 17 00:00:00 2001 From: Silarn Date: Thu, 31 Jan 2019 13:25:13 -0600 Subject: Implement using the DPAPI to encrypt credentials --- src/CMakeLists.txt | 2 +- src/modinforegular.h | 2 +- src/settings.cpp | 48 ++++++++++++++++++++++++++++++++++++------------ src/settings.h | 4 ++-- 4 files changed, 40 insertions(+), 16 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index a518ccd4..cc7d7a78 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -331,7 +331,7 @@ TARGET_LINK_LIBRARIES(ModOrganizer zlibstatic uibase esptk bsatk githubpp ${usvfs_name} - Dbghelp advapi32 Version Shlwapi liblz4) + Dbghelp advapi32 Version Shlwapi liblz4 Crypt32) IF (MSVC) SET_TARGET_PROPERTIES(ModOrganizer PROPERTIES COMPILE_FLAGS "/std:c++latest") diff --git a/src/modinforegular.h b/src/modinforegular.h index 13ce7e42..6ad51e5f 100644 --- a/src/modinforegular.h +++ b/src/modinforegular.h @@ -415,7 +415,7 @@ private: bool m_IsAlternate; bool m_Converted; bool m_Validated; - bool m_NexusFileStatus; + int m_NexusFileStatus; MOBase::VersionInfo m_NewestVersion; MOBase::VersionInfo m_IgnoredVersion; diff --git a/src/settings.cpp b/src/settings.cpp index fdc767bf..1d5da376 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -57,6 +57,7 @@ along with Mod Organizer. If not, see . #include // for qDebug, qWarning #include // For ShellExecuteW, HINSTANCE, etc +#include // For storage #include // for sort #include @@ -175,26 +176,49 @@ void Settings::registerPlugin(IPlugin *plugin) } } -QString Settings::obfuscate(const QString &password) +QString Settings::obfuscate(const QString &info) { - QByteArray temp = password.toUtf8(); + QString result; + DATA_BLOB input; + DATA_BLOB output; + BYTE *pbInput = (unsigned char *)malloc(info.size() + 1); + memcpy(pbInput, info.constData(), info.size() + 1); + DWORD cbInput = info.size() + 1; + input.pbData = pbInput; + input.cbData = cbInput; - QByteArray buffer; - for (int i = 0; i < temp.length(); ++i) { - buffer.append(temp.at(i) ^ Key2[i % 20]); + if (CryptProtectData(&input, NULL, NULL, NULL, NULL, 0, &output)) { + QByteArray buffer = QByteArray::fromRawData((const char *)output.pbData, output.cbData); + result = buffer.toBase64(); + } else { + qCritical() << "Failed to encrypt the data!"; } - return buffer.toBase64(); + LocalFree(input.pbData); + LocalFree(output.pbData); + return result; } -QString Settings::deObfuscate(const QString &password) +QString Settings::deObfuscate(const QString &info) { - QByteArray temp(QByteArray::fromBase64(password.toUtf8())); + QString result; + QByteArray realInfo = QByteArray::fromBase64(info.toUtf8()); + DATA_BLOB input; + DATA_BLOB output; + BYTE *pbInput = (unsigned char *)malloc(realInfo.size() + 1); + memcpy(pbInput, realInfo.constData(), realInfo.size() + 1); + DWORD cbInput = realInfo.size() + 1; + input.pbData = pbInput; + input.cbData = cbInput; - QByteArray buffer; - for (int i = 0; i < temp.length(); ++i) { - buffer.append(temp.at(i) ^ Key2[i % 20]); + if (CryptUnprotectData(&input, NULL, NULL, NULL, NULL, 0, &output)) { + QByteArray buffer = QByteArray::fromRawData((const char *)output.pbData, output.cbData); + result = buffer; + } else { + qCritical() << "Failed to decrypt data!"; } - return QString::fromUtf8(buffer.constData()); + LocalFree(input.pbData); + LocalFree(output.pbData); + return result; } QColor Settings::getIdealTextColor(const QColor& rBackgroundColor) diff --git a/src/settings.h b/src/settings.h index d692497e..83838d5c 100644 --- a/src/settings.h +++ b/src/settings.h @@ -393,8 +393,8 @@ public: static QColor getIdealTextColor(const QColor& rBackgroundColor); private: - static QString obfuscate(const QString &password); - static QString deObfuscate(const QString &password); + static QString obfuscate(const QString &info); + static QString deObfuscate(const QString &info); void addLanguages(QComboBox *languageBox); void addStyles(QComboBox *styleBox); -- cgit v1.3.1 From 42d8bba5d419d13fcc6334c9bd73cb3c3a6d5251 Mon Sep 17 00:00:00 2001 From: Silarn Date: Thu, 31 Jan 2019 14:10:09 -0600 Subject: Stop blindly following examples and use better code --- src/settings.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/settings.cpp b/src/settings.cpp index 1d5da376..80d429c3 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -181,7 +181,7 @@ QString Settings::obfuscate(const QString &info) QString result; DATA_BLOB input; DATA_BLOB output; - BYTE *pbInput = (unsigned char *)malloc(info.size() + 1); + BYTE *pbInput = new unsigned char[info.size() + 1]; memcpy(pbInput, info.constData(), info.size() + 1); DWORD cbInput = info.size() + 1; input.pbData = pbInput; @@ -193,8 +193,8 @@ QString Settings::obfuscate(const QString &info) } else { qCritical() << "Failed to encrypt the data!"; } - LocalFree(input.pbData); - LocalFree(output.pbData); + delete pbInput; + delete output.pbData; return result; } @@ -204,7 +204,7 @@ QString Settings::deObfuscate(const QString &info) QByteArray realInfo = QByteArray::fromBase64(info.toUtf8()); DATA_BLOB input; DATA_BLOB output; - BYTE *pbInput = (unsigned char *)malloc(realInfo.size() + 1); + BYTE *pbInput = new unsigned char[realInfo.size() + 1]; memcpy(pbInput, realInfo.constData(), realInfo.size() + 1); DWORD cbInput = realInfo.size() + 1; input.pbData = pbInput; @@ -216,8 +216,8 @@ QString Settings::deObfuscate(const QString &info) } else { qCritical() << "Failed to decrypt data!"; } - LocalFree(input.pbData); - LocalFree(output.pbData); + delete pbInput; + delete output.pbData; return result; } -- cgit v1.3.1 From f04c437960c0882e62af7ead176c3f22adcd681d Mon Sep 17 00:00:00 2001 From: Silarn Date: Thu, 31 Jan 2019 14:54:45 -0600 Subject: Rework the data and cleanup a bit --- src/settings.cpp | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/settings.cpp b/src/settings.cpp index 80d429c3..eb34ab29 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -181,10 +181,11 @@ QString Settings::obfuscate(const QString &info) QString result; DATA_BLOB input; DATA_BLOB output; - BYTE *pbInput = new unsigned char[info.size() + 1]; - memcpy(pbInput, info.constData(), info.size() + 1); + std::vector data; + data.reserve(info.size() + 1); + memcpy(data.data(), info.constData(), info.size() + 1); DWORD cbInput = info.size() + 1; - input.pbData = pbInput; + input.pbData = data.data(); input.cbData = cbInput; if (CryptProtectData(&input, NULL, NULL, NULL, NULL, 0, &output)) { @@ -193,8 +194,7 @@ QString Settings::obfuscate(const QString &info) } else { qCritical() << "Failed to encrypt the data!"; } - delete pbInput; - delete output.pbData; + LocalFree(output.pbData); return result; } @@ -204,10 +204,11 @@ QString Settings::deObfuscate(const QString &info) QByteArray realInfo = QByteArray::fromBase64(info.toUtf8()); DATA_BLOB input; DATA_BLOB output; - BYTE *pbInput = new unsigned char[realInfo.size() + 1]; - memcpy(pbInput, realInfo.constData(), realInfo.size() + 1); + std::vector data; + data.reserve(realInfo.size() + 1); + memcpy(data.data(), realInfo.constData(), realInfo.size() + 1); DWORD cbInput = realInfo.size() + 1; - input.pbData = pbInput; + input.pbData = data.data(); input.cbData = cbInput; if (CryptUnprotectData(&input, NULL, NULL, NULL, NULL, 0, &output)) { @@ -216,8 +217,7 @@ QString Settings::deObfuscate(const QString &info) } else { qCritical() << "Failed to decrypt data!"; } - delete pbInput; - delete output.pbData; + LocalFree(output.pbData); return result; } -- cgit v1.3.1 From b7d2a608d8c0364d76950bc908c53203e3f467ff Mon Sep 17 00:00:00 2001 From: Silarn Date: Thu, 31 Jan 2019 16:54:31 -0600 Subject: Fixe API Key storage and actually validate the response --- src/nexusinterface.cpp | 2 +- src/nxmaccessmanager.cpp | 39 +++++++++++++++++++++------------------ src/settings.cpp | 8 ++------ 3 files changed, 24 insertions(+), 25 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/nexusinterface.cpp b/src/nexusinterface.cpp index 06fbe451..3ea7fdac 100644 --- a/src/nexusinterface.cpp +++ b/src/nexusinterface.cpp @@ -148,7 +148,7 @@ QAtomicInt NexusInterface::NXMRequestInfo::s_NextID(0); NexusInterface::NexusInterface(PluginContainer *pluginContainer) - : m_NMMVersion(), m_PluginContainer(pluginContainer), m_RemainingDailyRequests(0), m_RemainingHourlyRequests(0), m_MaxDailyRequests(0), m_MaxHourlyRequests(0) + : m_NMMVersion(), m_PluginContainer(pluginContainer), m_RemainingDailyRequests(2500), m_RemainingHourlyRequests(100), m_MaxDailyRequests(2500), m_MaxHourlyRequests(100) { m_MOVersion = createVersionInfo(); diff --git a/src/nxmaccessmanager.cpp b/src/nxmaccessmanager.cpp index d9bb2905..77ffbebc 100644 --- a/src/nxmaccessmanager.cpp +++ b/src/nxmaccessmanager.cpp @@ -249,23 +249,26 @@ void NXMAccessManager::validateFinished() if (m_ValidateReply != nullptr) { QJsonDocument jdoc = QJsonDocument::fromJson(m_ValidateReply->readAll()); QJsonObject credentialsData = jdoc.object(); - QString test = jdoc.toJson(); - QString name = credentialsData.value("name").toString(); - bool premium = credentialsData.value("is_premium?").toBool(); - - std::tuple limits(std::make_tuple( - m_ValidateReply->rawHeader("x-rl-daily-remaining").toInt(), - m_ValidateReply->rawHeader("x-rl-daily-limit").toInt(), - m_ValidateReply->rawHeader("x-rl-hourly-remaining").toInt(), - m_ValidateReply->rawHeader("x-rl-hourly-limit").toInt() - )); - - emit credentialsReceived(name, premium, limits); - - m_ValidateReply->deleteLater(); - m_ValidateReply = nullptr; - - m_ValidateState = VALIDATE_VALID; - emit validateSuccessful(true); + if (credentialsData.contains("user_id")) { + QString name = credentialsData.value("name").toString(); + bool premium = credentialsData.value("is_premium").toBool(); + + std::tuple limits(std::make_tuple( + m_ValidateReply->rawHeader("x-rl-daily-remaining").toInt(), + m_ValidateReply->rawHeader("x-rl-daily-limit").toInt(), + m_ValidateReply->rawHeader("x-rl-hourly-remaining").toInt(), + m_ValidateReply->rawHeader("x-rl-hourly-limit").toInt() + )); + + emit credentialsReceived(name, premium, limits); + + m_ValidateReply->deleteLater(); + m_ValidateReply = nullptr; + + m_ValidateState = VALIDATE_VALID; + emit validateSuccessful(true); + } else { + emit validateFailed(tr("Validation failed, please reauthenticate in the Settings -> Nexus tab: %1").arg(credentialsData.value("message").toString())); + } } } diff --git a/src/settings.cpp b/src/settings.cpp index eb34ab29..42f2e43f 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -181,9 +181,7 @@ QString Settings::obfuscate(const QString &info) QString result; DATA_BLOB input; DATA_BLOB output; - std::vector data; - data.reserve(info.size() + 1); - memcpy(data.data(), info.constData(), info.size() + 1); + std::vector data(info.toUtf8().begin(), info.toUtf8().end()); DWORD cbInput = info.size() + 1; input.pbData = data.data(); input.cbData = cbInput; @@ -204,9 +202,7 @@ QString Settings::deObfuscate(const QString &info) QByteArray realInfo = QByteArray::fromBase64(info.toUtf8()); DATA_BLOB input; DATA_BLOB output; - std::vector data; - data.reserve(realInfo.size() + 1); - memcpy(data.data(), realInfo.constData(), realInfo.size() + 1); + std::vector data(realInfo.begin(), realInfo.end()); DWORD cbInput = realInfo.size() + 1; input.pbData = data.data(); input.cbData = cbInput; -- cgit v1.3.1 From d08b836265c3f2c44041cb4d6da37183245b9a0e Mon Sep 17 00:00:00 2001 From: Silarn Date: Thu, 31 Jan 2019 17:16:17 -0600 Subject: Fix various issues when not having a stored API key --- src/mainwindow.cpp | 14 +++++--------- src/nexusinterface.cpp | 24 ++++++++++++------------ src/nxmaccessmanager.cpp | 2 ++ src/settings.cpp | 7 ++++--- 4 files changed, 23 insertions(+), 24 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 9368192f..3a341298 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -3996,10 +3996,8 @@ void MainWindow::checkModsForUpdates() if (m_OrganizerCore.settings().getNexusApiKey(apiKey)) { m_OrganizerCore.doAfterLogin([this] () { this->checkModsForUpdates(); }); NexusInterface::instance(&m_PluginContainer)->getAccessManager()->apiCheck(apiKey); - } else { // otherwise there will be no endorsement info - MessageDialog::showMessage(tr("Not logged in, endorsement information will be wrong"), - this, true); - m_ModsToUpdate = ModInfo::checkAllForUpdate(&m_PluginContainer, this); + } else { + qWarning("You are not currently authenticated with Nexus. Please do so under Settings -> Nexus."); } } @@ -5457,12 +5455,10 @@ void MainWindow::modUpdateCheck() } else { QString apiKey; if (m_OrganizerCore.settings().getNexusApiKey(apiKey)) { - m_OrganizerCore.doAfterLogin([this]() { this->checkModsForUpdates(); }); + m_OrganizerCore.doAfterLogin([this]() { this->modUpdateCheck(); }); NexusInterface::instance(&m_PluginContainer)->getAccessManager()->apiCheck(apiKey); - } else { // otherwise there will be no endorsement info - MessageDialog::showMessage(tr("Not logged in, endorsement information will be wrong"), - this, true); - m_ModsToUpdate += ModInfo::autoUpdateCheck(&m_PluginContainer, this); + } else { + qWarning("You are not currently authenticated with Nexus. Please do so under Settings -> Nexus."); } } } diff --git a/src/nexusinterface.cpp b/src/nexusinterface.cpp index 3ea7fdac..16f96154 100644 --- a/src/nexusinterface.cpp +++ b/src/nexusinterface.cpp @@ -628,23 +628,23 @@ void NexusInterface::requestFinished(std::list::iterator iter) emit nxmEndorsementToggled(iter->m_GameName, iter->m_ModID, iter->m_UserData, result, iter->m_ID); } break; } + + m_RemainingDailyRequests = reply->rawHeader("x-rl-daily-remaining").toInt(); + m_MaxDailyRequests = reply->rawHeader("x-rl-daily-limit").toInt(); + m_RemainingHourlyRequests = reply->rawHeader("x-rl-hourly-remaining").toInt(); + m_MaxHourlyRequests = reply->rawHeader("x-rl-hourly-limit").toInt(); + + emit requestsChanged(m_RequestQueue.size(), std::tuple(std::make_tuple( + m_RemainingDailyRequests, + m_MaxDailyRequests, + m_RemainingHourlyRequests, + m_MaxHourlyRequests + ))); } else { emit nxmRequestFailed(iter->m_GameName, iter->m_ModID, iter->m_FileID, iter->m_UserData, iter->m_ID, reply->error(), tr("invalid response")); } } } - - m_RemainingDailyRequests = reply->rawHeader("x-rl-daily-remaining").toInt(); - m_MaxDailyRequests = reply->rawHeader("x-rl-daily-limit").toInt(); - m_RemainingHourlyRequests = reply->rawHeader("x-rl-hourly-remaining").toInt(); - m_MaxHourlyRequests = reply->rawHeader("x-rl-hourly-limit").toInt(); - - emit requestsChanged(m_RequestQueue.size(), std::tuple(std::make_tuple( - m_RemainingDailyRequests, - m_MaxDailyRequests, - m_RemainingHourlyRequests, - m_MaxHourlyRequests - ))); } diff --git a/src/nxmaccessmanager.cpp b/src/nxmaccessmanager.cpp index 77ffbebc..d1720c76 100644 --- a/src/nxmaccessmanager.cpp +++ b/src/nxmaccessmanager.cpp @@ -270,5 +270,7 @@ void NXMAccessManager::validateFinished() } else { emit validateFailed(tr("Validation failed, please reauthenticate in the Settings -> Nexus tab: %1").arg(credentialsData.value("message").toString())); } + } else { + emit validateFailed(tr("unknown error")); } } diff --git a/src/settings.cpp b/src/settings.cpp index 42f2e43f..cd0aec8e 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -178,11 +178,12 @@ void Settings::registerPlugin(IPlugin *plugin) QString Settings::obfuscate(const QString &info) { + QByteArray byteData = info.toUtf8(); QString result; DATA_BLOB input; DATA_BLOB output; - std::vector data(info.toUtf8().begin(), info.toUtf8().end()); - DWORD cbInput = info.size() + 1; + std::vector data(byteData.begin(), byteData.end()); + DWORD cbInput = data.size() + 1; input.pbData = data.data(); input.cbData = cbInput; @@ -203,7 +204,7 @@ QString Settings::deObfuscate(const QString &info) DATA_BLOB input; DATA_BLOB output; std::vector data(realInfo.begin(), realInfo.end()); - DWORD cbInput = realInfo.size() + 1; + DWORD cbInput = data.size() + 1; input.pbData = data.data(); input.cbData = cbInput; -- cgit v1.3.1 From eb575e2f92e00e32220e7aa8efaf14ece462c981 Mon Sep 17 00:00:00 2001 From: Silarn Date: Tue, 5 Feb 2019 20:19:20 -0600 Subject: Implement Windows Credential Manager --- src/settings.cpp | 131 ++++++++++++++++++++++++++++++++++--------------------- src/settings.h | 4 +- 2 files changed, 83 insertions(+), 52 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/settings.cpp b/src/settings.cpp index cd0aec8e..cb4520e7 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -57,7 +57,7 @@ along with Mod Organizer. If not, see . #include // for qDebug, qWarning #include // For ShellExecuteW, HINSTANCE, etc -#include // For storage +#include // For storage #include // for sort #include @@ -176,45 +176,59 @@ void Settings::registerPlugin(IPlugin *plugin) } } -QString Settings::obfuscate(const QString &info) +bool Settings::obfuscate(const QString key, const QString data) { - QByteArray byteData = info.toUtf8(); - QString result; - DATA_BLOB input; - DATA_BLOB output; - std::vector data(byteData.begin(), byteData.end()); - DWORD cbInput = data.size() + 1; - input.pbData = data.data(); - input.cbData = cbInput; - - if (CryptProtectData(&input, NULL, NULL, NULL, NULL, 0, &output)) { - QByteArray buffer = QByteArray::fromRawData((const char *)output.pbData, output.cbData); - result = buffer.toBase64(); + QString finalKey("ModOrganizer2_" + key); + wchar_t* keyData = new wchar_t[finalKey.size()+1]; + finalKey.toWCharArray(keyData); + keyData[finalKey.size()] = L'\0'; + bool result = false; + if (data.isEmpty()) { + result = CredDeleteW(keyData, CRED_TYPE_GENERIC, 0); + if (!result) + if (GetLastError() == ERROR_NOT_FOUND) + result = true; } else { - qCritical() << "Failed to encrypt the data!"; + wchar_t* charData = new wchar_t[data.size()]; + data.toWCharArray(charData); + + CREDENTIALW cred = {}; + cred.Flags = 0; + cred.Type = CRED_TYPE_GENERIC; + cred.TargetName = keyData; + cred.CredentialBlob = (LPBYTE)charData; + cred.CredentialBlobSize = sizeof(wchar_t) * data.size(); + cred.Persist = CRED_PERSIST_LOCAL_MACHINE; + + result = CredWriteW(&cred, 0); + delete[] charData; } - LocalFree(output.pbData); + delete[] keyData; return result; } -QString Settings::deObfuscate(const QString &info) +QString Settings::deObfuscate(const QString key) { QString result; - QByteArray realInfo = QByteArray::fromBase64(info.toUtf8()); - DATA_BLOB input; - DATA_BLOB output; - std::vector data(realInfo.begin(), realInfo.end()); - DWORD cbInput = data.size() + 1; - input.pbData = data.data(); - input.cbData = cbInput; - - if (CryptUnprotectData(&input, NULL, NULL, NULL, NULL, 0, &output)) { - QByteArray buffer = QByteArray::fromRawData((const char *)output.pbData, output.cbData); - result = buffer; + QString finalKey("ModOrganizer2_" + key); + wchar_t* keyData = new wchar_t[finalKey.size()+1]; + finalKey.toWCharArray(keyData); + keyData[finalKey.size()] = L'\0'; + PCREDENTIALW creds; + if (CredReadW(keyData, 1, 0, &creds)) { + wchar_t *charData = (wchar_t *)creds->CredentialBlob; + result = QString::fromWCharArray(charData, creds->CredentialBlobSize / sizeof(wchar_t)); } else { - qCritical() << "Failed to decrypt data!"; + if (GetLastError() != ERROR_NOT_FOUND) { + wchar_t buffer[256]; + FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + buffer, (sizeof(buffer) / sizeof(wchar_t)), NULL); + qCritical() << "Retrieving encrypted data failed:" << buffer; + } } - LocalFree(output.pbData); + CredFree(creds); + delete[] keyData; return result; } @@ -355,22 +369,24 @@ QString Settings::getNMMVersion() const bool Settings::getNexusApiKey(QString &apiKey) const { - if (m_Settings.value("Settings/nexus_api_key", "").toString().isEmpty()) + QString tempKey = deObfuscate("APIKEY"); + if (tempKey.isEmpty()) return false; - apiKey = deObfuscate(m_Settings.value("Settings/nexus_api_key", "").toString()); + apiKey = tempKey; return true; } bool Settings::getSteamLogin(QString &username, QString &password) const { - if (m_Settings.contains("Settings/steam_username") - && m_Settings.contains("Settings/steam_password")) { - username = m_Settings.value("Settings/steam_username").toString(); - password = deObfuscate(m_Settings.value("Settings/steam_password").toString()); - return true; - } else { - return false; + if (m_Settings.contains("Settings/steam_username")) { + QString tempPass = deObfuscate("steam_password"); + if (!tempPass.isEmpty()) { + username = m_Settings.value("Settings/steam_username").toString(); + password = tempPass; + return true; + } } + return false; } bool Settings::compactDownloads() const { @@ -451,7 +467,13 @@ QString Settings::executablesBlacklist() const void Settings::setNexusApiKey(QString apiKey) { - m_Settings.setValue("Settings/nexus_api_key", obfuscate(apiKey)); + if (!obfuscate("APIKEY", apiKey)) { + wchar_t buffer[256]; + FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + buffer, (sizeof(buffer) / sizeof(wchar_t)), NULL); + qCritical() << "Storing API key failed:" << buffer; + } } void Settings::setSteamLogin(QString username, QString password) @@ -462,10 +484,12 @@ void Settings::setSteamLogin(QString username, QString password) } else { m_Settings.setValue("Settings/steam_username", username); } - if (password == "") { - m_Settings.remove("Settings/steam_password"); - } else { - m_Settings.setValue("Settings/steam_password", obfuscate(password)); + if (!obfuscate("steam_password", password)) { + wchar_t buffer[256]; + FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + buffer, (sizeof(buffer) / sizeof(wchar_t)), NULL); + qCritical() << "Storing or deleting password failed:" << buffer; } } @@ -692,19 +716,25 @@ void Settings::resetDialogs() void Settings::processApiKey(const QString &apiKey) { - m_Settings.setValue("Settings/nexus_api_key", obfuscate(apiKey)); + if (!obfuscate("APIKEY", apiKey)) { + wchar_t buffer[256]; + FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + buffer, (sizeof(buffer) / sizeof(wchar_t)), NULL); + qCritical() << "Storing or deleting API key failed:" << buffer; + } } void Settings::clearApiKey(QPushButton *nexusButton) { - m_Settings.remove("Settings/nexus_api_key"); + obfuscate("APIKEY", ""); nexusButton->setEnabled(true); nexusButton->setText("Connect to Nexus"); } void Settings::checkApiKey(QPushButton *nexusButton) { - if (m_Settings.value("Settings/nexus_api_key", "").toString().isEmpty()) { + if (deObfuscate("APIKEY").isEmpty()) { nexusButton->setEnabled(true); nexusButton->setText("Connect to Nexus"); QMessageBox::warning(qApp->activeWindow(), tr("Error"), @@ -1010,7 +1040,7 @@ Settings::NexusTab::NexusTab(Settings *parent, SettingsDialog &dialog) dialog.findChild("preferredServersList")) , m_endorsementBox(dialog.findChild("endorsementBox")) { - if (!m_Settings.value("Settings/nexus_api_key", "").toString().isEmpty()) { + if (!deObfuscate("APIKEY").isEmpty()) { m_nexusConnect->setText("Nexus API Key Stored"); m_nexusConnect->setDisabled(true); } @@ -1088,8 +1118,9 @@ Settings::SteamTab::SteamTab(Settings *m_parent, SettingsDialog &m_dialog) { if (m_Settings.contains("Settings/steam_username")) { m_steamUserEdit->setText(m_Settings.value("Settings/steam_username", "").toString()); - if (m_Settings.contains("Settings/steam_password")) { - m_steamPassEdit->setText(deObfuscate(m_Settings.value("Settings/steam_password", "").toString())); + QString password = deObfuscate("steam_password"); + if (!password.isEmpty()) { + m_steamPassEdit->setText(password); } } } diff --git a/src/settings.h b/src/settings.h index 83838d5c..a1dc011d 100644 --- a/src/settings.h +++ b/src/settings.h @@ -393,8 +393,8 @@ public: static QColor getIdealTextColor(const QColor& rBackgroundColor); private: - static QString obfuscate(const QString &info); - static QString deObfuscate(const QString &info); + static bool obfuscate(const QString key, const QString data); + static QString deObfuscate(const QString key); void addLanguages(QComboBox *languageBox); void addStyles(QComboBox *styleBox); -- cgit v1.3.1 From 8bc9db23d98ae454899791af9e0fbc0bab4d0b15 Mon Sep 17 00:00:00 2001 From: Silarn Date: Tue, 5 Feb 2019 22:38:46 -0600 Subject: Add settings option to switch between fixed and dynamic cache timeouts --- src/modinforegular.cpp | 39 +++++++++++++++++++++++---------------- src/modlist.cpp | 8 ++++++-- src/settings.cpp | 19 +++++++++++++++---- src/settings.h | 17 +++++++++++++++++ src/settingsdialog.ui | 10 ++++++++++ 5 files changed, 71 insertions(+), 22 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/modinforegular.cpp b/src/modinforegular.cpp index 876ccf3d..10a1317c 100644 --- a/src/modinforegular.cpp +++ b/src/modinforegular.cpp @@ -507,22 +507,29 @@ bool ModInfoRegular::canBeUpdated() const QDateTime ModInfoRegular::getExpires() const { - qint64 diff = m_NexusLastModified.msecsTo(QDateTime::currentDateTimeUtc()); - qint64 year = 31536000000; - qint64 sixMonths = 15768000000; - qint64 threeMonths = 7884000000; - qint64 oneMonth = 1314000000; - - if (diff < oneMonth) - return m_LastNexusUpdate.addSecs(7200); - else if (diff < threeMonths) - return m_LastNexusUpdate.addSecs(14400); - else if (diff < sixMonths) - return m_LastNexusUpdate.addSecs(21600); - else if (diff < year) - return m_LastNexusUpdate.addSecs(43200); - else - return m_LastNexusUpdate.addSecs(86400); + switch (Settings::instance().nexusUpdateStrategy()) { + case Settings::NexusUpdateStrategy::Flexible: { + qint64 diff = m_NexusLastModified.msecsTo(QDateTime::currentDateTimeUtc()); + qint64 year = 31536000000; + qint64 sixMonths = 15768000000; + qint64 threeMonths = 7884000000; + qint64 oneMonth = 1314000000; + + if (diff < oneMonth) + return m_LastNexusUpdate.addSecs(7200); + else if (diff < threeMonths) + return m_LastNexusUpdate.addSecs(14400); + else if (diff < sixMonths) + return m_LastNexusUpdate.addSecs(21600); + else if (diff < year) + return m_LastNexusUpdate.addSecs(43200); + else + return m_LastNexusUpdate.addSecs(86400); + } break; + case Settings::NexusUpdateStrategy::Rigid: { + return m_LastNexusUpdate.addSecs(86400); + } break; + } } std::vector ModInfoRegular::getFlags() const diff --git a/src/modlist.cpp b/src/modlist.cpp index c252d73b..55241492 100644 --- a/src/modlist.cpp +++ b/src/modlist.cpp @@ -465,9 +465,13 @@ QVariant ModList::data(const QModelIndex &modelIndex, int role) const } if (modInfo->getNexusID() > 0) { if (!modInfo->canBeUpdated()) { - text += "
    " + tr("This mod was last checked on %1. It will be available to check after %2.") + qint64 remains = QDateTime::currentDateTimeUtc().secsTo(modInfo->getExpires()); + qint64 hours = remains / 3600; + qint64 minutes = (remains % 3600) / 60; + QString remainsStr(tr("%1 hours and %2 minutes").arg(hours).arg(minutes)); + text += "
    " + tr("This mod was last checked on %1. It will be available to check in %2.") .arg(modInfo->getLastNexusUpdate().toLocalTime().toString(Qt::DefaultLocaleShortDate)) - .arg(modInfo->getExpires().toLocalTime().time().toString(Qt::DefaultLocaleShortDate)); + .arg(remainsStr); } else { text += "
    " + tr("This mod is eligible for an update check."); text += "
    " + tr("It was last checked on %1").arg(modInfo->getLastNexusUpdate().toLocalTime().toString(Qt::DefaultLocaleShortDate)); diff --git a/src/settings.cpp b/src/settings.cpp index cb4520e7..6be5489d 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -81,10 +81,6 @@ private: int m_SortRole; }; - -static const unsigned char Key2[20] = { 0x99, 0xb8, 0x76, 0x42, 0x3e, 0xc1, 0x60, 0xa4, 0x5b, 0x01, - 0xdb, 0xf8, 0x43, 0x3a, 0xb7, 0xb6, 0x98, 0xd4, 0x7d, 0xa2 }; - Settings *Settings::s_Instance = nullptr; @@ -96,6 +92,8 @@ Settings::Settings(const QSettings &settingsSource) } else { s_Instance = this; } + + qRegisterMetaType("NexusUpdateStrategy"); } @@ -418,6 +416,11 @@ int Settings::crashDumpsMax() const return m_Settings.value("Settings/crash_dumps_max", 5).toInt(); } +Settings::NexusUpdateStrategy Settings::nexusUpdateStrategy() const +{ + return static_cast(m_Settings.value("Settings/nexus_update_strategy", std::rand() / ((RAND_MAX + 1u) / 2)).toInt()); +} + QColor Settings::modlistOverwrittenLooseColor() const { return m_Settings.value("Settings/overwrittenLooseFilesColor", QColor(0, 255, 0, 64)).value(); @@ -1039,7 +1042,10 @@ Settings::NexusTab::NexusTab(Settings *parent, SettingsDialog &dialog) , m_preferredServersList( dialog.findChild("preferredServersList")) , m_endorsementBox(dialog.findChild("endorsementBox")) + , m_updateStrategyBox(dialog.findChild("updateStrategy")) { + qRegisterMetaType("NexusUpdateStrategy"); + if (!deObfuscate("APIKEY").isEmpty()) { m_nexusConnect->setText("Nexus API Key Stored"); m_nexusConnect->setDisabled(true); @@ -1048,6 +1054,9 @@ Settings::NexusTab::NexusTab(Settings *parent, SettingsDialog &dialog) m_offlineBox->setChecked(parent->offlineMode()); m_proxyBox->setChecked(parent->useProxy()); m_endorsementBox->setChecked(parent->endorsementIntegration()); + if (parent->nexusUpdateStrategy() == Settings::NexusUpdateStrategy::Flexible) + m_updateStrategyBox->setChecked(true); + // display server preferences m_Settings.beginGroup("Servers"); @@ -1092,6 +1101,8 @@ void Settings::NexusTab::update() m_Settings.setValue("Settings/offline_mode", m_offlineBox->isChecked()); m_Settings.setValue("Settings/use_proxy", m_proxyBox->isChecked()); m_Settings.setValue("Settings/endorsement_integration", m_endorsementBox->isChecked()); + m_Settings.setValue("Settings/nexus_update_strategy", m_updateStrategyBox->isChecked() + ? Settings::NexusUpdateStrategy::Flexible : Settings::NexusUpdateStrategy::Rigid); // store server preference m_Settings.beginGroup("Servers"); diff --git a/src/settings.h b/src/settings.h index a1dc011d..ddb7cac0 100644 --- a/src/settings.h +++ b/src/settings.h @@ -31,6 +31,7 @@ along with Mod Organizer. If not, see . #include #include #include +#include #include //for uint @@ -64,6 +65,14 @@ class Settings : public QObject { Q_OBJECT + Q_ENUMS(NexusUpdateStrategy) + +public: + + enum NexusUpdateStrategy { + Rigid, + Flexible + }; public: @@ -230,6 +239,11 @@ public: */ int crashDumpsMax() const; + /** + * @return the configured Nexus update strategy + */ + NexusUpdateStrategy nexusUpdateStrategy() const; + QColor modlistOverwrittenLooseColor() const; QColor modlistOverwritingLooseColor() const; @@ -485,6 +499,7 @@ private: QListWidget *m_knownServersList; QListWidget *m_preferredServersList; QCheckBox *m_endorsementBox; + QCheckBox *m_updateStrategyBox; }; /** Display/store the configuration in the 'steam' tab of the settings dialogue */ @@ -563,4 +578,6 @@ private: }; +Q_DECLARE_METATYPE(Settings::NexusUpdateStrategy) + #endif // SETTINGS_H diff --git a/src/settingsdialog.ui b/src/settingsdialog.ui index 127c94c7..cfbcf429 100644 --- a/src/settingsdialog.ui +++ b/src/settingsdialog.ui @@ -578,6 +578,16 @@ p, li { white-space: pre-wrap; }
    + + + + <html><head/><body><p>Rather than a global <span style=" font-weight:600;">1 day</span> cache, update caches will expire at different rates depending on how recently a mod has been updated on Nexus.</p><p><br/></p><p>Less than a month: <span style=" font-style:italic;">2 hours</span></p><p>Less than three months: <span style=" font-style:italic;">4 hours</span></p><p>Less than six months: <span style=" font-style:italic;">6 hours</span></p><p>Less than one year: <span style=" font-style:italic;">12 hours</span></p><p>More than one year: <span style=" font-style:italic;">1 day</span></p></body></html> + + + Use dynamic update timeouts + + +
    -- cgit v1.3.1 From 3f86a94ff73914460db72c1f20eca075de8caea6 Mon Sep 17 00:00:00 2001 From: Silarn Date: Wed, 6 Feb 2019 00:56:48 -0600 Subject: Freeing the credential object when there's no result causes overruns --- src/settings.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/settings.cpp') diff --git a/src/settings.cpp b/src/settings.cpp index 6be5489d..64a39e12 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -216,6 +216,7 @@ QString Settings::deObfuscate(const QString key) if (CredReadW(keyData, 1, 0, &creds)) { wchar_t *charData = (wchar_t *)creds->CredentialBlob; result = QString::fromWCharArray(charData, creds->CredentialBlobSize / sizeof(wchar_t)); + CredFree(creds); } else { if (GetLastError() != ERROR_NOT_FOUND) { wchar_t buffer[256]; @@ -225,7 +226,6 @@ QString Settings::deObfuscate(const QString key) qCritical() << "Retrieving encrypted data failed:" << buffer; } } - CredFree(creds); delete[] keyData; return result; } -- cgit v1.3.1 From f7d1ce1fae80e42141198547d6c54689e085327f Mon Sep 17 00:00:00 2001 From: Silarn Date: Mon, 11 Feb 2019 20:30:45 -0600 Subject: Small updates, cleanup, update code, cache settings, tooltips --- src/CMakeLists.txt | 2 - src/json.cpp | 522 ----------------------------------------------- src/json.h | 94 --------- src/mainwindow.cpp | 22 +- src/mainwindow.h | 5 +- src/mainwindow.ui | 4 +- src/modinforegular.cpp | 25 --- src/modlist.cpp | 12 +- src/nexusinterface.cpp | 14 +- src/nxmaccessmanager.cpp | 53 ++--- src/settings.cpp | 14 -- src/settings.h | 16 -- src/settingsdialog.ui | 10 - 13 files changed, 65 insertions(+), 728 deletions(-) delete mode 100644 src/json.cpp delete mode 100644 src/json.h (limited to 'src/settings.cpp') diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index cc7d7a78..b241d99a 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -79,7 +79,6 @@ SET(organizer_SRCS previewgenerator.cpp previewdialog.cpp aboutdialog.cpp - json.cpp modflagicondelegate.cpp genericicondelegate.cpp organizerproxy.cpp @@ -173,7 +172,6 @@ SET(organizer_HDRS previewgenerator.h previewdialog.h aboutdialog.h - json.h modflagicondelegate.h genericicondelegate.h organizerproxy.h diff --git a/src/json.cpp b/src/json.cpp deleted file mode 100644 index 05a2665a..00000000 --- a/src/json.cpp +++ /dev/null @@ -1,522 +0,0 @@ -/** - * QtJson - A simple class for parsing JSON data into a QVariant hierarchies and vice-versa. - * Copyright (C) 2011 Eeli Reilin - * - * This program 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. - * - * This program 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 this program. If not, see . - */ - -/** - * \file json.cpp - */ - -#include "json.h" - -namespace QtJson { - static QString sanitizeString(QString str); - static QByteArray join(const QList &list, const QByteArray &sep); - static QVariant parseValue(const QString &json, int &index, bool &success); - static QVariant parseObject(const QString &json, int &index, bool &success); - static QVariant parseArray(const QString &json, int &index, bool &success); - static QVariant parseString(const QString &json, int &index, bool &success); - static QVariant parseNumber(const QString &json, int &index); - static int lastIndexOfNumber(const QString &json, int index); - static void eatWhitespace(const QString &json, int &index); - static int lookAhead(const QString &json, int index); - static int nextToken(const QString &json, int &index); - - template - QByteArray serializeMap(const T &map, bool &success) { - QByteArray str = "{ "; - QList pairs; - for (typename T::const_iterator it = map.begin(), itend = map.end(); it != itend; ++it) { - QByteArray serializedValue = serialize(it.value()); - if (serializedValue.isNull()) { - success = false; - break; - } - pairs << sanitizeString(it.key()).toUtf8() + " : " + serializedValue; - } - - str += join(pairs, ", "); - str += " }"; - return str; - } - - - /** - * parse - */ - QVariant parse(const QString &json) { - bool success = true; - return parse(json, success); - } - - /** - * parse - */ - QVariant parse(const QString &json, bool &success) { - success = true; - - // Return an empty QVariant if the JSON data is either null or empty - if (!json.isNull() || !json.isEmpty()) { - QString data = json; - // We'll start from index 0 - int index = 0; - - // Parse the first value - QVariant value = parseValue(data, index, success); - - // Return the parsed value - return value; - } else { - // Return the empty QVariant - return QVariant(); - } - } - - QByteArray serialize(const QVariant &data) { - bool success = true; - return serialize(data, success); - } - - QByteArray serialize(const QVariant &data, bool &success) { - QByteArray str; - success = true; - - if (!data.isValid()) { // invalid or null? - str = "null"; - } else if ((data.type() == QVariant::List) || - (data.type() == QVariant::StringList)) { // variant is a list? - QList values; - const QVariantList list = data.toList(); - Q_FOREACH(const QVariant& v, list) { - QByteArray serializedValue = serialize(v); - if (serializedValue.isNull()) { - success = false; - break; - } - values << serializedValue; - } - - str = "[ " + join( values, ", " ) + " ]"; - } else if (data.type() == QVariant::Hash) { // variant is a hash? - str = serializeMap<>(data.toHash(), success); - } else if (data.type() == QVariant::Map) { // variant is a map? - str = serializeMap<>(data.toMap(), success); - } else if ((data.type() == QVariant::String) || - (data.type() == QVariant::ByteArray)) {// a string or a byte array? - str = sanitizeString(data.toString()).toUtf8(); - } else if (data.type() == QVariant::Double) { // double? - double value = data.toDouble(); - if ((value - value) == 0.0) { - str = QByteArray::number(value, 'g'); - if (!str.contains(".") && ! str.contains("e")) { - str += ".0"; - } - } else { - success = false; - } - } else if (data.type() == QVariant::Bool) { // boolean value? - str = data.toBool() ? "true" : "false"; - } else if (data.type() == QVariant::ULongLong) { // large unsigned number? - str = QByteArray::number(data.value()); - } else if (data.canConvert()) { // any signed number? - str = QByteArray::number(data.value()); - } else if (data.canConvert()) { //TODO: this code is never executed - str = QString::number(data.value()).toUtf8(); - } else if (data.canConvert()) { // can value be converted to string? - // this will catch QDate, QDateTime, QUrl, ... - str = sanitizeString(data.toString()).toUtf8(); - } else { - success = false; - } - - if (success) { - return str; - } else { - return QByteArray(); - } - } - - QString serializeStr(const QVariant &data) { - return QString::fromUtf8(serialize(data)); - } - - QString serializeStr(const QVariant &data, bool &success) { - return QString::fromUtf8(serialize(data, success)); - } - - - /** - * \enum JsonToken - */ - enum JsonToken { - JsonTokenNone = 0, - JsonTokenCurlyOpen = 1, - JsonTokenCurlyClose = 2, - JsonTokenSquaredOpen = 3, - JsonTokenSquaredClose = 4, - JsonTokenColon = 5, - JsonTokenComma = 6, - JsonTokenString = 7, - JsonTokenNumber = 8, - JsonTokenTrue = 9, - JsonTokenFalse = 10, - JsonTokenNull = 11 - }; - - static QString sanitizeString(QString str) { - str.replace(QLatin1String("\\"), QLatin1String("\\\\")); - str.replace(QLatin1String("\""), QLatin1String("\\\"")); - str.replace(QLatin1String("\b"), QLatin1String("\\b")); - str.replace(QLatin1String("\f"), QLatin1String("\\f")); - str.replace(QLatin1String("\n"), QLatin1String("\\n")); - str.replace(QLatin1String("\r"), QLatin1String("\\r")); - str.replace(QLatin1String("\t"), QLatin1String("\\t")); - return QString(QLatin1String("\"%1\"")).arg(str); - } - - static QByteArray join(const QList &list, const QByteArray &sep) { - QByteArray res; - Q_FOREACH(const QByteArray &i, list) { - if (!res.isEmpty()) { - res += sep; - } - res += i; - } - return res; - } - - /** - * parseValue - */ - static QVariant parseValue(const QString &json, int &index, bool &success) { - // Determine what kind of data we should parse by - // checking out the upcoming token - switch(lookAhead(json, index)) { - case JsonTokenString: - return parseString(json, index, success); - case JsonTokenNumber: - return parseNumber(json, index); - case JsonTokenCurlyOpen: - return parseObject(json, index, success); - case JsonTokenSquaredOpen: - return parseArray(json, index, success); - case JsonTokenTrue: - nextToken(json, index); - return QVariant(true); - case JsonTokenFalse: - nextToken(json, index); - return QVariant(false); - case JsonTokenNull: - nextToken(json, index); - return QVariant(); - case JsonTokenNone: - break; - } - - // If there were no tokens, flag the failure and return an empty QVariant - success = false; - return QVariant(); - } - - /** - * parseObject - */ - static QVariant parseObject(const QString &json, int &index, bool &success) { - QVariantMap map; - int token; - - // Get rid of the whitespace and increment index - nextToken(json, index); - - // Loop through all of the key/value pairs of the object - bool done = false; - while (!done) { - // Get the upcoming token - token = lookAhead(json, index); - - if (token == JsonTokenNone) { - success = false; - return QVariantMap(); - } else if (token == JsonTokenComma) { - nextToken(json, index); - } else if (token == JsonTokenCurlyClose) { - nextToken(json, index); - return map; - } else { - // Parse the key/value pair's name - QString name = parseString(json, index, success).toString(); - - if (!success) { - return QVariantMap(); - } - - // Get the next token - token = nextToken(json, index); - - // If the next token is not a colon, flag the failure - // return an empty QVariant - if (token != JsonTokenColon) { - success = false; - return QVariant(QVariantMap()); - } - - // Parse the key/value pair's value - QVariant value = parseValue(json, index, success); - - if (!success) { - return QVariantMap(); - } - - // Assign the value to the key in the map - map[name] = value; - } - } - - // Return the map successfully - return QVariant(map); - } - - /** - * parseArray - */ - static QVariant parseArray(const QString &json, int &index, bool &success) { - QVariantList list; - - nextToken(json, index); - - bool done = false; - while(!done) { - int token = lookAhead(json, index); - - if (token == JsonTokenNone) { - success = false; - return QVariantList(); - } else if (token == JsonTokenComma) { - nextToken(json, index); - } else if (token == JsonTokenSquaredClose) { - nextToken(json, index); - break; - } else { - QVariant value = parseValue(json, index, success); - if (!success) { - return QVariantList(); - } - list.push_back(value); - } - } - - return QVariant(list); - } - - /** - * parseString - */ - static QVariant parseString(const QString &json, int &index, bool &success) { - QString s; - QChar c; - - eatWhitespace(json, index); - - c = json[index++]; - - bool complete = false; - while(!complete) { - if (index == json.size()) { - break; - } - - c = json[index++]; - - if (c == '\"') { - complete = true; - break; - } else if (c == '\\') { - if (index == json.size()) { - break; - } - - c = json[index++]; - - if (c == '\"') { - s.append('\"'); - } else if (c == '\\') { - s.append('\\'); - } else if (c == '/') { - s.append('/'); - } else if (c == 'b') { - s.append('\b'); - } else if (c == 'f') { - s.append('\f'); - } else if (c == 'n') { - s.append('\n'); - } else if (c == 'r') { - s.append('\r'); - } else if (c == 't') { - s.append('\t'); - } else if (c == 'u') { - int remainingLength = json.size() - index; - if (remainingLength >= 4) { - QString unicodeStr = json.mid(index, 4); - - int symbol = unicodeStr.toInt(0, 16); - - s.append(QChar(symbol)); - - index += 4; - } else { - break; - } - } - } else { - s.append(c); - } - } - - if (!complete) { - success = false; - return QVariant(); - } - - return QVariant(s); - } - - /** - * parseNumber - */ - static QVariant parseNumber(const QString &json, int &index) { - eatWhitespace(json, index); - - int lastIndex = lastIndexOfNumber(json, index); - int charLength = (lastIndex - index) + 1; - QString numberStr; - - numberStr = json.mid(index, charLength); - - index = lastIndex + 1; - bool ok; - - if (numberStr.contains('.')) { - return QVariant(numberStr.toDouble(nullptr)); - } else if (numberStr.startsWith('-')) { - int i = numberStr.toInt(&ok); - if (!ok) { - qlonglong ll = numberStr.toLongLong(&ok); - return ok ? ll : QVariant(numberStr); - } - return i; - } else { - uint u = numberStr.toUInt(&ok); - if (!ok) { - qulonglong ull = numberStr.toULongLong(&ok); - return ok ? ull : QVariant(numberStr); - } - return u; - } - } - - /** - * lastIndexOfNumber - */ - static int lastIndexOfNumber(const QString &json, int index) { - int lastIndex; - - for(lastIndex = index; lastIndex < json.size(); lastIndex++) { - if (QString("0123456789+-.eE").indexOf(json[lastIndex]) == -1) { - break; - } - } - - return lastIndex -1; - } - - /** - * eatWhitespace - */ - static void eatWhitespace(const QString &json, int &index) { - for(; index < json.size(); index++) { - if (QString(" \t\n\r").indexOf(json[index]) == -1) { - break; - } - } - } - - /** - * lookAhead - */ - static int lookAhead(const QString &json, int index) { - int saveIndex = index; - return nextToken(json, saveIndex); - } - - /** - * nextToken - */ - static int nextToken(const QString &json, int &index) { - eatWhitespace(json, index); - - if (index == json.size()) { - return JsonTokenNone; - } - - QChar c = json[index]; - index++; - switch(c.toLatin1()) { - case '{': return JsonTokenCurlyOpen; - case '}': return JsonTokenCurlyClose; - case '[': return JsonTokenSquaredOpen; - case ']': return JsonTokenSquaredClose; - case ',': return JsonTokenComma; - case '"': return JsonTokenString; - case '0': case '1': case '2': case '3': case '4': - case '5': case '6': case '7': case '8': case '9': - case '-': return JsonTokenNumber; - case ':': return JsonTokenColon; - } - index--; // ^ WTF? - - int remainingLength = json.size() - index; - - // True - if (remainingLength >= 4) { - if (json[index] == 't' && json[index + 1] == 'r' && - json[index + 2] == 'u' && json[index + 3] == 'e') { - index += 4; - return JsonTokenTrue; - } - } - - // False - if (remainingLength >= 5) { - if (json[index] == 'f' && json[index + 1] == 'a' && - json[index + 2] == 'l' && json[index + 3] == 's' && - json[index + 4] == 'e') { - index += 5; - return JsonTokenFalse; - } - } - - // Null - if (remainingLength >= 4) { - if (json[index] == 'n' && json[index + 1] == 'u' && - json[index + 2] == 'l' && json[index + 3] == 'l') { - index += 4; - return JsonTokenNull; - } - } - - return JsonTokenNone; - } -} //end namespace diff --git a/src/json.h b/src/json.h deleted file mode 100644 index 57842e37..00000000 --- a/src/json.h +++ /dev/null @@ -1,94 +0,0 @@ -/** - * QtJson - A simple class for parsing JSON data into a QVariant hierarchies and vice-versa. - * Copyright (C) 2011 Eeli Reilin - * - * This program 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. - * - * This program 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 this program. If not, see . - */ - -/** - * \file json.h - */ - -#ifndef JSON_H -#define JSON_H - -#include -#include - - -/** - * \namespace QtJson - * \brief A JSON data parser - * - * Json parses a JSON data into a QVariant hierarchy. - */ -namespace QtJson { - typedef QVariantMap JsonObject; - typedef QVariantList JsonArray; - - /** - * Parse a JSON string - * - * \param json The JSON data - */ - QVariant parse(const QString &json); - - /** - * Parse a JSON string - * - * \param json The JSON data - * \param success The success of the parsing - */ - QVariant parse(const QString &json, bool &success); - - /** - * This method generates a textual JSON representation - * - * \param data The JSON data generated by the parser. - * - * \return QByteArray Textual JSON representation in UTF-8 - */ - QByteArray serialize(const QVariant &data); - - /** - * This method generates a textual JSON representation - * - * \param data The JSON data generated by the parser. - * \param success The success of the serialization - * - * \return QByteArray Textual JSON representation in UTF-8 - */ - QByteArray serialize(const QVariant &data, bool &success); - - /** - * This method generates a textual JSON representation - * - * \param data The JSON data generated by the parser. - * - * \return QString Textual JSON representation - */ - QString serializeStr(const QVariant &data); - - /** - * This method generates a textual JSON representation - * - * \param data The JSON data generated by the parser. - * \param success The success of the serialization - * - * \return QString Textual JSON representation - */ - QString serializeStr(const QVariant &data, bool &success); -} - -#endif //JSON_H diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 7592bd1e..1ecb6417 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -749,11 +749,11 @@ void MainWindow::createEndorseWidget() buttonMenu->clear(); QAction *endorseAction = new QAction(tr("Endorse"), buttonMenu); - connect(endorseAction, SIGNAL(triggered()), this, SLOT(on_actionEndorseMO_triggered())); + connect(endorseAction, SIGNAL(triggered()), this, SLOT(actionEndorseMO())); buttonMenu->addAction(endorseAction); QAction *wontEndorseAction = new QAction(tr("Won't Endorse"), buttonMenu); - connect(wontEndorseAction, SIGNAL(triggered()), this, SLOT(on_actionWontEndorseMO_triggered())); + connect(wontEndorseAction, SIGNAL(triggered()), this, SLOT(actionWontEndorseMO())); buttonMenu->addAction(wontEndorseAction); } @@ -1866,9 +1866,21 @@ void MainWindow::processUpdates() { lastHidden = hidden; } } - if (lastVersion < QVersionNumber(2,1,6)) { + if (lastVersion < QVersionNumber(2, 1, 6)) { ui->modList->header()->setSectionHidden(ModList::COL_NOTES, true); } + if (lastVersion < QVersionNumber(2, 2, 0)) { + QSettings &instance = Settings::instance().directInterface(); + instance.beginGroup("Settings"); + instance.remove("steam_password"); + instance.remove("nexus_username"); + instance.remove("nexus_password"); + instance.remove("nexus_api_key"); + instance.endGroup(); + instance.beginGroup("Servers"); + instance.remove(""); + instance.endGroup(); + } } if (currentVersion > lastVersion) { @@ -5366,7 +5378,7 @@ void MainWindow::on_actionUpdate_triggered() } -void MainWindow::on_actionEndorseMO_triggered() +void MainWindow::actionEndorseMO() { // Normally this would be the managed game but MO2 is only uploaded to the Skyrim SE site right now IPluginGame * game = m_OrganizerCore.getGame("skyrimse"); @@ -5381,7 +5393,7 @@ void MainWindow::on_actionEndorseMO_triggered() } } -void MainWindow::on_actionWontEndorseMO_triggered() +void MainWindow::actionWontEndorseMO() { // Normally this would be the managed game but MO2 is only uploaded to the Skyrim SE site right now IPluginGame * game = m_OrganizerCore.getGame("skyrimse"); diff --git a/src/mainwindow.h b/src/mainwindow.h index a0c043a1..ff23b8fb 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -494,6 +494,9 @@ private slots: void updateAvailable(); + void actionEndorseMO(); + void actionWontEndorseMO(); + void motdReceived(const QString &motd); void originModified(int originID); @@ -621,8 +624,6 @@ private slots: // ui slots void on_actionNotifications_triggered(); void on_actionSettings_triggered(); void on_actionUpdate_triggered(); - void on_actionEndorseMO_triggered(); - void on_actionWontEndorseMO_triggered(); void on_bsaList_customContextMenuRequested(const QPoint &pos); void on_clearFiltersButton_clicked(); diff --git a/src/mainwindow.ui b/src/mainwindow.ui index ad6b3e38..5ac8f092 100644 --- a/src/mainwindow.ui +++ b/src/mainwindow.ui @@ -550,10 +550,10 @@ p, li { white-space: pre-wrap; } - API Queued and Remaining Requests + Nexus API Queued and Remaining Requests - <html><head/><body><p>This tracks the number of queued Nexus API requests on the left (<span style=" font-weight:600;">Q</span>) and the remaining daily (<span style=" font-weight:600;">D</span>) and hourly (<span style=" font-weight:600;">H</span>) requests on the right. The Nexus API limits you to a pool of <span style=" font-weight:600;">2500</span> requests per day and <span style=" font-weight:600;">100</span> requests per hour. It is dynamically updated every time a request is completed. If you exceed this limit, you will be unable to queue downloads, check updates, parse mod info, or even log in.</p></body></html> + <html><head/><body><p>This tracks the number of queued Nexus API requests on the left (<span style=" font-weight:600;">Q</span>) and the remaining daily (<span style=" font-weight:600;">D</span>) and hourly (<span style=" font-weight:600;">H</span>) requests on the right. The Nexus API limits you to a pool of requests per day and requests per hour. It is dynamically updated every time a request is completed. If you run out of requests, you will be unable to queue downloads, check updates, parse mod info, or even log in. Both pools must be consumed before this happens.</p></body></html> QFrame::StyledPanel diff --git a/src/modinforegular.cpp b/src/modinforegular.cpp index ac1c46d6..8bef1c28 100644 --- a/src/modinforegular.cpp +++ b/src/modinforegular.cpp @@ -508,31 +508,6 @@ bool ModInfoRegular::canBeUpdated() const QDateTime ModInfoRegular::getExpires() const { return m_LastNexusUpdate.addSecs(300); - /* - switch (Settings::instance().nexusUpdateStrategy()) { - case Settings::NexusUpdateStrategy::Flexible: { - qint64 diff = m_NexusLastModified.msecsTo(QDateTime::currentDateTimeUtc()); - qint64 year = 31536000000; - qint64 sixMonths = 15768000000; - qint64 threeMonths = 7884000000; - qint64 oneMonth = 1314000000; - - if (diff < oneMonth) - return m_LastNexusUpdate.addSecs(7200); - else if (diff < threeMonths) - return m_LastNexusUpdate.addSecs(14400); - else if (diff < sixMonths) - return m_LastNexusUpdate.addSecs(21600); - else if (diff < year) - return m_LastNexusUpdate.addSecs(43200); - else - return m_LastNexusUpdate.addSecs(86400); - } break; - case Settings::NexusUpdateStrategy::Rigid: { - return m_LastNexusUpdate.addSecs(86400); - } break; - } - */ } std::vector ModInfoRegular::getFlags() const diff --git a/src/modlist.cpp b/src/modlist.cpp index 55241492..bb490113 100644 --- a/src/modlist.cpp +++ b/src/modlist.cpp @@ -466,15 +466,11 @@ QVariant ModList::data(const QModelIndex &modelIndex, int role) const if (modInfo->getNexusID() > 0) { if (!modInfo->canBeUpdated()) { qint64 remains = QDateTime::currentDateTimeUtc().secsTo(modInfo->getExpires()); - qint64 hours = remains / 3600; - qint64 minutes = (remains % 3600) / 60; - QString remainsStr(tr("%1 hours and %2 minutes").arg(hours).arg(minutes)); - text += "
    " + tr("This mod was last checked on %1. It will be available to check in %2.") - .arg(modInfo->getLastNexusUpdate().toLocalTime().toString(Qt::DefaultLocaleShortDate)) + qint64 minutes = remains / 60; + qint64 seconds = (remains % 60) / 60; + QString remainsStr(tr("%1 minute(s) and %2 second(s)").arg(minutes).arg(seconds)); + text += "
    " + tr("This mod will be available to check in %2.") .arg(remainsStr); - } else { - text += "
    " + tr("This mod is eligible for an update check."); - text += "
    " + tr("It was last checked on %1").arg(modInfo->getLastNexusUpdate().toLocalTime().toString(Qt::DefaultLocaleShortDate)); } } return text; diff --git a/src/nexusinterface.cpp b/src/nexusinterface.cpp index e657dfc1..265d898c 100644 --- a/src/nexusinterface.cpp +++ b/src/nexusinterface.cpp @@ -21,7 +21,6 @@ along with Mod Organizer. If not, see . #include "iplugingame.h" #include "nxmaccessmanager.h" -#include "json.h" #include "selectiondialog.h" #include "bbcode.h" #include @@ -613,6 +612,8 @@ void NexusInterface::nextRequest() url = info.m_URL; } QNetworkRequest request(url); + request.setAttribute(QNetworkRequest::CacheSaveControlAttribute, false); + request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::AlwaysNetwork); request.setRawHeader("APIKEY", m_AccessManager->apiKey().toUtf8()); request.setHeader(QNetworkRequest::KnownHeaders::UserAgentHeader, m_AccessManager->userAgent(info.m_SubModule)); request.setHeader(QNetworkRequest::KnownHeaders::ContentTypeHeader, "application/json"); @@ -645,7 +646,10 @@ void NexusInterface::requestFinished(std::list::iterator iter) if (reply->error() != QNetworkReply::NoError) { int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); if (statusCode == 429) { - qWarning("All API requests have been consumed and are now being denied."); + if (reply->rawHeader("x-rl-daily-remaining").toInt() || reply->rawHeader("x-rl-hourly-remaining").toInt()) + qWarning("You appear to be making requests to the Nexus API too quickly and are being throttled. Please inform the MO2 team."); + else + qWarning("All API requests have been consumed and are now being denied."); qWarning("Error: %s", reply->errorString().toUtf8().constData()); } else { qWarning("request failed: %s", reply->errorString().toUtf8().constData()); @@ -670,9 +674,9 @@ void NexusInterface::requestFinished(std::list::iterator iter) qDebug("nexus error: %s", qUtf8Printable(nexusError)); emit nxmRequestFailed(iter->m_GameName, iter->m_ModID, iter->m_FileID, iter->m_UserData, iter->m_ID, reply->error(), nexusError); } else { - bool ok; - QVariant result = QtJson::parse(data, ok); - if (result.isValid() && ok) { + QJsonDocument responseDoc = QJsonDocument::fromJson(data); + if (!responseDoc.isNull()) { + QVariant result = responseDoc.toVariant(); switch (iter->m_Type) { case NXMRequestInfo::TYPE_DESCRIPTION: { emit nxmDescriptionAvailable(iter->m_GameName, iter->m_ModID, iter->m_UserData, result, iter->m_ID); diff --git a/src/nxmaccessmanager.cpp b/src/nxmaccessmanager.cpp index 1e0ac49b..aca1d785 100644 --- a/src/nxmaccessmanager.cpp +++ b/src/nxmaccessmanager.cpp @@ -259,33 +259,40 @@ void NXMAccessManager::validateFinished() if (m_ValidateReply != nullptr) { QJsonDocument jdoc = QJsonDocument::fromJson(m_ValidateReply->readAll()); - QJsonObject credentialsData = jdoc.object(); - if (credentialsData.contains("user_id")) { - QString name = credentialsData.value("name").toString(); - bool premium = credentialsData.value("is_premium").toBool(); - - std::tuple limits(std::make_tuple( - m_ValidateReply->rawHeader("x-rl-daily-remaining").toInt(), - m_ValidateReply->rawHeader("x-rl-daily-limit").toInt(), - m_ValidateReply->rawHeader("x-rl-hourly-remaining").toInt(), - m_ValidateReply->rawHeader("x-rl-hourly-limit").toInt() - )); - - emit credentialsReceived(name, premium, limits); - - m_ValidateReply->deleteLater(); - m_ValidateReply = nullptr; - - m_ValidateState = VALIDATE_VALID; - emit validateSuccessful(true); + if (!jdoc.isNull()) { + QJsonObject credentialsData = jdoc.object(); + if (credentialsData.contains("user_id")) { + QString name = credentialsData.value("name").toString(); + bool premium = credentialsData.value("is_premium").toBool(); + + std::tuple limits(std::make_tuple( + m_ValidateReply->rawHeader("x-rl-daily-remaining").toInt(), + m_ValidateReply->rawHeader("x-rl-daily-limit").toInt(), + m_ValidateReply->rawHeader("x-rl-hourly-remaining").toInt(), + m_ValidateReply->rawHeader("x-rl-hourly-limit").toInt() + )); + + emit credentialsReceived(name, premium, limits); + + m_ValidateReply->deleteLater(); + m_ValidateReply = nullptr; + + m_ValidateState = VALIDATE_VALID; + emit validateSuccessful(true); + } else { + m_ApiKey.clear(); + m_ValidateState = VALIDATE_NOT_VALID; + emit validateFailed(tr("Validation failed, please reauthenticate in the Settings -> Nexus tab: %1").arg(credentialsData.value("message").toString())); + } } else { m_ApiKey.clear(); - m_ValidateState = VALIDATE_NOT_VALID; - emit validateFailed(tr("Validation failed, please reauthenticate in the Settings -> Nexus tab: %1").arg(credentialsData.value("message").toString())); + m_ValidateState = VALIDATE_NOT_CHECKED; + emit validateFailed(tr("Could not parse response. Invalid JSON.")); } - } else { + } + else { m_ApiKey.clear(); m_ValidateState = VALIDATE_NOT_CHECKED; - emit validateFailed(tr("unknown error")); + emit validateFailed(tr("Unknown error.")); } } diff --git a/src/settings.cpp b/src/settings.cpp index 64a39e12..7b4b3a67 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -92,8 +92,6 @@ Settings::Settings(const QSettings &settingsSource) } else { s_Instance = this; } - - qRegisterMetaType("NexusUpdateStrategy"); } @@ -416,11 +414,6 @@ int Settings::crashDumpsMax() const return m_Settings.value("Settings/crash_dumps_max", 5).toInt(); } -Settings::NexusUpdateStrategy Settings::nexusUpdateStrategy() const -{ - return static_cast(m_Settings.value("Settings/nexus_update_strategy", std::rand() / ((RAND_MAX + 1u) / 2)).toInt()); -} - QColor Settings::modlistOverwrittenLooseColor() const { return m_Settings.value("Settings/overwrittenLooseFilesColor", QColor(0, 255, 0, 64)).value(); @@ -1042,10 +1035,7 @@ Settings::NexusTab::NexusTab(Settings *parent, SettingsDialog &dialog) , m_preferredServersList( dialog.findChild("preferredServersList")) , m_endorsementBox(dialog.findChild("endorsementBox")) - , m_updateStrategyBox(dialog.findChild("updateStrategy")) { - qRegisterMetaType("NexusUpdateStrategy"); - if (!deObfuscate("APIKEY").isEmpty()) { m_nexusConnect->setText("Nexus API Key Stored"); m_nexusConnect->setDisabled(true); @@ -1054,8 +1044,6 @@ Settings::NexusTab::NexusTab(Settings *parent, SettingsDialog &dialog) m_offlineBox->setChecked(parent->offlineMode()); m_proxyBox->setChecked(parent->useProxy()); m_endorsementBox->setChecked(parent->endorsementIntegration()); - if (parent->nexusUpdateStrategy() == Settings::NexusUpdateStrategy::Flexible) - m_updateStrategyBox->setChecked(true); // display server preferences @@ -1101,8 +1089,6 @@ void Settings::NexusTab::update() m_Settings.setValue("Settings/offline_mode", m_offlineBox->isChecked()); m_Settings.setValue("Settings/use_proxy", m_proxyBox->isChecked()); m_Settings.setValue("Settings/endorsement_integration", m_endorsementBox->isChecked()); - m_Settings.setValue("Settings/nexus_update_strategy", m_updateStrategyBox->isChecked() - ? Settings::NexusUpdateStrategy::Flexible : Settings::NexusUpdateStrategy::Rigid); // store server preference m_Settings.beginGroup("Servers"); diff --git a/src/settings.h b/src/settings.h index ddb7cac0..2cd3f0b6 100644 --- a/src/settings.h +++ b/src/settings.h @@ -65,14 +65,6 @@ class Settings : public QObject { Q_OBJECT - Q_ENUMS(NexusUpdateStrategy) - -public: - - enum NexusUpdateStrategy { - Rigid, - Flexible - }; public: @@ -239,11 +231,6 @@ public: */ int crashDumpsMax() const; - /** - * @return the configured Nexus update strategy - */ - NexusUpdateStrategy nexusUpdateStrategy() const; - QColor modlistOverwrittenLooseColor() const; QColor modlistOverwritingLooseColor() const; @@ -499,7 +486,6 @@ private: QListWidget *m_knownServersList; QListWidget *m_preferredServersList; QCheckBox *m_endorsementBox; - QCheckBox *m_updateStrategyBox; }; /** Display/store the configuration in the 'steam' tab of the settings dialogue */ @@ -578,6 +564,4 @@ private: }; -Q_DECLARE_METATYPE(Settings::NexusUpdateStrategy) - #endif // SETTINGS_H diff --git a/src/settingsdialog.ui b/src/settingsdialog.ui index cfbcf429..127c94c7 100644 --- a/src/settingsdialog.ui +++ b/src/settingsdialog.ui @@ -578,16 +578,6 @@ p, li { white-space: pre-wrap; }
    - - - - <html><head/><body><p>Rather than a global <span style=" font-weight:600;">1 day</span> cache, update caches will expire at different rates depending on how recently a mod has been updated on Nexus.</p><p><br/></p><p>Less than a month: <span style=" font-style:italic;">2 hours</span></p><p>Less than three months: <span style=" font-style:italic;">4 hours</span></p><p>Less than six months: <span style=" font-style:italic;">6 hours</span></p><p>Less than one year: <span style=" font-style:italic;">12 hours</span></p><p>More than one year: <span style=" font-style:italic;">1 day</span></p></body></html> - - - Use dynamic update timeouts - - -
    -- cgit v1.3.1 From 330ff910d16c381157afa7aae744dc160abb250d Mon Sep 17 00:00:00 2001 From: LostDragonist Date: Thu, 21 Feb 2019 03:16:41 -0600 Subject: Add space --- src/settings.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/settings.cpp') diff --git a/src/settings.cpp b/src/settings.cpp index 7b4b3a67..67a84c0a 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -734,7 +734,7 @@ void Settings::checkApiKey(QPushButton *nexusButton) nexusButton->setEnabled(true); nexusButton->setText("Connect to Nexus"); QMessageBox::warning(qApp->activeWindow(), tr("Error"), - tr("Failed to retrieve a Nexus API key! Please try again." + tr("Failed to retrieve a Nexus API key! Please try again. " "A browser window should open asking you to authorize.")); } } -- cgit v1.3.1 From ef80a8bacaab525be21b9beae4992955f5e907d0 Mon Sep 17 00:00:00 2001 From: LostDragonist Date: Fri, 22 Feb 2019 04:33:21 -0600 Subject: Remove the spoofed NMM version The new API does not require this and it serves no purpose to keep it. --- src/mainwindow.cpp | 3 +-- src/nexusinterface.cpp | 8 +------- src/nexusinterface.h | 7 ------- src/nxmaccessmanager.cpp | 6 ------ src/nxmaccessmanager.h | 3 --- src/organizercore.cpp | 1 - src/settings.cpp | 13 ------------- src/settings.h | 6 ------ src/settingsdialog.ui | 48 ------------------------------------------------ 9 files changed, 2 insertions(+), 93 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 282c9674..602c32df 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -1878,6 +1878,7 @@ void MainWindow::processUpdates() { instance.remove("nexus_login"); instance.remove("nexus_api_key"); instance.remove("ask_for_nexuspw"); + instance.remove("nmm_version"); instance.endGroup(); instance.beginGroup("Servers"); instance.remove(""); @@ -4905,8 +4906,6 @@ void MainWindow::on_actionSettings_triggered() activateProxy(settings.useProxy()); } - NexusInterface::instance(&m_PluginContainer)->setNMMVersion(settings.getNMMVersion()); - updateDownloadView(); m_OrganizerCore.updateVFSParams(settings.logLevel(), settings.crashDumpsType(), settings.executablesBlacklist()); diff --git a/src/nexusinterface.cpp b/src/nexusinterface.cpp index ee40be22..23dd7dbe 100644 --- a/src/nexusinterface.cpp +++ b/src/nexusinterface.cpp @@ -156,7 +156,7 @@ QAtomicInt NexusInterface::NXMRequestInfo::s_NextID(0); NexusInterface::NexusInterface(PluginContainer *pluginContainer) - : m_NMMVersion(), m_PluginContainer(pluginContainer), m_RemainingDailyRequests(2500), m_RemainingHourlyRequests(100), m_MaxDailyRequests(2500), m_MaxHourlyRequests(100) + : m_PluginContainer(pluginContainer), m_RemainingDailyRequests(2500), m_RemainingHourlyRequests(100), m_MaxDailyRequests(2500), m_MaxHourlyRequests(100) { m_MOVersion = createVersionInfo(); @@ -187,12 +187,6 @@ void NexusInterface::setCacheDirectory(const QString &directory) m_AccessManager->setCache(m_DiskCache); } -void NexusInterface::setNMMVersion(const QString &nmmVersion) -{ - m_NMMVersion = nmmVersion; - m_AccessManager->setNMMVersion(nmmVersion); -} - void NexusInterface::loginCompleted() { nextRequest(); diff --git a/src/nexusinterface.h b/src/nexusinterface.h index c18c7103..c1f9da41 100644 --- a/src/nexusinterface.h +++ b/src/nexusinterface.h @@ -335,12 +335,6 @@ public: **/ void setCacheDirectory(const QString &directory); - /** - * MO has to send a "Nexus Client Vx.y.z" as part of the user agent to be allowed to use the API - * @param nmmVersion the version of nmm to impersonate - **/ - void setNMMVersion(const QString &nmmVersion); - /** * @brief called when the log-in completes. This was, requests waiting for the log-in can be run */ @@ -485,7 +479,6 @@ private: QQueue m_RequestQueue; MOBase::VersionInfo m_MOVersion; - QString m_NMMVersion; PluginContainer *m_PluginContainer; diff --git a/src/nxmaccessmanager.cpp b/src/nxmaccessmanager.cpp index aca1d785..428aa3f3 100644 --- a/src/nxmaccessmanager.cpp +++ b/src/nxmaccessmanager.cpp @@ -69,11 +69,6 @@ NXMAccessManager::~NXMAccessManager() } } -void NXMAccessManager::setNMMVersion(const QString &nmmVersion) -{ - m_NMMVersion = nmmVersion; -} - QNetworkReply *NXMAccessManager::createRequest( QNetworkAccessManager::Operation operation, const QNetworkRequest &request, QIODevice *device) @@ -202,7 +197,6 @@ QString NXMAccessManager::userAgent(const QString &subModule) const else comments << QSysInfo::kernelType().left(1).toUpper() + QSysInfo::kernelType().mid(1) << QSysInfo::productType().left(1).toUpper() + QSysInfo::kernelType().mid(1) + " " + QSysInfo::productVersion(); - comments << "Nexus Client v" + m_NMMVersion; if (!subModule.isEmpty()) { comments << "module: " + subModule; } diff --git a/src/nxmaccessmanager.h b/src/nxmaccessmanager.h index 7fdb508f..da7736cc 100644 --- a/src/nxmaccessmanager.h +++ b/src/nxmaccessmanager.h @@ -41,8 +41,6 @@ public: ~NXMAccessManager(); - void setNMMVersion(const QString &nmmVersion); - bool validated() const; bool validateAttempted() const; @@ -101,7 +99,6 @@ private: QProgressDialog *m_ProgressDialog { nullptr }; QString m_MOVersion; - QString m_NMMVersion; QString m_ApiKey; diff --git a/src/organizercore.cpp b/src/organizercore.cpp index 2f75439d..caad45c9 100644 --- a/src/organizercore.cpp +++ b/src/organizercore.cpp @@ -292,7 +292,6 @@ OrganizerCore::OrganizerCore(const QSettings &initSettings) m_DownloadManager.setPreferredServers(m_Settings.getPreferredServers()); NexusInterface::instance(m_PluginContainer)->setCacheDirectory(m_Settings.getCacheDirectory()); - NexusInterface::instance(m_PluginContainer)->setNMMVersion(m_Settings.getNMMVersion()); MOBase::QuestionBoxMemory::init(initSettings.fileName()); diff --git a/src/settings.cpp b/src/settings.cpp index 67a84c0a..942005f8 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -353,16 +353,6 @@ QString Settings::getOverwriteDirectory(bool resolve) const ToQString(AppConfig::overwritePath()), resolve); } -QString Settings::getNMMVersion() const -{ - static const QString MIN_NMM_VERSION = "0.65.2"; - QString result = m_Settings.value("Settings/nmm_version", MIN_NMM_VERSION).toString(); - if (VersionInfo(result) < VersionInfo(MIN_NMM_VERSION)) { - result = MIN_NMM_VERSION; - } - return result; -} - bool Settings::getNexusApiKey(QString &apiKey) const { QString tempKey = deObfuscate("APIKEY"); @@ -1179,7 +1169,6 @@ Settings::WorkaroundsTab::WorkaroundsTab(Settings *m_parent, : Settings::SettingsTab(m_parent, m_dialog) , m_appIDEdit(m_dialog.findChild("appIDEdit")) , m_mechanismBox(m_dialog.findChild("mechanismBox")) - , m_nmmVersionEdit(m_dialog.findChild("nmmVersionEdit")) , m_hideUncheckedBox(m_dialog.findChild("hideUncheckedBox")) , m_forceEnableBox(m_dialog.findChild("forceEnableBox")) , m_displayForeignBox(m_dialog.findChild("displayForeignBox")) @@ -1214,7 +1203,6 @@ Settings::WorkaroundsTab::WorkaroundsTab(Settings *m_parent, m_mechanismBox->setCurrentIndex(index); - m_nmmVersionEdit->setText(m_parent->getNMMVersion()); m_hideUncheckedBox->setChecked(m_parent->hideUncheckedPlugins()); m_forceEnableBox->setChecked(m_parent->forceEnableCoreFiles()); m_displayForeignBox->setChecked(m_parent->displayForeign()); @@ -1233,7 +1221,6 @@ void Settings::WorkaroundsTab::update() m_Settings.remove("Settings/app_id"); } m_Settings.setValue("Settings/load_mechanism", m_mechanismBox->itemData(m_mechanismBox->currentIndex()).toInt()); - m_Settings.setValue("Settings/nmm_version", m_nmmVersionEdit->text()); m_Settings.setValue("Settings/hide_unchecked_plugins", m_hideUncheckedBox->isChecked()); m_Settings.setValue("Settings/force_enable_core_files", m_forceEnableBox->isChecked()); m_Settings.setValue("Settings/display_foreign", m_displayForeignBox->isChecked()); diff --git a/src/settings.h b/src/settings.h index 2cd3f0b6..3744a493 100644 --- a/src/settings.h +++ b/src/settings.h @@ -152,11 +152,6 @@ public: **/ QString getModDirectory(bool resolve = true) const; - /** - * returns the version of nmm to impersonate when connecting to nexus - **/ - QString getNMMVersion() const; - /** * retrieve the directory where the web cache is stored (with native separators) **/ @@ -525,7 +520,6 @@ private: private: QLineEdit *m_appIDEdit; QComboBox *m_mechanismBox; - QLineEdit *m_nmmVersionEdit; QCheckBox *m_hideUncheckedBox; QCheckBox *m_forceEnableBox; QCheckBox *m_displayForeignBox; diff --git a/src/settingsdialog.ui b/src/settingsdialog.ui index 127c94c7..e56b3435 100644 --- a/src/settingsdialog.ui +++ b/src/settingsdialog.ui @@ -959,53 +959,6 @@ If you use the Steam version of Oblivion the default will NOT work. In this case
    - - - - - - NMM Version - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - The Version of Nexus Mod Manager to impersonate. - - - Mod Organizer uses an API provided by the Nexus to provide features like checking for updates and downloading files. Unfortunately this API has not been made available officially to third party tools like MO so we have to impersonate the Nexus Mod Manager to be allowed in. -On top of this Nexus has used the client identification to lock out outdated versions of NMM to force users to update. This means that MO also needs to impersonate the new version of NMM even if MO doesn't need an update. Therefore you can configure the version to identify as here. -Please note that MO does identify itself as MO to the webserver, it's not lying about what it is. It is merely adding a "compatible" NMM version to the user agent. - -tl;dr-version: If Nexus-features don't work, insert the current version number of NMM here and try again. - - - 009.009.009 - - - Qt::AlignCenter - - - - - - - - @@ -1388,7 +1341,6 @@ programs you are intentionally running. pluginBlacklist appIDEdit mechanismBox - nmmVersionEdit bsaDateBtn tabWidget -- cgit v1.3.1 From dfc992f467eb841c91b04185b525842534820d40 Mon Sep 17 00:00:00 2001 From: LostDragonist Date: Wed, 6 Mar 2019 17:20:53 -0600 Subject: Add setting to hide the API counter --- src/mainwindow.cpp | 3 +++ src/settings.cpp | 9 ++++++++- src/settings.h | 6 ++++++ src/settingsdialog.cpp | 13 ------------- src/settingsdialog.ui | 13 +++++++++++++ 5 files changed, 30 insertions(+), 14 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index bb1a9ec5..58c80b87 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -369,6 +369,7 @@ MainWindow::MainWindow(QSettings &initSettings palette.setColor(ui->apiRequests->backgroundRole(), Qt::darkGreen); palette.setColor(ui->apiRequests->foregroundRole(), Qt::white); ui->apiRequests->setPalette(palette); + ui->apiRequests->setVisible(!m_OrganizerCore.settings().hideAPICounter()); connect(ui->savegameList, SIGNAL(itemEntered(QListWidgetItem*)), this, SLOT(saveSelectionChanged(QListWidgetItem*))); @@ -4912,6 +4913,8 @@ void MainWindow::on_actionSettings_triggered() activateProxy(settings.useProxy()); } + ui->apiRequests->setVisible(!settings.hideAPICounter()); + updateDownloadView(); m_OrganizerCore.updateVFSParams(settings.logLevel(), settings.crashDumpsType(), settings.executablesBlacklist()); diff --git a/src/settings.cpp b/src/settings.cpp index 942005f8..1e932e49 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -506,6 +506,11 @@ bool Settings::endorsementIntegration() const return m_Settings.value("Settings/endorsement_integration", true).toBool(); } +bool Settings::hideAPICounter() const +{ + return m_Settings.value("Settings/hide_api_counter", false).toBool(); +} + bool Settings::displayForeign() const { return m_Settings.value("Settings/display_foreign", true).toBool(); @@ -1025,6 +1030,7 @@ Settings::NexusTab::NexusTab(Settings *parent, SettingsDialog &dialog) , m_preferredServersList( dialog.findChild("preferredServersList")) , m_endorsementBox(dialog.findChild("endorsementBox")) + , m_hideAPICounterBox(dialog.findChild("hideAPICounterBox")) { if (!deObfuscate("APIKEY").isEmpty()) { m_nexusConnect->setText("Nexus API Key Stored"); @@ -1034,7 +1040,7 @@ Settings::NexusTab::NexusTab(Settings *parent, SettingsDialog &dialog) m_offlineBox->setChecked(parent->offlineMode()); m_proxyBox->setChecked(parent->useProxy()); m_endorsementBox->setChecked(parent->endorsementIntegration()); - + m_hideAPICounterBox->setChecked(parent->hideAPICounter()); // display server preferences m_Settings.beginGroup("Servers"); @@ -1079,6 +1085,7 @@ void Settings::NexusTab::update() m_Settings.setValue("Settings/offline_mode", m_offlineBox->isChecked()); m_Settings.setValue("Settings/use_proxy", m_proxyBox->isChecked()); m_Settings.setValue("Settings/endorsement_integration", m_endorsementBox->isChecked()); + m_Settings.setValue("Settings/hide_api_counter", m_hideAPICounterBox->isChecked()); // store server preference m_Settings.beginGroup("Servers"); diff --git a/src/settings.h b/src/settings.h index 3744a493..324fa0b6 100644 --- a/src/settings.h +++ b/src/settings.h @@ -276,6 +276,11 @@ public: */ bool endorsementIntegration() const; + /** + * @return true if the API counter should be hidden + */ + bool hideAPICounter() const; + /** * @return true if the user wants to see non-official plugins installed outside MO in his mod list */ @@ -481,6 +486,7 @@ private: QListWidget *m_knownServersList; QListWidget *m_preferredServersList; QCheckBox *m_endorsementBox; + QCheckBox *m_hideAPICounterBox; }; /** Display/store the configuration in the 'steam' tab of the settings dialogue */ diff --git a/src/settingsdialog.cpp b/src/settingsdialog.cpp index ee7edead..f9f4f255 100644 --- a/src/settingsdialog.cpp +++ b/src/settingsdialog.cpp @@ -131,19 +131,6 @@ bool SettingsDialog::getResetGeometries() return ui->resetGeometryBtn->isChecked(); } -//void SettingsDialog::on_loginCheckBox_toggled(bool checked) -//{ -// QLineEdit *usernameEdit = findChild("usernameEdit"); -// QLineEdit *passwordEdit = findChild("passwordEdit"); -// if (checked) { -// passwordEdit->setEnabled(true); -// usernameEdit->setEnabled(true); -// } else { -// passwordEdit->setEnabled(false); -// usernameEdit->setEnabled(false); -// } -//} - void SettingsDialog::on_categoriesBtn_clicked() { CategoriesDialog dialog(this); diff --git a/src/settingsdialog.ui b/src/settingsdialog.ui index e56b3435..d6ac76a8 100644 --- a/src/settingsdialog.ui +++ b/src/settingsdialog.ui @@ -578,6 +578,19 @@ p, li { white-space: pre-wrap; }
    + + + + <html><head/><body><p>By default, a counter is displayed under the mod list. This informs the user of their remaining API requests. The Nexus API becomes unusable once these API requests run out. Checking this option will hide that counter.</p></body></html> + + + <html><head/><body><p>By default, a counter is displayed under the mod list. This informs the user of their remaining API requests. The Nexus API becomes unusable once these API requests run out. Checking this option will hide that counter.</p></body></html> + + + Hide API Request Counter + + +
    -- cgit v1.3.1 From 3061a15822dda0f7ed01aeb45ce9ccf4ad0f6af5 Mon Sep 17 00:00:00 2001 From: LostDragonist Date: Tue, 30 Apr 2019 04:51:32 -0500 Subject: Restart MO if the API key is changed or the reset geometries button was clicked --- src/settings.cpp | 33 ++++++++++++++++++++++----------- src/settings.h | 1 + src/settingsdialog.cpp | 14 ++++++++++++++ src/settingsdialog.h | 5 +++++ 4 files changed, 42 insertions(+), 11 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/settings.cpp b/src/settings.cpp index 1e932e49..231487bb 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -788,6 +788,25 @@ void Settings::query(PluginContainer *pluginContainer, QWidget *parent) } m_Settings.setValue(key, dialog.saveGeometry()); + // These changes happen regardless of accepted or rejected + bool restartNeeded = false; + if (dialog.getApiKeyChanged()) { + restartNeeded = true; + } + if (dialog.getResetGeometries()) { + restartNeeded = true; + m_Settings.setValue("reset_geometry", true); + } + if (restartNeeded) { + if (QMessageBox::question(nullptr, + tr("Restart Mod Organizer?"), + tr("In order to finish configuration changes, MO must be restarted.\n" + "Restart it now?"), + QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { + qApp->exit(INT_MAX); + } + } + } Settings::SettingsTab::SettingsTab(Settings *m_parent, SettingsDialog &m_dialog) @@ -1181,6 +1200,7 @@ Settings::WorkaroundsTab::WorkaroundsTab(Settings *m_parent, , m_displayForeignBox(m_dialog.findChild("displayForeignBox")) , m_lockGUIBox(m_dialog.findChild("lockGUIBox")) , m_enableArchiveParsingBox(m_dialog.findChild("enableArchiveParsingBox")) + , m_resetGeometriesBtn(m_dialog.findChild("resetGeometryBtn")) { m_appIDEdit->setText(m_parent->getSteamAppID()); @@ -1216,6 +1236,8 @@ Settings::WorkaroundsTab::WorkaroundsTab(Settings *m_parent, m_lockGUIBox->setChecked(m_parent->lockGUI()); m_enableArchiveParsingBox->setChecked(m_parent->archiveParsing()); + m_resetGeometriesBtn->setChecked(m_parent->directInterface().value("reset_geometry", false).toBool()); + m_dialog.setExecutableBlacklist(m_parent->executablesBlacklist()); } @@ -1235,15 +1257,4 @@ void Settings::WorkaroundsTab::update() m_Settings.setValue("Settings/archive_parsing_experimental", m_enableArchiveParsingBox->isChecked()); m_Settings.setValue("Settings/executable_blacklist", m_dialog.getExecutableBlacklist()); - - if (m_dialog.getResetGeometries()) { - m_Settings.setValue("reset_geometry", true); - if (QMessageBox::question(nullptr, - tr("Restart Mod Organizer?"), - tr("In order to reset the window geometries, MO must be restarted.\n" - "Restart it now?"), - QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { - qApp->exit(INT_MAX); - } - } } diff --git a/src/settings.h b/src/settings.h index 324fa0b6..ed49a1bc 100644 --- a/src/settings.h +++ b/src/settings.h @@ -531,6 +531,7 @@ private: QCheckBox *m_displayForeignBox; QCheckBox *m_lockGUIBox; QCheckBox *m_enableArchiveParsingBox; + QPushButton *m_resetGeometriesBtn; }; private slots: diff --git a/src/settingsdialog.cpp b/src/settingsdialog.cpp index f9f4f255..74091469 100644 --- a/src/settingsdialog.cpp +++ b/src/settingsdialog.cpp @@ -53,6 +53,8 @@ SettingsDialog::SettingsDialog(PluginContainer *pluginContainer, QWidget *parent , m_PluginContainer(pluginContainer) , m_nexusLogin(new QWebSocket) , m_KeyReceived(false) + , m_KeyCleared(false) + , m_GeometriesReset(false) { ui->setupUi(this); ui->pluginSettingsList->setStyleSheet("QTreeWidget::item {padding-right: 10px;}"); @@ -131,6 +133,11 @@ bool SettingsDialog::getResetGeometries() return ui->resetGeometryBtn->isChecked(); } +bool SettingsDialog::getApiKeyChanged() +{ + return m_KeyReceived || m_KeyCleared; +} + void SettingsDialog::on_categoriesBtn_clicked() { CategoriesDialog dialog(this); @@ -476,6 +483,7 @@ void SettingsDialog::on_clearCacheButton_clicked() void SettingsDialog::on_revokeNexusAuthButton_clicked() { emit revokeApiKey(ui->nexusConnect); + m_KeyCleared = true; } void SettingsDialog::normalizePath(QLineEdit *lineEdit) @@ -516,3 +524,9 @@ void SettingsDialog::on_overwriteDirEdit_editingFinished() { normalizePath(ui->overwriteDirEdit); } + +void SettingsDialog::on_resetGeometryBtn_clicked() +{ + m_GeometriesReset = true; + ui->resetGeometryBtn->setChecked(true); +} diff --git a/src/settingsdialog.h b/src/settingsdialog.h index d6dfe384..92a97c3f 100644 --- a/src/settingsdialog.h +++ b/src/settingsdialog.h @@ -82,6 +82,7 @@ public: QColor getContainedColor() { return m_ContainedColor; } QString getExecutableBlacklist() { return m_ExecutableBlacklist; } bool getResetGeometries(); + bool getApiKeyChanged(); void setOverwritingColor(QColor col) { m_OverwritingColor = col; } void setOverwrittenColor(QColor col) { m_OverwrittenColor = col; } @@ -165,6 +166,8 @@ private slots: void completeApiConnection(); + void on_resetGeometryBtn_clicked(); + private: Ui::SettingsDialog *ui; PluginContainer *m_PluginContainer; @@ -177,6 +180,8 @@ private: QColor m_ContainedColor; bool m_KeyReceived; + bool m_KeyCleared; + bool m_GeometriesReset; QString m_UUID; QString m_AuthToken; -- cgit v1.3.1