Merge branch 'develop' into fix/network_and_signals

Signed-off-by: Rachel Powers <508861+Ryex@users.noreply.github.com>
This commit is contained in:
Rachel Powers 2023-05-12 01:13:17 -07:00 committed by GitHub
commit 6b6d6a01dc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
121 changed files with 4944 additions and 2471 deletions

View File

@ -152,7 +152,7 @@ jobs:
- name: Setup ccache - name: Setup ccache
if: (runner.os != 'Windows' || matrix.msystem == '') && inputs.build_type == 'Debug' if: (runner.os != 'Windows' || matrix.msystem == '') && inputs.build_type == 'Debug'
uses: hendrikmuhs/ccache-action@v1.2.8 uses: hendrikmuhs/ccache-action@v1.2.9
with: with:
key: ${{ matrix.os }}-qt${{ matrix.qt_ver }}-${{ matrix.architecture }} key: ${{ matrix.os }}-qt${{ matrix.qt_ver }}-${{ matrix.architecture }}
@ -400,7 +400,7 @@ jobs:
if (Get-Content ./codesign.pfx){ if (Get-Content ./codesign.pfx){
cd ${{ env.INSTALL_DIR }} cd ${{ env.INSTALL_DIR }}
# We ship the exact same executable for portable and non-portable editions, so signing just once is fine # We ship the exact same executable for portable and non-portable editions, so signing just once is fine
SignTool sign /fd sha256 /td sha256 /f ../codesign.pfx /p '${{ secrets.WINDOWS_CODESIGN_PASSWORD }}' /tr http://timestamp.digicert.com prismlauncher.exe SignTool sign /fd sha256 /td sha256 /f ../codesign.pfx /p '${{ secrets.WINDOWS_CODESIGN_PASSWORD }}' /tr http://timestamp.digicert.com prismlauncher.exe prismlauncher_filelink.exe
} else { } else {
":warning: Skipped code signing for Windows, as certificate was not present." >> $env:GITHUB_STEP_SUMMARY ":warning: Skipped code signing for Windows, as certificate was not present." >> $env:GITHUB_STEP_SUMMARY
} }

2
.gitignore vendored
View File

@ -12,6 +12,8 @@ html/
CMakeLists.txt.user CMakeLists.txt.user
CMakeLists.txt.user.* CMakeLists.txt.user.*
CMakeSettings.json CMakeSettings.json
/CMakeFiles
CMakeCache.txt
/.project /.project
/.settings /.settings
/.idea /.idea

View File

@ -345,6 +345,8 @@ elseif(UNIX)
install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/${Launcher_SVG} DESTINATION "${KDE_INSTALL_ICONDIR}/hicolor/scalable/apps") install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/${Launcher_SVG} DESTINATION "${KDE_INSTALL_ICONDIR}/hicolor/scalable/apps")
install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/${Launcher_mrpack_MIMEInfo} DESTINATION ${KDE_INSTALL_MIMEDIR}) install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/${Launcher_mrpack_MIMEInfo} DESTINATION ${KDE_INSTALL_MIMEDIR})
install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/launcher/qtlogging.ini" DESTINATION "${KDE_INSTALL_DATADIR}/${Launcher_Name}")
if(Launcher_ManPage) if(Launcher_ManPage)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${Launcher_ManPage} DESTINATION "${KDE_INSTALL_MANDIR}/man6") install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${Launcher_ManPage} DESTINATION "${KDE_INSTALL_MANDIR}/man6")
endif() endif()
@ -372,6 +374,8 @@ else()
message(FATAL_ERROR "Platform not supported") message(FATAL_ERROR "Platform not supported")
endif() endif()
################################ Included Libs ################################ ################################ Included Libs ################################
include(ExternalProject) include(ExternalProject)

View File

@ -8,6 +8,7 @@
* Copyright (C) 2022 Lenny McLennington <lenny@sneed.church> * Copyright (C) 2022 Lenny McLennington <lenny@sneed.church>
* Copyright (C) 2022 Tayou <tayou@gmx.net> * Copyright (C) 2022 Tayou <tayou@gmx.net>
* Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me> * Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me>
* Copyright (C) 2023 Rachel Powers <508861+Ryex@users.noreply.github.com>
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -46,6 +47,7 @@
#include "net/PasteUpload.h" #include "net/PasteUpload.h"
#include "pathmatcher/MultiMatcher.h" #include "pathmatcher/MultiMatcher.h"
#include "pathmatcher/SimplePrefixMatcher.h" #include "pathmatcher/SimplePrefixMatcher.h"
#include "settings/INIFile.h"
#include "ui/MainWindow.h" #include "ui/MainWindow.h"
#include "ui/InstanceWindow.h" #include "ui/InstanceWindow.h"
@ -286,6 +288,7 @@ Application::Application(int &argc, char **argv) : QApplication(argc, argv)
if (QFile::exists(FS::PathCombine(m_rootPath, "portable.txt"))) { if (QFile::exists(FS::PathCombine(m_rootPath, "portable.txt"))) {
dataPath = m_rootPath; dataPath = m_rootPath;
adjustedBy = "Portable data path"; adjustedBy = "Portable data path";
m_portable = true;
} }
#endif #endif
} }
@ -411,6 +414,47 @@ Application::Application(int &argc, char **argv) : QApplication(argc, argv)
"%{if-category}[%{category}]: %{endif}" "%{if-category}[%{category}]: %{endif}"
"%{message}"); "%{message}");
bool foundLoggingRules = false;
auto logRulesFile = QStringLiteral("qtlogging.ini");
auto logRulesPath = FS::PathCombine(dataPath, logRulesFile);
qDebug() << "Testing" << logRulesPath << "...";
foundLoggingRules = QFile::exists(logRulesPath);
// search the dataPath()
// seach app data standard path
if(!foundLoggingRules && !isPortable() && dirParam.isEmpty()) {
logRulesPath = QStandardPaths::locate(QStandardPaths::AppDataLocation, FS::PathCombine("..", logRulesFile));
if(!logRulesPath.isEmpty()) {
qDebug() << "Found" << logRulesPath << "...";
foundLoggingRules = true;
}
}
// seach root path
if(!foundLoggingRules) {
logRulesPath = FS::PathCombine(m_rootPath, logRulesFile);
qDebug() << "Testing" << logRulesPath << "...";
foundLoggingRules = QFile::exists(logRulesPath);
}
if(foundLoggingRules) {
// load and set logging rules
qDebug() << "Loading logging rules from:" << logRulesPath;
QSettings loggingRules(logRulesPath, QSettings::IniFormat);
loggingRules.beginGroup("Rules");
QStringList rule_names = loggingRules.childKeys();
QStringList rules;
qDebug() << "Setting log rules:";
for (auto rule_name : rule_names) {
auto rule = QString("%1=%2").arg(rule_name).arg(loggingRules.value(rule_name).toString());
rules.append(rule);
qDebug() << " " << rule;
}
auto rules_str = rules.join("\n");
QLoggingCategory::setFilterRules(rules_str);
}
qDebug() << "<> Log initialized."; qDebug() << "<> Log initialized.";
} }

View File

@ -187,6 +187,10 @@ public:
return m_rootPath; return m_rootPath;
} }
bool isPortable() {
return m_portable;
}
const Capabilities capabilities() { const Capabilities capabilities() {
return m_capabilities; return m_capabilities;
} }
@ -275,6 +279,7 @@ private:
QString m_rootPath; QString m_rootPath;
Status m_status = Application::StartingUp; Status m_status = Application::StartingUp;
Capabilities m_capabilities; Capabilities m_capabilities;
bool m_portable = false;
#ifdef Q_OS_MACOS #ifdef Q_OS_MACOS
Qt::ApplicationState m_prevAppState = Qt::ApplicationInactive; Qt::ApplicationState m_prevAppState = Qt::ApplicationInactive;

View File

@ -40,6 +40,8 @@
#include <QDir> #include <QDir>
#include <QDebug> #include <QDebug>
#include <QRegularExpression> #include <QRegularExpression>
#include <QJsonDocument>
#include <QJsonObject>
#include "settings/INISettingsObject.h" #include "settings/INISettingsObject.h"
#include "settings/Setting.h" #include "settings/Setting.h"
@ -64,6 +66,8 @@ BaseInstance::BaseInstance(SettingsObjectPtr globalSettings, SettingsObjectPtr s
m_settings->registerSetting("totalTimePlayed", 0); m_settings->registerSetting("totalTimePlayed", 0);
m_settings->registerSetting("lastTimePlayed", 0); m_settings->registerSetting("lastTimePlayed", 0);
m_settings->registerSetting("linkedInstances", "[]");
// Game time override // Game time override
auto gameTimeOverride = m_settings->registerSetting("OverrideGameTime", false); auto gameTimeOverride = m_settings->registerSetting("OverrideGameTime", false);
m_settings->registerOverride(globalSettings->getSetting("ShowGameTime"), gameTimeOverride); m_settings->registerOverride(globalSettings->getSetting("ShowGameTime"), gameTimeOverride);
@ -182,6 +186,38 @@ bool BaseInstance::shouldStopOnConsoleOverflow() const
return m_settings->get("ConsoleOverflowStop").toBool(); return m_settings->get("ConsoleOverflowStop").toBool();
} }
QStringList BaseInstance::getLinkedInstances() const
{
return m_settings->get("linkedInstances").toStringList();
}
void BaseInstance::setLinkedInstances(const QStringList& list)
{
auto linkedInstances = m_settings->get("linkedInstances").toStringList();
m_settings->set("linkedInstances", list);
}
void BaseInstance::addLinkedInstanceId(const QString& id)
{
auto linkedInstances = m_settings->get("linkedInstances").toStringList();
linkedInstances.append(id);
setLinkedInstances(linkedInstances);
}
bool BaseInstance::removeLinkedInstanceId(const QString& id)
{
auto linkedInstances = m_settings->get("linkedInstances").toStringList();
int numRemoved = linkedInstances.removeAll(id);
setLinkedInstances(linkedInstances);
return numRemoved > 0;
}
bool BaseInstance::isLinkedToInstanceId(const QString& id) const
{
auto linkedInstances = m_settings->get("linkedInstances").toStringList();
return linkedInstances.contains(id);
}
void BaseInstance::iconUpdated(QString key) void BaseInstance::iconUpdated(QString key)
{ {
if(iconKey() == key) if(iconKey() == key)

View File

@ -282,6 +282,12 @@ public:
int getConsoleMaxLines() const; int getConsoleMaxLines() const;
bool shouldStopOnConsoleOverflow() const; bool shouldStopOnConsoleOverflow() const;
QStringList getLinkedInstances() const;
void setLinkedInstances(const QStringList& list);
void addLinkedInstanceId(const QString& id);
bool removeLinkedInstanceId(const QString& id);
bool isLinkedToInstanceId(const QString& id) const;
protected: protected:
void changeStatus(Status newStatus); void changeStatus(Status newStatus);

View File

@ -26,6 +26,7 @@ set(CORE_SOURCES
MMCZip.cpp MMCZip.cpp
StringUtils.h StringUtils.h
StringUtils.cpp StringUtils.cpp
QVariantUtils.h
RuntimeContext.h RuntimeContext.h
# Basic instance manipulation tasks (derived from InstanceTask) # Basic instance manipulation tasks (derived from InstanceTask)
@ -123,6 +124,8 @@ set(NET_SOURCES
net/HttpMetaCache.h net/HttpMetaCache.h
net/MetaCacheSink.cpp net/MetaCacheSink.cpp
net/MetaCacheSink.h net/MetaCacheSink.h
net/Logging.h
net/Logging.cpp
net/NetAction.h net/NetAction.h
net/NetJob.cpp net/NetJob.cpp
net/NetJob.h net/NetJob.h
@ -524,13 +527,6 @@ set(MODRINTH_SOURCES
modplatform/modrinth/ModrinthInstanceCreationTask.h modplatform/modrinth/ModrinthInstanceCreationTask.h
) )
set(MODPACKSCH_SOURCES
modplatform/modpacksch/FTBPackInstallTask.h
modplatform/modpacksch/FTBPackInstallTask.cpp
modplatform/modpacksch/FTBPackManifest.h
modplatform/modpacksch/FTBPackManifest.cpp
)
set(PACKWIZ_SOURCES set(PACKWIZ_SOURCES
modplatform/packwiz/Packwiz.h modplatform/packwiz/Packwiz.h
modplatform/packwiz/Packwiz.cpp modplatform/packwiz/Packwiz.cpp
@ -559,6 +555,18 @@ set(ATLAUNCHER_SOURCES
modplatform/atlauncher/ATLShareCode.h modplatform/atlauncher/ATLShareCode.h
) )
set(LINKEXE_SOURCES
filelink/FileLink.h
filelink/FileLink.cpp
FileSystem.h
FileSystem.cpp
Exception.h
StringUtils.h
StringUtils.cpp
DesktopServices.h
DesktopServices.cpp
)
######## Logging categories ######## ######## Logging categories ########
ecm_qt_declare_logging_category(CORE_SOURCES ecm_qt_declare_logging_category(CORE_SOURCES
@ -570,6 +578,55 @@ ecm_qt_declare_logging_category(CORE_SOURCES
EXPORT "${Launcher_Name}" EXPORT "${Launcher_Name}"
) )
ecm_qt_export_logging_category(
IDENTIFIER taskLogC
CATEGORY_NAME "launcher.task"
DEFAULT_SEVERITY Debug
DESCRIPTION "Task actions"
EXPORT "${Launcher_Name}"
)
ecm_qt_export_logging_category(
IDENTIFIER taskNetLogC
CATEGORY_NAME "launcher.task.net"
DEFAULT_SEVERITY Debug
DESCRIPTION "task network action"
EXPORT "${Launcher_Name}"
)
ecm_qt_export_logging_category(
IDENTIFIER taskDownloadLogC
CATEGORY_NAME "launcher.task.net.download"
DEFAULT_SEVERITY Debug
DESCRIPTION "task network download actions"
EXPORT "${Launcher_Name}"
)
ecm_qt_export_logging_category(
IDENTIFIER taskUploadLogC
CATEGORY_NAME "launcher.task.net.upload"
DEFAULT_SEVERITY Debug
DESCRIPTION "task network upload actions"
EXPORT "${Launcher_Name}"
)
ecm_qt_export_logging_category(
IDENTIFIER taskMetaCacheLogC
CATEGORY_NAME "launcher.task.net.metacache"
DEFAULT_SEVERITY Debug
DESCRIPTION "task network meta-cache actions"
EXPORT "${Launcher_Name}"
)
ecm_qt_export_logging_category(
IDENTIFIER taskHttpMetaCacheLogC
CATEGORY_NAME "launcher.task.net.metacache.http"
DEFAULT_SEVERITY Debug
DESCRIPTION "task network http meta-cache actions"
EXPORT "${Launcher_Name}"
)
if(KDE_INSTALL_LOGGINGCATEGORIESDIR) # only install if there is a standard path for this if(KDE_INSTALL_LOGGINGCATEGORIESDIR) # only install if there is a standard path for this
ecm_qt_install_logging_categories( ecm_qt_install_logging_categories(
EXPORT "${Launcher_Name}" EXPORT "${Launcher_Name}"
@ -599,7 +656,6 @@ set(LOGIC_SOURCES
${FTB_SOURCES} ${FTB_SOURCES}
${FLAME_SOURCES} ${FLAME_SOURCES}
${MODRINTH_SOURCES} ${MODRINTH_SOURCES}
${MODPACKSCH_SOURCES}
${PACKWIZ_SOURCES} ${PACKWIZ_SOURCES}
${TECHNIC_SOURCES} ${TECHNIC_SOURCES}
${ATLAUNCHER_SOURCES} ${ATLAUNCHER_SOURCES}
@ -797,13 +853,6 @@ SET(LAUNCHER_SOURCES
ui/pages/modplatform/atlauncher/AtlUserInteractionSupportImpl.cpp ui/pages/modplatform/atlauncher/AtlUserInteractionSupportImpl.cpp
ui/pages/modplatform/atlauncher/AtlUserInteractionSupportImpl.h ui/pages/modplatform/atlauncher/AtlUserInteractionSupportImpl.h
ui/pages/modplatform/ftb/FtbFilterModel.cpp
ui/pages/modplatform/ftb/FtbFilterModel.h
ui/pages/modplatform/ftb/FtbListModel.cpp
ui/pages/modplatform/ftb/FtbListModel.h
ui/pages/modplatform/ftb/FtbPage.cpp
ui/pages/modplatform/ftb/FtbPage.h
ui/pages/modplatform/legacy_ftb/Page.cpp ui/pages/modplatform/legacy_ftb/Page.cpp
ui/pages/modplatform/legacy_ftb/Page.h ui/pages/modplatform/legacy_ftb/Page.h
ui/pages/modplatform/legacy_ftb/ListModel.h ui/pages/modplatform/legacy_ftb/ListModel.h
@ -924,6 +973,8 @@ SET(LAUNCHER_SOURCES
ui/widgets/VariableSizedImageObject.cpp ui/widgets/VariableSizedImageObject.cpp
ui/widgets/ProjectItem.h ui/widgets/ProjectItem.h
ui/widgets/ProjectItem.cpp ui/widgets/ProjectItem.cpp
ui/widgets/SubTaskProgressBar.h
ui/widgets/SubTaskProgressBar.cpp
ui/widgets/VersionListView.cpp ui/widgets/VersionListView.cpp
ui/widgets/VersionListView.h ui/widgets/VersionListView.h
ui/widgets/VersionSelectWidget.cpp ui/widgets/VersionSelectWidget.cpp
@ -978,13 +1029,13 @@ qt_wrap_ui(LAUNCHER_UI
ui/pages/modplatform/flame/FlamePage.ui ui/pages/modplatform/flame/FlamePage.ui
ui/pages/modplatform/legacy_ftb/Page.ui ui/pages/modplatform/legacy_ftb/Page.ui
ui/pages/modplatform/ImportPage.ui ui/pages/modplatform/ImportPage.ui
ui/pages/modplatform/ftb/FtbPage.ui
ui/pages/modplatform/modrinth/ModrinthPage.ui ui/pages/modplatform/modrinth/ModrinthPage.ui
ui/pages/modplatform/technic/TechnicPage.ui ui/pages/modplatform/technic/TechnicPage.ui
ui/widgets/InstanceCardWidget.ui ui/widgets/InstanceCardWidget.ui
ui/widgets/CustomCommands.ui ui/widgets/CustomCommands.ui
ui/widgets/InfoFrame.ui ui/widgets/InfoFrame.ui
ui/widgets/ModFilterWidget.ui ui/widgets/ModFilterWidget.ui
ui/widgets/SubTaskProgressBar.ui
ui/widgets/ThemeCustomizationWidget.ui ui/widgets/ThemeCustomizationWidget.ui
ui/dialogs/CopyInstanceDialog.ui ui/dialogs/CopyInstanceDialog.ui
ui/dialogs/ProfileSetupDialog.ui ui/dialogs/ProfileSetupDialog.ui
@ -1107,6 +1158,41 @@ install(TARGETS ${Launcher_Name}
FRAMEWORK DESTINATION ${FRAMEWORK_DEST_DIR} COMPONENT Runtime FRAMEWORK DESTINATION ${FRAMEWORK_DEST_DIR} COMPONENT Runtime
) )
if(WIN32)
add_library(filelink_logic STATIC ${LINKEXE_SOURCES})
target_include_directories(filelink_logic PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(filelink_logic
systeminfo
BuildConfig
ghcFilesystem::ghc_filesystem
Qt${QT_VERSION_MAJOR}::Widgets
Qt${QT_VERSION_MAJOR}::Core
Qt${QT_VERSION_MAJOR}::Network
# Qt${QT_VERSION_MAJOR}::Concurrent
${Launcher_QT_LIBS}
)
add_executable("${Launcher_Name}_filelink" WIN32 filelink/main.cpp)
target_sources("${Launcher_Name}_filelink" PRIVATE filelink/filelink.exe.manifest)
target_link_libraries("${Launcher_Name}_filelink" filelink_logic)
if(DEFINED Launcher_APP_BINARY_NAME)
set_target_properties("${Launcher_Name}_filelink" PROPERTIES OUTPUT_NAME "${Launcher_APP_BINARY_NAME}_filelink")
endif()
if(DEFINED Launcher_BINARY_RPATH)
SET_TARGET_PROPERTIES("${Launcher_Name}_filelink" PROPERTIES INSTALL_RPATH "${Launcher_BINARY_RPATH}")
endif()
install(TARGETS "${Launcher_Name}_filelink"
BUNDLE DESTINATION "." COMPONENT Runtime
LIBRARY DESTINATION ${LIBRARY_DEST_DIR} COMPONENT Runtime
RUNTIME DESTINATION ${BINARY_DEST_DIR} COMPONENT Runtime
FRAMEWORK DESTINATION ${FRAMEWORK_DEST_DIR} COMPONENT Runtime
)
endif()
if (UNIX AND APPLE) if (UNIX AND APPLE)
# Add Sparkle updater # Add Sparkle updater
# It has to be copied here instead of just allowing fixup_bundle to install it, otherwise essential parts of # It has to be copied here instead of just allowing fixup_bundle to install it, otherwise essential parts of
@ -1123,6 +1209,12 @@ if(INSTALL_BUNDLE STREQUAL "full")
CODE "file(WRITE \"\${CMAKE_INSTALL_PREFIX}/${RESOURCES_DEST_DIR}/qt.conf\" \" \")" CODE "file(WRITE \"\${CMAKE_INSTALL_PREFIX}/${RESOURCES_DEST_DIR}/qt.conf\" \" \")"
COMPONENT Runtime COMPONENT Runtime
) )
# add qtlogging.ini as a config file
install(
FILES "qtlogging.ini"
DESTINATION ${CMAKE_INSTALL_PREFIX}/${RESOURCES_DEST_DIR}
COMPONENT Runtime
)
# Bundle plugins # Bundle plugins
# Image formats # Image formats
install( install(

View File

@ -37,7 +37,6 @@
#include <QDesktopServices> #include <QDesktopServices>
#include <QProcess> #include <QProcess>
#include <QDebug> #include <QDebug>
#include "Application.h"
/** /**
* This shouldn't exist, but until QTBUG-9328 and other unreported bugs are fixed, it needs to be a thing. * This shouldn't exist, but until QTBUG-9328 and other unreported bugs are fixed, it needs to be a thing.

File diff suppressed because it is too large Load Diff

View File

@ -3,6 +3,7 @@
* Prism Launcher - Minecraft Launcher * Prism Launcher - Minecraft Launcher
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
* Copyright (C) 2022 TheKodeToad <TheKodeToad@proton.me> * Copyright (C) 2022 TheKodeToad <TheKodeToad@proton.me>
* Copyright (C) 2022 Rachel Powers <508861+Ryex@users.noreply.github.com>
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -39,9 +40,13 @@
#include "Exception.h" #include "Exception.h"
#include "pathmatcher/IPathMatcher.h" #include "pathmatcher/IPathMatcher.h"
#include <system_error>
#include <QDir> #include <QDir>
#include <QFlags> #include <QFlags>
#include <QLocalServer>
#include <QObject> #include <QObject>
#include <QThread>
namespace FS { namespace FS {
@ -77,7 +82,9 @@ bool ensureFilePathExists(QString filenamepath);
*/ */
bool ensureFolderPathExists(QString filenamepath); bool ensureFolderPathExists(QString filenamepath);
/// @brief Copies a directory and it's contents from src to dest /**
* @brief Copies a directory and it's contents from src to dest
*/
class copy : public QObject { class copy : public QObject {
Q_OBJECT Q_OBJECT
public: public:
@ -122,13 +129,134 @@ class copy : public QObject {
int m_copied; int m_copied;
}; };
struct LinkPair {
QString src;
QString dst;
};
struct LinkResult {
QString src;
QString dst;
QString err_msg;
int err_value;
};
class ExternalLinkFileProcess : public QThread {
Q_OBJECT
public:
ExternalLinkFileProcess(QString server, bool useHardLinks, QObject* parent = nullptr)
: QThread(parent), m_useHardLinks(useHardLinks), m_server(server)
{}
void run() override
{
runLinkFile();
emit processExited();
}
signals:
void processExited();
private:
void runLinkFile();
bool m_useHardLinks = false;
QString m_server;
};
/**
* @brief links (a file / a directory and it's contents) from src to dest
*/
class create_link : public QObject {
Q_OBJECT
public:
create_link(const QList<LinkPair> path_pairs, QObject* parent = nullptr) : QObject(parent) { m_path_pairs.append(path_pairs); }
create_link(const QString& src, const QString& dst, QObject* parent = nullptr) : QObject(parent)
{
LinkPair pair = { src, dst };
m_path_pairs.append(pair);
}
create_link& useHardLinks(const bool useHard)
{
m_useHardLinks = useHard;
return *this;
}
create_link& matcher(const IPathMatcher* filter)
{
m_matcher = filter;
return *this;
}
create_link& whitelist(bool whitelist)
{
m_whitelist = whitelist;
return *this;
}
create_link& linkRecursively(bool recursive)
{
m_recursive = recursive;
return *this;
}
create_link& setMaxDepth(int depth)
{
m_max_depth = depth;
return *this;
}
create_link& debug(bool d)
{
m_debug = d;
return *this;
}
std::error_code getOSError() { return m_os_err; }
bool operator()(bool dryRun = false) { return operator()(QString(), dryRun); }
int totalLinked() { return m_linked; }
void runPrivileged() { runPrivileged(QString()); }
void runPrivileged(const QString& offset);
QList<LinkResult> getResults() { return m_path_results; }
signals:
void fileLinked(const QString& srcName, const QString& dstName);
void linkFailed(const QString& srcName, const QString& dstName, const QString& err_msg, int err_value);
void finished();
void finishedPrivileged(bool gotResults);
private:
bool operator()(const QString& offset, bool dryRun = false);
void make_link_list(const QString& offset);
bool make_links();
private:
bool m_useHardLinks = false;
const IPathMatcher* m_matcher = nullptr;
bool m_whitelist = false;
bool m_recursive = true;
/// @brief >= -1 = infinite, 0 = link files at src/* to dest/*, 1 = link files at src/*/* to dest/*/*, etc.
int m_max_depth = -1;
QList<LinkPair> m_path_pairs;
QList<LinkResult> m_path_results;
QList<LinkPair> m_links_to_make;
int m_linked;
bool m_debug = false;
std::error_code m_os_err;
QLocalServer m_linkServer;
};
/** /**
* @brief moves a file by renaming it * @brief moves a file by renaming it
* @param source source file path * @param source source file path
* @param dest destination filepath * @param dest destination filepath
* *
*/ */
bool move(const QString& source, const QString& dest); bool move(const QString& source, const QString& dest);
/** /**
* Delete a folder recursively * Delete a folder recursively
@ -138,13 +266,30 @@ bool deletePath(QString path);
/** /**
* Trash a folder / file * Trash a folder / file
*/ */
bool trash(QString path, QString *pathInTrash = nullptr); bool trash(QString path, QString* pathInTrash = nullptr);
QString PathCombine(const QString& path1, const QString& path2); QString PathCombine(const QString& path1, const QString& path2);
QString PathCombine(const QString& path1, const QString& path2, const QString& path3); QString PathCombine(const QString& path1, const QString& path2, const QString& path3);
QString PathCombine(const QString& path1, const QString& path2, const QString& path3, const QString& path4); QString PathCombine(const QString& path1, const QString& path2, const QString& path3, const QString& path4);
QString AbsolutePath(QString path); QString AbsolutePath(const QString& path);
/**
* @brief depth of path. "foo.txt" -> 0 , "bar/foo.txt" -> 1, /baz/bar/foo.txt -> 2, etc.
*
* @param path path to measure
* @return int number of components before base path
*/
int pathDepth(const QString& path);
/**
* @brief cut off segments of path until it is a max of length depth
*
* @param path path to truncate
* @param depth max depth of new path
* @return QString truncated path
*/
QString pathTruncate(const QString& path, int depth);
/** /**
* Resolve an executable * Resolve an executable
@ -186,4 +331,194 @@ bool overrideFolder(QString overwritten_path, QString override_path);
* Creates a shortcut to the specified target file at the specified destination path. * Creates a shortcut to the specified target file at the specified destination path.
*/ */
bool createShortcut(QString destination, QString target, QStringList args, QString name, QString icon); bool createShortcut(QString destination, QString target, QStringList args, QString name, QString icon);
}
enum class FilesystemType {
FAT,
NTFS,
REFS,
EXT,
EXT_2_OLD,
EXT_2_3_4,
XFS,
BTRFS,
NFS,
ZFS,
APFS,
HFS,
HFSPLUS,
HFSX,
FUSEBLK,
F2FS,
UNKNOWN
};
/**
* @brief Ordered Mapping of enum types to reported filesystem names
* this mapping is non exsaustive, it just attempts to capture the filesystems which could be reasonalbly be in use .
* all string values are in uppercase, use `QString.toUpper()` or equivalent during lookup.
*
* QMap is ordered
*
*/
static const QMap<FilesystemType, QStringList> s_filesystem_type_names = {
{FilesystemType::FAT, { "FAT" }},
{FilesystemType::NTFS, { "NTFS" }},
{FilesystemType::REFS, { "REFS" }},
{FilesystemType::EXT_2_OLD, { "EXT_2_OLD", "EXT2_OLD" }},
{FilesystemType::EXT_2_3_4, { "EXT2/3/4", "EXT_2_3_4", "EXT2", "EXT3", "EXT4" }},
{FilesystemType::EXT, { "EXT" }},
{FilesystemType::XFS, { "XFS" }},
{FilesystemType::BTRFS, { "BTRFS" }},
{FilesystemType::NFS, { "NFS" }},
{FilesystemType::ZFS, { "ZFS" }},
{FilesystemType::APFS, { "APFS" }},
{FilesystemType::HFS, { "HFS" }},
{FilesystemType::HFSPLUS, { "HFSPLUS" }},
{FilesystemType::HFSX, { "HFSX" }},
{FilesystemType::FUSEBLK, { "FUSEBLK" }},
{FilesystemType::F2FS, { "F2FS" }},
{FilesystemType::UNKNOWN, { "UNKNOWN" }}
};
/**
* @brief Get the string name of Filesystem enum object
*
* @param type
* @return QString
*/
QString getFilesystemTypeName(FilesystemType type);
/**
* @brief Get the Filesystem enum object from a name
* Does a lookup of the type name and returns an exact match
*
* @param name
* @return FilesystemType
*/
FilesystemType getFilesystemType(const QString& name);
/**
* @brief Get the Filesystem enum object from a name
* Does a fuzzy lookup of the type name and returns an apropreate match
*
* @param name
* @return FilesystemType
*/
FilesystemType getFilesystemTypeFuzzy(const QString& name);
struct FilesystemInfo {
FilesystemType fsType = FilesystemType::UNKNOWN;
QString fsTypeName;
int blockSize;
qint64 bytesAvailable;
qint64 bytesFree;
qint64 bytesTotal;
QString name;
QString rootPath;
};
/**
* @brief path to the near ancestor that exists
*
*/
QString nearestExistentAncestor(const QString& path);
/**
* @brief colect information about the filesystem under a file
*
*/
FilesystemInfo statFS(const QString& path);
static const QList<FilesystemType> s_clone_filesystems = { FilesystemType::BTRFS, FilesystemType::APFS, FilesystemType::ZFS,
FilesystemType::XFS, FilesystemType::REFS };
/**
* @brief if the Filesystem is reflink/clone capable
*
*/
bool canCloneOnFS(const QString& path);
bool canCloneOnFS(const FilesystemInfo& info);
bool canCloneOnFS(FilesystemType type);
/**
* @brief if the Filesystems are reflink/clone capable and both are on the same device
*
*/
bool canClone(const QString& src, const QString& dst);
/**
* @brief Copies a directory and it's contents from src to dest
*/
class clone : public QObject {
Q_OBJECT
public:
clone(const QString& src, const QString& dst, QObject* parent = nullptr) : QObject(parent)
{
m_src.setPath(src);
m_dst.setPath(dst);
}
clone& matcher(const IPathMatcher* filter)
{
m_matcher = filter;
return *this;
}
clone& whitelist(bool whitelist)
{
m_whitelist = whitelist;
return *this;
}
bool operator()(bool dryRun = false) { return operator()(QString(), dryRun); }
int totalCloned() { return m_cloned; }
signals:
void fileCloned(const QString& src, const QString& dst);
void cloneFailed(const QString& src, const QString& dst);
private:
bool operator()(const QString& offset, bool dryRun = false);
private:
const IPathMatcher* m_matcher = nullptr;
bool m_whitelist = false;
QDir m_src;
QDir m_dst;
int m_cloned;
};
/**
* @brief clone/reflink file from src to dst
*
*/
bool clone_file(const QString& src, const QString& dst, std::error_code& ec);
#if defined(Q_OS_WIN)
bool win_ioctl_clone(const std::wstring& src_path, const std::wstring& dst_path, std::error_code& ec);
#elif defined(Q_OS_LINUX)
bool linux_ficlone(const std::string& src_path, const std::string& dst_path, std::error_code& ec);
#elif defined(Q_OS_MACOS) || defined(Q_OS_FREEBSD) || defined(Q_OS_OPENBSD)
bool macos_bsd_clonefile(const std::string& src_path, const std::string& dst_path, std::error_code& ec);
#endif
static const QList<FilesystemType> s_non_link_filesystems = {
FilesystemType::FAT,
};
/**
* @brief if the Filesystem is symlink capable
*
*/
bool canLinkOnFS(const QString& path);
bool canLinkOnFS(const FilesystemInfo& info);
bool canLinkOnFS(FilesystemType type);
/**
* @brief if the Filesystem is symlink capable on both ends
*
*/
bool canLink(const QString& src, const QString& dst);
uintmax_t hardLinkCount(const QString& path);
} // namespace FS

View File

@ -16,8 +16,13 @@ bool InstanceCopyPrefs::allTrue() const
copyScreenshots; copyScreenshots;
} }
// Returns a single RegEx string of the selected folders/files to filter out (ex: ".minecraft/saves|.minecraft/server.dat") // Returns a single RegEx string of the selected folders/files to filter out (ex: ".minecraft/saves|.minecraft/server.dat")
QString InstanceCopyPrefs::getSelectedFiltersAsRegex() const QString InstanceCopyPrefs::getSelectedFiltersAsRegex() const
{
return getSelectedFiltersAsRegex({});
}
QString InstanceCopyPrefs::getSelectedFiltersAsRegex(const QStringList& additionalFilters) const
{ {
QStringList filters; QStringList filters;
@ -42,6 +47,10 @@ QString InstanceCopyPrefs::getSelectedFiltersAsRegex() const
if(!copyScreenshots) if(!copyScreenshots)
filters << "screenshots"; filters << "screenshots";
for (auto filter : additionalFilters) {
filters << filter;
}
// If we have any filters to add, join them as a single regex string to return: // If we have any filters to add, join them as a single regex string to return:
if (!filters.isEmpty()) { if (!filters.isEmpty()) {
const QString MC_ROOT = "[.]?minecraft/"; const QString MC_ROOT = "[.]?minecraft/";
@ -93,6 +102,31 @@ bool InstanceCopyPrefs::isCopyScreenshotsEnabled() const
return copyScreenshots; return copyScreenshots;
} }
bool InstanceCopyPrefs::isUseSymLinksEnabled() const
{
return useSymLinks;
}
bool InstanceCopyPrefs::isUseHardLinksEnabled() const
{
return useHardLinks;
}
bool InstanceCopyPrefs::isLinkRecursivelyEnabled() const
{
return linkRecursively;
}
bool InstanceCopyPrefs::isDontLinkSavesEnabled() const
{
return dontLinkSaves;
}
bool InstanceCopyPrefs::isUseCloneEnabled() const
{
return useClone;
}
// ======= Setters ======= // ======= Setters =======
void InstanceCopyPrefs::enableCopySaves(bool b) void InstanceCopyPrefs::enableCopySaves(bool b)
{ {
@ -133,3 +167,28 @@ void InstanceCopyPrefs::enableCopyScreenshots(bool b)
{ {
copyScreenshots = b; copyScreenshots = b;
} }
void InstanceCopyPrefs::enableUseSymLinks(bool b)
{
useSymLinks = b;
}
void InstanceCopyPrefs::enableLinkRecursively(bool b)
{
linkRecursively = b;
}
void InstanceCopyPrefs::enableUseHardLinks(bool b)
{
useHardLinks = b;
}
void InstanceCopyPrefs::enableDontLinkSaves(bool b)
{
dontLinkSaves = b;
}
void InstanceCopyPrefs::enableUseClone(bool b)
{
useClone = b;
}

View File

@ -10,6 +10,7 @@ struct InstanceCopyPrefs {
public: public:
[[nodiscard]] bool allTrue() const; [[nodiscard]] bool allTrue() const;
[[nodiscard]] QString getSelectedFiltersAsRegex() const; [[nodiscard]] QString getSelectedFiltersAsRegex() const;
[[nodiscard]] QString getSelectedFiltersAsRegex(const QStringList& additionalFilters) const;
// Getters // Getters
[[nodiscard]] bool isCopySavesEnabled() const; [[nodiscard]] bool isCopySavesEnabled() const;
[[nodiscard]] bool isKeepPlaytimeEnabled() const; [[nodiscard]] bool isKeepPlaytimeEnabled() const;
@ -19,6 +20,11 @@ struct InstanceCopyPrefs {
[[nodiscard]] bool isCopyServersEnabled() const; [[nodiscard]] bool isCopyServersEnabled() const;
[[nodiscard]] bool isCopyModsEnabled() const; [[nodiscard]] bool isCopyModsEnabled() const;
[[nodiscard]] bool isCopyScreenshotsEnabled() const; [[nodiscard]] bool isCopyScreenshotsEnabled() const;
[[nodiscard]] bool isUseSymLinksEnabled() const;
[[nodiscard]] bool isLinkRecursivelyEnabled() const;
[[nodiscard]] bool isUseHardLinksEnabled() const;
[[nodiscard]] bool isDontLinkSavesEnabled() const;
[[nodiscard]] bool isUseCloneEnabled() const;
// Setters // Setters
void enableCopySaves(bool b); void enableCopySaves(bool b);
void enableKeepPlaytime(bool b); void enableKeepPlaytime(bool b);
@ -28,6 +34,11 @@ struct InstanceCopyPrefs {
void enableCopyServers(bool b); void enableCopyServers(bool b);
void enableCopyMods(bool b); void enableCopyMods(bool b);
void enableCopyScreenshots(bool b); void enableCopyScreenshots(bool b);
void enableUseSymLinks(bool b);
void enableLinkRecursively(bool b);
void enableUseHardLinks(bool b);
void enableDontLinkSaves(bool b);
void enableUseClone(bool b);
protected: // data protected: // data
bool copySaves = true; bool copySaves = true;
@ -38,4 +49,9 @@ struct InstanceCopyPrefs {
bool copyServers = true; bool copyServers = true;
bool copyMods = true; bool copyMods = true;
bool copyScreenshots = true; bool copyScreenshots = true;
bool useSymLinks = false;
bool linkRecursively = false;
bool useHardLinks = false;
bool dontLinkSaves = false;
bool useClone = false;
}; };

View File

@ -1,18 +1,31 @@
#include "InstanceCopyTask.h" #include "InstanceCopyTask.h"
#include "settings/INISettingsObject.h" #include <QDebug>
#include <QtConcurrentRun>
#include "FileSystem.h" #include "FileSystem.h"
#include "NullInstance.h" #include "NullInstance.h"
#include "pathmatcher/RegexpMatcher.h" #include "pathmatcher/RegexpMatcher.h"
#include <QtConcurrentRun> #include "settings/INISettingsObject.h"
InstanceCopyTask::InstanceCopyTask(InstancePtr origInstance, const InstanceCopyPrefs& prefs) InstanceCopyTask::InstanceCopyTask(InstancePtr origInstance, const InstanceCopyPrefs& prefs)
{ {
m_origInstance = origInstance; m_origInstance = origInstance;
m_keepPlaytime = prefs.isKeepPlaytimeEnabled(); m_keepPlaytime = prefs.isKeepPlaytimeEnabled();
m_useLinks = prefs.isUseSymLinksEnabled();
m_linkRecursively = prefs.isLinkRecursivelyEnabled();
m_useHardLinks = prefs.isLinkRecursivelyEnabled() && prefs.isUseHardLinksEnabled();
m_copySaves = prefs.isLinkRecursivelyEnabled() && prefs.isDontLinkSavesEnabled() && prefs.isCopySavesEnabled();
m_useClone = prefs.isUseCloneEnabled();
QString filters = prefs.getSelectedFiltersAsRegex(); QString filters = prefs.getSelectedFiltersAsRegex();
if (!filters.isEmpty()) if (m_useLinks || m_useHardLinks) {
{ if (!filters.isEmpty())
filters += "|";
filters += "instance.cfg";
}
qDebug() << "CopyFilters:" << filters;
if (!filters.isEmpty()) {
// Set regex filter: // Set regex filter:
// FIXME: get this from the original instance type... // FIXME: get this from the original instance type...
auto matcherReal = new RegexpMatcher(filters); auto matcherReal = new RegexpMatcher(filters);
@ -25,11 +38,78 @@ void InstanceCopyTask::executeTask()
{ {
setStatus(tr("Copying instance %1").arg(m_origInstance->name())); setStatus(tr("Copying instance %1").arg(m_origInstance->name()));
m_copyFuture = QtConcurrent::run(QThreadPool::globalInstance(), [this]{ auto copySaves = [&]() {
FS::copy folderCopy(m_origInstance->instanceRoot(), m_stagingPath); FS::copy savesCopy(FS::PathCombine(m_origInstance->instanceRoot(), "saves"), FS::PathCombine(m_stagingPath, "saves"));
folderCopy.followSymlinks(false).matcher(m_matcher.get()); savesCopy.followSymlinks(true);
return folderCopy(); return savesCopy();
};
m_copyFuture = QtConcurrent::run(QThreadPool::globalInstance(), [this, copySaves] {
if (m_useClone) {
FS::clone folderClone(m_origInstance->instanceRoot(), m_stagingPath);
folderClone.matcher(m_matcher.get());
return folderClone();
} else if (m_useLinks || m_useHardLinks) {
FS::create_link folderLink(m_origInstance->instanceRoot(), m_stagingPath);
int depth = m_linkRecursively ? -1 : 0; // we need to at least link the top level instead of the instance folder
folderLink.linkRecursively(true).setMaxDepth(depth).useHardLinks(m_useHardLinks).matcher(m_matcher.get());
bool there_were_errors = false;
if (!folderLink()) {
#if defined Q_OS_WIN32
if (!m_useHardLinks) {
qDebug() << "EXPECTED: Link failure, Windows requires permissions for symlinks";
qDebug() << "attempting to run with privelage";
QEventLoop loop;
bool got_priv_results = false;
connect(&folderLink, &FS::create_link::finishedPrivileged, this, [&](bool gotResults) {
if (!gotResults) {
qDebug() << "Privileged run exited without results!";
}
got_priv_results = gotResults;
loop.quit();
});
folderLink.runPrivileged();
loop.exec(); // wait for the finished signal
for (auto result : folderLink.getResults()) {
if (result.err_value != 0) {
there_were_errors = true;
}
}
if (m_copySaves) {
there_were_errors |= !copySaves();
}
return got_priv_results && !there_were_errors;
} else {
qDebug() << "Link Failed!" << folderLink.getOSError().value() << folderLink.getOSError().message().c_str();
}
#else
qDebug() << "Link Failed!" << folderLink.getOSError().value() << folderLink.getOSError().message().c_str();
#endif
return false;
}
if (m_copySaves) {
there_were_errors |= !copySaves();
}
return !there_were_errors;
} else {
FS::copy folderCopy(m_origInstance->instanceRoot(), m_stagingPath);
folderCopy.followSymlinks(false).matcher(m_matcher.get());
return folderCopy();
}
}); });
connect(&m_copyFutureWatcher, &QFutureWatcher<bool>::finished, this, &InstanceCopyTask::copyFinished); connect(&m_copyFutureWatcher, &QFutureWatcher<bool>::finished, this, &InstanceCopyTask::copyFinished);
connect(&m_copyFutureWatcher, &QFutureWatcher<bool>::canceled, this, &InstanceCopyTask::copyAborted); connect(&m_copyFutureWatcher, &QFutureWatcher<bool>::canceled, this, &InstanceCopyTask::copyAborted);
@ -39,8 +119,7 @@ void InstanceCopyTask::executeTask()
void InstanceCopyTask::copyFinished() void InstanceCopyTask::copyFinished()
{ {
auto successful = m_copyFuture.result(); auto successful = m_copyFuture.result();
if(!successful) if (!successful) {
{
emitFailed(tr("Instance folder copy failed.")); emitFailed(tr("Instance folder copy failed."));
return; return;
} }
@ -50,9 +129,11 @@ void InstanceCopyTask::copyFinished()
InstancePtr inst(new NullInstance(m_globalSettings, instanceSettings, m_stagingPath)); InstancePtr inst(new NullInstance(m_globalSettings, instanceSettings, m_stagingPath));
inst->setName(name()); inst->setName(name());
inst->setIconKey(m_instIcon); inst->setIconKey(m_instIcon);
if(!m_keepPlaytime) { if (!m_keepPlaytime) {
inst->resetTimePlayed(); inst->resetTimePlayed();
} }
if (m_useLinks)
inst->addLinkedInstanceId(m_origInstance->id());
emitSucceeded(); emitSucceeded();
} }

View File

@ -30,4 +30,9 @@ private:
QFutureWatcher<bool> m_copyFutureWatcher; QFutureWatcher<bool> m_copyFutureWatcher;
std::unique_ptr<IPathMatcher> m_matcher; std::unique_ptr<IPathMatcher> m_matcher;
bool m_keepPlaytime; bool m_keepPlaytime;
bool m_useLinks = false;
bool m_useHardLinks = false;
bool m_copySaves = false;
bool m_linkRecursively = false;
bool m_useClone = false;
}; };

View File

@ -98,6 +98,7 @@ void InstanceImportTask::executeTask()
connect(m_filesNetJob.get(), &NetJob::succeeded, this, &InstanceImportTask::downloadSucceeded); connect(m_filesNetJob.get(), &NetJob::succeeded, this, &InstanceImportTask::downloadSucceeded);
connect(m_filesNetJob.get(), &NetJob::progress, this, &InstanceImportTask::downloadProgressChanged); connect(m_filesNetJob.get(), &NetJob::progress, this, &InstanceImportTask::downloadProgressChanged);
connect(m_filesNetJob.get(), &NetJob::stepProgress, this, &InstanceImportTask::propogateStepProgress);
connect(m_filesNetJob.get(), &NetJob::failed, this, &InstanceImportTask::downloadFailed); connect(m_filesNetJob.get(), &NetJob::failed, this, &InstanceImportTask::downloadFailed);
connect(m_filesNetJob.get(), &NetJob::aborted, this, &InstanceImportTask::downloadAborted); connect(m_filesNetJob.get(), &NetJob::aborted, this, &InstanceImportTask::downloadAborted);
@ -291,7 +292,9 @@ void InstanceImportTask::processFlame()
}); });
connect(inst_creation_task, &Task::failed, this, &InstanceImportTask::emitFailed); connect(inst_creation_task, &Task::failed, this, &InstanceImportTask::emitFailed);
connect(inst_creation_task, &Task::progress, this, &InstanceImportTask::setProgress); connect(inst_creation_task, &Task::progress, this, &InstanceImportTask::setProgress);
connect(inst_creation_task, &Task::stepProgress, this, &InstanceImportTask::propogateStepProgress);
connect(inst_creation_task, &Task::status, this, &InstanceImportTask::setStatus); connect(inst_creation_task, &Task::status, this, &InstanceImportTask::setStatus);
connect(inst_creation_task, &Task::details, this, &InstanceImportTask::setDetails);
connect(inst_creation_task, &Task::finished, inst_creation_task, &InstanceCreationTask::deleteLater); connect(inst_creation_task, &Task::finished, inst_creation_task, &InstanceCreationTask::deleteLater);
connect(this, &Task::aborted, inst_creation_task, &InstanceCreationTask::abort); connect(this, &Task::aborted, inst_creation_task, &InstanceCreationTask::abort);
@ -382,7 +385,9 @@ void InstanceImportTask::processModrinth()
}); });
connect(inst_creation_task, &Task::failed, this, &InstanceImportTask::emitFailed); connect(inst_creation_task, &Task::failed, this, &InstanceImportTask::emitFailed);
connect(inst_creation_task, &Task::progress, this, &InstanceImportTask::setProgress); connect(inst_creation_task, &Task::progress, this, &InstanceImportTask::setProgress);
connect(inst_creation_task, &Task::stepProgress, this, &InstanceImportTask::propogateStepProgress);
connect(inst_creation_task, &Task::status, this, &InstanceImportTask::setStatus); connect(inst_creation_task, &Task::status, this, &InstanceImportTask::setStatus);
connect(inst_creation_task, &Task::details, this, &InstanceImportTask::setDetails);
connect(inst_creation_task, &Task::finished, inst_creation_task, &InstanceCreationTask::deleteLater); connect(inst_creation_task, &Task::finished, inst_creation_task, &InstanceCreationTask::deleteLater);
connect(this, &Task::aborted, inst_creation_task, &InstanceCreationTask::abort); connect(this, &Task::aborted, inst_creation_task, &InstanceCreationTask::abort);

View File

@ -129,6 +129,16 @@ QMimeData* InstanceList::mimeData(const QModelIndexList& indexes) const
return mimeData; return mimeData;
} }
QStringList InstanceList::getLinkedInstancesById(const QString &id) const
{
QStringList linkedInstances;
for (auto inst : m_instances) {
if (inst->isLinkedToInstanceId(id))
linkedInstances.append(inst->id());
}
return linkedInstances;
}
int InstanceList::rowCount(const QModelIndex& parent) const int InstanceList::rowCount(const QModelIndex& parent) const
{ {
Q_UNUSED(parent); Q_UNUSED(parent);
@ -787,7 +797,9 @@ class InstanceStaging : public Task {
connect(child, &Task::aborted, this, &InstanceStaging::childAborted); connect(child, &Task::aborted, this, &InstanceStaging::childAborted);
connect(child, &Task::abortStatusChanged, this, &InstanceStaging::setAbortable); connect(child, &Task::abortStatusChanged, this, &InstanceStaging::setAbortable);
connect(child, &Task::status, this, &InstanceStaging::setStatus); connect(child, &Task::status, this, &InstanceStaging::setStatus);
connect(child, &Task::details, this, &InstanceStaging::setDetails);
connect(child, &Task::progress, this, &InstanceStaging::setProgress); connect(child, &Task::progress, this, &InstanceStaging::setProgress);
connect(child, &Task::stepProgress, this, &InstanceStaging::propogateStepProgress);
connect(&m_backoffTimer, &QTimer::timeout, this, &InstanceStaging::childSucceded); connect(&m_backoffTimer, &QTimer::timeout, this, &InstanceStaging::childSucceded);
} }
@ -865,7 +877,7 @@ Task* InstanceList::wrapInstanceTask(InstanceTask* task)
QString InstanceList::getStagedInstancePath() QString InstanceList::getStagedInstancePath()
{ {
QString key = QUuid::createUuid().toString(); QString key = QUuid::createUuid().toString(QUuid::WithoutBraces);
QString tempDir = ".LAUNCHER_TEMP/"; QString tempDir = ".LAUNCHER_TEMP/";
QString relPath = FS::PathCombine(tempDir, key); QString relPath = FS::PathCombine(tempDir, key);
QDir rootPath(m_instDir); QDir rootPath(m_instDir);

View File

@ -154,6 +154,8 @@ public:
QStringList mimeTypes() const override; QStringList mimeTypes() const override;
QMimeData *mimeData(const QModelIndexList &indexes) const override; QMimeData *mimeData(const QModelIndexList &indexes) const override;
QStringList getLinkedInstancesById(const QString &id) const;
signals: signals:
void dataIsInvalid(); void dataIsInvalid();
void instancesChanged(); void instancesChanged();

View File

@ -18,6 +18,8 @@
#include <MMCTime.h> #include <MMCTime.h>
#include <QObject> #include <QObject>
#include <QDateTime>
#include <QTextStream>
QString Time::prettifyDuration(int64_t duration) { QString Time::prettifyDuration(int64_t duration) {
int seconds = (int) (duration % 60); int seconds = (int) (duration % 60);
@ -36,3 +38,65 @@ QString Time::prettifyDuration(int64_t duration) {
} }
return QObject::tr("%1d %2h %3min").arg(days).arg(hours).arg(minutes); return QObject::tr("%1d %2h %3min").arg(days).arg(hours).arg(minutes);
} }
QString Time::humanReadableDuration(double duration, int precision) {
using days = std::chrono::duration<int, std::ratio<86400>>;
QString outStr;
QTextStream os(&outStr);
bool neg = false;
if (duration < 0) {
neg = true; // flag
duration *= -1; // invert
}
auto std_duration = std::chrono::duration<double>(duration);
auto d = std::chrono::duration_cast<days>(std_duration);
std_duration -= d;
auto h = std::chrono::duration_cast<std::chrono::hours>(std_duration);
std_duration -= h;
auto m = std::chrono::duration_cast<std::chrono::minutes>(std_duration);
std_duration -= m;
auto s = std::chrono::duration_cast<std::chrono::seconds>(std_duration);
std_duration -= s;
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(std_duration);
auto dc = d.count();
auto hc = h.count();
auto mc = m.count();
auto sc = s.count();
auto msc = ms.count();
if (neg) {
os << '-';
}
if (dc) {
os << dc << QObject::tr("days");
}
if (hc) {
if (dc)
os << " ";
os << qSetFieldWidth(2) << hc << QObject::tr("h"); // hours
}
if (mc) {
if (dc || hc)
os << " ";
os << qSetFieldWidth(2) << mc << QObject::tr("m"); // minutes
}
if (dc || hc || mc || sc) {
if (dc || hc || mc)
os << " ";
os << qSetFieldWidth(2) << sc << QObject::tr("s"); // seconds
}
if ((msc && (precision > 0)) || !(dc || hc || mc || sc)) {
if (dc || hc || mc || sc)
os << " ";
os << qSetFieldWidth(0) << qSetRealNumberPrecision(precision) << msc << QObject::tr("ms"); // miliseconds
}
os.flush();
return outStr;
}

View File

@ -22,4 +22,13 @@ namespace Time {
QString prettifyDuration(int64_t duration); QString prettifyDuration(int64_t duration);
/**
* @brief Returns a string with short form time duration ie. `2days 1h3m4s56.0ms`.
* miliseconds are only included if `precision` is greater than 0.
*
* @param duration a number of seconds as floating point
* @param precision number of decmial points to display on fractons of a second, defualts to 0.
* @return QString
*/
QString humanReadableDuration(double duration, int precision = 0);
} }

View File

@ -94,20 +94,28 @@ bool MMCZip::mergeZipFiles(QuaZip *into, QFileInfo from, QSet<QString> &containe
return true; return true;
} }
bool MMCZip::compressDirFiles(QuaZip *zip, QString dir, QFileInfoList files) bool MMCZip::compressDirFiles(QuaZip *zip, QString dir, QFileInfoList files, bool followSymlinks)
{ {
QDir directory(dir); QDir directory(dir);
if (!directory.exists()) return false; if (!directory.exists()) return false;
for (auto e : files) { for (auto e : files) {
auto filePath = directory.relativeFilePath(e.absoluteFilePath()); auto filePath = directory.relativeFilePath(e.absoluteFilePath());
if( !JlCompress::compressFile(zip, e.absoluteFilePath(), filePath)) return false; auto srcPath = e.absoluteFilePath();
if (followSymlinks) {
if (e.isSymLink()) {
srcPath = e.symLinkTarget();
} else {
srcPath = e.canonicalFilePath();
}
}
if( !JlCompress::compressFile(zip, srcPath, filePath)) return false;
} }
return true; return true;
} }
bool MMCZip::compressDirFiles(QString fileCompressed, QString dir, QFileInfoList files) bool MMCZip::compressDirFiles(QString fileCompressed, QString dir, QFileInfoList files, bool followSymlinks)
{ {
QuaZip zip(fileCompressed); QuaZip zip(fileCompressed);
QDir().mkpath(QFileInfo(fileCompressed).absolutePath()); QDir().mkpath(QFileInfo(fileCompressed).absolutePath());
@ -116,7 +124,7 @@ bool MMCZip::compressDirFiles(QString fileCompressed, QString dir, QFileInfoList
return false; return false;
} }
auto result = compressDirFiles(&zip, dir, files); auto result = compressDirFiles(&zip, dir, files, followSymlinks);
zip.close(); zip.close();
if(zip.getZipError()!=0) { if(zip.getZipError()!=0) {

View File

@ -59,18 +59,20 @@ namespace MMCZip
* \param zip target archive * \param zip target archive
* \param dir directory that will be compressed (to compress with relative paths) * \param dir directory that will be compressed (to compress with relative paths)
* \param files list of files to compress * \param files list of files to compress
* \param followSymlinks should follow symlinks when compressing file data
* \return true for success or false for failure * \return true for success or false for failure
*/ */
bool compressDirFiles(QuaZip *zip, QString dir, QFileInfoList files); bool compressDirFiles(QuaZip *zip, QString dir, QFileInfoList files, bool followSymlinks = false);
/** /**
* Compress directory, by providing a list of files to compress * Compress directory, by providing a list of files to compress
* \param fileCompressed target archive file * \param fileCompressed target archive file
* \param dir directory that will be compressed (to compress with relative paths) * \param dir directory that will be compressed (to compress with relative paths)
* \param files list of files to compress * \param files list of files to compress
* \param followSymlinks should follow symlinks when compressing file data
* \return true for success or false for failure * \return true for success or false for failure
*/ */
bool compressDirFiles(QString fileCompressed, QString dir, QFileInfoList files); bool compressDirFiles(QString fileCompressed, QString dir, QFileInfoList files, bool followSymlinks = false);
/** /**
* take a source jar, add mods to it, resulting in target jar * take a source jar, add mods to it, resulting in target jar

70
launcher/QVariantUtils.h Normal file
View File

@ -0,0 +1,70 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
* Copyright (C) 2023 flowln <flowlnlnln@gmail.com>
*
* 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, version 3.
*
* 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 <https://www.gnu.org/licenses/>.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QVariant>
#include <QList>
namespace QVariantUtils {
template <typename T>
inline QList<T> toList(QVariant src) {
QVariantList variantList = src.toList();
QList<T> list_t;
list_t.reserve(variantList.size());
for (const QVariant& v : variantList)
{
list_t.append(v.value<T>());
}
return list_t;
}
template <typename T>
inline QVariant fromList(QList<T> val) {
QVariantList variantList;
variantList.reserve(val.size());
for (const T& v : val)
{
variantList.append(v);
}
return variantList;
}
}

View File

@ -53,6 +53,7 @@ ResourceDownloadTask::ResourceDownloadTask(ModPlatform::IndexedPack pack,
m_filesNetJob->addNetAction(Net::Download::makeFile(m_pack_version.downloadUrl, dir.absoluteFilePath(getFilename()))); m_filesNetJob->addNetAction(Net::Download::makeFile(m_pack_version.downloadUrl, dir.absoluteFilePath(getFilename())));
connect(m_filesNetJob.get(), &NetJob::succeeded, this, &ResourceDownloadTask::downloadSucceeded); connect(m_filesNetJob.get(), &NetJob::succeeded, this, &ResourceDownloadTask::downloadSucceeded);
connect(m_filesNetJob.get(), &NetJob::progress, this, &ResourceDownloadTask::downloadProgressChanged); connect(m_filesNetJob.get(), &NetJob::progress, this, &ResourceDownloadTask::downloadProgressChanged);
connect(m_filesNetJob.get(), &NetJob::stepProgress, this, &ResourceDownloadTask::propogateStepProgress);
connect(m_filesNetJob.get(), &NetJob::failed, this, &ResourceDownloadTask::downloadFailed); connect(m_filesNetJob.get(), &NetJob::failed, this, &ResourceDownloadTask::downloadFailed);
addTask(m_filesNetJob); addTask(m_filesNetJob);

View File

@ -1,5 +1,45 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
* Copyright (C) 2023 flowln <flowlnlnln@gmail.com>
*
* 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, version 3.
*
* 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 <https://www.gnu.org/licenses/>.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "StringUtils.h" #include "StringUtils.h"
#include <QRegularExpression>
#include <QUuid>
#include <cmath>
/// If you're wondering where these came from exactly, then know you're not the only one =D /// If you're wondering where these came from exactly, then know you're not the only one =D
/// TAKEN FROM Qt, because it doesn't expose it intelligently /// TAKEN FROM Qt, because it doesn't expose it intelligently
@ -74,3 +114,71 @@ int StringUtils::naturalCompare(const QString& s1, const QString& s2, Qt::CaseSe
// The two strings are the same (02 == 2) so fall back to the normal sort // The two strings are the same (02 == 2) so fall back to the normal sort
return QString::compare(s1, s2, cs); return QString::compare(s1, s2, cs);
} }
QString StringUtils::truncateUrlHumanFriendly(QUrl& url, int max_len, bool hard_limit)
{
auto display_options = QUrl::RemoveUserInfo | QUrl::RemoveFragment | QUrl::NormalizePathSegments;
auto str_url = url.toDisplayString(display_options);
if (str_url.length() <= max_len)
return str_url;
auto url_path_parts = url.path().split('/');
QString last_path_segment = url_path_parts.takeLast();
if (url_path_parts.size() >= 1 && url_path_parts.first().isEmpty())
url_path_parts.removeFirst(); // drop empty first segment (from leading / )
if (url_path_parts.size() >= 1)
url_path_parts.removeLast(); // drop the next to last path segment
auto url_template = QStringLiteral("%1://%2/%3%4");
auto url_compact = url_path_parts.isEmpty()
? url_template.arg(url.scheme(), url.host(), QStringList({ "...", last_path_segment }).join('/'), url.query())
: url_template.arg(url.scheme(), url.host(),
QStringList({ url_path_parts.join('/'), "...", last_path_segment }).join('/'), url.query());
// remove url parts one by one if it's still too long
while (url_compact.length() > max_len && url_path_parts.size() >= 1) {
url_path_parts.removeLast(); // drop the next to last path segment
url_compact = url_path_parts.isEmpty()
? url_template.arg(url.scheme(), url.host(), QStringList({ "...", last_path_segment }).join('/'), url.query())
: url_template.arg(url.scheme(), url.host(),
QStringList({ url_path_parts.join('/'), "...", last_path_segment }).join('/'), url.query());
}
if ((url_compact.length() >= max_len) && hard_limit) {
// still too long, truncate normaly
url_compact = QString(str_url);
auto to_remove = url_compact.length() - max_len + 3;
url_compact.remove(url_compact.length() - to_remove - 1, to_remove);
url_compact.append("...");
}
return url_compact;
}
static const QStringList s_units_si{ "KB", "MB", "GB", "TB" };
static const QStringList s_units_kibi{ "KiB", "MiB", "GiB", "TiB" };
QString StringUtils::humanReadableFileSize(double bytes, bool use_si, int decimal_points)
{
const QStringList units = use_si ? s_units_si : s_units_kibi;
const int scale = use_si ? 1000 : 1024;
int u = -1;
double r = pow(10, decimal_points);
do {
bytes /= scale;
u++;
} while (round(abs(bytes) * r) / r >= scale && u < units.length() - 1);
return QString::number(bytes, 'f', 2) + " " + units[u];
}
QString StringUtils::getRandomAlphaNumeric()
{
return QUuid::createUuid().toString(QUuid::Id128);
}

View File

@ -1,6 +1,43 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
* Copyright (C) 2023 flowln <flowlnlnln@gmail.com>
*
* 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, version 3.
*
* 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 <https://www.gnu.org/licenses/>.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once #pragma once
#include <QString> #include <QString>
#include <QUrl>
namespace StringUtils { namespace StringUtils {
@ -29,4 +66,17 @@ inline QString fromStdString(string s)
#endif #endif
int naturalCompare(const QString& s1, const QString& s2, Qt::CaseSensitivity cs); int naturalCompare(const QString& s1, const QString& s2, Qt::CaseSensitivity cs);
/**
* @brief Truncate a url while keeping its readability py placing the `...` in the middle of the path
* @param url Url to truncate
* @param max_len max lenght of url in charaters
* @param hard_limit if truncating the path can't get the url short enough, truncate it normaly.
*/
QString truncateUrlHumanFriendly(QUrl &url, int max_len, bool hard_limit = false);
QString humanReadableFileSize(double bytes, bool use_si = false, int decimal_points = 1);
QString getRandomAlphaNumeric();
} // namespace StringUtils } // namespace StringUtils

View File

@ -0,0 +1,277 @@
// SPDX-FileCopyrightText: 2022 Rachel Powers <508861+Ryex@users.noreply.github.com>
//
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2022 Rachel Powers <508861+Ryex@users.noreply.github.com>
*
* 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, version 3.
*
* 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 <https://www.gnu.org/licenses/>.
*
*/
#include "FileLink.h"
#include "BuildConfig.h"
#include "StringUtils.h"
#include <iostream>
#include <QAccessible>
#include <QCommandLineParser>
#include <QDebug>
#include <DesktopServices.h>
#include <sys.h>
#if defined Q_OS_WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <stdio.h>
#include <windows.h>
#endif
// Snippet from https://github.com/gulrak/filesystem#using-it-as-single-file-header
#ifdef __APPLE__
#include <Availability.h> // for deployment target to support pre-catalina targets without std::fs
#endif // __APPLE__
#if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || (defined(__cplusplus) && __cplusplus >= 201703L)) && defined(__has_include)
#if __has_include(<filesystem>) && (!defined(__MAC_OS_X_VERSION_MIN_REQUIRED) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 101500)
#define GHC_USE_STD_FS
#include <filesystem>
namespace fs = std::filesystem;
#endif // MacOS min version check
#endif // Other OSes version check
#ifndef GHC_USE_STD_FS
#include <ghc/filesystem.hpp>
namespace fs = ghc::filesystem;
#endif
FileLinkApp::FileLinkApp(int& argc, char** argv) : QCoreApplication(argc, argv), socket(new QLocalSocket(this))
{
#if defined Q_OS_WIN32
// attach the parent console
if (AttachConsole(ATTACH_PARENT_PROCESS)) {
// if attach succeeds, reopen and sync all the i/o
if (freopen("CON", "w", stdout)) {
std::cout.sync_with_stdio();
}
if (freopen("CON", "w", stderr)) {
std::cerr.sync_with_stdio();
}
if (freopen("CON", "r", stdin)) {
std::cin.sync_with_stdio();
}
auto out = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD written;
const char* endline = "\n";
WriteConsole(out, endline, strlen(endline), &written, NULL);
consoleAttached = true;
}
#endif
setOrganizationName(BuildConfig.LAUNCHER_NAME);
setOrganizationDomain(BuildConfig.LAUNCHER_DOMAIN);
setApplicationName(BuildConfig.LAUNCHER_NAME + "FileLink");
setApplicationVersion(BuildConfig.printableVersionString() + "\n" + BuildConfig.GIT_COMMIT);
// Commandline parsing
QCommandLineParser parser;
parser.setApplicationDescription(QObject::tr("a batch MKLINK program for windows to be used with prismlauncher"));
parser.addOptions({ { { "s", "server" }, "Join the specified server on launch", "pipe name" },
{ { "H", "hard" }, "use hard links instead of symbolic", "true/false" } });
parser.addHelpOption();
parser.addVersionOption();
parser.process(arguments());
QString serverToJoin = parser.value("server");
m_useHardLinks = QVariant(parser.value("hard")).toBool();
qDebug() << "link program launched";
if (!serverToJoin.isEmpty()) {
qDebug() << "joining server" << serverToJoin;
joinServer(serverToJoin);
} else {
qDebug() << "no server to join";
exit();
}
}
void FileLinkApp::joinServer(QString server)
{
blockSize = 0;
in.setDevice(&socket);
connect(&socket, &QLocalSocket::connected, this, [&]() { qDebug() << "connected to server"; });
connect(&socket, &QLocalSocket::readyRead, this, &FileLinkApp::readPathPairs);
connect(&socket, &QLocalSocket::errorOccurred, this, [&](QLocalSocket::LocalSocketError socketError) {
switch (socketError) {
case QLocalSocket::ServerNotFoundError:
qDebug()
<< ("The host was not found. Please make sure "
"that the server is running and that the "
"server name is correct.");
break;
case QLocalSocket::ConnectionRefusedError:
qDebug()
<< ("The connection was refused by the peer. "
"Make sure the server is running, "
"and check that the server name "
"is correct.");
break;
case QLocalSocket::PeerClosedError:
qDebug() << ("The connection was closed by the peer. ");
break;
default:
qDebug() << "The following error occurred: " << socket.errorString();
}
});
connect(&socket, &QLocalSocket::disconnected, this, [&]() {
qDebug() << "disconnected from server, should exit";
exit();
});
socket.connectToServer(server);
}
void FileLinkApp::runLink()
{
std::error_code os_err;
qDebug() << "creating links";
for (auto link : m_links_to_make) {
QString src_path = link.src;
QString dst_path = link.dst;
FS::ensureFilePathExists(dst_path);
if (m_useHardLinks) {
qDebug() << "making hard link:" << src_path << "to" << dst_path;
fs::create_hard_link(StringUtils::toStdString(src_path), StringUtils::toStdString(dst_path), os_err);
} else if (fs::is_directory(StringUtils::toStdString(src_path))) {
qDebug() << "making directory_symlink:" << src_path << "to" << dst_path;
fs::create_directory_symlink(StringUtils::toStdString(src_path), StringUtils::toStdString(dst_path), os_err);
} else {
qDebug() << "making symlink:" << src_path << "to" << dst_path;
fs::create_symlink(StringUtils::toStdString(src_path), StringUtils::toStdString(dst_path), os_err);
}
if (os_err) {
qWarning() << "Failed to link files:" << QString::fromStdString(os_err.message());
qDebug() << "Source file:" << src_path;
qDebug() << "Destination file:" << dst_path;
qDebug() << "Error category:" << os_err.category().name();
qDebug() << "Error code:" << os_err.value();
FS::LinkResult result = { src_path, dst_path, QString::fromStdString(os_err.message()), os_err.value() };
m_path_results.append(result);
} else {
FS::LinkResult result = { src_path, dst_path };
m_path_results.append(result);
}
}
sendResults();
qDebug() << "done, should exit soon";
}
void FileLinkApp::sendResults()
{
// construct block of data to send
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
qint32 blocksize = quint32(sizeof(quint32));
for (auto result : m_path_results) {
blocksize += quint32(result.src.size());
blocksize += quint32(result.dst.size());
blocksize += quint32(result.err_msg.size());
blocksize += quint32(sizeof(quint32));
}
qDebug() << "About to write block of size:" << blocksize;
out << blocksize;
out << quint32(m_path_results.length());
for (auto result : m_path_results) {
out << result.src;
out << result.dst;
out << result.err_msg;
out << quint32(result.err_value);
}
qint64 byteswritten = socket.write(block);
bool bytesflushed = socket.flush();
qDebug() << "block flushed" << byteswritten << bytesflushed;
}
void FileLinkApp::readPathPairs()
{
m_links_to_make.clear();
qDebug() << "Reading path pairs from server";
qDebug() << "bytes available" << socket.bytesAvailable();
if (blockSize == 0) {
// Relies on the fact that QDataStream serializes a quint32 into
// sizeof(quint32) bytes
if (socket.bytesAvailable() < (int)sizeof(quint32))
return;
qDebug() << "reading block size";
in >> blockSize;
}
qDebug() << "blocksize is" << blockSize;
qDebug() << "bytes available" << socket.bytesAvailable();
if (socket.bytesAvailable() < blockSize || in.atEnd())
return;
quint32 numLinks;
in >> numLinks;
qDebug() << "numLinks" << numLinks;
for (int i = 0; i < numLinks; i++) {
FS::LinkPair pair;
in >> pair.src;
in >> pair.dst;
qDebug() << "link" << pair.src << "to" << pair.dst;
m_links_to_make.append(pair);
}
runLink();
}
FileLinkApp::~FileLinkApp()
{
qDebug() << "link program shutting down";
// Shut down logger by setting the logger function to nothing
qInstallMessageHandler(nullptr);
#if defined Q_OS_WIN32
// Detach from Windows console
if (consoleAttached) {
fclose(stdout);
fclose(stdin);
fclose(stderr);
FreeConsole();
}
#endif
}

View File

@ -0,0 +1,67 @@
// SPDX-FileCopyrightText: 2022 Rachel Powers <508861+Ryex@users.noreply.github.com>
//
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2022 Rachel Powers <508861+Ryex@users.noreply.github.com>
*
* 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, version 3.
*
* 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 <https://www.gnu.org/licenses/>.
*
*/
#pragma once
#include <QtCore>
#include <QApplication>
#include <QDataStream>
#include <QDateTime>
#include <QDebug>
#include <QFlag>
#include <QIcon>
#include <QLocalSocket>
#include <QUrl>
#include <memory>
#define PRISM_EXTERNAL_EXE
#include "FileSystem.h"
class FileLinkApp : public QCoreApplication {
// friends for the purpose of limiting access to deprecated stuff
Q_OBJECT
public:
FileLinkApp(int& argc, char** argv);
virtual ~FileLinkApp();
private:
void joinServer(QString server);
void readPathPairs();
void runLink();
void sendResults();
bool m_useHardLinks = false;
QDateTime m_startTime;
QLocalSocket socket;
QDataStream in;
quint32 blockSize;
QList<FS::LinkPair> m_links_to_make;
QList<FS::LinkResult> m_path_results;
#if defined Q_OS_WIN32
// used on Windows to attach the standard IO streams
bool consoleAttached = false;
#endif
};

View File

@ -0,0 +1,28 @@
<?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>
</windowsSettings>
</application>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<!-- Windows 10, Windows 11 -->
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>
<!-- Windows 8.1 -->
<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/>
<!-- Windows 8 -->
<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}"/>
<!-- Windows 7 -->
<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/>
</application>
</compatibility>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges>
<requestedExecutionLevel
level="requireAdministrator"
uiAccess="false"/>
</requestedPrivileges>
</security>
</trustInfo>
</assembly>

View File

@ -0,0 +1,30 @@
// SPDX-FileCopyrightText: 2022 Rachel Powers <508861+Ryex@users.noreply.github.com>
//
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2022 Rachel Powers <508861+Ryex@users.noreply.github.com>
*
* 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, version 3.
*
* 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 <https://www.gnu.org/licenses/>.
*
*/
#include "FileLink.h"
int main(int argc, char* argv[])
{
FileLinkApp ldh(argc, argv);
return ldh.exec();
}

View File

@ -28,7 +28,9 @@ void Update::executeTask()
{ {
connect(m_updateTask.get(), &Task::finished, this, &Update::updateFinished); connect(m_updateTask.get(), &Task::finished, this, &Update::updateFinished);
connect(m_updateTask.get(), &Task::progress, this, &Update::setProgress); connect(m_updateTask.get(), &Task::progress, this, &Update::setProgress);
connect(m_updateTask.get(), &Task::stepProgress, this, &Update::propogateStepProgress);
connect(m_updateTask.get(), &Task::status, this, &Update::setStatus); connect(m_updateTask.get(), &Task::status, this, &Update::setStatus);
connect(m_updateTask.get(), &Task::details, this, &Update::setDetails);
emit progressReportingRequest(); emit progressReportingRequest();
return; return;
} }

View File

@ -925,7 +925,10 @@ QString MinecraftInstance::getStatusbarDescription()
if(m_settings->get("ShowGameTime").toBool()) if(m_settings->get("ShowGameTime").toBool())
{ {
if (lastTimePlayed() > 0) { if (lastTimePlayed() > 0) {
description.append(tr(", last played for %1").arg(Time::prettifyDuration(lastTimePlayed()))); QDateTime lastLaunchTime = QDateTime::fromMSecsSinceEpoch(lastLaunch());
description.append(tr(", last played on %1 for %2")
.arg(QLocale().toString(lastLaunchTime, QLocale::ShortFormat))
.arg(Time::prettifyDuration(lastTimePlayed())));
} }
if (totalTimePlayed() > 0) { if (totalTimePlayed() > 0) {
@ -1111,7 +1114,7 @@ std::shared_ptr<ModFolderModel> MinecraftInstance::loaderModList() const
if (!m_loader_mod_list) if (!m_loader_mod_list)
{ {
bool is_indexed = !APPLICATION->settings()->get("ModMetadataDisabled").toBool(); bool is_indexed = !APPLICATION->settings()->get("ModMetadataDisabled").toBool();
m_loader_mod_list.reset(new ModFolderModel(modsRoot(), is_indexed)); m_loader_mod_list.reset(new ModFolderModel(modsRoot(), shared_from_this(), is_indexed));
m_loader_mod_list->disableInteraction(isRunning()); m_loader_mod_list->disableInteraction(isRunning());
connect(this, &BaseInstance::runningStatusChanged, m_loader_mod_list.get(), &ModFolderModel::disableInteraction); connect(this, &BaseInstance::runningStatusChanged, m_loader_mod_list.get(), &ModFolderModel::disableInteraction);
} }
@ -1123,7 +1126,7 @@ std::shared_ptr<ModFolderModel> MinecraftInstance::coreModList() const
if (!m_core_mod_list) if (!m_core_mod_list)
{ {
bool is_indexed = !APPLICATION->settings()->get("ModMetadataDisabled").toBool(); bool is_indexed = !APPLICATION->settings()->get("ModMetadataDisabled").toBool();
m_core_mod_list.reset(new ModFolderModel(coreModsDir(), is_indexed)); m_core_mod_list.reset(new ModFolderModel(coreModsDir(), shared_from_this(), is_indexed));
m_core_mod_list->disableInteraction(isRunning()); m_core_mod_list->disableInteraction(isRunning());
connect(this, &BaseInstance::runningStatusChanged, m_core_mod_list.get(), &ModFolderModel::disableInteraction); connect(this, &BaseInstance::runningStatusChanged, m_core_mod_list.get(), &ModFolderModel::disableInteraction);
} }
@ -1135,7 +1138,7 @@ std::shared_ptr<ModFolderModel> MinecraftInstance::nilModList() const
if (!m_nil_mod_list) if (!m_nil_mod_list)
{ {
bool is_indexed = !APPLICATION->settings()->get("ModMetadataDisabled").toBool(); bool is_indexed = !APPLICATION->settings()->get("ModMetadataDisabled").toBool();
m_nil_mod_list.reset(new ModFolderModel(nilModsDir(), is_indexed, false)); m_nil_mod_list.reset(new ModFolderModel(nilModsDir(), shared_from_this(), is_indexed, false));
m_nil_mod_list->disableInteraction(isRunning()); m_nil_mod_list->disableInteraction(isRunning());
connect(this, &BaseInstance::runningStatusChanged, m_nil_mod_list.get(), &ModFolderModel::disableInteraction); connect(this, &BaseInstance::runningStatusChanged, m_nil_mod_list.get(), &ModFolderModel::disableInteraction);
} }
@ -1146,7 +1149,7 @@ std::shared_ptr<ResourcePackFolderModel> MinecraftInstance::resourcePackList() c
{ {
if (!m_resource_pack_list) if (!m_resource_pack_list)
{ {
m_resource_pack_list.reset(new ResourcePackFolderModel(resourcePacksDir())); m_resource_pack_list.reset(new ResourcePackFolderModel(resourcePacksDir(), shared_from_this()));
} }
return m_resource_pack_list; return m_resource_pack_list;
} }
@ -1155,7 +1158,7 @@ std::shared_ptr<TexturePackFolderModel> MinecraftInstance::texturePackList() con
{ {
if (!m_texture_pack_list) if (!m_texture_pack_list)
{ {
m_texture_pack_list.reset(new TexturePackFolderModel(texturePacksDir())); m_texture_pack_list.reset(new TexturePackFolderModel(texturePacksDir(), shared_from_this()));
} }
return m_texture_pack_list; return m_texture_pack_list;
} }
@ -1164,7 +1167,7 @@ std::shared_ptr<ShaderPackFolderModel> MinecraftInstance::shaderPackList() const
{ {
if (!m_shader_pack_list) if (!m_shader_pack_list)
{ {
m_shader_pack_list.reset(new ShaderPackFolderModel(shaderPacksDir())); m_shader_pack_list.reset(new ShaderPackFolderModel(shaderPacksDir(), shared_from_this()));
} }
return m_shader_pack_list; return m_shader_pack_list;
} }
@ -1173,7 +1176,7 @@ std::shared_ptr<WorldList> MinecraftInstance::worldList() const
{ {
if (!m_world_list) if (!m_world_list)
{ {
m_world_list.reset(new WorldList(worldDir())); m_world_list.reset(new WorldList(worldDir(), shared_from_this()));
} }
return m_world_list; return m_world_list;
} }

View File

@ -22,6 +22,7 @@ void MinecraftLoadAndCheck::executeTask()
connect(m_task.get(), &Task::failed, this, &MinecraftLoadAndCheck::subtaskFailed); connect(m_task.get(), &Task::failed, this, &MinecraftLoadAndCheck::subtaskFailed);
connect(m_task.get(), &Task::aborted, this, [this]{ subtaskFailed(tr("Aborted")); }); connect(m_task.get(), &Task::aborted, this, [this]{ subtaskFailed(tr("Aborted")); });
connect(m_task.get(), &Task::progress, this, &MinecraftLoadAndCheck::progress); connect(m_task.get(), &Task::progress, this, &MinecraftLoadAndCheck::progress);
connect(m_task.get(), &Task::stepProgress, this, &MinecraftLoadAndCheck::propogateStepProgress);
connect(m_task.get(), &Task::status, this, &MinecraftLoadAndCheck::setStatus); connect(m_task.get(), &Task::status, this, &MinecraftLoadAndCheck::setStatus);
} }

View File

@ -100,7 +100,9 @@ void MinecraftUpdate::next()
disconnect(task.get(), &Task::failed, this, &MinecraftUpdate::subtaskFailed); disconnect(task.get(), &Task::failed, this, &MinecraftUpdate::subtaskFailed);
disconnect(task.get(), &Task::aborted, this, &Task::abort); disconnect(task.get(), &Task::aborted, this, &Task::abort);
disconnect(task.get(), &Task::progress, this, &MinecraftUpdate::progress); disconnect(task.get(), &Task::progress, this, &MinecraftUpdate::progress);
disconnect(task.get(), &Task::stepProgress, this, &MinecraftUpdate::propogateStepProgress);
disconnect(task.get(), &Task::status, this, &MinecraftUpdate::setStatus); disconnect(task.get(), &Task::status, this, &MinecraftUpdate::setStatus);
disconnect(task.get(), &Task::details, this, &MinecraftUpdate::setDetails);
} }
if(m_currentTask == m_tasks.size()) if(m_currentTask == m_tasks.size())
{ {
@ -118,7 +120,9 @@ void MinecraftUpdate::next()
connect(task.get(), &Task::failed, this, &MinecraftUpdate::subtaskFailed); connect(task.get(), &Task::failed, this, &MinecraftUpdate::subtaskFailed);
connect(task.get(), &Task::aborted, this, &Task::abort); connect(task.get(), &Task::aborted, this, &Task::abort);
connect(task.get(), &Task::progress, this, &MinecraftUpdate::progress); connect(task.get(), &Task::progress, this, &MinecraftUpdate::progress);
connect(task.get(), &Task::stepProgress, this, &MinecraftUpdate::propogateStepProgress);
connect(task.get(), &Task::status, this, &MinecraftUpdate::setStatus); connect(task.get(), &Task::status, this, &MinecraftUpdate::setStatus);
connect(task.get(), &Task::details, this, &MinecraftUpdate::setDetails);
// if the task is already running, do not start it again // if the task is already running, do not start it again
if(!task->isRunning()) if(!task->isRunning())
{ {

View File

@ -56,6 +56,8 @@
#include <optional> #include <optional>
#include "FileSystem.h"
using std::optional; using std::optional;
using std::nullopt; using std::nullopt;
@ -567,3 +569,25 @@ bool World::operator==(const World &other) const
{ {
return is_valid == other.is_valid && folderName() == other.folderName(); return is_valid == other.is_valid && folderName() == other.folderName();
} }
bool World::isSymLinkUnder(const QString& instPath) const
{
if (isSymLink())
return true;
auto instDir = QDir(instPath);
auto relAbsPath = instDir.relativeFilePath(m_containerFile.absoluteFilePath());
auto relCanonPath = instDir.relativeFilePath(m_containerFile.canonicalFilePath());
return relAbsPath != relCanonPath;
}
bool World::isMoreThanOneHardLink() const
{
if (m_containerFile.isDir())
{
return FS::hardLinkCount(QDir(m_containerFile.absoluteFilePath()).filePath("level.dat")) > 1;
}
return FS::hardLinkCount(m_containerFile.absoluteFilePath()) > 1;
}

View File

@ -95,6 +95,21 @@ public:
// WEAK compare operator - used for replacing worlds // WEAK compare operator - used for replacing worlds
bool operator==(const World &other) const; bool operator==(const World &other) const;
[[nodiscard]] auto isSymLink() const -> bool{ return m_containerFile.isSymLink(); }
/**
* @brief Take a instance path, checks if the file pointed to by the resource is a symlink or under a symlink in that instance
*
* @param instPath path to an instance directory
* @return true
* @return false
*/
[[nodiscard]] bool isSymLinkUnder(const QString& instPath) const;
[[nodiscard]] bool isMoreThanOneHardLink() const;
QString canonicalFilePath() const { return m_containerFile.canonicalFilePath(); }
private: private:
void readFromZip(const QFileInfo &file); void readFromZip(const QFileInfo &file);
void readFromFS(const QFileInfo &file); void readFromFS(const QFileInfo &file);

View File

@ -45,8 +45,8 @@
#include <QFileSystemWatcher> #include <QFileSystemWatcher>
#include <QDebug> #include <QDebug>
WorldList::WorldList(const QString &dir) WorldList::WorldList(const QString &dir, std::shared_ptr<const BaseInstance> instance)
: QAbstractListModel(), m_dir(dir) : QAbstractListModel(), m_instance(instance), m_dir(dir)
{ {
FS::ensureFolderPathExists(m_dir.absolutePath()); FS::ensureFolderPathExists(m_dir.absolutePath());
m_dir.setFilter(QDir::Readable | QDir::NoDotAndDotDot | QDir::Files | QDir::Dirs); m_dir.setFilter(QDir::Readable | QDir::NoDotAndDotDot | QDir::Files | QDir::Dirs);
@ -127,6 +127,10 @@ bool WorldList::isValid()
return m_dir.exists() && m_dir.isReadable(); return m_dir.exists() && m_dir.isReadable();
} }
QString WorldList::instDirPath() const {
return QFileInfo(m_instance->instanceRoot()).absoluteFilePath();
}
bool WorldList::deleteWorld(int index) bool WorldList::deleteWorld(int index)
{ {
if (index >= worlds.size() || index < 0) if (index >= worlds.size() || index < 0)
@ -172,7 +176,7 @@ bool WorldList::resetIcon(int row)
int WorldList::columnCount(const QModelIndex &parent) const int WorldList::columnCount(const QModelIndex &parent) const
{ {
return parent.isValid()? 0 : 4; return parent.isValid()? 0 : 5;
} }
QVariant WorldList::data(const QModelIndex &index, int role) const QVariant WorldList::data(const QModelIndex &index, int role) const
@ -206,6 +210,14 @@ QVariant WorldList::data(const QModelIndex &index, int role) const
case SizeColumn: case SizeColumn:
return locale.formattedDataSize(world.bytes()); return locale.formattedDataSize(world.bytes());
case InfoColumn:
if (world.isSymLinkUnder(instDirPath())) {
return tr("This world is symbolically linked from elsewhere.");
}
if (world.isMoreThanOneHardLink()) {
return tr("\nThis world is hard linked elsewhere.");
}
return "";
default: default:
return QVariant(); return QVariant();
} }
@ -222,6 +234,15 @@ QVariant WorldList::data(const QModelIndex &index, int role) const
case Qt::ToolTipRole: case Qt::ToolTipRole:
{ {
if (column == InfoColumn) {
if (world.isSymLinkUnder(instDirPath())) {
return tr("Warning: This world is symbolically linked from elsewhere. Editing it will also change the original."
"\nCanonical Path: %1").arg(world.canonicalFilePath());
}
if (world.isMoreThanOneHardLink()) {
return tr("Warning: This world is hard linked elsewhere. Editing it will also change the original.");
}
}
return world.folderName(); return world.folderName();
} }
case ObjectRole: case ObjectRole:
@ -273,6 +294,9 @@ QVariant WorldList::headerData(int section, Qt::Orientation orientation, int rol
case SizeColumn: case SizeColumn:
//: World size on disk //: World size on disk
return tr("Size"); return tr("Size");
case InfoColumn:
//: special warnings?
return tr("Info");
default: default:
return QVariant(); return QVariant();
} }
@ -288,6 +312,8 @@ QVariant WorldList::headerData(int section, Qt::Orientation orientation, int rol
return tr("Date and time the world was last played."); return tr("Date and time the world was last played.");
case SizeColumn: case SizeColumn:
return tr("Size of the world on disk."); return tr("Size of the world on disk.");
case InfoColumn:
return tr("Information and warnings about the world.");
default: default:
return QVariant(); return QVariant();
} }

View File

@ -21,6 +21,7 @@
#include <QAbstractListModel> #include <QAbstractListModel>
#include <QMimeData> #include <QMimeData>
#include "minecraft/World.h" #include "minecraft/World.h"
#include "BaseInstance.h"
class QFileSystemWatcher; class QFileSystemWatcher;
@ -33,7 +34,8 @@ public:
NameColumn, NameColumn,
GameModeColumn, GameModeColumn,
LastPlayedColumn, LastPlayedColumn,
SizeColumn SizeColumn,
InfoColumn
}; };
enum Roles enum Roles
@ -48,7 +50,7 @@ public:
IconFileRole IconFileRole
}; };
WorldList(const QString &dir); WorldList(const QString &dir, std::shared_ptr<const BaseInstance> instance);
virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
@ -112,6 +114,8 @@ public:
return m_dir; return m_dir;
} }
QString instDirPath() const;
const QList<World> &allWorlds() const const QList<World> &allWorlds() const
{ {
return worlds; return worlds;
@ -124,6 +128,7 @@ signals:
void changed(); void changed();
protected: protected:
std::shared_ptr<const BaseInstance> m_instance;
QFileSystemWatcher *m_watcher; QFileSystemWatcher *m_watcher;
bool is_watching; bool is_watching;
QDir m_dir; QDir m_dir;

View File

@ -39,18 +39,23 @@
#include <FileSystem.h> #include <FileSystem.h>
#include <QDebug> #include <QDebug>
#include <QFileSystemWatcher> #include <QFileSystemWatcher>
#include <QIcon>
#include <QMimeData> #include <QMimeData>
#include <QString> #include <QString>
#include <QStyle>
#include <QThreadPool> #include <QThreadPool>
#include <QUrl> #include <QUrl>
#include <QUuid> #include <QUuid>
#include <algorithm> #include <algorithm>
#include "Application.h"
#include "minecraft/mod/tasks/LocalModParseTask.h" #include "minecraft/mod/tasks/LocalModParseTask.h"
#include "minecraft/mod/tasks/ModFolderLoadTask.h" #include "minecraft/mod/tasks/ModFolderLoadTask.h"
#include "modplatform/ModIndex.h" #include "modplatform/ModIndex.h"
ModFolderModel::ModFolderModel(const QString &dir, bool is_indexed, bool create_dir) : ResourceFolderModel(QDir(dir), nullptr, create_dir), m_is_indexed(is_indexed) ModFolderModel::ModFolderModel(const QString& dir, std::shared_ptr<const BaseInstance> instance, bool is_indexed, bool create_dir)
: ResourceFolderModel(QDir(dir), instance, nullptr, create_dir), m_is_indexed(is_indexed)
{ {
m_column_sort_keys = { SortType::ENABLED, SortType::NAME, SortType::VERSION, SortType::DATE, SortType::PROVIDER }; m_column_sort_keys = { SortType::ENABLED, SortType::NAME, SortType::VERSION, SortType::DATE, SortType::PROVIDER };
} }
@ -97,8 +102,25 @@ QVariant ModFolderModel::data(const QModelIndex &index, int role) const
} }
case Qt::ToolTipRole: case Qt::ToolTipRole:
if (column == NAME_COLUMN) {
if (at(row)->isSymLinkUnder(instDirPath())) {
return m_resources[row]->internal_id() +
tr("\nWarning: This resource is symbolically linked from elsewhere. Editing it will also change the original."
"\nCanonical Path: %1")
.arg(at(row)->fileinfo().canonicalFilePath());
}
if (at(row)->isMoreThanOneHardLink()) {
return m_resources[row]->internal_id() +
tr("\nWarning: This resource is hard linked elsewhere. Editing it will also change the original.");
}
}
return m_resources[row]->internal_id(); return m_resources[row]->internal_id();
case Qt::DecorationRole: {
if (column == NAME_COLUMN && (at(row)->isSymLinkUnder(instDirPath()) || at(row)->isMoreThanOneHardLink()))
return APPLICATION->getThemedIcon("status-yellow");
return {};
}
case Qt::CheckStateRole: case Qt::CheckStateRole:
switch (column) switch (column)
{ {

View File

@ -75,7 +75,7 @@ public:
Enable, Enable,
Toggle Toggle
}; };
ModFolderModel(const QString &dir, bool is_indexed = false, bool create_dir = true); ModFolderModel(const QString &dir, std::shared_ptr<const BaseInstance> instance, bool is_indexed = false, bool create_dir = true);
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;

View File

@ -1,6 +1,8 @@
#include "Resource.h" #include "Resource.h"
#include <QRegularExpression> #include <QRegularExpression>
#include <QFileInfo>
#include "FileSystem.h" #include "FileSystem.h"
@ -152,3 +154,21 @@ bool Resource::destroy()
return FS::deletePath(m_file_info.filePath()); return FS::deletePath(m_file_info.filePath());
} }
bool Resource::isSymLinkUnder(const QString& instPath) const
{
if (isSymLink())
return true;
auto instDir = QDir(instPath);
auto relAbsPath = instDir.relativeFilePath(m_file_info.absoluteFilePath());
auto relCanonPath = instDir.relativeFilePath(m_file_info.canonicalFilePath());
return relAbsPath != relCanonPath;
}
bool Resource::isMoreThanOneHardLink() const
{
return FS::hardLinkCount(m_file_info.absoluteFilePath()) > 1;
}

View File

@ -94,6 +94,19 @@ class Resource : public QObject {
// Delete all files of this resource. // Delete all files of this resource.
bool destroy(); bool destroy();
[[nodiscard]] auto isSymLink() const -> bool { return m_file_info.isSymLink(); }
/**
* @brief Take a instance path, checks if the file pointed to by the resource is a symlink or under a symlink in that instance
*
* @param instPath path to an instance directory
* @return true
* @return false
*/
[[nodiscard]] bool isSymLinkUnder(const QString& instPath) const;
[[nodiscard]] bool isMoreThanOneHardLink() const;
protected: protected:
/* The file corresponding to this resource. */ /* The file corresponding to this resource. */
QFileInfo m_file_info; QFileInfo m_file_info;

View File

@ -2,17 +2,22 @@
#include <QCoreApplication> #include <QCoreApplication>
#include <QDebug> #include <QDebug>
#include <QFileInfo>
#include <QIcon>
#include <QMimeData> #include <QMimeData>
#include <QStyle>
#include <QThreadPool> #include <QThreadPool>
#include <QUrl> #include <QUrl>
#include "Application.h"
#include "FileSystem.h" #include "FileSystem.h"
#include "minecraft/mod/tasks/BasicFolderLoadTask.h" #include "minecraft/mod/tasks/BasicFolderLoadTask.h"
#include "tasks/Task.h" #include "tasks/Task.h"
ResourceFolderModel::ResourceFolderModel(QDir dir, QObject* parent, bool create_dir) : QAbstractListModel(parent), m_dir(dir), m_watcher(this) ResourceFolderModel::ResourceFolderModel(QDir dir, std::shared_ptr<const BaseInstance> instance, QObject* parent, bool create_dir)
: QAbstractListModel(parent), m_dir(dir), m_instance(instance), m_watcher(this)
{ {
if (create_dir) { if (create_dir) {
FS::ensureFolderPathExists(m_dir.absolutePath()); FS::ensureFolderPathExists(m_dir.absolutePath());
@ -22,7 +27,7 @@ ResourceFolderModel::ResourceFolderModel(QDir dir, QObject* parent, bool create_
m_dir.setSorting(QDir::Name | QDir::IgnoreCase | QDir::LocaleAware); m_dir.setSorting(QDir::Name | QDir::IgnoreCase | QDir::LocaleAware);
connect(&m_watcher, &QFileSystemWatcher::directoryChanged, this, &ResourceFolderModel::directoryChanged); connect(&m_watcher, &QFileSystemWatcher::directoryChanged, this, &ResourceFolderModel::directoryChanged);
connect(&m_helper_thread_task, &ConcurrentTask::finished, this, [this]{ m_helper_thread_task.clear(); }); connect(&m_helper_thread_task, &ConcurrentTask::finished, this, [this] { m_helper_thread_task.clear(); });
} }
ResourceFolderModel::~ResourceFolderModel() ResourceFolderModel::~ResourceFolderModel()
@ -417,7 +422,26 @@ QVariant ResourceFolderModel::data(const QModelIndex& index, int role) const
return {}; return {};
} }
case Qt::ToolTipRole: case Qt::ToolTipRole:
if (column == NAME_COLUMN) {
if (at(row).isSymLinkUnder(instDirPath())) {
return m_resources[row]->internal_id() +
tr("\nWarning: This resource is symbolically linked from elsewhere. Editing it will also change the original."
"\nCanonical Path: %1")
.arg(at(row).fileinfo().canonicalFilePath());;
}
if (at(row).isMoreThanOneHardLink()) {
return m_resources[row]->internal_id() +
tr("\nWarning: This resource is hard linked elsewhere. Editing it will also change the original.");
}
}
return m_resources[row]->internal_id(); return m_resources[row]->internal_id();
case Qt::DecorationRole: {
if (column == NAME_COLUMN && (at(row).isSymLinkUnder(instDirPath()) || at(row).isMoreThanOneHardLink()))
return APPLICATION->getThemedIcon("status-yellow");
return {};
}
case Qt::CheckStateRole: case Qt::CheckStateRole:
switch (column) { switch (column) {
case ACTIVE_COLUMN: case ACTIVE_COLUMN:
@ -531,3 +555,7 @@ void ResourceFolderModel::enableInteraction(bool enabled)
return (compare_result.first < 0); return (compare_result.first < 0);
return (compare_result.first > 0); return (compare_result.first > 0);
} }
QString ResourceFolderModel::instDirPath() const {
return QFileInfo(m_instance->instanceRoot()).absoluteFilePath();
}

View File

@ -9,6 +9,8 @@
#include "Resource.h" #include "Resource.h"
#include "BaseInstance.h"
#include "tasks/Task.h" #include "tasks/Task.h"
#include "tasks/ConcurrentTask.h" #include "tasks/ConcurrentTask.h"
@ -24,7 +26,7 @@ class QSortFilterProxyModel;
class ResourceFolderModel : public QAbstractListModel { class ResourceFolderModel : public QAbstractListModel {
Q_OBJECT Q_OBJECT
public: public:
ResourceFolderModel(QDir, QObject* parent = nullptr, bool create_dir = true); ResourceFolderModel(QDir, std::shared_ptr<const BaseInstance>, QObject* parent = nullptr, bool create_dir = true);
~ResourceFolderModel() override; ~ResourceFolderModel() override;
/** Starts watching the paths for changes. /** Starts watching the paths for changes.
@ -125,6 +127,8 @@ class ResourceFolderModel : public QAbstractListModel {
[[nodiscard]] bool lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const override; [[nodiscard]] bool lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const override;
}; };
QString instDirPath() const;
public slots: public slots:
void enableInteraction(bool enabled); void enableInteraction(bool enabled);
void disableInteraction(bool disabled) { enableInteraction(!disabled); } void disableInteraction(bool disabled) { enableInteraction(!disabled); }
@ -187,6 +191,7 @@ class ResourceFolderModel : public QAbstractListModel {
bool m_can_interact = true; bool m_can_interact = true;
QDir m_dir; QDir m_dir;
std::shared_ptr<const BaseInstance> m_instance;
QFileSystemWatcher m_watcher; QFileSystemWatcher m_watcher;
bool m_is_watching = false; bool m_is_watching = false;

View File

@ -36,12 +36,17 @@
#include "ResourcePackFolderModel.h" #include "ResourcePackFolderModel.h"
#include <QIcon>
#include <QStyle>
#include "Application.h"
#include "Version.h" #include "Version.h"
#include "minecraft/mod/tasks/BasicFolderLoadTask.h" #include "minecraft/mod/tasks/BasicFolderLoadTask.h"
#include "minecraft/mod/tasks/LocalResourcePackParseTask.h" #include "minecraft/mod/tasks/LocalResourcePackParseTask.h"
ResourcePackFolderModel::ResourcePackFolderModel(const QString& dir) : ResourceFolderModel(QDir(dir)) ResourcePackFolderModel::ResourcePackFolderModel(const QString& dir, std::shared_ptr<const BaseInstance> instance)
: ResourceFolderModel(QDir(dir), instance)
{ {
m_column_sort_keys = { SortType::ENABLED, SortType::NAME, SortType::PACK_FORMAT, SortType::DATE }; m_column_sort_keys = { SortType::ENABLED, SortType::NAME, SortType::PACK_FORMAT, SortType::DATE };
} }
@ -78,12 +83,29 @@ QVariant ResourcePackFolderModel::data(const QModelIndex& index, int role) const
default: default:
return {}; return {};
} }
case Qt::DecorationRole: {
if (column == NAME_COLUMN && (at(row)->isSymLinkUnder(instDirPath()) || at(row)->isMoreThanOneHardLink()))
return APPLICATION->getThemedIcon("status-yellow");
return {};
}
case Qt::ToolTipRole: { case Qt::ToolTipRole: {
if (column == PackFormatColumn) { if (column == PackFormatColumn) {
//: The string being explained by this is in the format: ID (Lower version - Upper version) //: The string being explained by this is in the format: ID (Lower version - Upper version)
return tr("The resource pack format ID, as well as the Minecraft versions it was designed for."); return tr("The resource pack format ID, as well as the Minecraft versions it was designed for.");
} }
if (column == NAME_COLUMN) {
if (at(row)->isSymLinkUnder(instDirPath())) {
return m_resources[row]->internal_id() +
tr("\nWarning: This resource is symbolically linked from elsewhere. Editing it will also change the original."
"\nCanonical Path: %1")
.arg(at(row)->fileinfo().canonicalFilePath());;
}
if (at(row)->isMoreThanOneHardLink()) {
return m_resources[row]->internal_id() +
tr("\nWarning: This resource is hard linked elsewhere. Editing it will also change the original.");
}
}
return m_resources[row]->internal_id(); return m_resources[row]->internal_id();
} }
case Qt::CheckStateRole: case Qt::CheckStateRole:

View File

@ -17,7 +17,7 @@ public:
NUM_COLUMNS NUM_COLUMNS
}; };
explicit ResourcePackFolderModel(const QString &dir); explicit ResourcePackFolderModel(const QString &dir, std::shared_ptr<const BaseInstance> instance);
[[nodiscard]] QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; [[nodiscard]] QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;

View File

@ -6,5 +6,7 @@ class ShaderPackFolderModel : public ResourceFolderModel {
Q_OBJECT Q_OBJECT
public: public:
explicit ShaderPackFolderModel(const QString& dir) : ResourceFolderModel(QDir(dir)) {} explicit ShaderPackFolderModel(const QString& dir, std::shared_ptr<const BaseInstance> instance)
: ResourceFolderModel(QDir(dir), instance)
{}
}; };

View File

@ -39,7 +39,9 @@
#include "minecraft/mod/tasks/BasicFolderLoadTask.h" #include "minecraft/mod/tasks/BasicFolderLoadTask.h"
#include "minecraft/mod/tasks/LocalTexturePackParseTask.h" #include "minecraft/mod/tasks/LocalTexturePackParseTask.h"
TexturePackFolderModel::TexturePackFolderModel(const QString &dir) : ResourceFolderModel(QDir(dir)) {} TexturePackFolderModel::TexturePackFolderModel(const QString& dir, std::shared_ptr<const BaseInstance> instance)
: ResourceFolderModel(QDir(dir), instance)
{}
Task* TexturePackFolderModel::createUpdateTask() Task* TexturePackFolderModel::createUpdateTask()
{ {

View File

@ -43,7 +43,7 @@ class TexturePackFolderModel : public ResourceFolderModel
Q_OBJECT Q_OBJECT
public: public:
explicit TexturePackFolderModel(const QString &dir); explicit TexturePackFolderModel(const QString &dir, std::shared_ptr<const BaseInstance> instance);
[[nodiscard]] Task* createUpdateTask() override; [[nodiscard]] Task* createUpdateTask() override;
[[nodiscard]] Task* createParseTask(Resource&) override; [[nodiscard]] Task* createParseTask(Resource&) override;
}; };

View File

@ -242,7 +242,7 @@ ModDetails ReadQuiltModInfo(QByteArray contents)
return details; return details;
} }
ModDetails ReadForgeInfo(QByteArray contents) ModDetails ReadForgeInfo(QString fileName)
{ {
ModDetails details; ModDetails details;
// Read the data // Read the data
@ -250,7 +250,7 @@ ModDetails ReadForgeInfo(QByteArray contents)
details.mod_id = "Forge"; details.mod_id = "Forge";
details.homeurl = "http://www.minecraftforge.net/forum/"; details.homeurl = "http://www.minecraftforge.net/forum/";
INIFile ini; INIFile ini;
if (!ini.loadFile(contents)) if (!ini.loadFile(fileName))
return details; return details;
QString major = ini.get("forge.major.number", "0").toString(); QString major = ini.get("forge.major.number", "0").toString();
@ -422,7 +422,7 @@ bool processZIP(Mod& mod, ProcessingLevel level)
return false; return false;
} }
details = ReadForgeInfo(file.readAll()); details = ReadForgeInfo(file.getFileName());
file.close(); file.close();
zip.close(); zip.close();

View File

@ -45,6 +45,7 @@ void AssetUpdateTask::executeTask()
connect(downloadJob.get(), &NetJob::failed, this, &AssetUpdateTask::assetIndexFailed); connect(downloadJob.get(), &NetJob::failed, this, &AssetUpdateTask::assetIndexFailed);
connect(downloadJob.get(), &NetJob::aborted, this, [this]{ emitFailed(tr("Aborted")); }); connect(downloadJob.get(), &NetJob::aborted, this, [this]{ emitFailed(tr("Aborted")); });
connect(downloadJob.get(), &NetJob::progress, this, &AssetUpdateTask::progress); connect(downloadJob.get(), &NetJob::progress, this, &AssetUpdateTask::progress);
connect(downloadJob.get(), &NetJob::stepProgress, this, &AssetUpdateTask::propogateStepProgress);
qDebug() << m_inst->name() << ": Starting asset index download"; qDebug() << m_inst->name() << ": Starting asset index download";
downloadJob->start(); downloadJob->start();
@ -83,6 +84,7 @@ void AssetUpdateTask::assetIndexFinished()
connect(downloadJob.get(), &NetJob::failed, this, &AssetUpdateTask::assetsFailed); connect(downloadJob.get(), &NetJob::failed, this, &AssetUpdateTask::assetsFailed);
connect(downloadJob.get(), &NetJob::aborted, this, [this]{ emitFailed(tr("Aborted")); }); connect(downloadJob.get(), &NetJob::aborted, this, [this]{ emitFailed(tr("Aborted")); });
connect(downloadJob.get(), &NetJob::progress, this, &AssetUpdateTask::progress); connect(downloadJob.get(), &NetJob::progress, this, &AssetUpdateTask::progress);
connect(downloadJob.get(), &NetJob::stepProgress, this, &AssetUpdateTask::propogateStepProgress);
downloadJob->start(); downloadJob->start();
return; return;
} }

View File

@ -75,6 +75,7 @@ void FMLLibrariesTask::executeTask()
connect(dljob.get(), &NetJob::failed, this, &FMLLibrariesTask::fmllibsFailed); connect(dljob.get(), &NetJob::failed, this, &FMLLibrariesTask::fmllibsFailed);
connect(dljob.get(), &NetJob::aborted, this, [this]{ emitFailed(tr("Aborted")); }); connect(dljob.get(), &NetJob::aborted, this, [this]{ emitFailed(tr("Aborted")); });
connect(dljob.get(), &NetJob::progress, this, &FMLLibrariesTask::progress); connect(dljob.get(), &NetJob::progress, this, &FMLLibrariesTask::progress);
connect(dljob.get(), &NetJob::stepProgress, this, &FMLLibrariesTask::propogateStepProgress);
downloadJob.reset(dljob); downloadJob.reset(dljob);
downloadJob->start(); downloadJob->start();
} }

View File

@ -70,6 +70,8 @@ void LibrariesTask::executeTask()
connect(downloadJob.get(), &NetJob::failed, this, &LibrariesTask::jarlibFailed); connect(downloadJob.get(), &NetJob::failed, this, &LibrariesTask::jarlibFailed);
connect(downloadJob.get(), &NetJob::aborted, this, [this]{ emitFailed(tr("Aborted")); }); connect(downloadJob.get(), &NetJob::aborted, this, [this]{ emitFailed(tr("Aborted")); });
connect(downloadJob.get(), &NetJob::progress, this, &LibrariesTask::progress); connect(downloadJob.get(), &NetJob::progress, this, &LibrariesTask::progress);
connect(downloadJob.get(), &NetJob::stepProgress, this, &LibrariesTask::propogateStepProgress);
downloadJob->start(); downloadJob->start();
} }

View File

@ -683,6 +683,7 @@ void PackInstallTask::installConfigs()
abortable = true; abortable = true;
setProgress(current, total); setProgress(current, total);
}); });
connect(jobPtr.get(), &NetJob::stepProgress, this, &PackInstallTask::propogateStepProgress);
connect(jobPtr.get(), &NetJob::aborted, [&]{ connect(jobPtr.get(), &NetJob::aborted, [&]{
abortable = false; abortable = false;
jobPtr.reset(); jobPtr.reset();
@ -846,9 +847,11 @@ void PackInstallTask::downloadMods()
}); });
connect(jobPtr.get(), &NetJob::progress, [&](qint64 current, qint64 total) connect(jobPtr.get(), &NetJob::progress, [&](qint64 current, qint64 total)
{ {
setDetails(tr("%1 out of %2 complete").arg(current).arg(total));
abortable = true; abortable = true;
setProgress(current, total); setProgress(current, total);
}); });
connect(jobPtr.get(), &NetJob::stepProgress, this, &PackInstallTask::propogateStepProgress);
connect(jobPtr.get(), &NetJob::aborted, [&] connect(jobPtr.get(), &NetJob::aborted, [&]
{ {
abortable = false; abortable = false;

View File

@ -35,6 +35,7 @@
#include "FlameInstanceCreationTask.h" #include "FlameInstanceCreationTask.h"
#include "modplatform/flame/FileResolvingTask.h"
#include "modplatform/flame/FlameAPI.h" #include "modplatform/flame/FlameAPI.h"
#include "modplatform/flame/PackManifest.h" #include "modplatform/flame/PackManifest.h"
@ -382,7 +383,7 @@ bool FlameCreationTask::createInstance()
}); });
connect(m_mod_id_resolver.get(), &Flame::FileResolvingTask::progress, this, &FlameCreationTask::setProgress); connect(m_mod_id_resolver.get(), &Flame::FileResolvingTask::progress, this, &FlameCreationTask::setProgress);
connect(m_mod_id_resolver.get(), &Flame::FileResolvingTask::status, this, &FlameCreationTask::setStatus); connect(m_mod_id_resolver.get(), &Flame::FileResolvingTask::status, this, &FlameCreationTask::setStatus);
connect(m_mod_id_resolver.get(), &Flame::FileResolvingTask::stepProgress, this, &FlameCreationTask::propogateStepProgress);
m_mod_id_resolver->start(); m_mod_id_resolver->start();
loop.exec(); loop.exec();
@ -452,7 +453,7 @@ void FlameCreationTask::idResolverSucceeded(QEventLoop& loop)
void FlameCreationTask::setupDownloadJob(QEventLoop& loop) void FlameCreationTask::setupDownloadJob(QEventLoop& loop)
{ {
m_files_job.reset(new NetJob(tr("Mod download"), APPLICATION->network())); m_files_job.reset(new NetJob(tr("Mod Download Flame"), APPLICATION->network()));
for (const auto& result : m_mod_id_resolver->getResults().files) { for (const auto& result : m_mod_id_resolver->getResults().files) {
QString filename = result.fileName; QString filename = result.fileName;
if (!result.required) { if (!result.required) {
@ -496,7 +497,11 @@ void FlameCreationTask::setupDownloadJob(QEventLoop& loop)
m_files_job.reset(); m_files_job.reset();
setError(reason); setError(reason);
}); });
connect(m_files_job.get(), &NetJob::progress, this, &FlameCreationTask::setProgress); connect(m_files_job.get(), &NetJob::progress, this, [this](qint64 current, qint64 total){
setDetails(tr("%1 out of %2 complete").arg(current).arg(total));
setProgress(current, total);
});
connect(m_files_job.get(), &NetJob::stepProgress, this, &FlameCreationTask::propogateStepProgress);
connect(m_files_job.get(), &NetJob::finished, &loop, &QEventLoop::quit); connect(m_files_job.get(), &NetJob::finished, &loop, &QEventLoop::quit);
setStatus(tr("Downloading mods...")); setStatus(tr("Downloading mods..."));

View File

@ -81,6 +81,7 @@ void PackInstallTask::downloadPack()
connect(netJobContainer.get(), &NetJob::succeeded, this, &PackInstallTask::onDownloadSucceeded); connect(netJobContainer.get(), &NetJob::succeeded, this, &PackInstallTask::onDownloadSucceeded);
connect(netJobContainer.get(), &NetJob::failed, this, &PackInstallTask::onDownloadFailed); connect(netJobContainer.get(), &NetJob::failed, this, &PackInstallTask::onDownloadFailed);
connect(netJobContainer.get(), &NetJob::progress, this, &PackInstallTask::onDownloadProgress); connect(netJobContainer.get(), &NetJob::progress, this, &PackInstallTask::onDownloadProgress);
connect(netJobContainer.get(), &NetJob::stepProgress, this, &PackInstallTask::propogateStepProgress);
connect(netJobContainer.get(), &NetJob::aborted, this, &PackInstallTask::onDownloadAborted); connect(netJobContainer.get(), &NetJob::aborted, this, &PackInstallTask::onDownloadAborted);
netJobContainer->start(); netJobContainer->start();

View File

@ -1,387 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2022 flowln <flowlnlnln@gmail.com>
* Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org>
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
*
* 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, version 3.
*
* 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 <https://www.gnu.org/licenses/>.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2020-2021 Jamie Mansfield <jmansfield@cadixdev.org>
* Copyright 2020-2021 Petr Mrazek <peterix@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "FTBPackInstallTask.h"
#include "FileSystem.h"
#include "Json.h"
#include "minecraft/MinecraftInstance.h"
#include "minecraft/PackProfile.h"
#include "modplatform/flame/PackManifest.h"
#include "net/ChecksumValidator.h"
#include "settings/INISettingsObject.h"
#include "Application.h"
#include "BuildConfig.h"
#include "ui/dialogs/BlockedModsDialog.h"
namespace ModpacksCH {
PackInstallTask::PackInstallTask(Modpack pack, QString version, QWidget* parent)
: m_pack(std::move(pack)), m_version_name(std::move(version)), m_parent(parent)
{}
bool PackInstallTask::abort()
{
if (!canAbort())
return false;
bool aborted = true;
if (m_net_job)
aborted &= m_net_job->abort();
if (m_mod_id_resolver_task)
aborted &= m_mod_id_resolver_task->abort();
return aborted ? InstanceTask::abort() : false;
}
void PackInstallTask::executeTask()
{
setStatus(tr("Getting the manifest..."));
setAbortable(false);
// Find pack version
auto version_it = std::find_if(m_pack.versions.constBegin(), m_pack.versions.constEnd(),
[this](ModpacksCH::VersionInfo const& a) { return a.name == m_version_name; });
if (version_it == m_pack.versions.constEnd()) {
emitFailed(tr("Failed to find pack version %1").arg(m_version_name));
return;
}
auto version = *version_it;
auto netJob = makeShared<NetJob>("ModpacksCH::VersionFetch", APPLICATION->network());
auto searchUrl = QString(BuildConfig.MODPACKSCH_API_BASE_URL + "public/modpack/%1/%2").arg(m_pack.id).arg(version.id);
netJob->addNetAction(Net::Download::makeByteArray(QUrl(searchUrl), &m_response));
QObject::connect(netJob.get(), &NetJob::succeeded, this, &PackInstallTask::onManifestDownloadSucceeded);
QObject::connect(netJob.get(), &NetJob::failed, this, &PackInstallTask::onManifestDownloadFailed);
QObject::connect(netJob.get(), &NetJob::aborted, this, &PackInstallTask::abort);
QObject::connect(netJob.get(), &NetJob::progress, this, &PackInstallTask::setProgress);
m_net_job = netJob;
setAbortable(true);
netJob->start();
}
void PackInstallTask::onManifestDownloadSucceeded()
{
m_net_job.reset();
QJsonParseError parse_error{};
QJsonDocument doc = QJsonDocument::fromJson(m_response, &parse_error);
if (parse_error.error != QJsonParseError::NoError) {
qWarning() << "Error while parsing JSON response from ModpacksCH at " << parse_error.offset
<< " reason: " << parse_error.errorString();
qWarning() << m_response;
return;
}
ModpacksCH::Version version;
try {
auto obj = Json::requireObject(doc);
ModpacksCH::loadVersion(version, obj);
} catch (const JSONValidationError& e) {
emitFailed(tr("Could not understand pack manifest:\n") + e.cause());
return;
}
m_version = version;
resolveMods();
}
void PackInstallTask::resolveMods()
{
setStatus(tr("Resolving mods..."));
setAbortable(false);
setProgress(0, 100);
m_file_id_map.clear();
Flame::Manifest manifest;
int index = 0;
for (auto const& file : m_version.files) {
if (!file.serverOnly && file.url.isEmpty()) {
if (file.curseforge.file_id <= 0) {
emitFailed(tr("Invalid manifest: There's no information available to download the file '%1'!").arg(file.name));
return;
}
Flame::File flame_file;
flame_file.projectId = file.curseforge.project_id;
flame_file.fileId = file.curseforge.file_id;
flame_file.hash = file.sha1;
manifest.files.insert(flame_file.fileId, flame_file);
m_file_id_map.append(flame_file.fileId);
} else {
m_file_id_map.append(-1);
}
index++;
}
m_mod_id_resolver_task.reset(new Flame::FileResolvingTask(APPLICATION->network(), manifest));
connect(m_mod_id_resolver_task.get(), &Flame::FileResolvingTask::succeeded, this, &PackInstallTask::onResolveModsSucceeded);
connect(m_mod_id_resolver_task.get(), &Flame::FileResolvingTask::failed, this, &PackInstallTask::onResolveModsFailed);
connect(m_mod_id_resolver_task.get(), &Flame::FileResolvingTask::aborted, this, &PackInstallTask::abort);
connect(m_mod_id_resolver_task.get(), &Flame::FileResolvingTask::progress, this, &PackInstallTask::setProgress);
setAbortable(true);
m_mod_id_resolver_task->start();
}
void PackInstallTask::onResolveModsSucceeded()
{
auto anyBlocked = false;
Flame::Manifest results = m_mod_id_resolver_task->getResults();
for (int index = 0; index < m_file_id_map.size(); index++) {
auto const file_id = m_file_id_map.at(index);
if (file_id < 0)
continue;
Flame::File results_file = results.files[file_id];
VersionFile& local_file = m_version.files[index];
// First check for blocked mods
if (!results_file.resolved || results_file.url.isEmpty()) {
BlockedMod blocked_mod;
blocked_mod.name = local_file.name;
blocked_mod.websiteUrl = results_file.websiteUrl;
blocked_mod.hash = results_file.hash;
blocked_mod.matched = false;
blocked_mod.localPath = "";
blocked_mod.targetFolder = results_file.targetFolder;
m_blocked_mods.append(blocked_mod);
anyBlocked = true;
} else {
local_file.url = results_file.url.toString();
}
}
m_mod_id_resolver_task.reset();
if (anyBlocked) {
qDebug() << "Blocked files found, displaying file list";
BlockedModsDialog message_dialog(m_parent, tr("Blocked files found"),
tr("The following files are not available for download in third party launchers.<br/>"
"You will need to manually download them and add them to the instance."),
m_blocked_mods);
message_dialog.setModal(true);
if (message_dialog.exec() == QDialog::Accepted) {
qDebug() << "Post dialog blocked mods list: " << m_blocked_mods;
createInstance();
} else {
abort();
}
} else {
createInstance();
}
}
void PackInstallTask::createInstance()
{
setAbortable(false);
setStatus(tr("Creating the instance..."));
QCoreApplication::processEvents();
auto instanceConfigPath = FS::PathCombine(m_stagingPath, "instance.cfg");
auto instanceSettings = std::make_shared<INISettingsObject>(instanceConfigPath);
MinecraftInstance instance(m_globalSettings, instanceSettings, m_stagingPath);
auto components = instance.getPackProfile();
components->buildingFromScratch();
for (auto target : m_version.targets) {
if (target.type == "game" && target.name == "minecraft") {
components->setComponentVersion("net.minecraft", target.version, true);
break;
}
}
for (auto target : m_version.targets) {
if (target.type != "modloader")
continue;
if (target.name == "forge") {
components->setComponentVersion("net.minecraftforge", target.version);
} else if (target.name == "fabric") {
components->setComponentVersion("net.fabricmc.fabric-loader", target.version);
}
}
// install any jar mods
QDir jarModsDir(FS::PathCombine(m_stagingPath, "minecraft", "jarmods"));
if (jarModsDir.exists()) {
QStringList jarMods;
for (const auto& info : jarModsDir.entryInfoList(QDir::NoDotAndDotDot | QDir::Files)) {
jarMods.push_back(info.absoluteFilePath());
}
components->installJarMods(jarMods);
}
components->saveNow();
instance.setName(name());
instance.setIconKey(m_instIcon);
instance.setManagedPack("modpacksch", QString::number(m_pack.id), m_pack.name, QString::number(m_version.id), m_version.name);
instance.saveNow();
onCreateInstanceSucceeded();
}
void PackInstallTask::onCreateInstanceSucceeded()
{
downloadPack();
}
void PackInstallTask::downloadPack()
{
setStatus(tr("Downloading mods..."));
setAbortable(false);
auto jobPtr = makeShared<NetJob>(tr("Mod download"), APPLICATION->network());
for (auto const& file : m_version.files) {
if (file.serverOnly || file.url.isEmpty())
continue;
auto path = FS::PathCombine(m_stagingPath, ".minecraft", file.path, file.name);
qDebug() << "Will try to download" << file.url << "to" << path;
QFileInfo file_info(file.name);
auto dl = Net::Download::makeFile(file.url, path);
if (!file.sha1.isEmpty()) {
auto rawSha1 = QByteArray::fromHex(file.sha1.toLatin1());
dl->addValidator(new Net::ChecksumValidator(QCryptographicHash::Sha1, rawSha1));
}
jobPtr->addNetAction(dl);
}
connect(jobPtr.get(), &NetJob::succeeded, this, &PackInstallTask::onModDownloadSucceeded);
connect(jobPtr.get(), &NetJob::failed, this, &PackInstallTask::onModDownloadFailed);
connect(jobPtr.get(), &NetJob::aborted, this, &PackInstallTask::abort);
connect(jobPtr.get(), &NetJob::progress, this, &PackInstallTask::setProgress);
m_net_job = jobPtr;
setAbortable(true);
jobPtr->start();
}
void PackInstallTask::onModDownloadSucceeded()
{
m_net_job.reset();
if (!m_blocked_mods.isEmpty()) {
copyBlockedMods();
}
emitSucceeded();
}
void PackInstallTask::onManifestDownloadFailed(QString reason)
{
m_net_job.reset();
emitFailed(reason);
}
void PackInstallTask::onResolveModsFailed(QString reason)
{
m_net_job.reset();
emitFailed(reason);
}
void PackInstallTask::onCreateInstanceFailed(QString reason)
{
emitFailed(reason);
}
void PackInstallTask::onModDownloadFailed(QString reason)
{
m_net_job.reset();
emitFailed(reason);
}
/// @brief copy the matched blocked mods to the instance staging area
void PackInstallTask::copyBlockedMods()
{
setStatus(tr("Copying Blocked Mods..."));
setAbortable(false);
int i = 0;
int total = m_blocked_mods.length();
setProgress(i, total);
for (auto const& mod : m_blocked_mods) {
if (!mod.matched) {
qDebug() << mod.name << "was not matched to a local file, skipping copy";
continue;
}
auto dest_path = FS::PathCombine(m_stagingPath, ".minecraft", mod.targetFolder, mod.name);
setStatus(tr("Copying Blocked Mods (%1 out of %2 are done)").arg(QString::number(i), QString::number(total)));
qDebug() << "Will try to copy" << mod.localPath << "to" << dest_path;
if (!FS::copy(mod.localPath, dest_path)()) {
qDebug() << "Copy of" << mod.localPath << "to" << dest_path << "Failed";
}
i++;
setProgress(i, total);
}
setAbortable(true);
}
} // namespace ModpacksCH

View File

@ -1,101 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2022 flowln <flowlnlnln@gmail.com>
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
*
* 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, version 3.
*
* 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 <https://www.gnu.org/licenses/>.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2020-2021 Jamie Mansfield <jmansfield@cadixdev.org>
* Copyright 2020-2021 Petr Mrazek <peterix@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "FTBPackManifest.h"
#include "InstanceTask.h"
#include "QObjectPtr.h"
#include "modplatform/flame/FileResolvingTask.h"
#include "net/NetJob.h"
#include "ui/dialogs/BlockedModsDialog.h"
#include <QWidget>
namespace ModpacksCH {
class PackInstallTask final : public InstanceTask
{
Q_OBJECT
public:
explicit PackInstallTask(Modpack pack, QString version, QWidget* parent = nullptr);
~PackInstallTask() override = default;
bool abort() override;
protected:
void executeTask() override;
private slots:
void onManifestDownloadSucceeded();
void onResolveModsSucceeded();
void onCreateInstanceSucceeded();
void onModDownloadSucceeded();
void onManifestDownloadFailed(QString reason);
void onResolveModsFailed(QString reason);
void onCreateInstanceFailed(QString reason);
void onModDownloadFailed(QString reason);
private:
void resolveMods();
void createInstance();
void downloadPack();
void copyBlockedMods();
private:
NetJob::Ptr m_net_job = nullptr;
shared_qobject_ptr<Flame::FileResolvingTask> m_mod_id_resolver_task = nullptr;
QList<int> m_file_id_map;
QByteArray m_response;
Modpack m_pack;
QString m_version_name;
Version m_version;
QMap<QString, QString> m_files_to_copy;
QList<BlockedMod> m_blocked_mods;
//FIXME: nuke
QWidget* m_parent;
};
}

View File

@ -1,195 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* PolyMC - Minecraft Launcher
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
*
* 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, version 3.
*
* 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 <https://www.gnu.org/licenses/>.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2020 Jamie Mansfield <jmansfield@cadixdev.org>
* Copyright 2020-2021 Petr Mrazek <peterix@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "FTBPackManifest.h"
#include "Json.h"
static void loadSpecs(ModpacksCH::Specs & s, QJsonObject & obj)
{
s.id = Json::requireInteger(obj, "id");
s.minimum = Json::requireInteger(obj, "minimum");
s.recommended = Json::requireInteger(obj, "recommended");
}
static void loadTag(ModpacksCH::Tag & t, QJsonObject & obj)
{
t.id = Json::requireInteger(obj, "id");
t.name = Json::requireString(obj, "name");
}
static void loadArt(ModpacksCH::Art & a, QJsonObject & obj)
{
a.id = Json::requireInteger(obj, "id");
a.url = Json::requireString(obj, "url");
a.type = Json::requireString(obj, "type");
a.width = Json::requireInteger(obj, "width");
a.height = Json::requireInteger(obj, "height");
a.compressed = Json::requireBoolean(obj, "compressed");
a.sha1 = Json::requireString(obj, "sha1");
a.size = Json::requireInteger(obj, "size");
a.updated = Json::requireInteger(obj, "updated");
}
static void loadAuthor(ModpacksCH::Author & a, QJsonObject & obj)
{
a.id = Json::requireInteger(obj, "id");
a.name = Json::requireString(obj, "name");
a.type = Json::requireString(obj, "type");
a.website = Json::requireString(obj, "website");
a.updated = Json::requireInteger(obj, "updated");
}
static void loadVersionInfo(ModpacksCH::VersionInfo & v, QJsonObject & obj)
{
v.id = Json::requireInteger(obj, "id");
v.name = Json::requireString(obj, "name");
v.type = Json::requireString(obj, "type");
v.updated = Json::requireInteger(obj, "updated");
auto specs = Json::requireObject(obj, "specs");
loadSpecs(v.specs, specs);
}
void ModpacksCH::loadModpack(ModpacksCH::Modpack & m, QJsonObject & obj)
{
m.id = Json::requireInteger(obj, "id");
m.name = Json::requireString(obj, "name");
m.synopsis = Json::requireString(obj, "synopsis");
m.description = Json::requireString(obj, "description");
m.type = Json::requireString(obj, "type");
m.featured = Json::requireBoolean(obj, "featured");
m.installs = Json::requireInteger(obj, "installs");
m.plays = Json::requireInteger(obj, "plays");
m.updated = Json::requireInteger(obj, "updated");
m.refreshed = Json::requireInteger(obj, "refreshed");
auto artArr = Json::requireArray(obj, "art");
for (QJsonValueRef artRaw : artArr)
{
auto artObj = Json::requireObject(artRaw);
ModpacksCH::Art art;
loadArt(art, artObj);
m.art.append(art);
}
auto authorArr = Json::requireArray(obj, "authors");
for (QJsonValueRef authorRaw : authorArr)
{
auto authorObj = Json::requireObject(authorRaw);
ModpacksCH::Author author;
loadAuthor(author, authorObj);
m.authors.append(author);
}
auto versionArr = Json::requireArray(obj, "versions");
for (QJsonValueRef versionRaw : versionArr)
{
auto versionObj = Json::requireObject(versionRaw);
ModpacksCH::VersionInfo version;
loadVersionInfo(version, versionObj);
m.versions.append(version);
}
auto tagArr = Json::requireArray(obj, "tags");
for (QJsonValueRef tagRaw : tagArr)
{
auto tagObj = Json::requireObject(tagRaw);
ModpacksCH::Tag tag;
loadTag(tag, tagObj);
m.tags.append(tag);
}
m.updated = Json::requireInteger(obj, "updated");
}
static void loadVersionTarget(ModpacksCH::VersionTarget & a, QJsonObject & obj)
{
a.id = Json::requireInteger(obj, "id");
a.name = Json::requireString(obj, "name");
a.type = Json::requireString(obj, "type");
a.version = Json::requireString(obj, "version");
a.updated = Json::requireInteger(obj, "updated");
}
static void loadVersionFile(ModpacksCH::VersionFile & a, QJsonObject & obj)
{
a.id = Json::requireInteger(obj, "id");
a.type = Json::requireString(obj, "type");
a.path = Json::requireString(obj, "path");
a.name = Json::requireString(obj, "name");
a.version = Json::requireString(obj, "version");
a.url = Json::ensureString(obj, "url"); // optional
a.sha1 = Json::requireString(obj, "sha1");
a.size = Json::requireInteger(obj, "size");
a.clientOnly = Json::requireBoolean(obj, "clientonly");
a.serverOnly = Json::requireBoolean(obj, "serveronly");
a.optional = Json::requireBoolean(obj, "optional");
a.updated = Json::requireInteger(obj, "updated");
auto curseforgeObj = Json::ensureObject(obj, "curseforge"); // optional
a.curseforge.project_id = Json::ensureInteger(curseforgeObj, "project");
a.curseforge.file_id = Json::ensureInteger(curseforgeObj, "file");
}
void ModpacksCH::loadVersion(ModpacksCH::Version & m, QJsonObject & obj)
{
m.id = Json::requireInteger(obj, "id");
m.parent = Json::requireInteger(obj, "parent");
m.name = Json::requireString(obj, "name");
m.type = Json::requireString(obj, "type");
m.installs = Json::requireInteger(obj, "installs");
m.plays = Json::requireInteger(obj, "plays");
m.updated = Json::requireInteger(obj, "updated");
m.refreshed = Json::requireInteger(obj, "refreshed");
auto specs = Json::requireObject(obj, "specs");
loadSpecs(m.specs, specs);
auto targetArr = Json::requireArray(obj, "targets");
for (QJsonValueRef targetRaw : targetArr)
{
auto versionObj = Json::requireObject(targetRaw);
ModpacksCH::VersionTarget target;
loadVersionTarget(target, versionObj);
m.targets.append(target);
}
auto fileArr = Json::requireArray(obj, "files");
for (QJsonValueRef fileRaw : fileArr)
{
auto fileObj = Json::requireObject(fileRaw);
ModpacksCH::VersionFile file;
loadVersionFile(file, fileObj);
m.files.append(file);
}
}
//static void loadVersionChangelog(ModpacksCH::VersionChangelog & m, QJsonObject & obj)
//{
// m.content = Json::requireString(obj, "content");
// m.updated = Json::requireInteger(obj, "updated");
//}

View File

@ -1,168 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* PolyMC - Minecraft Launcher
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
*
* 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, version 3.
*
* 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 <https://www.gnu.org/licenses/>.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2020-2021 Jamie Mansfield <jmansfield@cadixdev.org>
* Copyright 2020 Petr Mrazek <peterix@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QString>
#include <QVector>
#include <QUrl>
#include <QJsonObject>
#include <QMetaType>
namespace ModpacksCH
{
struct Specs
{
int id;
int minimum;
int recommended;
};
struct Tag
{
int id;
QString name;
};
struct Art
{
int id;
QString url;
QString type;
int width;
int height;
bool compressed;
QString sha1;
int size;
int64_t updated;
};
struct Author
{
int id;
QString name;
QString type;
QString website;
int64_t updated;
};
struct VersionInfo
{
int id;
QString name;
QString type;
int64_t updated;
Specs specs;
};
struct Modpack
{
int id;
QString name;
QString synopsis;
QString description;
QString type;
bool featured;
int installs;
int plays;
int64_t updated;
int64_t refreshed;
QVector<Art> art;
QVector<Author> authors;
QVector<VersionInfo> versions;
QVector<Tag> tags;
};
struct VersionTarget
{
int id;
QString type;
QString name;
QString version;
int64_t updated;
};
struct VersionFileCurseForge
{
int project_id;
int file_id;
};
struct VersionFile
{
int id;
QString type;
QString path;
QString name;
QString version;
QString url;
QString sha1;
int size;
bool clientOnly;
bool serverOnly;
bool optional;
int64_t updated;
VersionFileCurseForge curseforge;
};
struct Version
{
int id;
int parent;
QString name;
QString type;
int installs;
int plays;
int64_t updated;
int64_t refreshed;
Specs specs;
QVector<VersionTarget> targets;
QVector<VersionFile> files;
};
struct VersionChangelog
{
QString content;
int64_t updated;
};
void loadModpack(Modpack & m, QJsonObject & obj);
void loadVersion(Version & m, QJsonObject & obj);
}
Q_DECLARE_METATYPE(ModpacksCH::Modpack)

View File

@ -11,6 +11,7 @@
#include "net/ChecksumValidator.h" #include "net/ChecksumValidator.h"
#include "net/NetJob.h"
#include "settings/INISettingsObject.h" #include "settings/INISettingsObject.h"
#include "ui/dialogs/CustomMessageBox.h" #include "ui/dialogs/CustomMessageBox.h"
@ -223,7 +224,7 @@ bool ModrinthCreationTask::createInstance()
instance.setName(name()); instance.setName(name());
instance.saveNow(); instance.saveNow();
m_files_job.reset(new NetJob(tr("Mod download"), APPLICATION->network())); m_files_job.reset(new NetJob(tr("Mod Download Modrinth"), APPLICATION->network()));
auto root_modpack_path = FS::PathCombine(m_stagingPath, ".minecraft"); auto root_modpack_path = FS::PathCombine(m_stagingPath, ".minecraft");
auto root_modpack_url = QUrl::fromLocalFile(root_modpack_path); auto root_modpack_url = QUrl::fromLocalFile(root_modpack_path);
@ -262,7 +263,11 @@ bool ModrinthCreationTask::createInstance()
setError(reason); setError(reason);
}); });
connect(m_files_job.get(), &NetJob::finished, &loop, &QEventLoop::quit); connect(m_files_job.get(), &NetJob::finished, &loop, &QEventLoop::quit);
connect(m_files_job.get(), &NetJob::progress, [&](qint64 current, qint64 total) { setProgress(current, total); }); connect(m_files_job.get(), &NetJob::progress, [&](qint64 current, qint64 total) {
setDetails(tr("%1 out of %2 complete").arg(current).arg(total));
setProgress(current, total);
});
connect(m_files_job.get(), &NetJob::stepProgress, this, &ModrinthCreationTask::propogateStepProgress);
setStatus(tr("Downloading mods...")); setStatus(tr("Downloading mods..."));
m_files_job->start(); m_files_job->start();

View File

@ -50,6 +50,7 @@ void Technic::SingleZipPackInstallTask::executeTask()
auto job = m_filesNetJob.get(); auto job = m_filesNetJob.get();
connect(job, &NetJob::succeeded, this, &Technic::SingleZipPackInstallTask::downloadSucceeded); connect(job, &NetJob::succeeded, this, &Technic::SingleZipPackInstallTask::downloadSucceeded);
connect(job, &NetJob::progress, this, &Technic::SingleZipPackInstallTask::downloadProgressChanged); connect(job, &NetJob::progress, this, &Technic::SingleZipPackInstallTask::downloadProgressChanged);
connect(job, &NetJob::stepProgress, this, &Technic::SingleZipPackInstallTask::propogateStepProgress);
connect(job, &NetJob::failed, this, &Technic::SingleZipPackInstallTask::downloadFailed); connect(job, &NetJob::failed, this, &Technic::SingleZipPackInstallTask::downloadFailed);
m_filesNetJob->start(); m_filesNetJob->start();
} }

View File

@ -127,6 +127,7 @@ void Technic::SolderPackInstallTask::fileListSucceeded()
connect(m_filesNetJob.get(), &NetJob::succeeded, this, &Technic::SolderPackInstallTask::downloadSucceeded); connect(m_filesNetJob.get(), &NetJob::succeeded, this, &Technic::SolderPackInstallTask::downloadSucceeded);
connect(m_filesNetJob.get(), &NetJob::progress, this, &Technic::SolderPackInstallTask::downloadProgressChanged); connect(m_filesNetJob.get(), &NetJob::progress, this, &Technic::SolderPackInstallTask::downloadProgressChanged);
connect(m_filesNetJob.get(), &NetJob::stepProgress, this, &Technic::SolderPackInstallTask::propogateStepProgress);
connect(m_filesNetJob.get(), &NetJob::failed, this, &Technic::SolderPackInstallTask::downloadFailed); connect(m_filesNetJob.get(), &NetJob::failed, this, &Technic::SolderPackInstallTask::downloadFailed);
connect(m_filesNetJob.get(), &NetJob::aborted, this, &Technic::SolderPackInstallTask::downloadAborted); connect(m_filesNetJob.get(), &NetJob::aborted, this, &Technic::SolderPackInstallTask::downloadAborted);
m_filesNetJob->start(); m_filesNetJob->start();

View File

@ -4,6 +4,7 @@
* Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (c) 2022 flowln <flowlnlnln@gmail.com>
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
* Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me> * Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me>
* Copyright (C) 2023 Rachel Powers <508861+Ryex@users.noreply.github.com>
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -36,17 +37,23 @@
*/ */
#include "Download.h" #include "Download.h"
#include <QUrl>
#include <QDateTime> #include <QDateTime>
#include <QFileInfo> #include <QFileInfo>
#include "ByteArraySink.h" #include "ByteArraySink.h"
#include "ChecksumValidator.h" #include "ChecksumValidator.h"
#include "FileSystem.h"
#include "MetaCacheSink.h" #include "MetaCacheSink.h"
#include "BuildConfig.h"
#include "Application.h" #include "Application.h"
#include "BuildConfig.h"
#include "net/Logging.h"
#include "net/NetAction.h"
#include "MMCTime.h"
#include "StringUtils.h"
namespace Net { namespace Net {
@ -54,6 +61,7 @@ auto Download::makeCached(QUrl url, MetaEntryPtr entry, Options options) -> Down
{ {
auto dl = makeShared<Download>(); auto dl = makeShared<Download>();
dl->m_url = url; dl->m_url = url;
dl->setObjectName(QString("CACHE:") + url.toString());
dl->m_options = options; dl->m_options = options;
auto md5Node = new ChecksumValidator(QCryptographicHash::Md5); auto md5Node = new ChecksumValidator(QCryptographicHash::Md5);
auto cachedNode = new MetaCacheSink(entry, md5Node, options.testFlag(Option::MakeEternal)); auto cachedNode = new MetaCacheSink(entry, md5Node, options.testFlag(Option::MakeEternal));
@ -65,6 +73,7 @@ auto Download::makeByteArray(QUrl url, QByteArray* output, Options options) -> D
{ {
auto dl = makeShared<Download>(); auto dl = makeShared<Download>();
dl->m_url = url; dl->m_url = url;
dl->setObjectName(QString("BYTES:") + url.toString());
dl->m_options = options; dl->m_options = options;
dl->m_sink.reset(new ByteArraySink(output)); dl->m_sink.reset(new ByteArraySink(output));
return dl; return dl;
@ -74,6 +83,7 @@ auto Download::makeFile(QUrl url, QString path, Options options) -> Download::Pt
{ {
auto dl = makeShared<Download>(); auto dl = makeShared<Download>();
dl->m_url = url; dl->m_url = url;
dl->setObjectName(QString("FILE:") + url.toString());
dl->m_options = options; dl->m_options = options;
dl->m_sink.reset(new FileSink(path)); dl->m_sink.reset(new FileSink(path));
return dl; return dl;
@ -86,10 +96,10 @@ void Download::addValidator(Validator* v)
void Download::executeTask() void Download::executeTask()
{ {
setStatus(tr("Downloading %1").arg(m_url.toString())); setStatus(tr("Downloading %1").arg(StringUtils::truncateUrlHumanFriendly(m_url, 80)));
if (getState() == Task::State::AbortedByUser) { if (getState() == Task::State::AbortedByUser) {
qWarning() << "Attempt to start an aborted Download:" << m_url.toString(); qCWarning(taskDownloadLogC) << getUid().toString() << "Attempt to start an aborted Download:" << m_url.toString();
emitAborted(); emitAborted();
return; return;
} }
@ -99,10 +109,10 @@ void Download::executeTask()
switch (m_state) { switch (m_state) {
case State::Succeeded: case State::Succeeded:
emit succeeded(); emit succeeded();
qDebug() << "Download cache hit " << m_url.toString(); qCDebug(taskDownloadLogC) << getUid().toString() << "Download cache hit " << m_url.toString();
return; return;
case State::Running: case State::Running:
qDebug() << "Downloading " << m_url.toString(); qCDebug(taskDownloadLogC) << getUid().toString() << "Downloading " << m_url.toString();
break; break;
case State::Inactive: case State::Inactive:
case State::Failed: case State::Failed:
@ -124,6 +134,9 @@ void Download::executeTask()
request.setRawHeader("Authorization", token.toUtf8()); request.setRawHeader("Authorization", token.toUtf8());
} }
m_last_progress_time = m_clock.now();
m_last_progress_bytes = 0;
QNetworkReply* rep = m_network->get(request); QNetworkReply* rep = m_network->get(request);
m_reply.reset(rep); m_reply.reset(rep);
@ -140,13 +153,39 @@ void Download::executeTask()
void Download::downloadProgress(qint64 bytesReceived, qint64 bytesTotal) void Download::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
{ {
auto now = m_clock.now();
auto elapsed = now - m_last_progress_time;
// use milliseconds for speed precision
auto elapsed_ms = std::chrono::duration_cast<std::chrono::milliseconds>(elapsed);
auto bytes_received_since = bytesReceived - m_last_progress_bytes;
auto dl_speed_bps = (double)bytes_received_since / elapsed_ms.count() * 1000;
auto remaing_time_s = (bytesTotal - bytesReceived) / dl_speed_bps;
//: Current amount of bytes downloaded, out of the total amount of bytes in the download
QString dl_progress =
tr("%1 / %2").arg(StringUtils::humanReadableFileSize(bytesReceived)).arg(StringUtils::humanReadableFileSize(bytesTotal));
QString dl_speed_str;
if (elapsed_ms.count() > 0) {
auto str_eta = bytesTotal > 0 ? Time::humanReadableDuration(remaing_time_s) : tr("unknown");
//: Download speed, in bytes per second (remaining download time in parenthesis)
dl_speed_str =
tr("%1 /s (%2)").arg(StringUtils::humanReadableFileSize(dl_speed_bps)).arg(str_eta);
} else {
//: Download speed at 0 bytes per second
dl_speed_str = tr("0 B/s");
}
setDetails(dl_progress + "\n" + dl_speed_str);
setProgress(bytesReceived, bytesTotal); setProgress(bytesReceived, bytesTotal);
} }
void Download::downloadError(QNetworkReply::NetworkError error) void Download::downloadError(QNetworkReply::NetworkError error)
{ {
if (error == QNetworkReply::OperationCanceledError) { if (error == QNetworkReply::OperationCanceledError) {
qCritical() << "Aborted " << m_url.toString(); qCCritical(taskDownloadLogC) << getUid().toString() << "Aborted " << m_url.toString();
m_state = State::AbortedByUser; m_state = State::AbortedByUser;
} else { } else {
if (m_options & Option::AcceptLocalFiles) { if (m_options & Option::AcceptLocalFiles) {
@ -156,7 +195,7 @@ void Download::downloadError(QNetworkReply::NetworkError error)
} }
} }
// error happened during download. // error happened during download.
qCritical() << "Failed " << m_url.toString() << " with reason " << error; qCCritical(taskDownloadLogC) << getUid().toString() << "Failed " << m_url.toString() << " with reason " << error;
m_state = State::Failed; m_state = State::Failed;
} }
} }
@ -165,9 +204,10 @@ void Download::sslErrors(const QList<QSslError>& errors)
{ {
int i = 1; int i = 1;
for (auto error : errors) { for (auto error : errors) {
qCritical() << "Download" << m_url.toString() << "SSL Error #" << i << " : " << error.errorString(); qCCritical(taskDownloadLogC) << getUid().toString() << "Download" << m_url.toString() << "SSL Error #" << i << " : "
<< error.errorString();
auto cert = error.certificate(); auto cert = error.certificate();
qCritical() << "Certificate in question:\n" << cert.toText(); qCCritical(taskDownloadLogC) << getUid().toString() << "Certificate in question:\n" << cert.toText();
i++; i++;
} }
} }
@ -210,17 +250,17 @@ auto Download::handleRedirect() -> bool
*/ */
redirect = QUrl(redirectStr, QUrl::TolerantMode); redirect = QUrl(redirectStr, QUrl::TolerantMode);
if (!redirect.isValid()) { if (!redirect.isValid()) {
qWarning() << "Failed to parse redirect URL:" << redirectStr; qCWarning(taskDownloadLogC) << getUid().toString() << "Failed to parse redirect URL:" << redirectStr;
downloadError(QNetworkReply::ProtocolFailure); downloadError(QNetworkReply::ProtocolFailure);
return false; return false;
} }
qDebug() << "Fixed location header:" << redirect; qCDebug(taskDownloadLogC) << getUid().toString() << "Fixed location header:" << redirect;
} else { } else {
qDebug() << "Location header:" << redirect; qCDebug(taskDownloadLogC) << getUid().toString() << "Location header:" << redirect;
} }
m_url = QUrl(redirect.toString()); m_url = QUrl(redirect.toString());
qDebug() << "Following redirect to " << m_url.toString(); qCDebug(taskDownloadLogC) << getUid().toString() << "Following redirect to " << m_url.toString();
startAction(m_network); startAction(m_network);
return true; return true;
@ -230,26 +270,26 @@ void Download::downloadFinished()
{ {
// handle HTTP redirection first // handle HTTP redirection first
if (handleRedirect()) { if (handleRedirect()) {
qDebug() << "Download redirected:" << m_url.toString(); qCDebug(taskDownloadLogC) << getUid().toString() << "Download redirected:" << m_url.toString();
return; return;
} }
// if the download failed before this point ... // if the download failed before this point ...
if (m_state == State::Succeeded) // pretend to succeed so we continue processing :) if (m_state == State::Succeeded) // pretend to succeed so we continue processing :)
{ {
qDebug() << "Download failed but we are allowed to proceed:" << m_url.toString(); qCDebug(taskDownloadLogC) << getUid().toString() << "Download failed but we are allowed to proceed:" << m_url.toString();
m_sink->abort(); m_sink->abort();
m_reply.reset(); m_reply.reset();
emit succeeded(); emit succeeded();
return; return;
} else if (m_state == State::Failed) { } else if (m_state == State::Failed) {
qDebug() << "Download failed in previous step:" << m_url.toString(); qCDebug(taskDownloadLogC) << getUid().toString() << "Download failed in previous step:" << m_url.toString();
m_sink->abort(); m_sink->abort();
m_reply.reset(); m_reply.reset();
emit failed(""); emit failed("");
return; return;
} else if (m_state == State::AbortedByUser) { } else if (m_state == State::AbortedByUser) {
qDebug() << "Download aborted in previous step:" << m_url.toString(); qCDebug(taskDownloadLogC) << getUid().toString() << "Download aborted in previous step:" << m_url.toString();
m_sink->abort(); m_sink->abort();
m_reply.reset(); m_reply.reset();
emit aborted(); emit aborted();
@ -259,14 +299,14 @@ void Download::downloadFinished()
// make sure we got all the remaining data, if any // make sure we got all the remaining data, if any
auto data = m_reply->readAll(); auto data = m_reply->readAll();
if (data.size()) { if (data.size()) {
qDebug() << "Writing extra" << data.size() << "bytes"; qCDebug(taskDownloadLogC) << getUid().toString() << "Writing extra" << data.size() << "bytes";
m_state = m_sink->write(data); m_state = m_sink->write(data);
} }
// otherwise, finalize the whole graph // otherwise, finalize the whole graph
m_state = m_sink->finalize(*m_reply.get()); m_state = m_sink->finalize(*m_reply.get());
if (m_state != State::Succeeded) { if (m_state != State::Succeeded) {
qDebug() << "Download failed to finalize:" << m_url.toString(); qCDebug(taskDownloadLogC) << getUid().toString() << "Download failed to finalize:" << m_url.toString();
m_sink->abort(); m_sink->abort();
m_reply.reset(); m_reply.reset();
emit failed(""); emit failed("");
@ -274,7 +314,7 @@ void Download::downloadFinished()
} }
m_reply.reset(); m_reply.reset();
qDebug() << "Download succeeded:" << m_url.toString(); qCDebug(taskDownloadLogC) << getUid().toString() << "Download succeeded:" << m_url.toString();
emit succeeded(); emit succeeded();
} }
@ -284,11 +324,11 @@ void Download::downloadReadyRead()
auto data = m_reply->readAll(); auto data = m_reply->readAll();
m_state = m_sink->write(data); m_state = m_sink->write(data);
if (m_state == State::Failed) { if (m_state == State::Failed) {
qCritical() << "Failed to process response chunk"; qCCritical(taskDownloadLogC) << getUid().toString() << "Failed to process response chunk";
} }
// qDebug() << "Download" << m_url.toString() << "gained" << data.size() << "bytes"; // qDebug() << "Download" << m_url.toString() << "gained" << data.size() << "bytes";
} else { } else {
qCritical() << "Cannot write download data! illegal status " << m_status; qCCritical(taskDownloadLogC) << getUid().toString() << "Cannot write download data! illegal status " << m_status;
} }
} }

View File

@ -1,8 +1,9 @@
// SPDX-License-Identifier: GPL-3.0-only // SPDX-License-Identifier: GPL-3.0-only
/* /*
* PolyMC - Minecraft Launcher * Prism Launcher - Minecraft Launcher
* Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (c) 2022 flowln <flowlnlnln@gmail.com>
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
* Copyright (C) 2023 Rachel Powers <508861+Ryex@users.noreply.github.com>
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -22,6 +23,7 @@
* Copyright 2013-2021 MultiMC Contributors * Copyright 2013-2021 MultiMC Contributors
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
@ -36,6 +38,8 @@
#pragma once #pragma once
#include <chrono>
#include "HttpMetaCache.h" #include "HttpMetaCache.h"
#include "NetAction.h" #include "NetAction.h"
#include "Sink.h" #include "Sink.h"
@ -80,6 +84,10 @@ class Download : public NetAction {
private: private:
std::unique_ptr<Sink> m_sink; std::unique_ptr<Sink> m_sink;
Options m_options; Options m_options;
std::chrono::steady_clock m_clock;
std::chrono::time_point<std::chrono::steady_clock> m_last_progress_time;
qint64 m_last_progress_bytes;
}; };
} // namespace Net } // namespace Net

View File

@ -1,6 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-only // SPDX-License-Identifier: GPL-3.0-only
/* /*
* PolyMC - Minecraft Launcher * Prism Launcher - Minecraft Launcher
* Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (c) 2022 flowln <flowlnlnln@gmail.com>
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
@ -37,6 +37,8 @@
#include "FileSystem.h" #include "FileSystem.h"
#include "net/Logging.h"
namespace Net { namespace Net {
Task::State FileSink::init(QNetworkRequest& request) Task::State FileSink::init(QNetworkRequest& request)
@ -48,14 +50,14 @@ Task::State FileSink::init(QNetworkRequest& request)
// create a new save file and open it for writing // create a new save file and open it for writing
if (!FS::ensureFilePathExists(m_filename)) { if (!FS::ensureFilePathExists(m_filename)) {
qCritical() << "Could not create folder for " + m_filename; qCCritical(taskNetLogC) << "Could not create folder for " + m_filename;
return Task::State::Failed; return Task::State::Failed;
} }
wroteAnyData = false; wroteAnyData = false;
m_output_file.reset(new QSaveFile(m_filename)); m_output_file.reset(new QSaveFile(m_filename));
if (!m_output_file->open(QIODevice::WriteOnly)) { if (!m_output_file->open(QIODevice::WriteOnly)) {
qCritical() << "Could not open " + m_filename + " for writing"; qCCritical(taskNetLogC) << "Could not open " + m_filename + " for writing";
return Task::State::Failed; return Task::State::Failed;
} }
@ -67,7 +69,7 @@ Task::State FileSink::init(QNetworkRequest& request)
Task::State FileSink::write(QByteArray& data) Task::State FileSink::write(QByteArray& data)
{ {
if (!writeAllValidators(data) || m_output_file->write(data) != data.size()) { if (!writeAllValidators(data) || m_output_file->write(data) != data.size()) {
qCritical() << "Failed writing into " + m_filename; qCCritical(taskNetLogC) << "Failed writing into " + m_filename;
m_output_file->cancelWriting(); m_output_file->cancelWriting();
m_output_file.reset(); m_output_file.reset();
wroteAnyData = false; wroteAnyData = false;
@ -106,7 +108,7 @@ Task::State FileSink::finalize(QNetworkReply& reply)
// nothing went wrong... // nothing went wrong...
if (!m_output_file->commit()) { if (!m_output_file->commit()) {
qCritical() << "Failed to commit changes to " << m_filename; qCCritical(taskNetLogC) << "Failed to commit changes to " << m_filename;
m_output_file->cancelWriting(); m_output_file->cancelWriting();
return Task::State::Failed; return Task::State::Failed;
} }

View File

@ -1,6 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-only // SPDX-License-Identifier: GPL-3.0-only
/* /*
* PolyMC - Minecraft Launcher * Prism Launcher - Minecraft Launcher
* Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (c) 2022 flowln <flowlnlnln@gmail.com>
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify

View File

@ -1,6 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-only // SPDX-License-Identifier: GPL-3.0-only
/* /*
* PolyMC - Minecraft Launcher * Prism Launcher - Minecraft Launcher
* Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (c) 2022 flowln <flowlnlnln@gmail.com>
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
@ -44,6 +44,8 @@
#include <QDebug> #include <QDebug>
#include "net/Logging.h"
auto MetaEntry::getFullPath() -> QString auto MetaEntry::getFullPath() -> QString
{ {
// FIXME: make local? // FIXME: make local?
@ -124,7 +126,7 @@ auto HttpMetaCache::resolveEntry(QString base, QString resource_path, QString ex
// Get rid of old entries, to prevent cache problems // Get rid of old entries, to prevent cache problems
auto current_time = QDateTime::currentSecsSinceEpoch(); auto current_time = QDateTime::currentSecsSinceEpoch();
if (entry->isExpired(current_time - ( file_last_changed / 1000 ))) { if (entry->isExpired(current_time - ( file_last_changed / 1000 ))) {
qWarning() << "Removing cache entry because of old age!"; qCWarning(taskNetLogC) << "[HttpMetaCache]" << "Removing cache entry because of old age!";
selected_base.entry_list.remove(resource_path); selected_base.entry_list.remove(resource_path);
return staleEntry(base, resource_path); return staleEntry(base, resource_path);
} }
@ -137,12 +139,12 @@ auto HttpMetaCache::resolveEntry(QString base, QString resource_path, QString ex
auto HttpMetaCache::updateEntry(MetaEntryPtr stale_entry) -> bool auto HttpMetaCache::updateEntry(MetaEntryPtr stale_entry) -> bool
{ {
if (!m_entries.contains(stale_entry->m_baseId)) { if (!m_entries.contains(stale_entry->m_baseId)) {
qCritical() << "Cannot add entry with unknown base: " << stale_entry->m_baseId.toLocal8Bit(); qCCritical(taskHttpMetaCacheLogC) << "Cannot add entry with unknown base: " << stale_entry->m_baseId.toLocal8Bit();
return false; return false;
} }
if (stale_entry->m_stale) { if (stale_entry->m_stale) {
qCritical() << "Cannot add stale entry: " << stale_entry->getFullPath().toLocal8Bit(); qCCritical(taskHttpMetaCacheLogC) << "Cannot add stale entry: " << stale_entry->getFullPath().toLocal8Bit();
return false; return false;
} }
@ -166,10 +168,10 @@ void HttpMetaCache::evictAll()
{ {
for (QString& base : m_entries.keys()) { for (QString& base : m_entries.keys()) {
EntryMap& map = m_entries[base]; EntryMap& map = m_entries[base];
qDebug() << "Evicting base" << base; qCDebug(taskHttpMetaCacheLogC) << "Evicting base" << base;
for (MetaEntryPtr entry : map.entry_list) { for (MetaEntryPtr entry : map.entry_list) {
if (!evictEntry(entry)) if (!evictEntry(entry))
qWarning() << "Unexpected missing cache entry" << entry->m_basePath; qCWarning(taskHttpMetaCacheLogC) << "Unexpected missing cache entry" << entry->m_basePath;
} }
} }
} }
@ -267,7 +269,7 @@ void HttpMetaCache::SaveNow()
if (m_index_file.isNull()) if (m_index_file.isNull())
return; return;
qDebug() << "[HttpMetaCache]" << "Saving metacache with" << m_entries.size() << "entries"; qCDebug(taskHttpMetaCacheLogC) << "Saving metacache with" << m_entries.size() << "entries";
QJsonObject toplevel; QJsonObject toplevel;
Json::writeString(toplevel, "version", "1"); Json::writeString(toplevel, "version", "1");
@ -302,6 +304,6 @@ void HttpMetaCache::SaveNow()
try { try {
Json::write(toplevel, m_index_file); Json::write(toplevel, m_index_file);
} catch (const Exception& e) { } catch (const Exception& e) {
qWarning() << e.what(); qCWarning(taskHttpMetaCacheLogC) << "Error writing cache:" << e.what();
} }
} }

View File

@ -1,6 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-only // SPDX-License-Identifier: GPL-3.0-only
/* /*
* PolyMC - Minecraft Launcher * Prism Launcher - Minecraft Launcher
* Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (c) 2022 flowln <flowlnlnln@gmail.com>
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify

26
launcher/net/Logging.cpp Normal file
View File

@ -0,0 +1,26 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2023 Rachel Powers <508861+Ryex@users.noreply.github.com>
*
* 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, version 3.
*
* 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 <https://www.gnu.org/licenses/>.
*
*/
#include "net/Logging.h"
Q_LOGGING_CATEGORY(taskNetLogC, "launcher.task.net")
Q_LOGGING_CATEGORY(taskDownloadLogC, "launcher.task.net.download")
Q_LOGGING_CATEGORY(taskUploadLogC, "launcher.task.net.upload")
Q_LOGGING_CATEGORY(taskMetaCacheLogC, "launcher.task.net.metacache")
Q_LOGGING_CATEGORY(taskHttpMetaCacheLogC, "launcher.task.net.metacache.http")

28
launcher/net/Logging.h Normal file
View File

@ -0,0 +1,28 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2023 Rachel Powers <508861+Ryex@users.noreply.github.com>
*
* 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, version 3.
*
* 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 <https://www.gnu.org/licenses/>.
*
*/
#pragma once
#include <QLoggingCategory>
Q_DECLARE_LOGGING_CATEGORY(taskNetLogC)
Q_DECLARE_LOGGING_CATEGORY(taskDownloadLogC)
Q_DECLARE_LOGGING_CATEGORY(taskUploadLogC)
Q_DECLARE_LOGGING_CATEGORY(taskMetaCacheLogC)
Q_DECLARE_LOGGING_CATEGORY(taskHttpMetaCacheLogC)

View File

@ -1,6 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-only // SPDX-License-Identifier: GPL-3.0-only
/* /*
* PolyMC - Minecraft Launcher * Prism Launcher - Minecraft Launcher
* Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (c) 2022 flowln <flowlnlnln@gmail.com>
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
@ -39,6 +39,8 @@
#include <QRegularExpression> #include <QRegularExpression>
#include "Application.h" #include "Application.h"
#include "net/Logging.h"
namespace Net { namespace Net {
/** Maximum time to hold a cache entry /** Maximum time to hold a cache entry
@ -97,11 +99,11 @@ Task::State MetaCacheSink::finalizeCache(QNetworkReply & reply)
{ // Cache lifetime { // Cache lifetime
if (m_is_eternal) { if (m_is_eternal) {
qDebug() << "[MetaCache] Adding eternal cache entry:" << m_entry->getFullPath(); qCDebug(taskMetaCacheLogC) << "Adding eternal cache entry:" << m_entry->getFullPath();
m_entry->makeEternal(true); m_entry->makeEternal(true);
} else if (reply.hasRawHeader("Cache-Control")) { } else if (reply.hasRawHeader("Cache-Control")) {
auto cache_control_header = reply.rawHeader("Cache-Control"); auto cache_control_header = reply.rawHeader("Cache-Control");
// qDebug() << "[MetaCache] Parsing 'Cache-Control' header with" << cache_control_header; qCDebug(taskMetaCacheLogC) << "Parsing 'Cache-Control' header with" << cache_control_header;
QRegularExpression max_age_expr("max-age=([0-9]+)"); QRegularExpression max_age_expr("max-age=([0-9]+)");
qint64 max_age = max_age_expr.match(cache_control_header).captured(1).toLongLong(); qint64 max_age = max_age_expr.match(cache_control_header).captured(1).toLongLong();
@ -109,7 +111,7 @@ Task::State MetaCacheSink::finalizeCache(QNetworkReply & reply)
} else if (reply.hasRawHeader("Expires")) { } else if (reply.hasRawHeader("Expires")) {
auto expires_header = reply.rawHeader("Expires"); auto expires_header = reply.rawHeader("Expires");
// qDebug() << "[MetaCache] Parsing 'Expires' header with" << expires_header; qCDebug(taskMetaCacheLogC) << "Parsing 'Expires' header with" << expires_header;
qint64 max_age = QDateTime::fromString(expires_header).toSecsSinceEpoch() - QDateTime::currentSecsSinceEpoch(); qint64 max_age = QDateTime::fromString(expires_header).toSecsSinceEpoch() - QDateTime::currentSecsSinceEpoch();
m_entry->setMaximumAge(max_age); m_entry->setMaximumAge(max_age);
@ -119,7 +121,7 @@ Task::State MetaCacheSink::finalizeCache(QNetworkReply & reply)
if (reply.hasRawHeader("Age")) { if (reply.hasRawHeader("Age")) {
auto age_header = reply.rawHeader("Age"); auto age_header = reply.rawHeader("Age");
// qDebug() << "[MetaCache] Parsing 'Age' header with" << age_header; qCDebug(taskMetaCacheLogC) << "Parsing 'Age' header with" << age_header;
qint64 current_age = age_header.toLongLong(); qint64 current_age = age_header.toLongLong();
m_entry->setCurrentAge(current_age); m_entry->setCurrentAge(current_age);

View File

@ -1,6 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-only // SPDX-License-Identifier: GPL-3.0-only
/* /*
* PolyMC - Minecraft Launcher * Prism Launcher - Minecraft Launcher
* Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (c) 2022 flowln <flowlnlnln@gmail.com>
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify

View File

@ -1,7 +1,8 @@
// SPDX-License-Identifier: GPL-3.0-only // SPDX-License-Identifier: GPL-3.0-only
/* /*
* PolyMC - Minecraft Launcher * Prism Launcher - Minecraft Launcher
* Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (c) 2022 flowln <flowlnlnln@gmail.com>
* Copyright (C) 2023 Rachel Powers <508861+Ryex@users.noreply.github.com>
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -44,7 +45,7 @@
class NetAction : public Task { class NetAction : public Task {
Q_OBJECT Q_OBJECT
protected: protected:
explicit NetAction() : Task() {}; explicit NetAction() : Task(){};
public: public:
using Ptr = shared_qobject_ptr<NetAction>; using Ptr = shared_qobject_ptr<NetAction>;
@ -80,7 +81,7 @@ class NetAction : public Task {
} }
protected: protected:
void executeTask() override {}; void executeTask() override{};
public: public:
shared_qobject_ptr<QNetworkAccessManager> m_network; shared_qobject_ptr<QNetworkAccessManager> m_network;

View File

@ -1,8 +1,9 @@
// SPDX-License-Identifier: GPL-3.0-only // SPDX-License-Identifier: GPL-3.0-only
/* /*
* PolyMC - Minecraft Launcher * Prism Launcher - Minecraft Launcher
* Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (c) 2022 flowln <flowlnlnln@gmail.com>
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
* Copyright (C) 2023 Rachel Powers <508861+Ryex@users.noreply.github.com>
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by

View File

@ -1,7 +1,8 @@
// SPDX-License-Identifier: GPL-3.0-only // SPDX-License-Identifier: GPL-3.0-only
/* /*
* PolyMC - Minecraft Launcher * Prism Launcher - Minecraft Launcher
* Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (c) 2022 flowln <flowlnlnln@gmail.com>
* Copyright (C) 2023 Rachel Powers <508861+Ryex@users.noreply.github.com>
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by

View File

@ -1,6 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-only // SPDX-License-Identifier: GPL-3.0-only
/* /*
* PolyMC - Minecraft Launcher * Prism Launcher - Minecraft Launcher
* Copyright (C) 2022 Lenny McLennington <lenny@sneed.church> * Copyright (C) 2022 Lenny McLennington <lenny@sneed.church>
* Copyright (C) 2022 Swirl <swurl@swurl.xyz> * Copyright (C) 2022 Swirl <swurl@swurl.xyz>
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
@ -47,6 +47,8 @@
#include <QFile> #include <QFile>
#include <QUrlQuery> #include <QUrlQuery>
#include "net/Logging.h"
std::array<PasteUpload::PasteTypeInfo, 4> PasteUpload::PasteTypes = { std::array<PasteUpload::PasteTypeInfo, 4> PasteUpload::PasteTypes = {
{{"0x0.st", "https://0x0.st", ""}, {{"0x0.st", "https://0x0.st", ""},
{"hastebin", "https://hst.sh", "/documents"}, {"hastebin", "https://hst.sh", "/documents"},
@ -147,7 +149,7 @@ void PasteUpload::executeTask()
void PasteUpload::downloadError(QNetworkReply::NetworkError error) void PasteUpload::downloadError(QNetworkReply::NetworkError error)
{ {
// error happened during download. // error happened during download.
qCritical() << "Network error: " << error; qCCritical(taskUploadLogC) << getUid().toString() << "Network error: " << error;
emitFailed(m_reply->errorString()); emitFailed(m_reply->errorString());
} }
@ -166,7 +168,7 @@ void PasteUpload::downloadFinished()
{ {
QString reasonPhrase = m_reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString(); QString reasonPhrase = m_reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString();
emitFailed(tr("Error: %1 returned unexpected status code %2 %3").arg(m_uploadUrl).arg(statusCode).arg(reasonPhrase)); emitFailed(tr("Error: %1 returned unexpected status code %2 %3").arg(m_uploadUrl).arg(statusCode).arg(reasonPhrase));
qCritical() << m_uploadUrl << " returned unexpected status code " << statusCode << " with body: " << data; qCCritical(taskUploadLogC) << getUid().toString() << m_uploadUrl << " returned unexpected status code " << statusCode << " with body: " << data;
m_reply.reset(); m_reply.reset();
return; return;
} }
@ -187,7 +189,7 @@ void PasteUpload::downloadFinished()
else else
{ {
emitFailed(tr("Error: %1 returned a malformed response body").arg(m_uploadUrl)); emitFailed(tr("Error: %1 returned a malformed response body").arg(m_uploadUrl));
qCritical() << m_uploadUrl << " returned malformed response body: " << data; qCCritical(taskUploadLogC) << getUid().toString() << getUid().toString() << m_uploadUrl << " returned malformed response body: " << data;
return; return;
} }
break; break;
@ -206,15 +208,15 @@ void PasteUpload::downloadFinished()
{ {
QString error = jsonObj["error"].toString(); QString error = jsonObj["error"].toString();
emitFailed(tr("Error: %1 returned an error: %2").arg(m_uploadUrl, error)); emitFailed(tr("Error: %1 returned an error: %2").arg(m_uploadUrl, error));
qCritical() << m_uploadUrl << " returned error: " << error; qCCritical(taskUploadLogC) << getUid().toString() << m_uploadUrl << " returned error: " << error;
qCritical() << "Response body: " << data; qCCritical(taskUploadLogC) << getUid().toString() << "Response body: " << data;
return; return;
} }
} }
else else
{ {
emitFailed(tr("Error: %1 returned a malformed response body").arg(m_uploadUrl)); emitFailed(tr("Error: %1 returned a malformed response body").arg(m_uploadUrl));
qCritical() << m_uploadUrl << " returned malformed response body: " << data; qCCritical(taskUploadLogC) << getUid().toString() << m_uploadUrl << " returned malformed response body: " << data;
return; return;
} }
break; break;
@ -234,16 +236,16 @@ void PasteUpload::downloadFinished()
QString error = jsonObj["error"].toString(); QString error = jsonObj["error"].toString();
QString message = (jsonObj.contains("message") && jsonObj["message"].isString()) ? jsonObj["message"].toString() : "none"; QString message = (jsonObj.contains("message") && jsonObj["message"].isString()) ? jsonObj["message"].toString() : "none";
emitFailed(tr("Error: %1 returned an error code: %2\nError message: %3").arg(m_uploadUrl, error, message)); emitFailed(tr("Error: %1 returned an error code: %2\nError message: %3").arg(m_uploadUrl, error, message));
qCritical() << m_uploadUrl << " returned error: " << error; qCCritical(taskUploadLogC) << getUid().toString() << m_uploadUrl << " returned error: " << error;
qCritical() << "Error message: " << message; qCCritical(taskUploadLogC) << getUid().toString() << "Error message: " << message;
qCritical() << "Response body: " << data; qCCritical(taskUploadLogC) << getUid().toString() << "Response body: " << data;
return; return;
} }
} }
else else
{ {
emitFailed(tr("Error: %1 returned a malformed response body").arg(m_uploadUrl)); emitFailed(tr("Error: %1 returned a malformed response body").arg(m_uploadUrl));
qCritical() << m_uploadUrl << " returned malformed response body: " << data; qCCritical(taskUploadLogC) << getUid().toString() << m_uploadUrl << " returned malformed response body: " << data;
return; return;
} }
break; break;

View File

@ -1,6 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-only // SPDX-License-Identifier: GPL-3.0-only
/* /*
* PolyMC - Minecraft Launcher * Prism Launcher - Minecraft Launcher
* Copyright (C) 2022 Lenny McLennington <lenny@sneed.church> * Copyright (C) 2022 Lenny McLennington <lenny@sneed.church>
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify

View File

@ -4,6 +4,7 @@
* Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (c) 2022 flowln <flowlnlnln@gmail.com>
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
* Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me> * Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me>
* Copyright (C) 2023 Rachel Powers <508861+Ryex@users.noreply.github.com>
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -42,6 +43,8 @@
#include "BuildConfig.h" #include "BuildConfig.h"
#include "Application.h" #include "Application.h"
#include "net/Logging.h"
namespace Net { namespace Net {
bool Upload::abort() bool Upload::abort()
@ -60,11 +63,11 @@ namespace Net {
void Upload::downloadError(QNetworkReply::NetworkError error) { void Upload::downloadError(QNetworkReply::NetworkError error) {
if (error == QNetworkReply::OperationCanceledError) { if (error == QNetworkReply::OperationCanceledError) {
qCritical() << "Aborted " << m_url.toString(); qCCritical(taskUploadLogC) << getUid().toString() << "Aborted " << m_url.toString();
m_state = State::AbortedByUser; m_state = State::AbortedByUser;
} else { } else {
// error happened during download. // error happened during download.
qCritical() << "Failed " << m_url.toString() << " with reason " << error; qCCritical(taskUploadLogC) << getUid().toString() << "Failed " << m_url.toString() << " with reason " << error;
m_state = State::Failed; m_state = State::Failed;
} }
} }
@ -72,9 +75,9 @@ namespace Net {
void Upload::sslErrors(const QList<QSslError> &errors) { void Upload::sslErrors(const QList<QSslError> &errors) {
int i = 1; int i = 1;
for (const auto& error : errors) { for (const auto& error : errors) {
qCritical() << "Upload" << m_url.toString() << "SSL Error #" << i << " : " << error.errorString(); qCCritical(taskUploadLogC) << getUid().toString() << "Upload" << m_url.toString() << "SSL Error #" << i << " : " << error.errorString();
auto cert = error.certificate(); auto cert = error.certificate();
qCritical() << "Certificate in question:\n" << cert.toText(); qCCritical(taskUploadLogC) << getUid().toString() << "Certificate in question:\n" << cert.toText();
i++; i++;
} }
} }
@ -117,17 +120,17 @@ namespace Net {
*/ */
redirect = QUrl(redirectStr, QUrl::TolerantMode); redirect = QUrl(redirectStr, QUrl::TolerantMode);
if (!redirect.isValid()) { if (!redirect.isValid()) {
qWarning() << "Failed to parse redirect URL:" << redirectStr; qCWarning(taskUploadLogC) << getUid().toString() << "Failed to parse redirect URL:" << redirectStr;
downloadError(QNetworkReply::ProtocolFailure); downloadError(QNetworkReply::ProtocolFailure);
return false; return false;
} }
qDebug() << "Fixed location header:" << redirect; qCDebug(taskUploadLogC) << getUid().toString() << "Fixed location header:" << redirect;
} else { } else {
qDebug() << "Location header:" << redirect; qCDebug(taskUploadLogC) << getUid().toString() << "Location header:" << redirect;
} }
m_url = QUrl(redirect.toString()); m_url = QUrl(redirect.toString());
qDebug() << "Following redirect to " << m_url.toString(); qCDebug(taskUploadLogC) << getUid().toString() << "Following redirect to " << m_url.toString();
startAction(m_network); startAction(m_network);
return true; return true;
} }
@ -136,25 +139,25 @@ namespace Net {
// handle HTTP redirection first // handle HTTP redirection first
// very unlikely for post requests, still can happen // very unlikely for post requests, still can happen
if (handleRedirect()) { if (handleRedirect()) {
qDebug() << "Upload redirected:" << m_url.toString(); qCDebug(taskUploadLogC) << getUid().toString() << "Upload redirected:" << m_url.toString();
return; return;
} }
// if the download failed before this point ... // if the download failed before this point ...
if (m_state == State::Succeeded) { if (m_state == State::Succeeded) {
qDebug() << "Upload failed but we are allowed to proceed:" << m_url.toString(); qCDebug(taskUploadLogC) << getUid().toString() << "Upload failed but we are allowed to proceed:" << m_url.toString();
m_sink->abort(); m_sink->abort();
m_reply.reset(); m_reply.reset();
emit succeeded(); emit succeeded();
return; return;
} else if (m_state == State::Failed) { } else if (m_state == State::Failed) {
qDebug() << "Upload failed in previous step:" << m_url.toString(); qCDebug(taskUploadLogC) << getUid().toString() << "Upload failed in previous step:" << m_url.toString();
m_sink->abort(); m_sink->abort();
m_reply.reset(); m_reply.reset();
emit failed(""); emit failed("");
return; return;
} else if (m_state == State::AbortedByUser) { } else if (m_state == State::AbortedByUser) {
qDebug() << "Upload aborted in previous step:" << m_url.toString(); qCDebug(taskUploadLogC) << getUid().toString() << "Upload aborted in previous step:" << m_url.toString();
m_sink->abort(); m_sink->abort();
m_reply.reset(); m_reply.reset();
emit aborted(); emit aborted();
@ -164,21 +167,21 @@ namespace Net {
// make sure we got all the remaining data, if any // make sure we got all the remaining data, if any
auto data = m_reply->readAll(); auto data = m_reply->readAll();
if (data.size()) { if (data.size()) {
qDebug() << "Writing extra" << data.size() << "bytes"; qCDebug(taskUploadLogC) << getUid().toString() << "Writing extra" << data.size() << "bytes";
m_state = m_sink->write(data); m_state = m_sink->write(data);
} }
// otherwise, finalize the whole graph // otherwise, finalize the whole graph
m_state = m_sink->finalize(*m_reply.get()); m_state = m_sink->finalize(*m_reply.get());
if (m_state != State::Succeeded) { if (m_state != State::Succeeded) {
qDebug() << "Upload failed to finalize:" << m_url.toString(); qCDebug(taskUploadLogC) << getUid().toString() << "Upload failed to finalize:" << m_url.toString();
m_sink->abort(); m_sink->abort();
m_reply.reset(); m_reply.reset();
emit failed(""); emit failed("");
return; return;
} }
m_reply.reset(); m_reply.reset();
qDebug() << "Upload succeeded:" << m_url.toString(); qCDebug(taskUploadLogC) << getUid().toString() << "Upload succeeded:" << m_url.toString();
emit succeeded(); emit succeeded();
} }
@ -193,7 +196,7 @@ namespace Net {
setStatus(tr("Uploading %1").arg(m_url.toString())); setStatus(tr("Uploading %1").arg(m_url.toString()));
if (m_state == State::AbortedByUser) { if (m_state == State::AbortedByUser) {
qWarning() << "Attempt to start an aborted Upload:" << m_url.toString(); qCWarning(taskUploadLogC) << getUid().toString() << "Attempt to start an aborted Upload:" << m_url.toString();
emit aborted(); emit aborted();
return; return;
} }
@ -202,10 +205,10 @@ namespace Net {
switch (m_state) { switch (m_state) {
case State::Succeeded: case State::Succeeded:
emitSucceeded(); emitSucceeded();
qDebug() << "Upload cache hit " << m_url.toString(); qCDebug(taskUploadLogC) << getUid().toString() << "Upload cache hit " << m_url.toString();
return; return;
case State::Running: case State::Running:
qDebug() << "Uploading " << m_url.toString(); qCDebug(taskUploadLogC) << getUid().toString() << "Uploading " << m_url.toString();
break; break;
case State::Inactive: case State::Inactive:
case State::Failed: case State::Failed:

View File

@ -1,8 +1,9 @@
// SPDX-License-Identifier: GPL-3.0-only // SPDX-License-Identifier: GPL-3.0-only
/* /*
* PolyMC - Minecraft Launcher * Prism Launcher - Minecraft Launcher
* Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (c) 2022 flowln <flowlnlnln@gmail.com>
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
* Copyright (C) 2023 Rachel Powers <508861+Ryex@users.noreply.github.com>
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by

16
launcher/qtlogging.ini Normal file
View File

@ -0,0 +1,16 @@
[Rules]
*.debug=true
# prevent log spam and strange bugs
# qt.qpa.drawing in particular causes theme artifacts on MacOS
qt.*.debug=false
# don't log credentials by default
launcher.auth.credentials.debug=false
# remove the debug lines, other log levels still get through
launcher.task.net.download.debug=false
# enable or disable whole catageries
launcher.task.net=true
launcher.task=false
launcher.task.net.upload=true
launcher.task.net.metacache=false
launcher.task.net.metacache.http=true

View File

@ -1,7 +1,8 @@
// SPDX-License-Identifier: GPL-3.0-only // SPDX-License-Identifier: GPL-3.0-only
/* /*
* PolyMC - Minecraft Launcher * Prism Launcher - Minecraft Launcher
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
* Copyright (C) 2023 flowln <flowlnlnln@gmail.com>
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -42,132 +43,51 @@
#include <QSaveFile> #include <QSaveFile>
#include <QDebug> #include <QDebug>
#include <QSettings>
INIFile::INIFile() INIFile::INIFile()
{ {
} }
QString INIFile::unescape(QString orig)
{
QString out;
QChar prev = QChar::Null;
for(auto c: orig)
{
if(prev == '\\')
{
if(c == 'n')
out += '\n';
else if(c == 't')
out += '\t';
else if(c == '#')
out += '#';
else
out += c;
prev = QChar::Null;
}
else
{
if(c == '\\')
{
prev = c;
continue;
}
out += c;
prev = QChar::Null;
}
}
return out;
}
QString INIFile::escape(QString orig)
{
QString out;
for(auto c: orig)
{
if(c == '\n')
out += "\\n";
else if (c == '\t')
out += "\\t";
else if(c == '\\')
out += "\\\\";
else if(c == '#')
out += "\\#";
else
out += c;
}
return out;
}
bool INIFile::saveFile(QString fileName) bool INIFile::saveFile(QString fileName)
{ {
QByteArray outArray; QSettings _settings_obj{ fileName, QSettings::Format::IniFormat };
for (Iterator iter = begin(); iter != end(); iter++) _settings_obj.setFallbacksEnabled(false);
{
QString value = iter.value().toString(); for (Iterator iter = begin(); iter != end(); iter++)
value = escape(value); _settings_obj.setValue(iter.key(), iter.value());
outArray.append(iter.key().toUtf8());
outArray.append('='); _settings_obj.sync();
outArray.append(value.toUtf8());
outArray.append('\n'); if (auto status = _settings_obj.status(); status != QSettings::Status::NoError) {
} // Shouldn't be possible!
Q_ASSERT(status != QSettings::Status::FormatError);
if (status == QSettings::Status::AccessError)
qCritical() << "An access error occurred (e.g. trying to write to a read-only file).";
try
{
FS::write(fileName, outArray);
}
catch (const Exception &e)
{
qCritical() << e.what();
return false; return false;
} }
return true; return true;
} }
bool INIFile::loadFile(QString fileName) bool INIFile::loadFile(QString fileName)
{ {
QFile file(fileName); QSettings _settings_obj{ fileName, QSettings::Format::IniFormat };
if (!file.open(QIODevice::ReadOnly)) _settings_obj.setFallbacksEnabled(false);
if (auto status = _settings_obj.status(); status != QSettings::Status::NoError) {
if (status == QSettings::Status::AccessError)
qCritical() << "An access error occurred (e.g. trying to write to a read-only file).";
if (status == QSettings::Status::FormatError)
qCritical() << "A format error occurred (e.g. loading a malformed INI file).";
return false; return false;
bool success = loadFile(file.readAll());
file.close();
return success;
}
bool INIFile::loadFile(QByteArray file)
{
QTextStream in(file);
#if QT_VERSION <= QT_VERSION_CHECK(6, 0, 0)
in.setCodec("UTF-8");
#endif
QStringList lines = in.readAll().split('\n');
for (int i = 0; i < lines.count(); i++)
{
QString &lineRaw = lines[i];
// Ignore comments.
int commentIndex = 0;
QString line = lineRaw;
// Search for comments until no more escaped # are available
while((commentIndex = line.indexOf('#', commentIndex + 1)) != -1) {
if(commentIndex > 0 && line.at(commentIndex - 1) == '\\') {
continue;
}
line = line.left(lineRaw.indexOf('#')).trimmed();
}
int eqPos = line.indexOf('=');
if (eqPos == -1)
continue;
QString key = line.left(eqPos).trimmed();
QString valueStr = line.right(line.length() - eqPos - 1).trimmed();
valueStr = unescape(valueStr);
QVariant value(valueStr);
this->operator[](key) = value;
} }
for (auto&& key : _settings_obj.allKeys())
insert(key, _settings_obj.value(key));
return true; return true;
} }
@ -183,3 +103,4 @@ void INIFile::set(QString key, QVariant val)
{ {
this->operator[](key) = val; this->operator[](key) = val;
} }

View File

@ -1,16 +1,37 @@
/* Copyright 2013-2021 MultiMC Contributors // SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
* Copyright (C) 2023 flowln <flowlnlnln@gmail.com>
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * This program is free software: you can redistribute it and/or modify
* you may not use this file except in compliance with the License. * it under the terms of the GNU General Public License as published by
* You may obtain a copy of the License at * the Free Software Foundation, version 3.
* *
* http://www.apache.org/licenses/LICENSE-2.0 * 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.
* *
* Unless required by applicable law or agreed to in writing, software * You should have received a copy of the GNU General Public License
* distributed under the License is distributed on an "AS IS" BASIS, * along with this program. If not, see <https://www.gnu.org/licenses/>.
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and * This file incorporates work covered by the following copyright and
* limitations under the License. * permission notice:
*
* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ */
#pragma once #pragma once
@ -19,18 +40,18 @@
#include <QVariant> #include <QVariant>
#include <QIODevice> #include <QIODevice>
#include <QJsonDocument>
#include <QJsonArray>
// Sectionless INI parser (for instance config files) // Sectionless INI parser (for instance config files)
class INIFile : public QMap<QString, QVariant> class INIFile : public QMap<QString, QVariant>
{ {
public: public:
explicit INIFile(); explicit INIFile();
bool loadFile(QByteArray file);
bool loadFile(QString fileName); bool loadFile(QString fileName);
bool saveFile(QString fileName); bool saveFile(QString fileName);
QVariant get(QString key, QVariant def) const; QVariant get(QString key, QVariant def) const;
void set(QString key, QVariant val); void set(QString key, QVariant val);
static QString unescape(QString orig);
static QString escape(QString orig);
}; };

View File

@ -19,6 +19,8 @@
#include <QMap> #include <QMap>
#include <QStringList> #include <QStringList>
#include <QVariant> #include <QVariant>
#include <QJsonDocument>
#include <QJsonArray>
#include <memory> #include <memory>
class Setting; class Setting;

View File

@ -1,11 +1,49 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (c) 2022 flowln <flowlnlnln@gmail.com>
* Copyright (c) 2023 Rachel Powers <508861+Ryex@users.noreply.github.com>
*
* 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, version 3.
*
* 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 <https://www.gnu.org/licenses/>.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ConcurrentTask.h" #include "ConcurrentTask.h"
#include <QDebug>
#include <QCoreApplication> #include <QCoreApplication>
#include <QDebug>
#include "tasks/Task.h"
ConcurrentTask::ConcurrentTask(QObject* parent, QString task_name, int max_concurrent) ConcurrentTask::ConcurrentTask(QObject* parent, QString task_name, int max_concurrent)
: Task(parent), m_name(task_name), m_total_max_size(max_concurrent) : Task(parent), m_name(task_name), m_total_max_size(max_concurrent)
{ setObjectName(task_name); } {
setObjectName(task_name);
}
ConcurrentTask::~ConcurrentTask() ConcurrentTask::~ConcurrentTask()
{ {
@ -15,14 +53,9 @@ ConcurrentTask::~ConcurrentTask()
} }
} }
auto ConcurrentTask::getStepProgress() const -> qint64 auto ConcurrentTask::getStepProgress() const -> TaskStepProgressList
{ {
return m_stepProgress; return m_task_progress.values();
}
auto ConcurrentTask::getStepTotalProgress() const -> qint64
{
return m_stepTotalProgress;
} }
void ConcurrentTask::addTask(Task::Ptr task) void ConcurrentTask::addTask(Task::Ptr task)
@ -32,11 +65,9 @@ void ConcurrentTask::addTask(Task::Ptr task)
void ConcurrentTask::executeTask() void ConcurrentTask::executeTask()
{ {
// Start the least amount of tasks needed, but at least one // Start one task, startNext handles starting the up to the m_total_max_size
int num_starts = qMax(1, qMin(m_total_max_size, m_queue.size())); // while tracking the number currently being done
for (int i = 0; i < num_starts; i++) { QMetaObject::invokeMethod(this, &ConcurrentTask::startNext, Qt::QueuedConnection);
QMetaObject::invokeMethod(this, &ConcurrentTask::startNext, Qt::QueuedConnection);
}
} }
bool ConcurrentTask::abort() bool ConcurrentTask::abort()
@ -97,18 +128,22 @@ void ConcurrentTask::startNext()
Task::Ptr next = m_queue.dequeue(); Task::Ptr next = m_queue.dequeue();
connect(next.get(), &Task::succeeded, this, [this, next] { subTaskSucceeded(next); }); connect(next.get(), &Task::succeeded, this, [this, next]() { subTaskSucceeded(next); });
connect(next.get(), &Task::failed, this, [this, next](QString msg) { subTaskFailed(next, msg); }); connect(next.get(), &Task::failed, this, [this, next](QString msg) { subTaskFailed(next, msg); });
connect(next.get(), &Task::status, this, &ConcurrentTask::subTaskStatus); connect(next.get(), &Task::status, this, [this, next](QString msg) { subTaskStatus(next, msg); });
connect(next.get(), &Task::stepStatus, this, &ConcurrentTask::subTaskStatus); connect(next.get(), &Task::details, this, [this, next](QString msg) { subTaskDetails(next, msg); });
connect(next.get(), &Task::stepProgress, this, [this, next](TaskStepProgress const& tp) { subTaskStepProgress(next, tp); });
connect(next.get(), &Task::progress, this, &ConcurrentTask::subTaskProgress); connect(next.get(), &Task::progress, this, [this, next](qint64 current, qint64 total) { subTaskProgress(next, current, total); });
m_doing.insert(next.get(), next); m_doing.insert(next.get(), next);
auto task_progress = std::make_shared<TaskStepProgress>(TaskStepProgress({ next->getUid() }));
m_task_progress.insert(next->getUid(), task_progress);
setStepStatus(next->isMultiStep() ? next->getStepStatus() : next->getStatus());
updateState(); updateState();
updateStepProgress(*task_progress.get(), Operation::ADDED);
QCoreApplication::processEvents(); QCoreApplication::processEvents();
@ -123,12 +158,17 @@ void ConcurrentTask::startNext()
void ConcurrentTask::subTaskSucceeded(Task::Ptr task) void ConcurrentTask::subTaskSucceeded(Task::Ptr task)
{ {
m_done.insert(task.get(), task); m_done.insert(task.get(), task);
m_succeeded.insert(task.get(), task);
m_doing.remove(task.get()); m_doing.remove(task.get());
auto task_progress = m_task_progress.value(task->getUid());
task_progress->state = TaskStepState::Succeeded;
disconnect(task.get(), 0, this, 0); disconnect(task.get(), 0, this, 0);
emit stepProgress(*task_progress.get());
updateState(); updateState();
updateStepProgress(*task_progress.get(), Operation::REMOVED);
startNext(); startNext();
} }
@ -139,27 +179,128 @@ void ConcurrentTask::subTaskFailed(Task::Ptr task, const QString& msg)
m_doing.remove(task.get()); m_doing.remove(task.get());
auto task_progress = m_task_progress.value(task->getUid());
task_progress->state = TaskStepState::Failed;
disconnect(task.get(), 0, this, 0); disconnect(task.get(), 0, this, 0);
emit stepProgress(*task_progress.get());
updateState(); updateState();
updateStepProgress(*task_progress.get(), Operation::REMOVED);
startNext(); startNext();
} }
void ConcurrentTask::subTaskStatus(const QString& msg) void ConcurrentTask::subTaskStatus(Task::Ptr task, const QString& msg)
{ {
setStepStatus(msg); auto task_progress = m_task_progress.value(task->getUid());
task_progress->status = msg;
task_progress->state = TaskStepState::Running;
emit stepProgress(*task_progress.get());
if (totalSize() == 1) {
setStatus(msg);
}
} }
void ConcurrentTask::subTaskProgress(qint64 current, qint64 total) void ConcurrentTask::subTaskDetails(Task::Ptr task, const QString& msg)
{ {
m_stepProgress = current; auto task_progress = m_task_progress.value(task->getUid());
m_stepTotalProgress = total; task_progress->details = msg;
task_progress->state = TaskStepState::Running;
emit stepProgress(*task_progress.get());
if (totalSize() == 1) {
setDetails(msg);
}
}
void ConcurrentTask::subTaskProgress(Task::Ptr task, qint64 current, qint64 total)
{
auto task_progress = m_task_progress.value(task->getUid());
task_progress->old_current = task_progress->current;
task_progress->old_total = task_progress->old_total;
task_progress->current = current;
task_progress->total = total;
task_progress->state = TaskStepState::Running;
emit stepProgress(*task_progress.get());
updateStepProgress(*task_progress.get(), Operation::CHANGED);
updateState();
if (totalSize() == 1) {
setProgress(task_progress->current, task_progress->total);
}
}
void ConcurrentTask::subTaskStepProgress(Task::Ptr task, TaskStepProgress const& task_progress)
{
Operation op = Operation::ADDED;
if (!m_task_progress.contains(task_progress.uid)) {
m_task_progress.insert(task_progress.uid, std::make_shared<TaskStepProgress>(task_progress));
op = Operation::ADDED;
emit stepProgress(task_progress);
updateStepProgress(task_progress, op);
} else {
auto tp = m_task_progress.value(task_progress.uid);
tp->old_current = tp->current;
tp->old_total = tp->total;
tp->current = task_progress.current;
tp->total = task_progress.total;
tp->status = task_progress.status;
tp->details = task_progress.details;
op = Operation::CHANGED;
emit stepProgress(*tp.get());
updateStepProgress(*tp.get(), op);
}
}
void ConcurrentTask::updateStepProgress(TaskStepProgress const& changed_progress, Operation op)
{
switch (op) {
case Operation::ADDED:
m_stepProgress += changed_progress.current;
m_stepTotalProgress += changed_progress.total;
break;
case Operation::REMOVED:
m_stepProgress -= changed_progress.current;
m_stepTotalProgress -= changed_progress.total;
break;
case Operation::CHANGED:
m_stepProgress -= changed_progress.old_current;
m_stepTotalProgress -= changed_progress.old_total;
m_stepProgress += changed_progress.current;
m_stepTotalProgress += changed_progress.total;
break;
}
} }
void ConcurrentTask::updateState() void ConcurrentTask::updateState()
{ {
setProgress(m_done.count(), totalSize()); if (totalSize() > 1) {
setStatus(tr("Executing %1 task(s) (%2 out of %3 are done)") setProgress(m_done.count(), totalSize());
.arg(QString::number(m_doing.count()), QString::number(m_done.count()), QString::number(totalSize()))); setStatus(tr("Executing %1 task(s) (%2 out of %3 are done)")
.arg(QString::number(m_doing.count()), QString::number(m_done.count()), QString::number(totalSize())));
} else {
setProgress(m_stepProgress, m_stepTotalProgress);
QString status = tr("Please wait...");
if (m_queue.size() > 0) {
status = tr("Waiting for a task to start...");
} else if (m_doing.size() > 0) {
status = tr("Executing 1 task:");
} else if (m_done.size() > 0) {
status = tr("Task finished.");
}
setStatus(status);
}
} }

View File

@ -1,13 +1,51 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (c) 2022 flowln <flowlnlnln@gmail.com>
* Copyright (c) 2023 Rachel Powers <508861+Ryex@users.noreply.github.com>
*
* 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, version 3.
*
* 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 <https://www.gnu.org/licenses/>.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once #pragma once
#include <QHash>
#include <QQueue> #include <QQueue>
#include <QSet> #include <QSet>
#include <QUuid>
#include <memory>
#include "tasks/Task.h" #include "tasks/Task.h"
class ConcurrentTask : public Task { class ConcurrentTask : public Task {
Q_OBJECT Q_OBJECT
public: public:
using Ptr = shared_qobject_ptr<ConcurrentTask>; using Ptr = shared_qobject_ptr<ConcurrentTask>;
explicit ConcurrentTask(QObject* parent = nullptr, QString task_name = "", int max_concurrent = 6); explicit ConcurrentTask(QObject* parent = nullptr, QString task_name = "", int max_concurrent = 6);
@ -15,15 +53,12 @@ public:
bool canAbort() const override { return true; } bool canAbort() const override { return true; }
inline auto isMultiStep() const -> bool override { return m_queue.size() > 1; }; inline auto isMultiStep() const -> bool override { return totalSize() > 1; };
auto getStepProgress() const -> qint64 override; auto getStepProgress() const -> TaskStepProgressList override;
auto getStepTotalProgress() const -> qint64 override;
inline auto getStepStatus() const -> QString override { return m_step_status; }
void addTask(Task::Ptr task); void addTask(Task::Ptr task);
public slots: public slots:
bool abort() override; bool abort() override;
/** Resets the internal state of the task. /** Resets the internal state of the task.
@ -31,26 +66,28 @@ public slots:
*/ */
void clear(); void clear();
protected protected slots:
slots:
void executeTask() override; void executeTask() override;
virtual void startNext(); virtual void startNext();
void subTaskSucceeded(Task::Ptr); void subTaskSucceeded(Task::Ptr);
void subTaskFailed(Task::Ptr, const QString &msg); void subTaskFailed(Task::Ptr, const QString& msg);
void subTaskStatus(const QString &msg); void subTaskStatus(Task::Ptr task, const QString& msg);
void subTaskProgress(qint64 current, qint64 total); void subTaskDetails(Task::Ptr task, const QString& msg);
void subTaskProgress(Task::Ptr task, qint64 current, qint64 total);
void subTaskStepProgress(Task::Ptr task, TaskStepProgress const& task_step_progress);
protected: protected:
// NOTE: This is not thread-safe. // NOTE: This is not thread-safe.
[[nodiscard]] unsigned int totalSize() const { return m_queue.size() + m_doing.size() + m_done.size(); } [[nodiscard]] unsigned int totalSize() const { return m_queue.size() + m_doing.size() + m_done.size(); }
void setStepStatus(QString status) { m_step_status = status; emit stepStatus(status); }; enum class Operation { ADDED, REMOVED, CHANGED };
void updateStepProgress(TaskStepProgress const& changed_progress, Operation);
virtual void updateState(); virtual void updateState();
protected: protected:
QString m_name; QString m_name;
QString m_step_status; QString m_step_status;
@ -59,6 +96,9 @@ protected:
QHash<Task*, Task::Ptr> m_doing; QHash<Task*, Task::Ptr> m_doing;
QHash<Task*, Task::Ptr> m_done; QHash<Task*, Task::Ptr> m_done;
QHash<Task*, Task::Ptr> m_failed; QHash<Task*, Task::Ptr> m_failed;
QHash<Task*, Task::Ptr> m_succeeded;
QHash<QUuid, std::shared_ptr<TaskStepProgress>> m_task_progress;
int m_total_max_size; int m_total_max_size;

View File

@ -1,3 +1,37 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (c) 2022 flowln <flowlnlnln@gmail.com>
*
* 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, version 3.
*
* 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 <https://www.gnu.org/licenses/>.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "MultipleOptionsTask.h" #include "MultipleOptionsTask.h"
#include <QDebug> #include <QDebug>

View File

@ -1,3 +1,37 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (c) 2022 flowln <flowlnlnln@gmail.com>
*
* 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, version 3.
*
* 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 <https://www.gnu.org/licenses/>.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once #pragma once
#include "SequentialTask.h" #include "SequentialTask.h"

View File

@ -1,3 +1,38 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (c) 2022 flowln <flowlnlnln@gmail.com>
* Copyright (c) 2023 Rachel Powers <508861+Ryex@users.noreply.github.com>
*
* 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, version 3.
*
* 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 <https://www.gnu.org/licenses/>.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "SequentialTask.h" #include "SequentialTask.h"
#include <QDebug> #include <QDebug>

View File

@ -1,3 +1,38 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (c) 2022 flowln <flowlnlnln@gmail.com>
* Copyright (c) 2023 Rachel Powers <508861+Ryex@users.noreply.github.com>
*
* 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, version 3.
*
* 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 <https://www.gnu.org/licenses/>.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once #pragma once
#include "ConcurrentTask.h" #include "ConcurrentTask.h"

View File

@ -2,6 +2,7 @@
/* /*
* PolyMC - Minecraft Launcher * PolyMC - Minecraft Launcher
* Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (c) 2022 flowln <flowlnlnln@gmail.com>
* Copyright (c) 2023 Rachel Powers <508861+Ryex@users.noreply.github.com>
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -37,8 +38,11 @@
#include <QDebug> #include <QDebug>
Q_LOGGING_CATEGORY(taskLogC, "launcher.task")
Task::Task(QObject *parent, bool show_debug) : QObject(parent), m_show_debug(show_debug) Task::Task(QObject *parent, bool show_debug) : QObject(parent), m_show_debug(show_debug)
{ {
m_uid = QUuid::createUuid();
setAutoDelete(false); setAutoDelete(false);
} }
@ -51,11 +55,23 @@ void Task::setStatus(const QString &new_status)
} }
} }
void Task::setDetails(const QString& new_details)
{
if (m_details != new_details)
{
m_details = new_details;
emit details(m_details);
}
}
void Task::setProgress(qint64 current, qint64 total) void Task::setProgress(qint64 current, qint64 total)
{ {
m_progress = current; if ((m_progress != current) || (m_progressTotal != total)) {
m_progressTotal = total; m_progress = current;
emit progress(m_progress, m_progressTotal); m_progressTotal = total;
emit progress(m_progress, m_progressTotal);
}
} }
void Task::start() void Task::start()
@ -65,31 +81,31 @@ void Task::start()
case State::Inactive: case State::Inactive:
{ {
if (m_show_debug) if (m_show_debug)
qDebug() << "Task" << describe() << "starting for the first time"; qCDebug(taskLogC) << "Task" << describe() << "starting for the first time";
break; break;
} }
case State::AbortedByUser: case State::AbortedByUser:
{ {
if (m_show_debug) if (m_show_debug)
qDebug() << "Task" << describe() << "restarting for after being aborted by user"; qCDebug(taskLogC) << "Task" << describe() << "restarting for after being aborted by user";
break; break;
} }
case State::Failed: case State::Failed:
{ {
if (m_show_debug) if (m_show_debug)
qDebug() << "Task" << describe() << "restarting for after failing at first"; qCDebug(taskLogC) << "Task" << describe() << "restarting for after failing at first";
break; break;
} }
case State::Succeeded: case State::Succeeded:
{ {
if (m_show_debug) if (m_show_debug)
qDebug() << "Task" << describe() << "restarting for after succeeding at first"; qCDebug(taskLogC) << "Task" << describe() << "restarting for after succeeding at first";
break; break;
} }
case State::Running: case State::Running:
{ {
if (m_show_debug) if (m_show_debug)
qWarning() << "The launcher tried to start task" << describe() << "while it was already running!"; qCWarning(taskLogC) << "The launcher tried to start task" << describe() << "while it was already running!";
return; return;
} }
} }
@ -104,12 +120,12 @@ void Task::emitFailed(QString reason)
// Don't fail twice. // Don't fail twice.
if (!isRunning()) if (!isRunning())
{ {
qCritical() << "Task" << describe() << "failed while not running!!!!: " << reason; qCCritical(taskLogC) << "Task" << describe() << "failed while not running!!!!: " << reason;
return; return;
} }
m_state = State::Failed; m_state = State::Failed;
m_failReason = reason; m_failReason = reason;
qCritical() << "Task" << describe() << "failed: " << reason; qCCritical(taskLogC) << "Task" << describe() << "failed: " << reason;
emit failed(reason); emit failed(reason);
emit finished(); emit finished();
} }
@ -119,13 +135,13 @@ void Task::emitAborted()
// Don't abort twice. // Don't abort twice.
if (!isRunning()) if (!isRunning())
{ {
qCritical() << "Task" << describe() << "aborted while not running!!!!"; qCCritical(taskLogC) << "Task" << describe() << "aborted while not running!!!!";
return; return;
} }
m_state = State::AbortedByUser; m_state = State::AbortedByUser;
m_failReason = "Aborted."; m_failReason = "Aborted.";
if (m_show_debug) if (m_show_debug)
qDebug() << "Task" << describe() << "aborted."; qCDebug(taskLogC) << "Task" << describe() << "aborted.";
emit aborted(); emit aborted();
emit finished(); emit finished();
} }
@ -135,16 +151,21 @@ void Task::emitSucceeded()
// Don't succeed twice. // Don't succeed twice.
if (!isRunning()) if (!isRunning())
{ {
qCritical() << "Task" << describe() << "succeeded while not running!!!!"; qCCritical(taskLogC) << "Task" << describe() << "succeeded while not running!!!!";
return; return;
} }
m_state = State::Succeeded; m_state = State::Succeeded;
if (m_show_debug) if (m_show_debug)
qDebug() << "Task" << describe() << "succeeded"; qCDebug(taskLogC) << "Task" << describe() << "succeeded";
emit succeeded(); emit succeeded();
emit finished(); emit finished();
} }
void Task::propogateStepProgress(TaskStepProgress const& task_progress)
{
emit stepProgress(task_progress);
}
QString Task::describe() QString Task::describe()
{ {
QString outStr; QString outStr;
@ -159,6 +180,7 @@ QString Task::describe()
{ {
out << name; out << name;
} }
out << " ID: " << m_uid.toString(QUuid::WithoutBraces);
out << QChar(')'); out << QChar(')');
out.flush(); out.flush();
return outStr; return outStr;

View File

@ -1,7 +1,8 @@
// SPDX-License-Identifier: GPL-3.0-only // SPDX-License-Identifier: GPL-3.0-only
/* /*
* PolyMC - Minecraft Launcher * PrismLauncher - Minecraft Launcher
* Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (c) 2022 flowln <flowlnlnln@gmail.com>
* Copyright (c) 2023 Rachel Powers <508861+Ryex@users.noreply.github.com>
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -36,9 +37,40 @@
#pragma once #pragma once
#include <QRunnable> #include <QRunnable>
#include <QUuid>
#include <QLoggingCategory>
#include "QObjectPtr.h" #include "QObjectPtr.h"
Q_DECLARE_LOGGING_CATEGORY(taskLogC)
enum class TaskStepState {
Waiting,
Running,
Failed,
Succeeded
};
Q_DECLARE_METATYPE(TaskStepState)
struct TaskStepProgress {
QUuid uid;
qint64 current = 0;
qint64 total = -1;
qint64 old_current = 0;
qint64 old_total = -1;
QString status = "";
QString details = "";
TaskStepState state = TaskStepState::Waiting;
bool isDone() const { return (state == TaskStepState::Failed) || (state == TaskStepState::Succeeded); }
};
Q_DECLARE_METATYPE(TaskStepProgress)
typedef QList<std::shared_ptr<TaskStepProgress>> TaskStepProgressList;
class Task : public QObject, public QRunnable { class Task : public QObject, public QRunnable {
Q_OBJECT Q_OBJECT
public: public:
@ -73,12 +105,15 @@ class Task : public QObject, public QRunnable {
auto getState() const -> State { return m_state; } auto getState() const -> State { return m_state; }
QString getStatus() { return m_status; } QString getStatus() { return m_status; }
virtual auto getStepStatus() const -> QString { return m_status; } QString getDetails() { return m_details; }
qint64 getProgress() { return m_progress; } qint64 getProgress() { return m_progress; }
qint64 getTotalProgress() { return m_progressTotal; } qint64 getTotalProgress() { return m_progressTotal; }
virtual auto getStepProgress() const -> qint64 { return 0; } virtual auto getStepProgress() const -> TaskStepProgressList { return {}; }
virtual auto getStepTotalProgress() const -> qint64 { return 100; }
QUuid getUid() { return m_uid; }
protected: protected:
void logWarning(const QString& line); void logWarning(const QString& line);
@ -94,7 +129,8 @@ class Task : public QObject, public QRunnable {
void aborted(); void aborted();
void failed(QString reason); void failed(QString reason);
void status(QString status); void status(QString status);
void stepStatus(QString status); void details(QString details);
void stepProgress(TaskStepProgress const& task_progress);
/** Emitted when the canAbort() status has changed. /** Emitted when the canAbort() status has changed.
*/ */
@ -117,8 +153,11 @@ class Task : public QObject, public QRunnable {
virtual void emitAborted(); virtual void emitAborted();
virtual void emitFailed(QString reason = ""); virtual void emitFailed(QString reason = "");
virtual void propogateStepProgress(TaskStepProgress const& task_progress);
public slots: public slots:
void setStatus(const QString& status); void setStatus(const QString& status);
void setDetails(const QString& details);
void setProgress(qint64 current, qint64 total); void setProgress(qint64 current, qint64 total);
protected: protected:
@ -126,6 +165,7 @@ class Task : public QObject, public QRunnable {
QStringList m_Warnings; QStringList m_Warnings;
QString m_failReason = ""; QString m_failReason = "";
QString m_status; QString m_status;
QString m_details;
int m_progress = 0; int m_progress = 0;
int m_progressTotal = 100; int m_progressTotal = 100;
@ -135,4 +175,6 @@ class Task : public QObject, public QRunnable {
private: private:
// Change using setAbortStatus // Change using setAbortStatus
bool m_can_abort = false; bool m_can_abort = false;
QUuid m_uid;
}; };

View File

@ -1337,6 +1337,20 @@ void MainWindow::on_actionDeleteInstance_triggered()
if (response != QMessageBox::Yes) if (response != QMessageBox::Yes)
return; return;
auto linkedInstances = APPLICATION->instances()->getLinkedInstancesById(id);
if (!linkedInstances.empty()) {
response = CustomMessageBox::selectable(
this, tr("There are linked instances"),
tr("The following instance(s) might reference files in this instance:\n\n"
"%1\n\n"
"Deleting it could break the other instance(s), \n\n"
"Do you wish to proceed?", nullptr, linkedInstances.count()).arg(linkedInstances.join("\n")),
QMessageBox::Warning, QMessageBox::Yes | QMessageBox::No, QMessageBox::No
)->exec();
if (response != QMessageBox::Yes)
return;
}
if (APPLICATION->instances()->trashInstance(id)) { if (APPLICATION->instances()->trashInstance(id)) {
ui->actionUndoTrashInstance->setEnabled(APPLICATION->instances()->trashedSomething()); ui->actionUndoTrashInstance->setEnabled(APPLICATION->instances()->trashedSomething());
return; return;

View File

@ -195,7 +195,7 @@ void BlockedModsDialog::watchPath(QString path, bool watch_recursive)
auto to_watch = QFileInfo(path); auto to_watch = QFileInfo(path);
auto to_watch_path = to_watch.canonicalFilePath(); auto to_watch_path = to_watch.canonicalFilePath();
if (m_watcher.directories().contains(to_watch_path)) if (m_watcher.directories().contains(to_watch_path))
return; // don't watch the same path twice (no loops!) return; // don't watch the same path twice (no loops!)
qDebug() << "[Blocked Mods Dialog] Adding Watch Path:" << path; qDebug() << "[Blocked Mods Dialog] Adding Watch Path:" << path;
m_watcher.addPath(to_watch_path); m_watcher.addPath(to_watch_path);
@ -203,10 +203,9 @@ void BlockedModsDialog::watchPath(QString path, bool watch_recursive)
if (!to_watch.isDir() || !watch_recursive) if (!to_watch.isDir() || !watch_recursive)
return; return;
QDirIterator it(to_watch_path, QDir::Filter::Dirs | QDir::Filter::NoDotAndDotDot, QDirIterator::NoIteratorFlags); QDirIterator it(to_watch_path, QDir::Filter::Dirs | QDir::Filter::NoDotAndDotDot, QDirIterator::NoIteratorFlags);
while (it.hasNext()) { while (it.hasNext()) {
QString watch_dir = QDir(it.next()).canonicalPath(); // resolve symlinks and relative paths QString watch_dir = QDir(it.next()).canonicalPath(); // resolve symlinks and relative paths
watchPath(watch_dir, watch_recursive); watchPath(watch_dir, watch_recursive);
} }
} }
@ -302,11 +301,35 @@ bool BlockedModsDialog::checkValidPath(QString path)
{ {
const QFileInfo file = QFileInfo(path); const QFileInfo file = QFileInfo(path);
const QString filename = file.fileName(); const QString filename = file.fileName();
QString laxFilename(filename);
laxFilename.replace('+', ' ');
auto compare = [](QString fsfilename, QString metadataFilename) { auto compare = [](QString fsFilename, QString metadataFilename) {
return metadataFilename.compare(fsfilename, Qt::CaseInsensitive) == 0; return metadataFilename.compare(fsFilename, Qt::CaseInsensitive) == 0;
};
// super lax compare (but not fuzzy)
// convert to lowercase
// convert all speratores to whitespace
// simplify sequence of internal whitespace to a single space
// efectivly compare two strings ignoring all separators and case
auto laxCompare = [](QString fsfilename, QString metadataFilename) {
// allowed character seperators
QList<QChar> allowedSeperators = { '-', '+', '.' , '_'};
// copy in lowercase
auto fsName = fsfilename.toLower();
auto metaName = metadataFilename.toLower();
// replace all potential allowed seperatores with whitespace
for (auto sep : allowedSeperators) {
fsName = fsName.replace(sep, ' ');
metaName = metaName.replace(sep, ' ');
}
// remove extraneous whitespace
fsName = fsName.simplified();
metaName = metaName.simplified();
return fsName.compare(metaName) == 0;
}; };
for (auto& mod : m_mods) { for (auto& mod : m_mods) {
@ -314,7 +337,7 @@ bool BlockedModsDialog::checkValidPath(QString path)
qDebug() << "[Blocked Mods Dialog] Name match found:" << mod.name << "| From path:" << path; qDebug() << "[Blocked Mods Dialog] Name match found:" << mod.name << "| From path:" << path;
return true; return true;
} }
if (compare(laxFilename, mod.name)) { if (laxCompare(filename, mod.name)) {
qDebug() << "[Blocked Mods Dialog] Lax name match found:" << mod.name << "| From path:" << path; qDebug() << "[Blocked Mods Dialog] Lax name match found:" << mod.name << "| From path:" << path;
return true; return true;
} }

View File

@ -37,18 +37,21 @@
#include <QPushButton> #include <QPushButton>
#include "Application.h" #include "Application.h"
#include "BuildConfig.h"
#include "CopyInstanceDialog.h" #include "CopyInstanceDialog.h"
#include "ui_CopyInstanceDialog.h" #include "ui_CopyInstanceDialog.h"
#include "ui/dialogs/IconPickerDialog.h" #include "ui/dialogs/IconPickerDialog.h"
#include "BaseVersion.h"
#include "icons/IconList.h"
#include "BaseInstance.h" #include "BaseInstance.h"
#include "BaseVersion.h"
#include "DesktopServices.h"
#include "FileSystem.h"
#include "InstanceList.h" #include "InstanceList.h"
#include "icons/IconList.h"
CopyInstanceDialog::CopyInstanceDialog(InstancePtr original, QWidget *parent) CopyInstanceDialog::CopyInstanceDialog(InstancePtr original, QWidget* parent)
:QDialog(parent), ui(new Ui::CopyInstanceDialog), m_original(original) : QDialog(parent), ui(new Ui::CopyInstanceDialog), m_original(original)
{ {
ui->setupUi(this); ui->setupUi(this);
resize(minimumSizeHint()); resize(minimumSizeHint());
@ -71,8 +74,7 @@ CopyInstanceDialog::CopyInstanceDialog(InstancePtr original, QWidget *parent)
groupList.push_front(""); groupList.push_front("");
ui->groupBox->addItems(groupList); ui->groupBox->addItems(groupList);
int index = groupList.indexOf(APPLICATION->instances()->getInstanceGroup(m_original->id())); int index = groupList.indexOf(APPLICATION->instances()->getInstanceGroup(m_original->id()));
if(index == -1) if (index == -1) {
{
index = 0; index = 0;
} }
ui->groupBox->setCurrentIndex(index); ui->groupBox->setCurrentIndex(index);
@ -85,6 +87,35 @@ CopyInstanceDialog::CopyInstanceDialog(InstancePtr original, QWidget *parent)
ui->copyServersCheckbox->setChecked(m_selectedOptions.isCopyServersEnabled()); ui->copyServersCheckbox->setChecked(m_selectedOptions.isCopyServersEnabled());
ui->copyModsCheckbox->setChecked(m_selectedOptions.isCopyModsEnabled()); ui->copyModsCheckbox->setChecked(m_selectedOptions.isCopyModsEnabled());
ui->copyScreenshotsCheckbox->setChecked(m_selectedOptions.isCopyScreenshotsEnabled()); ui->copyScreenshotsCheckbox->setChecked(m_selectedOptions.isCopyScreenshotsEnabled());
ui->symbolicLinksCheckbox->setChecked(m_selectedOptions.isUseSymLinksEnabled());
ui->hardLinksCheckbox->setChecked(m_selectedOptions.isUseHardLinksEnabled());
ui->recursiveLinkCheckbox->setChecked(m_selectedOptions.isLinkRecursivelyEnabled());
ui->dontLinkSavesCheckbox->setChecked(m_selectedOptions.isDontLinkSavesEnabled());
auto detectedFS = FS::statFS(m_original->instanceRoot()).fsType;
m_cloneSupported = FS::canCloneOnFS(detectedFS);
m_linkSupported = FS::canLinkOnFS(detectedFS);
if (m_cloneSupported) {
ui->cloneSupportedLabel->setText(tr("Reflinks are supported on %1").arg(FS::getFilesystemTypeName(detectedFS)));
} else {
ui->cloneSupportedLabel->setText(tr("Reflinks aren't supported on %1").arg(FS::getFilesystemTypeName(detectedFS)));
}
#if defined(Q_OS_WIN)
ui->symbolicLinksCheckbox->setIcon(style()->standardIcon(QStyle::SP_VistaShield));
ui->symbolicLinksCheckbox->setToolTip(tr("Use symbolic links instead of copying files.") +
"\n" + tr("On Windows, symbolic links may require admin permission to create."));
#endif
updateLinkOptions();
updateUseCloneCheckbox();
auto HelpButton = ui->buttonBox->button(QDialogButtonBox::Help);
connect(HelpButton, &QPushButton::clicked, this, &CopyInstanceDialog::help);
} }
CopyInstanceDialog::~CopyInstanceDialog() CopyInstanceDialog::~CopyInstanceDialog()
@ -96,8 +127,7 @@ void CopyInstanceDialog::updateDialogState()
{ {
auto allowOK = !instName().isEmpty(); auto allowOK = !instName().isEmpty();
auto OkButton = ui->buttonBox->button(QDialogButtonBox::Ok); auto OkButton = ui->buttonBox->button(QDialogButtonBox::Ok);
if(OkButton->isEnabled() != allowOK) if (OkButton->isEnabled() != allowOK) {
{
OkButton->setEnabled(allowOK); OkButton->setEnabled(allowOK);
} }
} }
@ -105,8 +135,7 @@ void CopyInstanceDialog::updateDialogState()
QString CopyInstanceDialog::instName() const QString CopyInstanceDialog::instName() const
{ {
auto result = ui->instNameTextBox->text().trimmed(); auto result = ui->instNameTextBox->text().trimmed();
if(result.size()) if (result.size()) {
{
return result; return result;
} }
return QString(); return QString();
@ -127,6 +156,11 @@ const InstanceCopyPrefs& CopyInstanceDialog::getChosenOptions() const
return m_selectedOptions; return m_selectedOptions;
} }
void CopyInstanceDialog::help()
{
DesktopServices::openUrl(QUrl(BuildConfig.HELP_URL.arg("instance-copy")));
}
void CopyInstanceDialog::checkAllCheckboxes(const bool& b) void CopyInstanceDialog::checkAllCheckboxes(const bool& b)
{ {
ui->keepPlaytimeCheckbox->setChecked(b); ui->keepPlaytimeCheckbox->setChecked(b);
@ -147,20 +181,46 @@ void CopyInstanceDialog::updateSelectAllCheckbox()
ui->selectAllCheckbox->blockSignals(false); ui->selectAllCheckbox->blockSignals(false);
} }
void CopyInstanceDialog::updateUseCloneCheckbox()
{
ui->useCloneCheckbox->setEnabled(m_cloneSupported && !ui->symbolicLinksCheckbox->isChecked() && !ui->hardLinksCheckbox->isChecked());
ui->useCloneCheckbox->setChecked(m_cloneSupported && m_selectedOptions.isUseCloneEnabled() && !ui->symbolicLinksCheckbox->isChecked() &&
!ui->hardLinksCheckbox->isChecked());
}
void CopyInstanceDialog::updateLinkOptions()
{
ui->symbolicLinksCheckbox->setEnabled(m_linkSupported && !ui->hardLinksCheckbox->isChecked() && !ui->useCloneCheckbox->isChecked());
ui->hardLinksCheckbox->setEnabled(m_linkSupported && !ui->symbolicLinksCheckbox->isChecked() && !ui->useCloneCheckbox->isChecked());
ui->symbolicLinksCheckbox->setChecked(m_linkSupported && m_selectedOptions.isUseSymLinksEnabled() &&
!ui->useCloneCheckbox->isChecked());
ui->hardLinksCheckbox->setChecked(m_linkSupported && m_selectedOptions.isUseHardLinksEnabled() && !ui->useCloneCheckbox->isChecked());
bool linksInUse = (ui->symbolicLinksCheckbox->isChecked() || ui->hardLinksCheckbox->isChecked());
ui->recursiveLinkCheckbox->setEnabled(m_linkSupported && linksInUse && !ui->hardLinksCheckbox->isChecked());
ui->dontLinkSavesCheckbox->setEnabled(m_linkSupported && linksInUse);
ui->recursiveLinkCheckbox->setChecked(m_linkSupported && linksInUse && m_selectedOptions.isLinkRecursivelyEnabled());
ui->dontLinkSavesCheckbox->setChecked(m_linkSupported && linksInUse && m_selectedOptions.isDontLinkSavesEnabled());
#if defined(Q_OS_WIN)
auto OkButton = ui->buttonBox->button(QDialogButtonBox::Ok);
OkButton->setIcon(m_selectedOptions.isUseSymLinksEnabled() ? style()->standardIcon(QStyle::SP_VistaShield) : QIcon());
#endif
}
void CopyInstanceDialog::on_iconButton_clicked() void CopyInstanceDialog::on_iconButton_clicked()
{ {
IconPickerDialog dlg(this); IconPickerDialog dlg(this);
dlg.execWithSelection(InstIconKey); dlg.execWithSelection(InstIconKey);
if (dlg.result() == QDialog::Accepted) if (dlg.result() == QDialog::Accepted) {
{
InstIconKey = dlg.selectedIconKey; InstIconKey = dlg.selectedIconKey;
ui->iconButton->setIcon(APPLICATION->icons()->getIcon(InstIconKey)); ui->iconButton->setIcon(APPLICATION->icons()->getIcon(InstIconKey));
} }
} }
void CopyInstanceDialog::on_instNameTextBox_textChanged(const QString& arg1)
void CopyInstanceDialog::on_instNameTextBox_textChanged(const QString &arg1)
{ {
updateDialogState(); updateDialogState();
} }
@ -175,10 +235,10 @@ void CopyInstanceDialog::on_selectAllCheckbox_stateChanged(int state)
void CopyInstanceDialog::on_copySavesCheckbox_stateChanged(int state) void CopyInstanceDialog::on_copySavesCheckbox_stateChanged(int state)
{ {
m_selectedOptions.enableCopySaves(state == Qt::Checked); m_selectedOptions.enableCopySaves(state == Qt::Checked);
ui->dontLinkSavesCheckbox->setChecked((state == Qt::Checked) && ui->dontLinkSavesCheckbox->isChecked());
updateSelectAllCheckbox(); updateSelectAllCheckbox();
} }
void CopyInstanceDialog::on_keepPlaytimeCheckbox_stateChanged(int state) void CopyInstanceDialog::on_keepPlaytimeCheckbox_stateChanged(int state)
{ {
m_selectedOptions.enableKeepPlaytime(state == Qt::Checked); m_selectedOptions.enableKeepPlaytime(state == Qt::Checked);
@ -220,3 +280,38 @@ void CopyInstanceDialog::on_copyScreenshotsCheckbox_stateChanged(int state)
m_selectedOptions.enableCopyScreenshots(state == Qt::Checked); m_selectedOptions.enableCopyScreenshots(state == Qt::Checked);
updateSelectAllCheckbox(); updateSelectAllCheckbox();
} }
void CopyInstanceDialog::on_symbolicLinksCheckbox_stateChanged(int state)
{
m_selectedOptions.enableUseSymLinks(state == Qt::Checked);
updateUseCloneCheckbox();
updateLinkOptions();
}
void CopyInstanceDialog::on_hardLinksCheckbox_stateChanged(int state)
{
m_selectedOptions.enableUseHardLinks(state == Qt::Checked);
if (state == Qt::Checked && !ui->recursiveLinkCheckbox->isChecked()) {
ui->recursiveLinkCheckbox->setChecked(true);
}
updateUseCloneCheckbox();
updateLinkOptions();
}
void CopyInstanceDialog::on_recursiveLinkCheckbox_stateChanged(int state)
{
m_selectedOptions.enableLinkRecursively(state == Qt::Checked);
updateLinkOptions();
}
void CopyInstanceDialog::on_dontLinkSavesCheckbox_stateChanged(int state)
{
m_selectedOptions.enableDontLinkSaves(state == Qt::Checked);
}
void CopyInstanceDialog::on_useCloneCheckbox_stateChanged(int state)
{
m_selectedOptions.enableUseClone(m_cloneSupported && (state == Qt::Checked));
updateUseCloneCheckbox();
updateLinkOptions();
}

View File

@ -16,22 +16,21 @@
#pragma once #pragma once
#include <QDialog> #include <QDialog>
#include "BaseInstance.h"
#include "BaseVersion.h" #include "BaseVersion.h"
#include "InstanceCopyPrefs.h" #include "InstanceCopyPrefs.h"
class BaseInstance; class BaseInstance;
namespace Ui namespace Ui {
{
class CopyInstanceDialog; class CopyInstanceDialog;
} }
class CopyInstanceDialog : public QDialog class CopyInstanceDialog : public QDialog {
{
Q_OBJECT Q_OBJECT
public: public:
explicit CopyInstanceDialog(InstancePtr original, QWidget *parent = 0); explicit CopyInstanceDialog(InstancePtr original, QWidget* parent = 0);
~CopyInstanceDialog(); ~CopyInstanceDialog();
void updateDialogState(); void updateDialogState();
@ -41,10 +40,12 @@ public:
QString iconKey() const; QString iconKey() const;
const InstanceCopyPrefs& getChosenOptions() const; const InstanceCopyPrefs& getChosenOptions() const;
private public slots:
slots: void help();
private slots:
void on_iconButton_clicked(); void on_iconButton_clicked();
void on_instNameTextBox_textChanged(const QString &arg1); void on_instNameTextBox_textChanged(const QString& arg1);
// Checkboxes // Checkboxes
void on_selectAllCheckbox_stateChanged(int state); void on_selectAllCheckbox_stateChanged(int state);
void on_copySavesCheckbox_stateChanged(int state); void on_copySavesCheckbox_stateChanged(int state);
@ -55,13 +56,23 @@ slots:
void on_copyServersCheckbox_stateChanged(int state); void on_copyServersCheckbox_stateChanged(int state);
void on_copyModsCheckbox_stateChanged(int state); void on_copyModsCheckbox_stateChanged(int state);
void on_copyScreenshotsCheckbox_stateChanged(int state); void on_copyScreenshotsCheckbox_stateChanged(int state);
void on_symbolicLinksCheckbox_stateChanged(int state);
void on_hardLinksCheckbox_stateChanged(int state);
void on_recursiveLinkCheckbox_stateChanged(int state);
void on_dontLinkSavesCheckbox_stateChanged(int state);
void on_useCloneCheckbox_stateChanged(int state);
private: private:
void checkAllCheckboxes(const bool& b); void checkAllCheckboxes(const bool& b);
void updateSelectAllCheckbox(); void updateSelectAllCheckbox();
void updateUseCloneCheckbox();
void updateLinkOptions();
/* data */ /* data */
Ui::CopyInstanceDialog *ui; Ui::CopyInstanceDialog* ui;
QString InstIconKey; QString InstIconKey;
InstancePtr m_original; InstancePtr m_original;
InstanceCopyPrefs m_selectedOptions; InstanceCopyPrefs m_selectedOptions;
bool m_cloneSupported = false;
bool m_linkSupported = false;
}; };

View File

@ -9,8 +9,8 @@
<rect> <rect>
<x>0</x> <x>0</x>
<y>0</y> <y>0</y>
<width>341</width> <width>575</width>
<height>399</height> <height>695</height>
</rect> </rect>
</property> </property>
<property name="windowTitle"> <property name="windowTitle">
@ -113,93 +113,268 @@
</layout> </layout>
</item> </item>
<item> <item>
<layout class="QHBoxLayout" name="selectAllButtonLayout"> <widget class="QGroupBox" name="copyOptionsGroup">
<property name="title">
<string>Instance Copy Options</string>
</property>
<layout class="QGridLayout" name="copyOptionsLayout">
<item row="1" column="0">
<widget class="QCheckBox" name="keepPlaytimeCheckbox">
<property name="text">
<string>Keep play time</string>
</property>
</widget>
</item>
<item row="6" column="1">
<widget class="QCheckBox" name="copyModsCheckbox">
<property name="toolTip">
<string>Disabling this will still keep the mod loader (ex: Fabric, Quilt, etc.) but erase the mods folder and their configs.</string>
</property>
<property name="text">
<string>Copy mods</string>
</property>
</widget>
</item>
<item row="6" column="0">
<widget class="QCheckBox" name="copyResPacksCheckbox">
<property name="enabled">
<bool>true</bool>
</property>
<property name="text">
<string>Copy resource packs</string>
</property>
</widget>
</item>
<item row="5" column="0">
<widget class="QCheckBox" name="copyGameOptionsCheckbox">
<property name="toolTip">
<string>Copy the in-game options like FOV, max framerate, etc.</string>
</property>
<property name="text">
<string>Copy game options</string>
</property>
</widget>
</item>
<item row="3" column="1">
<widget class="QCheckBox" name="copyShaderPacksCheckbox">
<property name="text">
<string>Copy shader packs</string>
</property>
</widget>
</item>
<item row="5" column="1">
<widget class="QCheckBox" name="copyServersCheckbox">
<property name="text">
<string>Copy servers</string>
</property>
</widget>
</item>
<item row="3" column="0">
<widget class="QCheckBox" name="copySavesCheckbox">
<property name="text">
<string>Copy saves</string>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QCheckBox" name="copyScreenshotsCheckbox">
<property name="text">
<string>Copy screenshots</string>
</property>
</widget>
</item>
<item row="7" column="1">
<widget class="QCheckBox" name="selectAllCheckbox">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="layoutDirection">
<enum>Qt::LeftToRight</enum>
</property>
<property name="text">
<string>Select all</string>
</property>
<property name="checked">
<bool>false</bool>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="Line" name="line_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="advancedOptionsLabel">
<property name="text">
<string>Advanced Copy Options</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<layout class="QVBoxLayout" name="copyModeLayout">
<item> <item>
<widget class="QCheckBox" name="selectAllCheckbox"> <widget class="QGroupBox" name="linkFilesGroup">
<property name="sizePolicy"> <property name="toolTip">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed"> <string>Use symbolic or hard links instead of copying files.</string>
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property> </property>
<property name="layoutDirection"> <property name="title">
<enum>Qt::LeftToRight</enum> <string>Symbolic and Hard Link Options</string>
</property> </property>
<property name="text"> <property name="flat">
<string>Select all</string> <bool>false</bool>
</property>
<property name="checkable">
<bool>false</bool>
</property> </property>
<property name="checked"> <property name="checked">
<bool>false</bool> <bool>false</bool>
</property> </property>
<layout class="QVBoxLayout" name="linkOptionsLayout">
<item>
<widget class="QLabel" name="linkOptionsLabel">
<property name="text">
<string>Links are supported on most filesystems except FAT</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<layout class="QGridLayout" name="linkOptionsGridLayout" rowstretch="0,0,0,0" columnstretch="0,0" rowminimumheight="0,0,0,0" columnminimumwidth="0,0">
<property name="leftMargin">
<number>6</number>
</property>
<property name="topMargin">
<number>6</number>
</property>
<property name="rightMargin">
<number>6</number>
</property>
<property name="bottomMargin">
<number>6</number>
</property>
<item row="2" column="1">
<widget class="QCheckBox" name="recursiveLinkCheckbox">
<property name="enabled">
<bool>false</bool>
</property>
<property name="toolTip">
<string>Link each resource individually instead of linking whole folders at once</string>
</property>
<property name="text">
<string>Link files recursively</string>
</property>
</widget>
</item>
<item row="3" column="1">
<widget class="QCheckBox" name="dontLinkSavesCheckbox">
<property name="enabled">
<bool>false</bool>
</property>
<property name="toolTip">
<string>If &quot;copy saves&quot; is selected world save data will be copied instead of linked and thus not shared between instances.</string>
</property>
<property name="text">
<string>Don't link saves</string>
</property>
<property name="checked">
<bool>false</bool>
</property>
</widget>
</item>
<item row="3" column="0">
<widget class="QCheckBox" name="hardLinksCheckbox">
<property name="enabled">
<bool>true</bool>
</property>
<property name="toolTip">
<string>Use hard links instead of copying files.</string>
</property>
<property name="text">
<string>Use hard links</string>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QCheckBox" name="symbolicLinksCheckbox">
<property name="toolTip">
<string>Use symbolic links instead of copying files.</string>
</property>
<property name="text">
<string>Use symbolic links</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget> </widget>
</item> </item>
</layout> <item>
</item> <widget class="QGroupBox" name="horizontalGroupBox">
<item> <property name="title">
<layout class="QGridLayout" name="copyOptionsLayout"> <string>CoW (Copy-on-Write) Options</string>
<item row="6" column="1">
<widget class="QCheckBox" name="copyModsCheckbox">
<property name="toolTip">
<string>Disabling this will still keep the mod loader (ex: Fabric, Quilt, etc.) but erase the mods folder and their configs.</string>
</property>
<property name="text">
<string>Copy mods</string>
</property>
</widget>
</item>
<item row="5" column="0">
<widget class="QCheckBox" name="copyGameOptionsCheckbox">
<property name="toolTip">
<string>Copy the in-game options like FOV, max framerate, etc.</string>
</property>
<property name="text">
<string>Copy game options</string>
</property>
</widget>
</item>
<item row="3" column="0">
<widget class="QCheckBox" name="copySavesCheckbox">
<property name="text">
<string>Copy saves</string>
</property>
</widget>
</item>
<item row="3" column="1">
<widget class="QCheckBox" name="copyShaderPacksCheckbox">
<property name="text">
<string>Copy shader packs</string>
</property>
</widget>
</item>
<item row="5" column="1">
<widget class="QCheckBox" name="copyServersCheckbox">
<property name="text">
<string>Copy servers</string>
</property>
</widget>
</item>
<item row="6" column="0">
<widget class="QCheckBox" name="copyResPacksCheckbox">
<property name="enabled">
<bool>true</bool>
</property>
<property name="text">
<string>Copy resource packs</string>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QCheckBox" name="keepPlaytimeCheckbox">
<property name="text">
<string>Keep play time</string>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QCheckBox" name="copyScreenshotsCheckbox">
<property name="text">
<string>Copy screenshots</string>
</property> </property>
<layout class="QHBoxLayout" name="useCloneLayout">
<item>
<widget class="QCheckBox" name="useCloneCheckbox">
<property name="enabled">
<bool>false</bool>
</property>
<property name="toolTip">
<string>Files cloned with reflinks take up no extra space until they are modified.</string>
</property>
<property name="text">
<string>Clone instead of copying</string>
</property>
</widget>
</item>
<item>
<spacer name="CoWSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QLabel" name="cloneSupportedLabel">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>1</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Your filesystem and/or OS doesn't support reflinks</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
<property name="margin">
<number>4</number>
</property>
</widget>
</item>
</layout>
</widget> </widget>
</item> </item>
</layout> </layout>
@ -210,7 +385,7 @@
<enum>Qt::Horizontal</enum> <enum>Qt::Horizontal</enum>
</property> </property>
<property name="standardButtons"> <property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set> <set>QDialogButtonBox::Cancel|QDialogButtonBox::Help|QDialogButtonBox::Ok</set>
</property> </property>
</widget> </widget>
</item> </item>
@ -220,10 +395,21 @@
<tabstop>iconButton</tabstop> <tabstop>iconButton</tabstop>
<tabstop>instNameTextBox</tabstop> <tabstop>instNameTextBox</tabstop>
<tabstop>groupBox</tabstop> <tabstop>groupBox</tabstop>
<tabstop>keepPlaytimeCheckbox</tabstop>
<tabstop>copyScreenshotsCheckbox</tabstop>
<tabstop>copySavesCheckbox</tabstop>
<tabstop>copyShaderPacksCheckbox</tabstop>
<tabstop>copyGameOptionsCheckbox</tabstop>
<tabstop>copyServersCheckbox</tabstop>
<tabstop>copyResPacksCheckbox</tabstop>
<tabstop>copyModsCheckbox</tabstop>
<tabstop>symbolicLinksCheckbox</tabstop>
<tabstop>recursiveLinkCheckbox</tabstop>
<tabstop>hardLinksCheckbox</tabstop>
<tabstop>dontLinkSavesCheckbox</tabstop>
<tabstop>useCloneCheckbox</tabstop>
</tabstops> </tabstops>
<resources> <resources/>
<include location="../../graphics.qrc"/>
</resources>
<connections> <connections>
<connection> <connection>
<sender>buttonBox</sender> <sender>buttonBox</sender>
@ -232,8 +418,8 @@
<slot>accept()</slot> <slot>accept()</slot>
<hints> <hints>
<hint type="sourcelabel"> <hint type="sourcelabel">
<x>254</x> <x>269</x>
<y>316</y> <y>692</y>
</hint> </hint>
<hint type="destinationlabel"> <hint type="destinationlabel">
<x>157</x> <x>157</x>
@ -248,8 +434,8 @@
<slot>reject()</slot> <slot>reject()</slot>
<hints> <hints>
<hint type="sourcelabel"> <hint type="sourcelabel">
<x>322</x> <x>337</x>
<y>316</y> <y>692</y>
</hint> </hint>
<hint type="destinationlabel"> <hint type="destinationlabel">
<x>286</x> <x>286</x>

View File

@ -45,6 +45,8 @@
#include <QDebug> #include <QDebug>
#include <QSaveFile> #include <QSaveFile>
#include <QStack> #include <QStack>
#include <QFileInfo>
#include "StringUtils.h" #include "StringUtils.h"
#include "SeparatorPrefixTree.h" #include "SeparatorPrefixTree.h"
#include "Application.h" #include "Application.h"
@ -429,7 +431,8 @@ bool ExportInstanceDialog::doExport()
QMessageBox::warning(this, tr("Error"), tr("Unable to export instance")); QMessageBox::warning(this, tr("Error"), tr("Unable to export instance"));
return false; return false;
} }
if (!MMCZip::compressDirFiles(output, m_instance->instanceRoot(), files))
if (!MMCZip::compressDirFiles(output, m_instance->instanceRoot(), files, true))
{ {
QMessageBox::warning(this, tr("Error"), tr("Unable to export instance")); QMessageBox::warning(this, tr("Error"), tr("Unable to export instance"));
return false; return false;

View File

@ -56,7 +56,6 @@
#include "ui/widgets/PageContainer.h" #include "ui/widgets/PageContainer.h"
#include "ui/pages/modplatform/VanillaPage.h" #include "ui/pages/modplatform/VanillaPage.h"
#include "ui/pages/modplatform/atlauncher/AtlPage.h" #include "ui/pages/modplatform/atlauncher/AtlPage.h"
#include "ui/pages/modplatform/ftb/FtbPage.h"
#include "ui/pages/modplatform/legacy_ftb/Page.h" #include "ui/pages/modplatform/legacy_ftb/Page.h"
#include "ui/pages/modplatform/flame/FlamePage.h" #include "ui/pages/modplatform/flame/FlamePage.h"
#include "ui/pages/modplatform/ImportPage.h" #include "ui/pages/modplatform/ImportPage.h"
@ -168,7 +167,6 @@ QList<BasePage *> NewInstanceDialog::getPages()
pages.append(new AtlPage(this)); pages.append(new AtlPage(this));
if (APPLICATION->capabilities() & Application::SupportsFlame) if (APPLICATION->capabilities() & Application::SupportsFlame)
pages.append(new FlamePage(this)); pages.append(new FlamePage(this));
pages.append(new FtbPage(this));
pages.append(new LegacyFTB::Page(this)); pages.append(new LegacyFTB::Page(this));
pages.append(new ModrinthPage(this)); pages.append(new ModrinthPage(this));
pages.append(new TechnicPage(this)); pages.append(new TechnicPage(this));

View File

@ -1,29 +1,69 @@
/* Copyright 2013-2021 MultiMC Contributors /// SPDX-License-Identifier: GPL-3.0-only
/*
* PrismLaucher - Minecraft Launcher
* Copyright (C) 2023 Rachel Powers <508861+Ryex@users.noreply.github.com>
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * This program is free software: you can redistribute it and/or modify
* you may not use this file except in compliance with the License. * it under the terms of the GNU General Public License as published by
* You may obtain a copy of the License at * the Free Software Foundation, version 3.
* *
* http://www.apache.org/licenses/LICENSE-2.0 * 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.
* *
* Unless required by applicable law or agreed to in writing, software * You should have received a copy of the GNU General Public License
* distributed under the License is distributed on an "AS IS" BASIS, * along with this program. If not, see <https://www.gnu.org/licenses/>.
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and * This file incorporates work covered by the following copyright and
* limitations under the License. * permission notice:
*
* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ */
#include "ProgressDialog.h" #include "ProgressDialog.h"
#include "ui_ProgressDialog.h" #include "ui_ProgressDialog.h"
#include <limits>
#include <QDebug> #include <QDebug>
#include <QKeyEvent> #include <QKeyEvent>
#include "tasks/Task.h" #include "tasks/Task.h"
#include "ui/widgets/SubTaskProgressBar.h"
// map a value in a numeric range of an arbitrary type to between 0 and INT_MAX
// for getting the best precision out of the qt progress bar
template<typename T, std::enable_if_t<std::is_arithmetic_v<T>, bool> = true>
std::tuple<int, int> map_int_zero_max(T current, T range_max, T range_min)
{
int int_max = std::numeric_limits<int>::max();
auto type_range = range_max - range_min;
double percentage = static_cast<double>(current - range_min) / static_cast<double>(type_range);
int mapped_current = percentage * int_max;
return {mapped_current, int_max};
}
ProgressDialog::ProgressDialog(QWidget* parent) : QDialog(parent), ui(new Ui::ProgressDialog) ProgressDialog::ProgressDialog(QWidget* parent) : QDialog(parent), ui(new Ui::ProgressDialog)
{ {
ui->setupUi(this); ui->setupUi(this);
ui->taskProgressScrollArea->setHidden(true);
this->setWindowFlags(this->windowFlags() & ~Qt::WindowContextHelpButtonHint); this->setWindowFlags(this->windowFlags() & ~Qt::WindowContextHelpButtonHint);
setAttribute(Qt::WidgetAttribute::WA_QuitOnClose, true); setAttribute(Qt::WidgetAttribute::WA_QuitOnClose, true);
setSkipButton(false); setSkipButton(false);
@ -55,9 +95,23 @@ ProgressDialog::~ProgressDialog()
void ProgressDialog::updateSize() void ProgressDialog::updateSize()
{ {
QSize lastSize = this->size();
QSize qSize = QSize(480, minimumSizeHint().height()); QSize qSize = QSize(480, minimumSizeHint().height());
resize(qSize);
setFixedSize(qSize); // if the current window is too small
if ((lastSize != qSize) && (lastSize.height() < qSize.height()))
{
resize(qSize);
// keep the dialog in the center after a resize
this->move(
this->parentWidget()->x() + (this->parentWidget()->width() - this->width()) / 2,
this->parentWidget()->y() + (this->parentWidget()->height() - this->height()) / 2
);
}
setMinimumSize(qSize);
} }
int ProgressDialog::execWithTask(Task* task) int ProgressDialog::execWithTask(Task* task)
@ -79,17 +133,15 @@ int ProgressDialog::execWithTask(Task* task)
connect(task, &Task::failed, this, &ProgressDialog::onTaskFailed); connect(task, &Task::failed, this, &ProgressDialog::onTaskFailed);
connect(task, &Task::succeeded, this, &ProgressDialog::onTaskSucceeded); connect(task, &Task::succeeded, this, &ProgressDialog::onTaskSucceeded);
connect(task, &Task::status, this, &ProgressDialog::changeStatus); connect(task, &Task::status, this, &ProgressDialog::changeStatus);
connect(task, &Task::stepStatus, this, &ProgressDialog::changeStatus); connect(task, &Task::details, this, &ProgressDialog::changeStatus);
connect(task, &Task::stepProgress, this, &ProgressDialog::changeStepProgress);
connect(task, &Task::progress, this, &ProgressDialog::changeProgress); connect(task, &Task::progress, this, &ProgressDialog::changeProgress);
connect(task, &Task::aborted, this, &ProgressDialog::hide); connect(task, &Task::aborted, this, &ProgressDialog::hide);
connect(task, &Task::abortStatusChanged, ui->skipButton, &QPushButton::setEnabled); connect(task, &Task::abortStatusChanged, ui->skipButton, &QPushButton::setEnabled);
m_is_multi_step = task->isMultiStep(); m_is_multi_step = task->isMultiStep();
if (!m_is_multi_step) { ui->taskProgressScrollArea->setHidden(!m_is_multi_step);
ui->globalStatusLabel->setHidden(true); updateSize();
ui->globalProgressBar->setHidden(true);
}
// It's a good idea to start the task after we entered the dialog's event loop :^) // It's a good idea to start the task after we entered the dialog's event loop :^)
if (!task->isRunning()) { if (!task->isRunning()) {
@ -149,23 +201,53 @@ void ProgressDialog::onTaskSucceeded()
void ProgressDialog::changeStatus(const QString& status) void ProgressDialog::changeStatus(const QString& status)
{ {
ui->globalStatusLabel->setText(task->getStatus()); ui->globalStatusLabel->setText(task->getStatus());
ui->statusLabel->setText(task->getStepStatus()); ui->globalStatusDetailsLabel->setText(task->getDetails());
updateSize(); updateSize();
} }
void ProgressDialog::addTaskProgress(TaskStepProgress const& progress)
{
SubTaskProgressBar* task_bar = new SubTaskProgressBar(this);
taskProgress.insert(progress.uid, task_bar);
ui->taskProgressLayout->addWidget(task_bar);
}
void ProgressDialog::changeStepProgress(TaskStepProgress const& task_progress)
{
m_is_multi_step = true;
if(ui->taskProgressScrollArea->isHidden()) {
ui->taskProgressScrollArea->setHidden(false);
updateSize();
}
if (!taskProgress.contains(task_progress.uid))
addTaskProgress(task_progress);
auto task_bar = taskProgress.value(task_progress.uid);
auto const [mapped_current, mapped_total] = map_int_zero_max<qint64>(task_progress.current, task_progress.total, 0);
if (task_progress.total <= 0) {
task_bar->setRange(0, 0);
} else {
task_bar->setRange(0, mapped_total);
}
task_bar->setValue(mapped_current);
task_bar->setStatus(task_progress.status);
task_bar->setDetails(task_progress.details);
if (task_progress.isDone()) {
task_bar->setVisible(false);
}
}
void ProgressDialog::changeProgress(qint64 current, qint64 total) void ProgressDialog::changeProgress(qint64 current, qint64 total)
{ {
ui->globalProgressBar->setMaximum(total); ui->globalProgressBar->setMaximum(total);
ui->globalProgressBar->setValue(current); ui->globalProgressBar->setValue(current);
if (!m_is_multi_step) {
ui->taskProgressBar->setMaximum(total);
ui->taskProgressBar->setValue(current);
} else {
ui->taskProgressBar->setMaximum(task->getStepProgress());
ui->taskProgressBar->setValue(task->getStepTotalProgress());
}
} }
void ProgressDialog::keyPressEvent(QKeyEvent* e) void ProgressDialog::keyPressEvent(QKeyEvent* e)

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