Compare commits

..
Author SHA1 Message Date
pre-commit-ci[bot] efe2a02d5d [pre-commit.ci] Pre-commit autoupdate. (#2421)
updates:
- [github.com/pre-commit/mirrors-clang-format: v22.1.2 → v22.1.5](https://github.com/pre-commit/mirrors-clang-format/compare/v22.1.2...v22.1.5)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2026-07-08 15:58:05 +02:00
Mikaël Capelle a931277b2b Update VCPKG registries to use 7z 26.01. (#2413) 2026-06-22 20:20:18 +02:00
Mikaël Capelle 4907704797 Send local saves to recycle bin when switching from global to local saves instead of deleting them directly. (#2401) 2026-06-06 09:28:12 +02:00
Jonathan Feenstra c097670b09 Update about dialog (#2400) 2026-05-23 10:28:27 -05:00
Jeremy Rimpo a329ce59ac Translation file updates 2026-05-21 23:53:44 -05:00
Jeremy Rimpo 7a4bb3652e Restore tutorials 2026-05-17 02:29:21 -05:00
Jonathan Feenstra ab38cf0e05 Improve code for reading text files line-by-line 2026-05-17 02:28:30 -05:00
Jeremy Rimpo 0c95bf22e6 Add app.manifest to set longPathAware 2026-05-17 02:25:59 -05:00
Jonathan Feenstra 55de581ee9 Add setting to show notifications when downloads complete or fail (#2338) 2026-05-15 02:23:09 -05:00
Jeremy Rimpo 6748953d35 Use new Nexus Tools location for MO2 2026-05-15 02:00:05 -05:00
Jonathan Feenstra 22b1695701 Install manager metadata updates
* Fix missing author and uploader when installing mods
* Refactor doInstall parameters into a struct
2026-05-14 01:43:46 -05:00
3efaf7c946 Migrating to OAuth Authentication (#2374)
Co-authored-by: aglowinthefield <146008217+aglowinthefield@users.noreply.github.com>
Co-authored-by: Jonathan Feenstra <26406078+JonathanFeenstra@users.noreply.github.com>
2026-05-12 13:50:45 -05:00
Jeremy Rimpo 41ffb25c03 Use filesystem paths with BSATK input / output (#2391) 2026-05-07 15:46:47 -05:00
9c6f48a440 Stable DownloadId refactor (#2375)
* Encapsulate the downloads directory watcher in DirWatcherManager

QFileSystemWatcher suppression currently relies on public static start/end
methods and a static counter. Seven call sites pair them raw, one of them
outside the class. Any exception between a pair permanently disables the
watcher, and the static counter implies a singleton DownloadManager.

A new DirWatcherManager owns the watcher, the counter (now an instance
member), and the filtering. The only way to suspend is an RAII Guard
obtained via a scopedGuard() factory. All raw pairs migrate to guards. A
TODO flags the existing processEvents() in the dtor as a known reentrancy
hazard worth replacing later.

* Replace aboutToUpdate/update(int) with ModelResetGuard

Replace the fragile two-signal protocol with a refcounted RAII
ModelResetGuard. Split update(int) into aboutToResetModel/modelReset
(guard only) and rowChanged(int); notifyRowChanged() is suppressed while
a reset is active.

Fixes "beginResetModel without endResetModel" warnings from three sites
in downloadFinished/removeDownload that were pairing reset with a row
update. removePending only opens a guard when an actual match is removed.

* Centralize row notifications in setState and fix missed emits

setState emits notifyRowChanged itself, uses indexByInfo (-1 when
untracked), and re-looks up the row at each use so reply->abort() and
plugin callbacks that re-enter and erase info don't produce stale
signals.

Remove the trailing emit loop from createMetaFile and the now-redundant
notifyRowChanged calls scattered after setState. Add the two missing
emits in restoreDownload (after m_Hidden) and metaDataChanged (after
rename). Guard downloadFinished with a top-level DirWatcherGuard to
prevent filesystem events from its writes racing with model updates.

* Fix comma operator in addNXMDownload pending-dedup check

The game-name comparison result was discarded by the comma operator,
so the dedup only matched modId/fileId across all games.

* Fix lost finished() signal on fast downloads

Hoist the file-exists prompt out of startDownload so setup is straight-line.
Connect finished() last and dispatch manually if the reply already finished.

* Fix memory leak in DownloadInfo::createFromMeta

Move the allocation past the early-return checks so path-mismatch and
hidden-skip paths no longer leak a fresh DownloadInfo.

* Sanitize suffix path in getDownloadFileName

The collision-avoidance branch was using the raw baseName, so invalid
characters sanitized out of the initial path leaked into the suffixed one.

* [pre-commit.ci] Auto fixes from pre-commit.com hooks.

* Remove unused alphabetical translation vector

m_AlphabeticalTranslation was written but never read; drop it along with
refreshAlphabeticalTranslation, ByName, and the LessThanWrapper helper.

* Address PR feedback: fix redundant check and move refresh outside try catch.

* Coalesce the removeDownload reset with the following refreshList

Moves the ModelResetGuard out of the try-catch so it also wraps the
refreshList() call below. Without this, one reset fires when the guard
destructs at the end of the try block and another fires from
refreshList's own guard, producing two resets where one is sufficient.

* Guard the .meta creation in openMetaFile against the directory watcher

openMetaFile creates the .meta file via QSettings when one does not
exist; the disk write fires directoryChanged and triggers a spurious
refreshList. Wrap it in a DirWatcherManager::Guard like the other
meta-file editing paths.

* Extract getValidGameShortName method in download manager (#2380)

* Add stable download id index and PendingDownload struct

Replace the (game, mod, file) tuple backing m_PendingDownloads with a
named struct, and add m_ByID as an O(1) m_DownloadID-to-info index kept
in sync with every m_ActiveDownloads mutation. Encapsulate the id
counter behind DownloadInfo::newDownloadID(), the only supported way to
consume from s_NextDownloadID.

Infrastructure only; external behaviour is unchanged.

* Return stable ids from the plugin-facing download API

startDownloadURLs / startDownloadNexusFile / addNXMDownload now reserve
and return m_DownloadID instead of a stale index. Plugin callbacks fire
with m_DownloadID; downloadPath looks up via m_ByID. nxmDownloadURLsAvailable
threads the reserved id into the materializing DownloadInfo, and Nexus
API failures wake waiting plugins via notifyPendingDownloadFailed.

Incidental: startDownload now returns bool and frees newDownload on
output-open failure; createMetaFile is deferred past that check so
failed starts no longer leave an orphan .meta.

* Split downloadFinished into onReplyFinished slot and finishDownload

The old dual-use downloadFinished(int = 0) took either an explicit index
or relied on sender() when called as a slot. Split into a sender-resolved
slot and an id-based direct call, removing the ambiguous index-zero path.

* Introduce DownloadID alias and row/id accessors

Add a DownloadID type alias for the stable per-download handle and two
public accessors (downloadIDAtRow, rowForDownloadID) so callers can
translate between the view's row vocabulary and the model's id
vocabulary without reaching into the manager's internals. DownloadList
now embeds the DownloadID in QModelIndex::internalId() so any code
holding an index can identify the download directly.

* Convert cancel/pause/resume action methods to take DownloadID

The four methods (cancel, pause, resume, resumeDownloadInt) now accept
a DownloadID, resolve through m_ByID, and no longer care about row
positions. Internal callers iterate DownloadInfo* or look up via id;
DownloadsTab translates row -> id at the connect boundary so the
view's int-shaped signals keep working unchanged.

Also switches the remaining unsigned int signatures that refer to the
download id (finishDownload, downloadInfoByID, PendingDownload::reservedID,
m_ByID, newDownloadID, s_NextDownloadID) to the DownloadID alias.

Drive-by fix: finishDownload's retry branch could read info->m_Tries
after info had been deleted in the CANCELED/retries-exhausted branch
above; now re-resolves via m_ByID.value(id) before touching any fields.

* [pre-commit.ci] Auto fixes from pre-commit.com hooks.

* fix warnings about unused variables and size_t types

* cleanup dead code

* avoid calling processEvents when releasing the DirWatcherGuard

* [pre-commit.ci] Auto fixes from pre-commit.com hooks.

* use QEventLoop instead of manual ProcessEvents

* don't call processEvents in download started and defer handling finish state in event loop

* Cleanup pending download in case of failure.

* Add missing notifyPendingDownloadFailed if user cancels

* [pre-commit.ci] Auto fixes from pre-commit.com hooks.

* Refactor pending download failure handling and cover rename failures

* fix rebase bug, addNXMDownload not returning the correct type

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Jonathan Feenstra <26406078+JonathanFeenstra@users.noreply.github.com>
2026-05-07 17:38:51 +02:00
Jonathan Feenstra 3070a60ab7 Don't apply LOOT-sorted load order until user clicks "Apply" (#2382)
* Add sorted plugin list to LOOT dialog (markdown and button)
* Prefix plugins with checkboxes to show whether they're enabled
2026-05-06 12:51:17 -05:00
Jeremy Rimpo 6d02ef2b75 Defer second nxmhandler call (#2390)
- Calls run in parallel leading to extraneous setup dialogs
- This only calls the nxm schema registration after modl is done
2026-05-06 11:08:57 -05:00
Jeremy Rimpo f5d89ad625 Download command: Add game instance check (#2388)
* Add game instance check
- Should be ignored if not passed to command
- Functions much like NXM game check
2026-05-04 16:40:32 -05:00
64 changed files with 4681 additions and 3471 deletions
+4 -1
View File
@@ -8,9 +8,12 @@ src/*.bak
CMakeLists.txt.user
edit
/CMakeFiles
.idea
.idea/*
!.idea/filetypes/
!.idea/filetypes/qt-translations.xml
/msbuild.log
/*std*.log
/*build
/src/version.aps
.idea/
+1 -1
View File
@@ -7,7 +7,7 @@ repos:
- id: check-merge-conflict
- id: check-case-conflict
- repo: https://github.com/pre-commit/mirrors-clang-format
rev: v22.1.2
rev: v22.1.5
hooks:
- id: clang-format
'types_or': [c++, c]
-3
View File
@@ -3,9 +3,6 @@ cmake_minimum_required(VERSION 3.16)
# TODO: clean include directives
set(MO2_CMAKE_DEPRECATED_UIBASE_INCLUDE ON)
# Remove tutorials until Qt is fixed
set(MO2_SKIP_TUTORIALS_INSTALL ON)
project(organizer)
# if MO2_INSTALL_IS_BIN is set, this means that we should install directly into the
+2 -4
View File
@@ -1,5 +1,3 @@
[![Build status](https://ci.appveyor.com/api/projects/status/hxenwxmpaob5xung?svg=true)](https://ci.appveyor.com/project/ModOrganizer2/modorganizer-736bd)
# Mod Organizer
Mod Organizer (MO) is a tool for managing mod collections of arbitrary size. It is specifically designed for people who like to experiment with mods and thus need an easy and reliable way to install and uninstall them.
@@ -20,14 +18,14 @@ If you want to submit your code changes, please use a good formatting style like
Through the work of a few people of the community MO2 has come quite far, now it needs some more of those people to go further.
## Reporting Issues:
Issues should be reported to the GitHub page or on the open discord server: [Mod Organizer 2](https://discord.gg/ewUVAqyrQX). Here is also where dev builds are tested, bugs are reported and investigated, suggestions are discussed and a lot more.
Issues should be reported to the GitHub page or on the open Discord server: [Mod Organizer 2](https://discord.gg/ewUVAqyrQX). Here is also where dev builds are tested, bugs are reported and investigated, suggestions are discussed and a lot more.
Credits to Tannin, LePresidente, Silarn, erasmux, AL12, LostDragonist, AnyOldName3, isa, Holt59, Project579, przester, Qudix, RJ, Jonathan Feenstra and many others for the development.
## Download Location
* on [GitHub.com](https://github.com/Modorganizer2/modorganizer/releases)
* on [NexusMods.com](https://www.nexusmods.com/skyrimspecialedition/mods/6194)
* on [NexusMods.com](https://www.nexusmods.com/site/mods/6)
## Old Download Location
+5 -2
View File
@@ -12,7 +12,7 @@ find_package(mo2-esptk CONFIG REQUIRED)
find_package(mo2-dds-header CONFIG REQUIRED)
find_package(mo2-libbsarch CONFIG REQUIRED)
find_package(Qt6 REQUIRED COMPONENTS WebEngineWidgets WebSockets)
find_package(Qt6 REQUIRED COMPONENTS WebEngineWidgets WebSockets NetworkAuth)
find_package(Boost CONFIG REQUIRED COMPONENTS program_options thread interprocess signals2 uuid accumulators)
find_package(7zip CONFIG REQUIRED)
find_package(lz4 CONFIG REQUIRED)
@@ -41,7 +41,7 @@ target_link_libraries(organizer PRIVATE
usvfs::usvfs mo2::uibase mo2::archive mo2::libbsarch
mo2::bsatk mo2::esptk mo2::lootcli-header
Boost::program_options Boost::signals2 Boost::uuid Boost::accumulators
Qt6::WebEngineWidgets Qt6::WebSockets Version Dbghelp)
Qt6::WebEngineWidgets Qt6::WebSockets Qt6::NetworkAuth Version Dbghelp)
install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/dlls.manifest.qt6"
DESTINATION ${_bin}/dlls
@@ -130,6 +130,9 @@ mo2_add_filter(NAME src/core GROUPS
githubpp
installationmanager
nexusinterface
nexusoauthlogin
nexusoauthtokens
nexusoauthconfig
nxmaccessmanager
organizercore
game_features
+893 -876
View File
File diff suppressed because it is too large Load Diff
+15 -4
View File
@@ -19,12 +19,17 @@ APIUserAccount::APIUserAccount() : m_type(APIUserAccountTypes::None) {}
bool APIUserAccount::isValid() const
{
return !m_key.isEmpty();
return !m_accessToken.isEmpty() || !m_apiKey.isEmpty();
}
const QString& APIUserAccount::accessToken() const
{
return m_accessToken;
}
const QString& APIUserAccount::apiKey() const
{
return m_key;
return m_apiKey;
}
const QString& APIUserAccount::id() const
@@ -47,9 +52,15 @@ const APILimits& APIUserAccount::limits() const
return m_limits;
}
APIUserAccount& APIUserAccount::apiKey(const QString& key)
APIUserAccount& APIUserAccount::accessToken(const QString& token)
{
m_key = key;
m_accessToken = token;
return *this;
}
APIUserAccount& APIUserAccount::apiKey(const QString& apiKey)
{
m_apiKey = apiKey;
return *this;
}
+14 -4
View File
@@ -65,7 +65,12 @@ public:
bool isValid() const;
/**
* api key
* OAuth access token
*/
const QString& accessToken() const;
/**
* OAuth access token
*/
const QString& apiKey() const;
@@ -90,9 +95,14 @@ public:
const APILimits& limits() const;
/**
* sets the api key
* sets the OAuth access token
*/
APIUserAccount& apiKey(const QString& key);
APIUserAccount& accessToken(const QString& token);
/**
* sets the OAuth access token
*/
APIUserAccount& apiKey(const QString& apiKey);
/**
* sets the user id
@@ -132,7 +142,7 @@ public:
bool exhausted() const;
private:
QString m_key, m_id, m_name;
QString m_accessToken, m_apiKey, m_id, m_name;
APIUserAccountTypes m_type;
APILimits m_limits;
};
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<longPathAware xmlns="microsoft.com">true</longPathAware>
</windowsSettings>
</application>
</assembly>
+20 -14
View File
@@ -57,13 +57,17 @@ void CategoryFactory::loadCategories()
QFile categoryFile(categoriesFilePath());
bool needLoad = false;
if (!categoryFile.open(QIODevice::ReadOnly)) {
if (!categoryFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
needLoad = true;
} else {
int lineNum = 0;
while (!categoryFile.atEnd()) {
QByteArray line = categoryFile.readLine();
++lineNum;
const auto lines = categoryFile.readAll().split('\n');
categoryFile.close();
for (int lineNum = 0; lineNum < lines.size(); ++lineNum) {
const auto& line = lines[lineNum];
if (line.isEmpty()) {
continue;
}
QList<QByteArray> cells = line.split('|');
if (cells.count() == 4) {
std::vector<NexusCategory> nexusCats;
@@ -76,7 +80,7 @@ void CategoryFactory::loadCategories()
if (!ok) {
log::error(tr("invalid category id {0}"), iter->constData());
}
nexusCats.push_back(NexusCategory("Unknown", temp));
nexusCats.emplace_back("Unknown", temp);
}
}
bool cell0Ok = true;
@@ -103,16 +107,19 @@ void CategoryFactory::loadCategories()
line.constData(), cells.count());
}
}
categoryFile.close();
QFile nexusMapFile(nexusMappingFilePath());
if (!nexusMapFile.open(QIODevice::ReadOnly)) {
if (!nexusMapFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
needLoad = true;
} else {
int nexLineNum = 0;
while (!nexusMapFile.atEnd()) {
QByteArray nexLine = nexusMapFile.readLine();
++nexLineNum;
const auto nexLines = nexusMapFile.readAll().split('\n');
nexusMapFile.close();
for (int nexLineNum = 0; nexLineNum < nexLines.size(); ++nexLineNum) {
const auto& nexLine = nexLines[nexLineNum];
if (nexLine.isEmpty()) {
continue;
}
QList<QByteArray> nexCells = nexLine.split('|');
if (nexCells.count() == 3) {
std::vector<NexusCategory> nexusCats;
@@ -129,12 +136,11 @@ void CategoryFactory::loadCategories()
m_NexusMap.insert_or_assign(nexID, NexusCategory(nexName, nexID));
m_NexusMap.at(nexID).setCategoryID(catID);
} else {
log::error(tr("invalid nexus category line {0}: {1} ({2} cells)"), lineNum,
log::error(tr("invalid nexus category line {0}: {1} ({2} cells)"), nexLineNum,
nexLine.constData(), nexCells.count());
}
}
}
nexusMapFile.close();
}
std::sort(m_Categories.begin(), m_Categories.end());
setParents();
+9 -2
View File
@@ -857,7 +857,8 @@ po::options_description DownloadFileCommand::getVisibleOptions() const
{
po::options_description d;
d.add_options()("name,n", po::value<std::string>(), "(optional) the download name")(
d.add_options()("game,g", po::value<std::string>(), "managed game")(
"name,n", po::value<std::string>(), "(optional) the download name")(
"modname,m", po::value<std::string>(), "(optional) the mod name")(
"version,v", po::value<std::string>(), "(optional) the download / mod version")(
"source,s", po::value<std::string>(), "(optional) the download source");
@@ -891,6 +892,7 @@ bool DownloadFileCommand::canForwardToPrimary() const
std::optional<int> DownloadFileCommand::runPostOrganizer(OrganizerCore& core)
{
const QString url = QString::fromStdString(vm()["URL"].as<std::string>());
QString game("");
QString name, modName, version, source;
if (!url.startsWith("https://")) {
@@ -898,6 +900,10 @@ std::optional<int> DownloadFileCommand::runPostOrganizer(OrganizerCore& core)
return 1;
}
if (vm().count("game")) {
game = QString::fromStdString(vm()["game"].as<std::string>());
}
if (vm().count("name")) {
name = QString::fromStdString(vm()["name"].as<std::string>());
}
@@ -917,7 +923,8 @@ std::optional<int> DownloadFileCommand::runPostOrganizer(OrganizerCore& core)
log::debug("starting direct download from command line: {}", url.toStdString());
MessageDialog::showMessage(QObject::tr("Download started"), qApp->activeWindow(),
false);
core.downloadManager()->startDownloadURLWithMeta(url, name, modName, version, source);
core.downloadManager()->startDownloadURLWithMeta(url, game, name, modName, version,
source);
return {};
}
+1 -1
View File
@@ -27,7 +27,7 @@ class Settings;
//
// pages can be disabled if they return true in skip(), which happens globally
// for some (IntroPage has a setting in the registry), depending on context
// (NexusPage is skipped if the API key already exists) or explicitly (when
// (NexusPage is skipped if the Nexus authorization already exists) or explicitly (when
// only some info about the instance is missing on startup, such as a game
// variant)
//
+2 -1
View File
@@ -103,6 +103,7 @@ void Page::next()
bool Page::action(CreateInstanceDialog::Actions a)
{
Q_UNUSED(a);
// no-op
return false;
}
@@ -1203,7 +1204,7 @@ NexusPage::NexusPage(CreateInstanceDialog& dlg) : Page(dlg), m_skip(false)
// just check it once, or connecting and then going back and forth would skip
// the page, which would be unexpected
m_skip = GlobalSettings::hasNexusApiKey();
m_skip = GlobalSettings::hasNexusOAuthTokens() || GlobalSettings::hasNexusApiKey();
}
NexusPage::~NexusPage() = default;
+1
View File
@@ -12,6 +12,7 @@
<file name="Qt6Cored.dll" />
<file name="Qt6Guid.dll" />
<file name="Qt6Networkd.dll" />
<file name="Qt6NetworkAuthd.dll" />
<file name="Qt6OpenGLd.dll" />
<file name="Qt6OpenGLWidgetsd.dll" />
<file name="Qt6Positioningd.dll" />
+1
View File
@@ -12,6 +12,7 @@
<file name="Qt6Core.dll" />
<file name="Qt6Gui.dll" />
<file name="Qt6Network.dll" />
<file name="Qt6NetworkAuth.dll" />
<file name="Qt6OpenGL.dll" />
<file name="Qt6OpenGLWidgets.dll" />
<file name="Qt6Positioning.dll" />
+7 -5
View File
@@ -58,7 +58,9 @@ int DownloadList::columnCount(const QModelIndex&) const
QModelIndex DownloadList::index(int row, int column, const QModelIndex&) const
{
return createIndex(row, column, row);
// Embed the stable DownloadID in internalId() so any consumer of the index
// can identify the download without having to track row shifts.
return createIndex(row, column, m_manager.downloadIDAtRow(row));
}
QModelIndex DownloadList::parent(const QModelIndex&) const
@@ -112,14 +114,14 @@ QVariant DownloadList::data(const QModelIndex& index, int role) const
bool pendingDownload = index.row() >= m_manager.numTotalDownloads();
if (role == Qt::DisplayRole) {
if (pendingDownload) {
std::tuple<QString, int, int> nexusids =
const DownloadManager::PendingDownload pending =
m_manager.getPendingDownload(index.row() - m_manager.numTotalDownloads());
switch (index.column()) {
case COL_NAME:
return tr("< game %1 mod %2 file %3 >")
.arg(std::get<0>(nexusids))
.arg(std::get<1>(nexusids))
.arg(std::get<2>(nexusids));
.arg(pending.gameName)
.arg(pending.modID)
.arg(pending.fileID);
case COL_SIZE:
return tr("Unknown");
case COL_STATUS:
+409 -279
View File
File diff suppressed because it is too large Load Diff
+136 -29
View File
@@ -24,6 +24,7 @@ along with Mod Organizer. If not, see <http://www.gnu.org/licenses/>.
#include <QElapsedTimer>
#include <QFile>
#include <QFileSystemWatcher>
#include <QHash>
#include <QMap>
#include <QNetworkReply>
#include <QObject>
@@ -31,7 +32,6 @@ along with Mod Organizer. If not, see <http://www.gnu.org/licenses/>.
#include <QSettings>
#include <QStringList>
#include <QTime>
#include <QTimer>
#include <QUrl>
#include <QVector>
#include <boost/accumulators/accumulators.hpp>
@@ -40,6 +40,7 @@ along with Mod Organizer. If not, see <http://www.gnu.org/licenses/>.
#include <boost/signals2.hpp>
#include <idownloadmanager.h>
#include <modrepositoryfileinfo.h>
#include <optional>
#include <set>
using namespace boost::accumulators;
@@ -100,6 +101,8 @@ private slots:
void onDirectoryChanged(const QString&);
private:
void releaseSuspension();
QFileSystemWatcher m_watcher;
int m_suspendDepth = 0;
};
@@ -150,6 +153,32 @@ public:
STATE_UNINSTALLED
};
/**
* @brief Stable identifier for a download.
*
* Monotonically increasing within a session and never reused. Distinct from
* row indices, which are positional and shift as the list is mutated.
*/
using DownloadID = unsigned int;
/**
* @brief A download that has been requested but has not yet produced a
* DownloadInfo.
*
* Created when the user initiates an NXM download; drained either when the
* Nexus API returns the actual download URL (at which point a DownloadInfo
* is created using reservedID as its download id so that external references
* handed out before the download existed remain valid) or when the request
* is cancelled or fails.
*/
struct PendingDownload
{
QString gameName;
int modID;
int fileID;
DownloadID reservedID;
};
private:
struct DownloadInfo
{
@@ -158,7 +187,7 @@ private:
accumulator_set<qint64, stats<tag::rolling_mean>> m_DownloadTimeAcc;
qint64 m_DownloadLast;
qint64 m_DownloadTimeLast;
unsigned int m_DownloadID;
DownloadID m_DownloadID;
QString m_FileName;
QFile m_Output;
QNetworkReply* m_Reply;
@@ -187,8 +216,26 @@ private:
bool m_Hidden;
/**
* @brief Issue a new download id.
*
* The only supported way to obtain one; ids are monotonically increasing
* within a session and never reused.
*/
static DownloadID newDownloadID();
/**
* @brief Create a new DownloadInfo for a fresh download.
*
* When reservedID is provided it is used as the download id. Callers that
* need to hand out an id before the DownloadInfo exists (e.g. the NXM flow
* reserves an id when the request is queued, long before the Nexus API
* returns the actual URL) should reserve via newDownloadID() and pass it
* here. Otherwise a fresh id is drawn internally.
*/
static DownloadInfo* createNew(const MOBase::ModRepositoryFileInfo* fileInfo,
const QStringList& URLs);
const QStringList& URLs,
std::optional<DownloadID> reservedID = {});
static DownloadInfo* createFromMeta(const QString& filePath, bool showHidden,
const QString outputDirectory,
std::optional<uint64_t> fileSize = {});
@@ -203,14 +250,14 @@ private:
**/
void setName(QString newName, bool renameFile);
unsigned int downloadID() { return m_DownloadID; }
DownloadID downloadID() { return m_DownloadID; }
bool isPausedState();
QString currentURL();
private:
static unsigned int s_NextDownloadID;
static DownloadID s_NextDownloadID;
private:
DownloadInfo()
@@ -297,18 +344,22 @@ public:
bool addDownload(QNetworkReply* reply, const QStringList& URLs,
const QString& fileName, QString gameName, int modID, int fileID = 0,
const MOBase::ModRepositoryFileInfo* fileInfo =
new MOBase::ModRepositoryFileInfo());
new MOBase::ModRepositoryFileInfo(),
std::optional<DownloadID> reservedID = {});
/**
* @brief start a download using a nxm-link
*
* starts a download using a nxm-link. The download manager will first query the nexus
* page for file information.
* Starts a download using a nxm-link. The download manager will first query the
* nexus page for file information. The returned id identifies the eventual
* download; it is reserved immediately so external references remain valid even
* before the Nexus API responds.
* @param url a nxm link looking like this: nxm://skyrim/mods/1234/files/4711
* @return the reserved download id
* @todo the game name encoded into the link is currently ignored, all downloads are
*incorrectly assumed to be for the identified game
**/
void addNXMDownload(const QString& url);
DownloadID addNXMDownload(const QString& url);
/**
* @brief retrieve the total number of downloads, both finished and unfinished
@@ -329,9 +380,24 @@ public:
* @brief retrieve the info of a pending download
* @param index index of the pending download (index in the range [0,
* numPendingDownloads()[)
* @return pair of modid, fileid
* @return the PendingDownload entry at the given index
*/
std::tuple<QString, int, int> getPendingDownload(int index);
PendingDownload getPendingDownload(int index);
/**
* @brief Resolve a view row to a stable DownloadID.
*
* Rows cover active downloads followed by pending ones. Returns 0 if the row
* is out of range.
*/
DownloadID downloadIDAtRow(int row) const;
/**
* @brief Resolve a stable DownloadID to its current view row.
*
* @return the current row, or -1 if no download with that id is tracked.
*/
int rowForDownloadID(DownloadID id) const;
/**
* @brief retrieve the full path to the download specified by index
@@ -474,9 +540,9 @@ public:
public: // IDownloadManager interface:
int startDownloadURLs(const QStringList& urls);
int startDownloadURLWithMeta(const QString& url, const QString& name,
const QString& modName, const QString& version,
const QString& source);
int startDownloadURLWithMeta(const QString& url, const QString& game,
const QString& name, const QString& modName,
const QString& version, const QString& source);
int startDownloadNexusFile(const QString& gameName, int modID, int fileID);
QString downloadPath(int id);
@@ -578,13 +644,13 @@ public slots:
* @brief cancel the specified download. This will lead to the corresponding file to
*be deleted
*
* @param index index of the download to cancel
* @param id id of the download to cancel
**/
void cancelDownload(int index);
void cancelDownload(DownloadID id);
void pauseDownload(int index);
void pauseDownload(DownloadID id);
void resumeDownload(int index);
void resumeDownload(DownloadID id);
void queryInfo(int index);
@@ -624,10 +690,23 @@ private slots:
void downloadProgress(qint64 bytesReceived, qint64 bytesTotal);
void downloadReadyRead();
void downloadFinished(int index = 0);
/**
* @brief Slot wired to QNetworkReply::finished().
*
* Resolves the originating reply through sender() and then dispatches to
* finishDownload. Use the public finishDownload directly for non-slot calls.
*/
void onReplyFinished();
/**
* @brief Run the post-download bookkeeping for the given download.
*
* Writes any remaining data, transitions the download's state, and emits
* the appropriate plugin signals.
*/
void finishDownload(DownloadID id);
void downloadError(QNetworkReply::NetworkError error);
void metaDataChanged();
void checkDownloadTimeout();
private:
void createMetaFile(DownloadInfo* info);
@@ -646,8 +725,15 @@ public:
QString getDownloadFileName(const QString& baseName, bool rename = false) const;
private:
void startDownload(QNetworkReply* reply, DownloadInfo* newDownload, bool resume);
void resumeDownloadInt(int index);
/**
* @brief Begin downloading into newDownload from reply.
*
* On the !resume path newDownload becomes owned by m_ActiveDownloads on
* success; on failure (e.g. the output file cannot be opened) it is deleted
* before returning. Returns whether the download actually started.
*/
bool startDownload(QNetworkReply* reply, DownloadInfo* newDownload, bool resume);
void resumeDownloadInt(DownloadID id);
/**
* @brief start a download from a url
@@ -658,7 +744,8 @@ private:
*only happens if there is a duplicate and the user decides not to download again
**/
bool addDownload(const QStringList& URLs, QString gameName, int modID, int fileID,
const MOBase::ModRepositoryFileInfo* fileInfo);
const MOBase::ModRepositoryFileInfo* fileInfo,
std::optional<DownloadID> reservedID = {});
// important: the caller has to lock the list-mutex, otherwise the
// DownloadInfo-pointer might get invalidated at any time
@@ -670,10 +757,30 @@ private:
void setState(DownloadInfo* info, DownloadManager::DownloadState state);
DownloadInfo* downloadInfoByID(unsigned int id);
DownloadInfo* downloadInfoByID(DownloadID id);
QString displayNameByInfo(const DownloadInfo* info) const;
void removePending(QString gameName, int modID, int fileID);
/**
* @brief Fire onDownloadFailed for a pending entry, if any matches.
*
* Used on Nexus API failures so callers holding a reserved id from
* addNXMDownload do not wait indefinitely for a result. No-op if no pending
* entry matches the (gameName, modID, fileID) triple.
*/
void notifyPendingDownloadFailed(const QString& gameName, int modID, int fileID);
/**
* @brief Roll back a download that has not yet been activated.
*
* Ensures a caller awaiting the reservedID receives an onDownloadFailed
* callback. Must not be called once the download has been registered as
* active.
*/
void cancelPendingDownload(DownloadInfo* newDownload, QNetworkReply* reply);
static QString getFileTypeString(int fileType);
void writeData(DownloadInfo* info);
@@ -689,10 +796,14 @@ private:
OrganizerCore* m_OrganizerCore;
QWidget* m_ParentWidget;
QVector<std::tuple<QString, int, int>> m_PendingDownloads;
QVector<PendingDownload> m_PendingDownloads;
QVector<DownloadInfo*> m_ActiveDownloads;
// Secondary index into m_ActiveDownloads keyed by m_DownloadID; kept in sync
// with every m_ActiveDownloads mutation.
QHash<DownloadID, DownloadInfo*> m_ByID;
QString m_OutputDirectory;
std::set<int> m_RequestIDs;
@@ -706,13 +817,9 @@ private:
SignalDownloadCallback m_DownloadFailed;
SignalDownloadCallback m_DownloadRemoved;
std::map<QString, int> m_DownloadFails;
bool m_ShowHidden;
MOBase::IPluginGame const* m_ManagedGame;
QTimer m_TimeoutTimer;
};
#endif // DOWNLOADMANAGER_H
+13 -7
View File
@@ -49,12 +49,17 @@ DownloadsTab::DownloadsTab(OrganizerCore& core, Ui::MainWindow* mwui)
SLOT(removeDownload(int, bool)));
connect(ui.list, SIGNAL(restoreDownload(int)), m_core.downloadManager(),
SLOT(restoreDownload(int)));
connect(ui.list, SIGNAL(cancelDownload(int)), m_core.downloadManager(),
SLOT(cancelDownload(int)));
connect(ui.list, SIGNAL(pauseDownload(int)), m_core.downloadManager(),
SLOT(pauseDownload(int)));
connect(ui.list, &DownloadListView::resumeDownload, [&](int i) {
resumeDownload(i);
// The view reports actions by row; translate to DownloadID at the boundary.
connect(ui.list, &DownloadListView::cancelDownload, this, [this](int row) {
auto* dm = m_core.downloadManager();
dm->cancelDownload(dm->downloadIDAtRow(row));
});
connect(ui.list, &DownloadListView::pauseDownload, this, [this](int row) {
auto* dm = m_core.downloadManager();
dm->pauseDownload(dm->downloadIDAtRow(row));
});
connect(ui.list, &DownloadListView::resumeDownload, this, [this](int row) {
resumeDownload(row);
});
}
@@ -105,6 +110,7 @@ void DownloadsTab::queryInfos()
void DownloadsTab::resumeDownload(int downloadIndex)
{
m_core.loggedInAction(ui.list, [this, downloadIndex] {
m_core.downloadManager()->resumeDownload(downloadIndex);
auto* dm = m_core.downloadManager();
dm->resumeDownload(dm->downloadIDAtRow(downloadIndex));
});
}
+31 -24
View File
@@ -480,28 +480,23 @@ bool InstallationManager::ensureValidModName(GuessedValue<QString>& name) const
return true;
}
InstallationResult InstallationManager::doInstall(GuessedValue<QString>& modName,
QString gameName, int modID,
const QString& version,
const QString& newestVersion,
int categoryID, int fileCategoryID,
const QString& repository)
InstallationResult InstallationManager::doInstall(ModInstallationInfo& info)
{
if (!ensureValidModName(modName)) {
if (!ensureValidModName(info.modName)) {
return {IPluginInstaller::RESULT_FAILED};
}
// determine target directory
InstallationResult result = testOverwrite(modName);
InstallationResult result = testOverwrite(info.modName);
if (!result) {
return result;
}
const bool merge = result.merged();
result.m_name = modName;
result.m_name = info.modName;
QString targetDirectory = QDir(m_ModsDirectory + "/" + modName).canonicalPath();
QString targetDirectory = QDir(m_ModsDirectory + "/" + info.modName).canonicalPath();
QString targetDirectoryNative = QDir::toNativeSeparators(targetDirectory);
log::debug("installing to \"{}\"", targetDirectoryNative);
@@ -532,28 +527,31 @@ InstallationResult InstallationManager::doInstall(GuessedValue<QString>& modName
// overwrite settings only if they are actually are available or haven't been set
// before
if ((gameName != "") || !settingsFile.contains("gameName")) {
settingsFile.setValue("gameName", gameName);
if ((info.gameName != "") || !settingsFile.contains("gameName")) {
settingsFile.setValue("gameName", info.gameName);
}
if ((modID != 0) || !settingsFile.contains("modid")) {
settingsFile.setValue("modid", modID);
if ((info.modID != 0) || !settingsFile.contains("modid")) {
settingsFile.setValue("modid", info.modID);
}
if (!settingsFile.contains("version") ||
(!version.isEmpty() &&
(!merge || (VersionInfo(version) >=
(!info.version.isEmpty() &&
(!merge || (VersionInfo(info.version) >=
VersionInfo(settingsFile.value("version").toString()))))) {
settingsFile.setValue("version", version);
settingsFile.setValue("version", info.version);
}
if (!newestVersion.isEmpty() || !settingsFile.contains("newestVersion")) {
settingsFile.setValue("newestVersion", newestVersion);
if (!info.newestVersion.isEmpty() || !settingsFile.contains("newestVersion")) {
settingsFile.setValue("newestVersion", info.newestVersion);
}
// issue #51 used to overwrite the manually set categories
if (!settingsFile.contains("category")) {
settingsFile.setValue("category", QString::number(categoryID));
settingsFile.setValue("category", QString::number(info.categoryID));
}
settingsFile.setValue("nexusFileStatus", fileCategoryID);
settingsFile.setValue("nexusFileStatus", info.fileCategoryID);
settingsFile.setValue("installationFile", m_CurrentFile);
settingsFile.setValue("repository", repository);
settingsFile.setValue("repository", info.repository);
settingsFile.setValue("author", info.author);
settingsFile.setValue("uploader", info.uploader);
settingsFile.setValue("uploaderUrl", info.uploaderUrl);
if (!merge) {
// this does not clear the list we have in memory but the mod is going to have to be
@@ -650,6 +648,9 @@ InstallationResult InstallationManager::install(const QString& fileName,
int categoryID = 0;
int fileCategoryID = 1;
QString repository = "Nexus";
QString author = "";
QString uploader = "";
QString uploaderUrl = "";
QString metaName = fileName + ".meta";
if (QFile(metaName).exists()) {
@@ -690,6 +691,9 @@ InstallationResult InstallationManager::install(const QString& fileName,
}
repository = metaFile.value("repository", "").toString();
fileCategoryID = metaFile.value("fileCategory", 1).toInt();
author = metaFile.value("author", "").toString();
uploader = metaFile.value("uploader", "").toString();
uploaderUrl = metaFile.value("uploaderUrl", "").toString();
}
if (version.isEmpty()) {
@@ -807,8 +811,11 @@ InstallationResult InstallationManager::install(const QString& fileName,
// the simple installer only prepares the installation, the rest
// works the same for all installers
installResult = doInstall(modName, gameName, modID, version, newestVersion,
categoryID, fileCategoryID, repository);
ModInstallationInfo info{
modName, gameName, modID, version, newestVersion, categoryID,
fileCategoryID, repository, author, uploader, uploaderUrl};
installResult = doInstall(info);
}
}
}

Some files were not shown because too many files have changed in this diff Show More