diff options
Diffstat (limited to 'launcher')
73 files changed, 1863 insertions, 637 deletions
diff --git a/launcher/Application.cpp b/launcher/Application.cpp index 01b62971..8bd434f0 100644 --- a/launcher/Application.cpp +++ b/launcher/Application.cpp @@ -317,6 +317,26 @@ Application::Application(int &argc, char **argv) : QApplication(argc, argv) QString origcwdPath = QDir::currentPath(); QString binPath = applicationDirPath(); + + { + // Root path is used for updates and portable data +#if defined(Q_OS_LINUX) || defined(Q_OS_FREEBSD) + QDir foo(FS::PathCombine(binPath, "..")); // typically portable-root or /usr + m_rootPath = foo.absolutePath(); +#elif defined(Q_OS_WIN32) + m_rootPath = binPath; +#elif defined(Q_OS_MAC) + QDir foo(FS::PathCombine(binPath, "../..")); + m_rootPath = foo.absolutePath(); + // on macOS, touch the root to force Finder to reload the .app metadata (and fix any icon change issues) + FS::updateTimestamp(m_rootPath); +#endif + +#ifdef LAUNCHER_JARS_LOCATION + m_jarsPath = TOSTRING(LAUNCHER_JARS_LOCATION); +#endif + } + QString adjustedBy; QString dataPath; // change folder @@ -325,15 +345,14 @@ Application::Application(int &argc, char **argv) : QApplication(argc, argv) { // the dir param. it makes multimc data path point to whatever the user specified // on command line - adjustedBy += "Command line " + dirParam; + adjustedBy = "Command line"; dataPath = dirParam; } else { -#if !defined(LAUNCHER_PORTABLE) || defined(Q_OS_MAC) QDir foo(FS::PathCombine(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation), "..")); dataPath = foo.absolutePath(); - adjustedBy += dataPath; + adjustedBy = "Persistent data path"; #ifdef Q_OS_LINUX // TODO: this should be removed in a future version @@ -341,12 +360,15 @@ Application::Application(int &argc, char **argv) : QApplication(argc, argv) QDir bar(FS::PathCombine(QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation), "polymc")); if (bar.exists()) { dataPath = bar.absolutePath(); - adjustedBy += "Legacy data path " + dataPath; + adjustedBy = "Legacy data path"; } #endif -#else - dataPath = applicationDirPath(); - adjustedBy += "Fallback to binary path " + dataPath; + +#ifndef Q_OS_MACOS + if (QFile::exists(FS::PathCombine(m_rootPath, "portable.txt"))) { + dataPath = m_rootPath; + adjustedBy = "Portable data path"; + } #endif } @@ -536,24 +558,7 @@ Application::Application(int &argc, char **argv) : QApplication(argc, argv) qDebug() << "<> Log initialized."; } - // Set up paths { - // Root path is used for updates. -#if defined(Q_OS_LINUX) || defined(Q_OS_FREEBSD) - QDir foo(FS::PathCombine(binPath, "..")); - m_rootPath = foo.absolutePath(); -#elif defined(Q_OS_WIN32) - m_rootPath = binPath; -#elif defined(Q_OS_MAC) - QDir foo(FS::PathCombine(binPath, "../..")); - m_rootPath = foo.absolutePath(); - // on macOS, touch the root to force Finder to reload the .app metadata (and fix any icon change issues) - FS::updateTimestamp(m_rootPath); -#endif - -#ifdef LAUNCHER_JARS_LOCATION - m_jarsPath = TOSTRING(LAUNCHER_JARS_LOCATION); -#endif qDebug() << BuildConfig.LAUNCHER_DISPLAYNAME << ", (c) 2013-2021 " << BuildConfig.LAUNCHER_COPYRIGHT; qDebug() << "Version : " << BuildConfig.printableVersionString(); @@ -699,6 +704,9 @@ Application::Application(int &argc, char **argv) : QApplication(argc, argv) // Minecraft launch method m_settings->registerSetting("MCLaunchMethod", "LauncherPart"); + // Minecraft offline player name + m_settings->registerSetting("LastOfflinePlayerName", ""); + // Wrapper command for launch m_settings->registerSetting("WrapperCommand", ""); diff --git a/launcher/CMakeLists.txt b/launcher/CMakeLists.txt index 692aebe5..6ed86726 100644 --- a/launcher/CMakeLists.txt +++ b/launcher/CMakeLists.txt @@ -348,7 +348,7 @@ set(MINECRAFT_SOURCES mojang/PackageManifest.h mojang/PackageManifest.cpp - ) + minecraft/Agent.h) add_unit_test(GradleSpecifier SOURCES minecraft/GradleSpecifier_test.cpp @@ -413,6 +413,11 @@ set(TASKS_SOURCES tasks/SequentialTask.cpp ) +add_unit_test(Task + SOURCES tasks/Task_test.cpp + LIBS Launcher_logic + ) + set(SETTINGS_SOURCES # Settings settings/INIFile.cpp @@ -539,6 +544,8 @@ set(TECHNIC_SOURCES modplatform/technic/SingleZipPackInstallTask.cpp modplatform/technic/SolderPackInstallTask.h modplatform/technic/SolderPackInstallTask.cpp + modplatform/technic/SolderPackManifest.h + modplatform/technic/SolderPackManifest.cpp modplatform/technic/TechnicPackProcessor.h modplatform/technic/TechnicPackProcessor.cpp ) @@ -818,7 +825,6 @@ SET(LAUNCHER_SOURCES ui/dialogs/ModDownloadDialog.cpp ui/dialogs/ModDownloadDialog.h - # GUI - widgets ui/widgets/Common.cpp ui/widgets/Common.h @@ -842,6 +848,8 @@ SET(LAUNCHER_SOURCES ui/widgets/LogView.h ui/widgets/MCModInfoFrame.cpp ui/widgets/MCModInfoFrame.h + ui/widgets/ModFilterWidget.cpp + ui/widgets/ModFilterWidget.h ui/widgets/ModListView.cpp ui/widgets/ModListView.h ui/widgets/PageContainer.cpp @@ -900,6 +908,7 @@ qt5_wrap_ui(LAUNCHER_UI ui/widgets/InstanceCardWidget.ui ui/widgets/CustomCommands.ui ui/widgets/MCModInfoFrame.ui + ui/widgets/ModFilterWidget.ui ui/dialogs/CopyInstanceDialog.ui ui/dialogs/ProfileSetupDialog.ui ui/dialogs/ProgressDialog.ui @@ -982,7 +991,7 @@ if(DEFINED Launcher_APP_BINARY_DEFS) endif() install(TARGETS ${Launcher_Name} - BUNDLE DESTINATION ${BUNDLE_DEST_DIR} COMPONENT Runtime + BUNDLE DESTINATION "." COMPONENT Runtime LIBRARY DESTINATION ${LIBRARY_DEST_DIR} COMPONENT Runtime RUNTIME DESTINATION ${BINARY_DEST_DIR} COMPONENT Runtime ) diff --git a/launcher/InstanceCreationTask.cpp b/launcher/InstanceCreationTask.cpp index 4c37bd7f..24bc5f46 100644 --- a/launcher/InstanceCreationTask.cpp +++ b/launcher/InstanceCreationTask.cpp @@ -9,6 +9,15 @@ InstanceCreationTask::InstanceCreationTask(BaseVersionPtr version) { m_version = version; + m_usingLoader = false; +} + +InstanceCreationTask::InstanceCreationTask(BaseVersionPtr version, QString loader, BaseVersionPtr loaderVersion) +{ + m_version = version; + m_usingLoader = true; + m_loader = loader; + m_loaderVersion = loaderVersion; } void InstanceCreationTask::executeTask() @@ -21,6 +30,8 @@ void InstanceCreationTask::executeTask() auto components = inst.getPackProfile(); components->buildingFromScratch(); components->setComponentVersion("net.minecraft", m_version->descriptor(), true); + if(m_usingLoader) + components->setComponentVersion(m_loader, m_loaderVersion->descriptor(), true); inst.setName(m_instName); inst.setIconKey(m_instIcon); instanceSettings->resumeSave(); diff --git a/launcher/InstanceCreationTask.h b/launcher/InstanceCreationTask.h index 54997116..23367c3f 100644 --- a/launcher/InstanceCreationTask.h +++ b/launcher/InstanceCreationTask.h @@ -12,6 +12,7 @@ class InstanceCreationTask : public InstanceTask Q_OBJECT public: explicit InstanceCreationTask(BaseVersionPtr version); + explicit InstanceCreationTask(BaseVersionPtr version, QString loader, BaseVersionPtr loaderVersion); protected: //! Entry point for tasks. @@ -19,4 +20,7 @@ protected: private: /* data */ BaseVersionPtr m_version; + bool m_usingLoader; + QString m_loader; + BaseVersionPtr m_loaderVersion; }; diff --git a/launcher/InstanceImportTask.cpp b/launcher/InstanceImportTask.cpp index a825e8d4..1a13c997 100644 --- a/launcher/InstanceImportTask.cpp +++ b/launcher/InstanceImportTask.cpp @@ -40,6 +40,14 @@ InstanceImportTask::InstanceImportTask(const QUrl sourceUrl) m_sourceUrl = sourceUrl; } +bool InstanceImportTask::abort() +{ + m_filesNetJob->abort(); + m_extractFuture.cancel(); + + return false; +} + void InstanceImportTask::executeTask() { if (m_sourceUrl.isLocalFile()) @@ -241,6 +249,7 @@ void InstanceImportTask::processFlame() QString forgeVersion; QString fabricVersion; + // TODO: is Quilt relevant here? for(auto &loader: pack.minecraft.modLoaders) { auto id = loader.id; diff --git a/launcher/InstanceImportTask.h b/launcher/InstanceImportTask.h index a1990647..365c3dc4 100644 --- a/launcher/InstanceImportTask.h +++ b/launcher/InstanceImportTask.h @@ -37,6 +37,9 @@ class InstanceImportTask : public InstanceTask public: explicit InstanceImportTask(const QUrl sourceUrl); + bool canAbort() const override { return true; } + bool abort() override; + protected: //! Entry point for tasks. virtual void executeTask() override; diff --git a/launcher/JavaCommon.cpp b/launcher/JavaCommon.cpp index a6542fa7..17278d86 100644 --- a/launcher/JavaCommon.cpp +++ b/launcher/JavaCommon.cpp @@ -17,6 +17,17 @@ bool JavaCommon::checkJVMArgs(QString jvmargs, QWidget *parent) QMessageBox::Warning)->exec(); return false; } + // block lunacy with passing required version to the JVM + if (jvmargs.contains(QRegExp("-version:.*"))) { + auto warnStr = QObject::tr( + "You tried to pass required Java version argument to the JVM (using \"-version:xxx\"). This is not safe and will not be allowed.\n" + "This message will be displayed until you remove this from the JVM arguments."); + CustomMessageBox::selectable( + parent, QObject::tr("JVM arguments warning"), + warnStr, + QMessageBox::Warning)->exec(); + return false; + } return true; } diff --git a/launcher/LaunchController.cpp b/launcher/LaunchController.cpp index 792d8381..4cb62e69 100644 --- a/launcher/LaunchController.cpp +++ b/launcher/LaunchController.cpp @@ -71,7 +71,10 @@ void LaunchController::executeTask() return; } - JavaCommon::checkJVMArgs(m_instance->settings()->get("JvmArgs").toString(), m_parentWidget); + if(!JavaCommon::checkJVMArgs(m_instance->settings()->get("JvmArgs").toString(), m_parentWidget)) { + emitFailed(tr("Invalid Java arguments specified. Please fix this first.")); + return; + } login(); } @@ -166,13 +169,14 @@ void LaunchController::login() { if(!m_session->wants_online) { // we ask the user for a player name bool ok = false; - QString usedname = m_session->player_name; + QString lastOfflinePlayerName = APPLICATION->settings()->get("LastOfflinePlayerName").toString(); + QString usedname = lastOfflinePlayerName.isEmpty() ? m_session->player_name : lastOfflinePlayerName; QString name = QInputDialog::getText( m_parentWidget, tr("Player name"), tr("Choose your offline mode player name."), QLineEdit::Normal, - m_session->player_name, + usedname, &ok ); if (!ok) @@ -183,6 +187,7 @@ void LaunchController::login() { if (name.length()) { usedname = name; + APPLICATION->settings()->set("LastOfflinePlayerName", usedname); } m_session->MakeOffline(usedname); // offline flavored game from here :3 diff --git a/launcher/Launcher.in b/launcher/Launcher.in index 5e5e2c2b..528e360e 100755 --- a/launcher/Launcher.in +++ b/launcher/Launcher.in @@ -21,7 +21,7 @@ echo "Launcher Dir: ${LAUNCHER_DIR}" # Set up env - filter out input LD_ variables but pass them in under different names export GAME_LIBRARY_PATH=${GAME_LIBRARY_PATH-${LD_LIBRARY_PATH}} export GAME_PRELOAD=${GAME_PRELOAD-${LD_PRELOAD}} -export LD_LIBRARY_PATH="${LAUNCHER_DIR}/bin":$LAUNCHER_LIBRARY_PATH +export LD_LIBRARY_PATH="${LAUNCHER_DIR}/lib@LIB_SUFFIX@":$LAUNCHER_LIBRARY_PATH export LD_PRELOAD=$LAUNCHER_PRELOAD export QT_PLUGIN_PATH="${LAUNCHER_DIR}/plugins" export QT_FONTPATH="${LAUNCHER_DIR}/fonts" diff --git a/launcher/java/JavaChecker.cpp b/launcher/java/JavaChecker.cpp index 35ddc35c..946599c5 100644 --- a/launcher/java/JavaChecker.cpp +++ b/launcher/java/JavaChecker.cpp @@ -129,7 +129,7 @@ void JavaChecker::finished(int exitcode, QProcess::ExitStatus status) auto os_arch = results["os.arch"]; auto java_version = results["java.version"]; auto java_vendor = results["java.vendor"]; - bool is_64 = os_arch == "x86_64" || os_arch == "amd64"; + bool is_64 = os_arch == "x86_64" || os_arch == "amd64" || os_arch == "aarch64" || os_arch == "arm64"; result.validity = JavaCheckResult::Validity::Valid; diff --git a/launcher/java/JavaInstallList.cpp b/launcher/java/JavaInstallList.cpp index a0a60871..9b745095 100644 --- a/launcher/java/JavaInstallList.cpp +++ b/launcher/java/JavaInstallList.cpp @@ -183,7 +183,7 @@ void JavaListLoadTask::javaCheckerFinished() JavaInstallPtr javaVersion(new JavaInstall()); javaVersion->id = result.javaVersion; - javaVersion->arch = result.mojangPlatform; + javaVersion->arch = result.realPlatform; javaVersion->path = result.path; candidates.append(javaVersion); diff --git a/launcher/launch/steps/CheckJava.cpp b/launcher/launch/steps/CheckJava.cpp index c2ebb334..3226fae7 100644 --- a/launcher/launch/steps/CheckJava.cpp +++ b/launcher/launch/steps/CheckJava.cpp @@ -124,7 +124,8 @@ void CheckJava::checkJavaFinished(JavaCheckResult result) case JavaCheckResult::Validity::Valid: { auto instance = m_parent->instance(); - printJavaInfo(result.javaVersion.toString(), result.mojangPlatform, result.javaVendor); + printJavaInfo(result.javaVersion.toString(), result.realPlatform, result.javaVendor); + printSystemInfo(true, result.is_64bit); instance->settings()->set("JavaVersion", result.javaVersion.toString()); instance->settings()->set("JavaArchitecture", result.mojangPlatform); instance->settings()->set("JavaVendor", result.javaVendor); @@ -137,8 +138,7 @@ void CheckJava::checkJavaFinished(JavaCheckResult result) void CheckJava::printJavaInfo(const QString& version, const QString& architecture, const QString & vendor) { - emit logLine(QString("Java is version %1, using %2-bit architecture, from %3.\n\n").arg(version, architecture, vendor), MessageLevel::Launcher); - printSystemInfo(true, architecture == "64"); + emit logLine(QString("Java is version %1, using %2 architecture, from %3.\n\n").arg(version, architecture, vendor), MessageLevel::Launcher); } void CheckJava::printSystemInfo(bool javaIsKnown, bool javaIs64bit) diff --git a/launcher/minecraft/Agent.h b/launcher/minecraft/Agent.h new file mode 100644 index 00000000..01109daf --- /dev/null +++ b/launcher/minecraft/Agent.h @@ -0,0 +1,36 @@ +#pragma once + +#include <QString> + +#include "Library.h" + +class Agent; + +typedef std::shared_ptr<Agent> AgentPtr; + +class Agent { +public: + Agent(LibraryPtr library, QString &argument) + { + m_library = library; + m_argument = argument; + } + +public: /* methods */ + + LibraryPtr library() { + return m_library; + } + QString argument() { + return m_argument; + } + +protected: /* data */ + + /// The library pointing to the jar this Java agent is contained within + LibraryPtr m_library; + + /// The argument to the Java agent, passed after an = if present + QString m_argument; + +}; diff --git a/launcher/minecraft/ComponentUpdateTask.cpp b/launcher/minecraft/ComponentUpdateTask.cpp index 8bc05a1b..ff7ed0af 100644 --- a/launcher/minecraft/ComponentUpdateTask.cpp +++ b/launcher/minecraft/ComponentUpdateTask.cpp @@ -591,7 +591,7 @@ void ComponentUpdateTask::resolveDependencies(bool checkOnly) { component->m_version = "3.1.2"; } - else if (add.uid == "net.fabricmc.intermediary") + else if (add.uid == "net.fabricmc.intermediary" || add.uid == "org.quiltmc.hashed") { auto minecraft = std::find_if(components.begin(), components.end(), [](ComponentPtr & cmp){ return cmp->getID() == "net.minecraft"; diff --git a/launcher/minecraft/LaunchProfile.cpp b/launcher/minecraft/LaunchProfile.cpp index cd77aa4a..39a342ca 100644 --- a/launcher/minecraft/LaunchProfile.cpp +++ b/launcher/minecraft/LaunchProfile.cpp @@ -42,11 +42,13 @@ void LaunchProfile::clear() m_minecraftVersionType.clear(); m_minecraftAssets.reset(); m_minecraftArguments.clear(); + m_addnJvmArguments.clear(); m_tweakers.clear(); m_mainClass.clear(); m_appletClass.clear(); m_libraries.clear(); m_mavenFiles.clear(); + m_agents.clear(); m_traits.clear(); m_jarMods.clear(); m_mainJar.reset(); @@ -80,6 +82,11 @@ void LaunchProfile::applyMinecraftArguments(const QString& minecraftArguments) applyString(minecraftArguments, this->m_minecraftArguments); } +void LaunchProfile::applyAddnJvmArguments(const QStringList& addnJvmArguments) +{ + this->m_addnJvmArguments.append(addnJvmArguments); +} + void LaunchProfile::applyMinecraftVersionType(const QString& type) { applyString(type, this->m_minecraftVersionType); @@ -214,6 +221,22 @@ void LaunchProfile::applyMavenFile(LibraryPtr mavenFile) m_mavenFiles.append(Library::limitedCopy(mavenFile)); } +void LaunchProfile::applyAgent(AgentPtr agent) +{ + auto lib = agent->library(); + if(!lib->isActive()) + { + return; + } + + if(lib->isNative()) + { + return; + } + + m_agents.append(agent); +} + const LibraryPtr LaunchProfile::getMainJar() const { return m_mainJar; @@ -295,6 +318,11 @@ QString LaunchProfile::getMinecraftArguments() const return m_minecraftArguments; } +const QStringList & LaunchProfile::getAddnJvmArguments() const +{ + return m_addnJvmArguments; +} + const QList<LibraryPtr> & LaunchProfile::getJarMods() const { return m_jarMods; @@ -315,6 +343,11 @@ const QList<LibraryPtr> & LaunchProfile::getMavenFiles() const return m_mavenFiles; } +const QList<AgentPtr> & LaunchProfile::getAgents() const +{ + return m_agents; +} + const QList<int> & LaunchProfile::getCompatibleJavaMajors() const { return m_compatibleJavaMajors; diff --git a/launcher/minecraft/LaunchProfile.h b/launcher/minecraft/LaunchProfile.h index 366ed805..b55cf661 100644 --- a/launcher/minecraft/LaunchProfile.h +++ b/launcher/minecraft/LaunchProfile.h @@ -36,6 +36,7 @@ #pragma once #include <QString> #include "Library.h" +#include "Agent.h" #include <ProblemProvider.h> class LaunchProfile: public ProblemProvider @@ -48,6 +49,7 @@ public: /* application of profile variables from patches */ void applyMainClass(const QString& mainClass); void applyAppletClass(const QString& appletClass); void applyMinecraftArguments(const QString& minecraftArguments); + void applyAddnJvmArguments(const QStringList& minecraftArguments); void applyMinecraftVersionType(const QString& type); void applyMinecraftAssets(MojangAssetIndexInfo::Ptr assets); void applyTraits(const QSet<QString> &traits); @@ -56,6 +58,7 @@ public: /* application of profile variables from patches */ void applyMods(const QList<LibraryPtr> &jarMods); void applyLibrary(LibraryPtr library); void applyMavenFile(LibraryPtr library); + void applyAgent(AgentPtr agent); void applyCompatibleJavaMajors(QList<int>& javaMajor); void applyMainJar(LibraryPtr jar); void applyProblemSeverity(ProblemSeverity severity); @@ -69,12 +72,14 @@ public: /* getters for profile variables */ QString getMinecraftVersionType() const; MojangAssetIndexInfo::Ptr getMinecraftAssets() const; QString getMinecraftArguments() const; + const QStringList & getAddnJvmArguments() const; const QSet<QString> & getTraits() const; const QStringList & getTweakers() const; const QList<LibraryPtr> & getJarMods() const; const QList<LibraryPtr> & getLibraries() const; const QList<LibraryPtr> & getNativeLibraries() const; const QList<LibraryPtr> & getMavenFiles() const; + const QList<AgentPtr> & getAgents() const; const QList<int> & getCompatibleJavaMajors() const; const LibraryPtr getMainJar() const; void getLibraryFiles( @@ -106,6 +111,12 @@ private: */ QString m_minecraftArguments; + /** + * Additional arguments to pass to the JVM in addition to those the user has configured, + * memory settings, etc. + */ + QStringList m_addnJvmArguments; + /// A list of all tweaker classes QStringList m_tweakers; @@ -121,6 +132,9 @@ private: /// the list of maven files to be placed in the libraries folder, but not acted upon QList<LibraryPtr> m_mavenFiles; + /// the list of java agents to add to JVM arguments + QList<AgentPtr> m_agents; + /// the main jar LibraryPtr m_mainJar; diff --git a/launcher/minecraft/MinecraftInstance.cpp b/launcher/minecraft/MinecraftInstance.cpp index fd933df7..503b34d9 100644 --- a/launcher/minecraft/MinecraftInstance.cpp +++ b/launcher/minecraft/MinecraftInstance.cpp @@ -213,8 +213,12 @@ QString MinecraftInstance::binRoot() const QString MinecraftInstance::getNativePath() const { +#ifdef Q_OS_FREEBSD + QDir natives_dir("/usr/local/lib/lwjgl/"); +#else QDir natives_dir(FS::PathCombine(instanceRoot(), "natives/")); return natives_dir.absolutePath(); +#endif } QString MinecraftInstance::getLocalLibraryPath() const @@ -330,6 +334,17 @@ QStringList MinecraftInstance::extraArguments() const list.append({"-Dfml.ignoreInvalidMinecraftCertificates=true", "-Dfml.ignorePatchDiscrepancies=true"}); } + auto addn = m_components->getProfile()->getAddnJvmArguments(); + if (!addn.isEmpty()) { + list.append(addn); + } + auto agents = m_components->getProfile()->getAgents(); + for (auto agent : agents) + { + QStringList jar, temp1, temp2, temp3; + agent->library()->getApplicableFiles(currentSystem, jar, temp1, temp2, temp3, getLocalLibraryPath()); + list.append("-javaagent:"+jar[0]+(agent->argument().isEmpty() ? "" : "="+agent->argument())); + } return list; } diff --git a/launcher/minecraft/OneSixVersionFormat.cpp b/launcher/minecraft/OneSixVersionFormat.cpp index 0329d70e..879f18c1 100644 --- a/launcher/minecraft/OneSixVersionFormat.cpp +++ b/launcher/minecraft/OneSixVersionFormat.cpp @@ -1,5 +1,6 @@ #include "OneSixVersionFormat.h" #include <Json.h> +#include "minecraft/Agent.h" #include "minecraft/ParseUtils.h" #include <minecraft/MojangVersionFormat.h> @@ -108,6 +109,14 @@ VersionFilePtr OneSixVersionFormat::versionFileFromJson(const QJsonDocument &doc } } + if (root.contains("+jvmArgs")) + { + for (auto arg : requireArray(root.value("+jvmArgs"))) + { + out->addnJvmArguments.append(requireString(arg)); + } + } + if (root.contains("jarMods")) { @@ -176,6 +185,21 @@ VersionFilePtr OneSixVersionFormat::versionFileFromJson(const QJsonDocument &doc readLibs("mavenFiles", out->mavenFiles); } + if(root.contains("+agents")) { + for (auto agentVal : requireArray(root.value("+agents"))) + { + QJsonObject agentObj = requireObject(agentVal); + auto lib = libraryFromJson(*out, agentObj, filename); + QString arg = ""; + if (agentObj.contains("argument")) + { + readString(agentObj, "argument", arg); + } + AgentPtr agent(new Agent(lib, arg)); + out->agents.append(agent); + } + } + // if we have mainJar, just use it if(root.contains("mainJar")) { diff --git a/launcher/minecraft/PackProfile.cpp b/launcher/minecraft/PackProfile.cpp index d516e555..d53f41e1 100644 --- a/launcher/minecraft/PackProfile.cpp +++ b/launcher/minecraft/PackProfile.cpp @@ -970,3 +970,20 @@ void PackProfile::disableInteraction(bool disable) } } } + +ModAPI::ModLoaderType PackProfile::getModLoader() +{ + if (!getComponentVersion("net.minecraftforge").isEmpty()) + { + return ModAPI::Forge; + } + else if (!getComponentVersion("net.fabricmc.fabric-loader").isEmpty()) + { + return ModAPI::Fabric; + } + else if (!getComponentVersion("org.quiltmc.quilt-loader").isEmpty()) + { + return ModAPI::Quilt; + } + return ModAPI::Unspecified; +} diff --git a/launcher/minecraft/PackProfile.h b/launcher/minecraft/PackProfile.h index 989d1c6a..ab4cd5c8 100644 --- a/launcher/minecraft/PackProfile.h +++ b/launcher/minecraft/PackProfile.h @@ -28,6 +28,7 @@ #include "BaseVersion.h" #include "MojangDownloadInfo.h" #include "net/Mode.h" +#include "modplatform/ModAPI.h" class MinecraftInstance; struct PackProfileData; @@ -117,6 +118,8 @@ public: // todo(merged): is this the best approach void appendComponent(ComponentPtr component); + ModAPI::ModLoaderType getModLoader(); + private: void scheduleSave(); bool saveIsScheduled() const; diff --git a/launcher/minecraft/VersionFile.cpp b/launcher/minecraft/VersionFile.cpp index 94fb6db7..9db30ba2 100644 --- a/launcher/minecraft/VersionFile.cpp +++ b/launcher/minecraft/VersionFile.cpp @@ -67,6 +67,7 @@ void VersionFile::applyTo(LaunchProfile *profile) profile->applyMainClass(mainClass); profile->applyAppletClass(appletClass); profile->applyMinecraftArguments(minecraftArguments); + profile->applyAddnJvmArguments(addnJvmArguments); profile->applyTweakers(addTweakers); profile->applyJarMods(jarMods); profile->applyMods(mods); @@ -81,6 +82,10 @@ void VersionFile::applyTo(LaunchProfile *profile) { profile->applyMavenFile(mavenFile); } + for (auto agent : agents) + { + profile->applyAgent(agent); + } profile->applyProblemSeverity(getProblemSeverity()); } diff --git a/launcher/minecraft/VersionFile.h b/launcher/minecraft/VersionFile.h index a7a19c4e..d4b29719 100644 --- a/launcher/minecraft/VersionFile.h +++ b/launcher/minecraft/VersionFile.h @@ -45,6 +45,7 @@ #include "minecraft/Rule.h" #include "ProblemProvider.h" #include "Library.h" +#include "Agent.h" #include <meta/JsonFormat.h> class PackProfile; @@ -92,6 +93,9 @@ public: /* data */ /// Mojang: Minecraft launch arguments (may contain placeholders for variable substitution) QString minecraftArguments; + /// PolyMC: Additional JVM launch arguments + QStringList addnJvmArguments; + /// Mojang: list of compatible java majors QList<int> compatibleJavaMajors; @@ -116,6 +120,9 @@ public: /* data */ /// PolyMC: list of maven files to put in the libraries folder, but not in classpath QList<LibraryPtr> mavenFiles; + /// PolyMC: list of agents to add to JVM arguments + QList<AgentPtr> agents; + /// The main jar (Minecraft version library, normally) LibraryPtr mainJar; diff --git a/launcher/minecraft/auth/steps/XboxAuthorizationStep.cpp b/launcher/minecraft/auth/steps/XboxAuthorizationStep.cpp index 07eeb7dc..589768e3 100644 --- a/launcher/minecraft/auth/steps/XboxAuthorizationStep.cpp +++ b/launcher/minecraft/auth/steps/XboxAuthorizationStep.cpp @@ -65,7 +65,7 @@ void XboxAuthorizationStep::onRequestDone( if(!processSTSError(error, data, headers)) { emit finished( AccountTaskState::STATE_FAILED_SOFT, - tr("Failed to get authorization for %1 services. Error %1.").arg(m_authorizationKind, error) + tr("Failed to get authorization for %1 services. Error %2.").arg(m_authorizationKind, error) ); } return; diff --git a/launcher/minecraft/mod/LocalModParseTask.cpp b/launcher/minecraft/mod/LocalModParseTask.cpp index 757a2187..f01da8ae 100644 --- a/launcher/minecraft/mod/LocalModParseTask.cpp +++ b/launcher/minecraft/mod/LocalModParseTask.cpp @@ -391,7 +391,7 @@ void LocalModParseTask::processAsZip() zip.close(); return; } - else if (zip.setCurrentFile("fabric.mod.json")) + else if (zip.setCurrentFile("fabric.mod.json")) // TODO: Support quilt.mod.json { if (!file.open(QIODevice::ReadOnly)) { diff --git a/launcher/minecraft/update/LibrariesTask.cpp b/launcher/minecraft/update/LibrariesTask.cpp index 667dd5d9..26679110 100644 --- a/launcher/minecraft/update/LibrariesTask.cpp +++ b/launcher/minecraft/update/LibrariesTask.cpp @@ -48,6 +48,10 @@ void LibrariesTask::executeTask() libArtifactPool.append(profile->getLibraries()); libArtifactPool.append(profile->getNativeLibraries()); libArtifactPool.append(profile->getMavenFiles()); + for (auto agent : profile->getAgents()) + { + libArtifactPool.append(agent->library()); + } libArtifactPool.append(profile->getMainJar()); processArtifactPool(libArtifactPool, failedLocalLibraries, inst->getLocalLibraryPath()); diff --git a/launcher/modplatform/ModAPI.h b/launcher/modplatform/ModAPI.h index ae6ac80f..8e6cd45c 100644 --- a/launcher/modplatform/ModAPI.h +++ b/launcher/modplatform/ModAPI.h @@ -3,6 +3,8 @@ #include <QString> #include <QList> +#include "Version.h" + namespace ModPlatform { class ListModel; } @@ -15,14 +17,14 @@ class ModAPI { virtual ~ModAPI() = default; // https://docs.curseforge.com/?http#tocS_ModLoaderType - enum ModLoaderType { Any = 0, Forge = 1, Cauldron = 2, LiteLoader = 3, Fabric = 4 }; + enum ModLoaderType { Unspecified = 0, Forge = 1, Cauldron = 2, LiteLoader = 3, Fabric = 4, Quilt = 5 }; struct SearchArgs { int offset; QString search; QString sorting; ModLoaderType mod_loader; - QString version; + std::list<Version> versions; }; virtual void searchMods(CallerType* caller, SearchArgs&& args) const = 0; @@ -30,9 +32,38 @@ class ModAPI { struct VersionSearchArgs { QString addonId; - QList<QString> mcVersions; + std::list<Version> mcVersions; ModLoaderType loader; }; virtual void getVersions(CallerType* caller, VersionSearchArgs&& args) const = 0; + + static auto getModLoaderString(ModLoaderType type) -> const QString { + switch (type) { + case Unspecified: + break; + case Forge: + return "forge"; + case Cauldron: + return "cauldron"; + case LiteLoader: + return "liteloader"; + case Fabric: + return "fabric"; + case Quilt: + return "quilt"; + } + return ""; + } + + protected: + inline auto getGameVersionsString(std::list<Version> mcVersions) const -> QString + { + QString s; + for(auto& ver : mcVersions){ + s += QString("%1,").arg(ver.toString()); + } + s.remove(s.length() - 1, 1); //remove last comma + return s; + } }; diff --git a/launcher/modplatform/flame/FlameAPI.h b/launcher/modplatform/flame/FlameAPI.h index 8654a693..ce02df65 100644 --- a/launcher/modplatform/flame/FlameAPI.h +++ b/launcher/modplatform/flame/FlameAPI.h @@ -6,6 +6,8 @@ class FlameAPI : public NetworkModAPI { private: inline auto getModSearchURL(SearchArgs& args) const -> QString override { + auto gameVersionStr = args.versions.size() != 0 ? QString("gameVersion=%1").arg(args.versions.front().toString()) : QString(); + return QString( "https://addons-ecs.forgesvc.net/api/v2/addon/search?" "gameId=432&" @@ -17,16 +19,25 @@ class FlameAPI : public NetworkModAPI { "searchFilter=%2&" "sort=%3&" "modLoaderType=%4&" - "gameVersion=%5") + "%5") .arg(args.offset) .arg(args.search) .arg(args.sorting) - .arg(args.mod_loader) - .arg(args.version); + .arg(getMappedModLoader(args.mod_loader)) + .arg(gameVersionStr); }; inline auto getVersionsURL(VersionSearchArgs& args) const -> QString override { return QString("https://addons-ecs.forgesvc.net/api/v2/addon/%1/files").arg(args.addonId); }; + + public: + static auto getMappedModLoader(const ModLoaderType type) -> const ModLoaderType + { + // TODO: remove this once Quilt drops official Fabric support + if (type == Quilt) // NOTE: Most if not all Fabric mods should work *currently* + return Fabric; + return type; + } }; diff --git a/launcher/modplatform/flame/FlameModIndex.cpp b/launcher/modplatform/flame/FlameModIndex.cpp index 2c3adee4..c7b86b5c 100644 --- a/launcher/modplatform/flame/FlameModIndex.cpp +++ b/launcher/modplatform/flame/FlameModIndex.cpp @@ -3,6 +3,7 @@ #include "Json.h" #include "minecraft/MinecraftInstance.h" #include "minecraft/PackProfile.h" +#include "modplatform/flame/FlameAPI.h" #include "net/NetJob.h" void FlameMod::loadIndexedPack(ModPlatform::IndexedPack& pack, QJsonObject& obj) @@ -43,8 +44,9 @@ void FlameMod::loadIndexedPackVersions(ModPlatform::IndexedPack& pack, BaseInstance* inst) { QVector<ModPlatform::IndexedVersion> unsortedVersions; - bool hasFabric = !(dynamic_cast<MinecraftInstance*>(inst))->getPackProfile()->getComponentVersion("net.fabricmc.fabric-loader").isEmpty(); - QString mcVersion = (dynamic_cast<MinecraftInstance*>(inst))->getPackProfile()->getComponentVersion("net.minecraft"); + auto profile = (dynamic_cast<MinecraftInstance*>(inst))->getPackProfile(); + bool hasFabric = FlameAPI::getMappedModLoader(profile->getModLoader()) == ModAPI::Fabric; + QString mcVersion = profile->getComponentVersion("net.minecraft"); for (auto versionIter : arr) { auto obj = versionIter.toObject(); @@ -69,6 +71,7 @@ void FlameMod::loadIndexedPackVersions(ModPlatform::IndexedPack& pack, for (auto m : modules) { auto fname = Json::requireString(m.toObject(), "foldername"); // FIXME: This does not work properly when a mod supports more than one mod loader, since + // FIXME: This also doesn't deal with Quilt mods at the moment // they bundle the meta files for all of them in the same arquive, even when that version // doesn't support the given mod loader. if (hasFabric) { diff --git a/launcher/modplatform/modrinth/ModrinthAPI.h b/launcher/modplatform/modrinth/ModrinthAPI.h index 30952e99..84dd7d03 100644 --- a/launcher/modplatform/modrinth/ModrinthAPI.h +++ b/launcher/modplatform/modrinth/ModrinthAPI.h @@ -22,12 +22,12 @@ class ModrinthAPI : public NetworkModAPI { "limit=25&" "query=%2&" "index=%3&" - "facets=[[\"categories:%4\"],[\"versions:%5\"],[\"project_type:mod\"]]") + "facets=[[\"categories:%4\"],%5[\"project_type:mod\"]]") .arg(args.offset) .arg(args.search) .arg(args.sorting) .arg(getModLoaderString(args.mod_loader)) - .arg(args.version); + .arg(getGameVersionsArray(args.versions)); }; inline auto getVersionsURL(VersionSearchArgs& args) const -> QString override @@ -40,34 +40,29 @@ class ModrinthAPI : public NetworkModAPI { .arg(getModLoaderString(args.loader)); }; - inline auto getGameVersionsString(QList<QString> mcVersions) const -> QString + auto getGameVersionsArray(std::list<Version> mcVersions) const -> QString { QString s; - for(int i = 0; i < mcVersions.count(); i++){ - s += mcVersions.at(i); - if(i < mcVersions.count() - 1) - s += ","; + for(auto& ver : mcVersions){ + s += QString("\"versions:%1\",").arg(ver.toString()); } - return s; + s.remove(s.length() - 1, 1); //remove last comma + return s.isEmpty() ? QString() : QString("[%1],").arg(s); } - inline auto getModLoaderString(ModLoaderType modLoader) const -> QString + static auto getModLoaderString(ModLoaderType type) -> const QString { - switch (modLoader) { - case Any: - return "fabric, forge"; - case Forge: - return "forge"; - case Fabric: - return "fabric"; - default: - return ""; - } + if (type == Unspecified) + return "fabric, forge, quilt"; + // TODO: remove this once Quilt drops official Fabric support + if (type == Quilt) // NOTE: Most if not all Fabric mods should work *currently* + return "fabric, quilt"; + return ModAPI::getModLoaderString(type); } inline auto validateModLoader(ModLoaderType modLoader) const -> bool { - return modLoader == Any || modLoader == Forge || modLoader == Fabric; + return modLoader == Unspecified || modLoader == Forge || modLoader == Fabric || modLoader == Quilt; } }; diff --git a/launcher/modplatform/modrinth/ModrinthPackIndex.cpp b/launcher/modplatform/modrinth/ModrinthPackIndex.cpp index 5b75f034..a3c2f166 100644 --- a/launcher/modplatform/modrinth/ModrinthPackIndex.cpp +++ b/launcher/modplatform/modrinth/ModrinthPackIndex.cpp @@ -12,7 +12,13 @@ void Modrinth::loadIndexedPack(ModPlatform::IndexedPack& pack, QJsonObject& obj) { pack.addonId = Json::requireString(obj, "project_id"); pack.name = Json::requireString(obj, "title"); - pack.websiteUrl = "https://modrinth.com/mod/" + Json::ensureString(obj, "slug", ""); + + QString slug = Json::ensureString(obj, "slug", ""); + if (!slug.isEmpty()) + pack.websiteUrl = "https://modrinth.com/mod/" + Json::ensureString(obj, "slug", ""); + else + pack.websiteUrl = ""; + pack.description = Json::ensureString(obj, "description", ""); pack.logoUrl = Json::requireString(obj, "icon_url"); diff --git a/launcher/modplatform/technic/SolderPackInstallTask.cpp b/launcher/modplatform/technic/SolderPackInstallTask.cpp index b5c91582..89dbf4ca 100644 --- a/launcher/modplatform/technic/SolderPackInstallTask.cpp +++ b/launcher/modplatform/technic/SolderPackInstallTask.cpp @@ -1,16 +1,36 @@ -/* Copyright 2013-2021 MultiMC Contributors +// SPDX-License-Identifier: GPL-3.0-only +/* + * PolyMC - Minecraft Launcher + * Copyright (c) 2021-2022 Jamie Mansfield <jmansfield@cadixdev.org> * - * 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 + * 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. * - * 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 - * 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. + * 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 "SolderPackInstallTask.h" @@ -19,16 +39,23 @@ #include <Json.h> #include <QtConcurrentRun> #include <MMCZip.h> + #include "TechnicPackProcessor.h" +#include "SolderPackManifest.h" +#include "net/ChecksumValidator.h" Technic::SolderPackInstallTask::SolderPackInstallTask( shared_qobject_ptr<QNetworkAccessManager> network, - const QUrl &sourceUrl, + const QUrl &solderUrl, + const QString &pack, + const QString &version, const QString &minecraftVersion ) { - m_sourceUrl = sourceUrl; - m_minecraftVersion = minecraftVersion; + m_solderUrl = solderUrl; + m_pack = pack; + m_version = version; m_network = network; + m_minecraftVersion = minecraftVersion; } bool Technic::SolderPackInstallTask::abort() { @@ -41,34 +68,12 @@ bool Technic::SolderPackInstallTask::abort() { void Technic::SolderPackInstallTask::executeTask() { - setStatus(tr("Finding recommended version:\n%1").arg(m_sourceUrl.toString())); - m_filesNetJob = new NetJob(tr("Finding recommended version"), m_network); - m_filesNetJob->addNetAction(Net::Download::makeByteArray(m_sourceUrl, &m_response)); - auto job = m_filesNetJob.get(); - connect(job, &NetJob::succeeded, this, &Technic::SolderPackInstallTask::versionSucceeded); - connect(job, &NetJob::failed, this, &Technic::SolderPackInstallTask::downloadFailed); - m_filesNetJob->start(); -} - -void Technic::SolderPackInstallTask::versionSucceeded() -{ - try - { - QJsonDocument doc = Json::requireDocument(m_response); - QJsonObject obj = Json::requireObject(doc); - QString version = Json::requireString(obj, "recommended", "__placeholder__"); - m_sourceUrl = m_sourceUrl.toString() + '/' + version; - } - catch (const JSONValidationError &e) - { - emitFailed(e.cause()); - m_filesNetJob.reset(); - return; - } + setStatus(tr("Resolving modpack files")); - setStatus(tr("Resolving modpack files:\n%1").arg(m_sourceUrl.toString())); m_filesNetJob = new NetJob(tr("Resolving modpack files"), m_network); - m_filesNetJob->addNetAction(Net::Download::makeByteArray(m_sourceUrl, &m_response)); + auto sourceUrl = QString("%1/modpack/%2/%3").arg(m_solderUrl.toString(), m_pack, m_version); + m_filesNetJob->addNetAction(Net::Download::makeByteArray(sourceUrl, &m_response)); + auto job = m_filesNetJob.get(); connect(job, &NetJob::succeeded, this, &Technic::SolderPackInstallTask::fileListSucceeded); connect(job, &NetJob::failed, this, &Technic::SolderPackInstallTask::downloadFailed); @@ -77,38 +82,47 @@ void Technic::SolderPackInstallTask::versionSucceeded() void Technic::SolderPackInstallTask::fileListSucceeded() { - setStatus(tr("Downloading modpack:")); - QStringList modUrls; - try - { - QJsonDocument doc = Json::requireDocument(m_response); - QJsonObject obj = Json::requireObject(doc); - QString minecraftVersion = Json::ensureString(obj, "minecraft", QString(), "__placeholder__"); - if (!minecraftVersion.isEmpty()) - m_minecraftVersion = minecraftVersion; - QJsonArray mods = Json::requireArray(obj, "mods", "'mods'"); - for (auto mod: mods) - { - QJsonObject modObject = Json::requireObject(mod); - modUrls.append(Json::requireString(modObject, "url", "'url'")); - } + setStatus(tr("Downloading modpack")); + + QJsonParseError parse_error {}; + QJsonDocument doc = QJsonDocument::fromJson(m_response, &parse_error); + if (parse_error.error != QJsonParseError::NoError) { + qWarning() << "Error while parsing JSON response from Solder at " << parse_error.offset << " reason: " << parse_error.errorString(); + qWarning() << m_response; + return; } - catch (const JSONValidationError &e) - { - emitFailed(e.cause()); + auto obj = doc.object(); + + TechnicSolder::PackBuild build; + try { + TechnicSolder::loadPackBuild(build, obj); + } + catch (const JSONValidationError& e) { + emitFailed(tr("Could not understand pack manifest:\n") + e.cause()); m_filesNetJob.reset(); return; } + + if (!build.minecraft.isEmpty()) + m_minecraftVersion = build.minecraft; + m_filesNetJob = new NetJob(tr("Downloading modpack"), m_network); + int i = 0; - for (auto &modUrl: modUrls) - { + for (const auto &mod : build.mods) { auto path = FS::PathCombine(m_outputDir.path(), QString("%1").arg(i)); - m_filesNetJob->addNetAction(Net::Download::makeFile(modUrl, path)); + + auto dl = Net::Download::makeFile(mod.url, path); + if (!mod.md5.isEmpty()) { + auto rawMd5 = QByteArray::fromHex(mod.md5.toLatin1()); + dl->addValidator(new Net::ChecksumValidator(QCryptographicHash::Md5, rawMd5)); + } + m_filesNetJob->addNetAction(dl); + i++; } - m_modCount = modUrls.size(); + m_modCount = build.mods.size(); connect(m_filesNetJob.get(), &NetJob::succeeded, this, &Technic::SolderPackInstallTask::downloadSucceeded); connect(m_filesNetJob.get(), &NetJob::progress, this, &Technic::SolderPackInstallTask::downloadProgressChanged); @@ -206,6 +220,5 @@ void Technic::SolderPackInstallTask::extractFinished() void Technic::SolderPackInstallTask::extractAborted() { emitFailed(tr("Instance import has been aborted.")); - return; } diff --git a/launcher/modplatform/technic/SolderPackInstallTask.h b/launcher/modplatform/technic/SolderPackInstallTask.h index 9b2058d8..117a7bd6 100644 --- a/launcher/modplatform/technic/SolderPackInstallTask.h +++ b/launcher/modplatform/technic/SolderPackInstallTask.h @@ -1,16 +1,36 @@ -/* Copyright 2013-2021 MultiMC Contributors +// SPDX-License-Identifier: GPL-3.0-only +/* + * PolyMC - Minecraft Launcher + * Copyright (c) 2021-2022 Jamie Mansfield <jmansfield@cadixdev.org> * - * 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 + * 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. * - * 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 - * 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. + * 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 @@ -27,7 +47,7 @@ namespace Technic { Q_OBJECT public: - explicit SolderPackInstallTask(shared_qobject_ptr<QNetworkAccessManager> network, const QUrl &sourceUrl, const QString &minecraftVersion); + explicit SolderPackInstallTask(shared_qobject_ptr<QNetworkAccessManager> network, const QUrl &solderUrl, const QString& pack, const QString& version, const QString &minecraftVersion); bool canAbort() const override { return true; } bool abort() override; @@ -37,7 +57,6 @@ namespace Technic virtual void executeTask() override; private slots: - void versionSucceeded(); void fileListSucceeded(); void downloadSucceeded(); void downloadFailed(QString reason); @@ -51,7 +70,9 @@ namespace Technic shared_qobject_ptr<QNetworkAccessManager> m_network; NetJob::Ptr m_filesNetJob; - QUrl m_sourceUrl; + QUrl m_solderUrl; + QString m_pack; + QString m_version; QString m_minecraftVersion; QByteArray m_response; QTemporaryDir m_outputDir; diff --git a/launcher/modplatform/technic/SolderPackManifest.cpp b/launcher/modplatform/technic/SolderPackManifest.cpp new file mode 100644 index 00000000..16fe0b0e --- /dev/null +++ b/launcher/modplatform/technic/SolderPackManifest.cpp @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: GPL-3.0-only +/* + * PolyMC - Minecraft Launcher + * Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org> + * + * 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 "SolderPackManifest.h" + +#include "Json.h" + +namespace TechnicSolder { + +void loadPack(Pack& v, QJsonObject& obj) +{ + v.recommended = Json::requireString(obj, "recommended"); + v.latest = Json::requireString(obj, "latest"); + + auto builds = Json::requireArray(obj, "builds"); + for (const auto buildRaw : builds) { + auto build = Json::requireString(buildRaw); + v.builds.append(build); + } +} + +static void loadPackBuildMod(PackBuildMod& b, QJsonObject& obj) +{ + b.name = Json::requireString(obj, "name"); + b.version = Json::requireString(obj, "version"); + b.md5 = Json::requireString(obj, "md5"); + b.url = Json::requireString(obj, "url"); +} + +void loadPackBuild(PackBuild& v, QJsonObject& obj) +{ + v.minecraft = Json::requireString(obj, "minecraft"); + + auto mods = Json::requireArray(obj, "mods"); + for (const auto modRaw : mods) { + auto modObj = Json::requireObject(modRaw); + PackBuildMod mod; + loadPackBuildMod(mod, modObj); + v.mods.append(mod); + } +} + +} diff --git a/launcher/modplatform/technic/SolderPackManifest.h b/launcher/modplatform/technic/SolderPackManifest.h new file mode 100644 index 00000000..09f18df0 --- /dev/null +++ b/launcher/modplatform/technic/SolderPackManifest.h @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: GPL-3.0-only +/* + * PolyMC - Minecraft Launcher + * Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org> + * + * 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 <QString> +#include <QVector> +#include <QJsonObject> + +namespace TechnicSolder { + +struct Pack { + QString recommended; + QString latest; + QVector<QString> builds; +}; + +void loadPack(Pack& v, QJsonObject& obj); + +struct PackBuildMod { + QString name; + QString version; + QString md5; + QString url; +}; + +struct PackBuild { + QString minecraft; + QVector<PackBuildMod> mods; +}; + +void loadPackBuild(PackBuild& v, QJsonObject& obj); + +} diff --git a/launcher/resources/multimc/scalable/discord.svg b/launcher/resources/multimc/scalable/discord.svg index 067be1e8..e37c3b84 100644 --- a/launcher/resources/multimc/scalable/discord.svg +++ b/launcher/resources/multimc/scalable/discord.svg @@ -1,108 +1,11 @@ -<?xml version="1.0" encoding="UTF-8" standalone="no"?> -<!-- Created with Inkscape (http://www.inkscape.org/) --> - -<svg - xmlns:dc="http://purl.org/dc/elements/1.1/" - xmlns:cc="http://creativecommons.org/ns#" - xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" - xmlns:svg="http://www.w3.org/2000/svg" - xmlns="http://www.w3.org/2000/svg" - xmlns:xlink="http://www.w3.org/1999/xlink" - xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" - xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" - width="128mm" - height="128mm" - viewBox="0 0 453.54331 453.54331" - id="svg2" - version="1.1" - inkscape:version="0.91 r13725" - sodipodi:docname="discord.svg"> - <defs - id="defs4"> - <linearGradient - inkscape:collect="always" - id="linearGradient4166"> - <stop - style="stop-color:#7593d7;stop-opacity:1" - offset="0" - id="stop4168" /> - <stop - style="stop-color:#4f6aa3;stop-opacity:1" - offset="1" - id="stop4170" /> - </linearGradient> - <linearGradient - inkscape:collect="always" - xlink:href="#linearGradient4166" - id="linearGradient4174" - x1="351.42856" - y1="513.79077" - x2="351.42856" - y2="943.79077" - gradientUnits="userSpaceOnUse" - gradientTransform="translate(24.999996,-5.8267714e-6)" /> - </defs> - <sodipodi:namedview - id="base" - pagecolor="#ffffff" - bordercolor="#666666" - borderopacity="1.0" - inkscape:pageopacity="0.0" - inkscape:pageshadow="2" - inkscape:zoom="0.98994949" - inkscape:cx="249.4082" - inkscape:cy="153.28604" - inkscape:document-units="px" - inkscape:current-layer="layer1" - showgrid="false" - fit-margin-top="0" - fit-margin-left="0" - fit-margin-right="0" - fit-margin-bottom="0" - inkscape:snap-nodes="true" - inkscape:snap-bbox="true" - inkscape:bbox-paths="false" - inkscape:snap-bbox-edge-midpoints="false" - inkscape:bbox-nodes="true" - inkscape:snap-bbox-midpoints="false" - inkscape:snap-page="true" - inkscape:window-width="1911" - inkscape:window-height="2120" - inkscape:window-x="2970" - inkscape:window-y="0" - inkscape:window-maximized="0"> - <inkscape:grid - type="xygrid" - id="grid4155" /> - </sodipodi:namedview> - <metadata - id="metadata7"> - <rdf:RDF> - <cc:Work - rdf:about=""> - <dc:format>image/svg+xml</dc:format> - <dc:type - rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> - <dc:title></dc:title> - </cc:Work> - </rdf:RDF> - </metadata> - <g - inkscape:label="Layer 1" - inkscape:groupmode="layer" - id="layer1" - transform="translate(-1.4285583,-500.24745)"> - <path - style="fill:url(#linearGradient4174);fill-opacity:1;fill-rule:evenodd" - d="m 73.928594,513.79076 a 37.5,37.5 0 0 0 -37.36914,34.88476 l -0.13086,0.11524 0,2.5 0,302.5 0.11914,0.11914 a 37.5,37.5 0 0 0 -0.11914,2.38086 37.5,37.5 0 0 0 37.5,37.5 37.5,37.5 0 0 0 2.41406,-0.0859 l 0.0859,0.0859 250.000006,0 -10,-40 100,90 0,-392.5 0,-2.5 -0.0918,-0.0918 a 37.5,37.5 0 0 0 -34.77734,-34.77734 l -0.13086,-0.13086 -2.5,0 -302.500006,0 -0.13477,0.11914 a 37.5,37.5 0 0 0 -2.36523,-0.11914 z" - id="path4157" - inkscape:connector-curvature="0" /> - <path - style="opacity:1;fill:#ffffff;fill-rule:evenodd" - d="m 262.51367,111.60742 -3.53515,4.79688 c 20.92905,7.8755 41.53825,15.82838 52.90625,26.01172 -54.51023,-27.29925 -111.94069,-29.57156 -173.11524,0.25195 13.83558,-12.04023 34.12183,-19.9521 56.31641,-26.64258 l -2.39844,-3.78711 c -19.87573,2.47189 -39.74673,4.97961 -57.48273,19.75608 -1.26426,1.0533 -2.43875,1.7112 -3.75946,3.35134 -1.04157,1.68882 -1.47654,2.94289 -2.20384,4.4259 -16.51968,33.6846 -29.13904,71.47893 -29.23561,122.47449 13.7929,19.97074 35.85963,31.20604 66.79492,33.08203 l 14.01563,-19.0664 c -16.32939,-4.839 -28.63498,-12.99042 -36.86914,-24.4961 68.24127,41.30702 122.04171,25.27927 169.32617,-0.50585 -10.12692,12.60017 -23.08016,21.50538 -39.39649,26.01171 l 14.52149,17.80469 c 31.64413,-2.6726 53.44205,-13.71547 66.03906,-32.57812 -1.25854,-42.6757 -9.40904,-79.47015 -23.71494,-111.01207 -2.51316,-5.54105 -4.27674,-11.49413 -8.10537,-16.14028 -3.45571,-4.1936 -7.96544,-7.13252 -12.90109,-9.9657 -12.42806,-7.13399 -28.6789,-11.32721 -47.20243,-13.77258 z m -76.00195,82.42383 c 12.33462,8e-5 22.33381,10.55717 22.33398,23.58008 -1.7e-4,13.02291 -9.99936,23.58 -22.33398,23.58008 -12.33462,-7e-5 -22.33382,-10.55716 -22.33399,-23.58008 1.7e-4,-13.02292 9.99937,-23.58001 22.33399,-23.58008 z m 79.54883,0 c 12.33462,8e-5 22.33381,10.55717 22.33398,23.58008 -1.7e-4,13.02291 -9.99936,23.58 -22.33398,23.58008 -12.33462,-7e-5 -22.33382,-10.55716 -22.33399,-23.58008 1.7e-4,-13.02292 9.99937,-23.58001 22.33399,-23.58008 z" - transform="translate(1.4285583,500.24745)" - id="path4176" - inkscape:connector-curvature="0" - sodipodi:nodetypes="ccccccscsccccccccsasccccccccccc" /> - </g> +<?xml version="1.0" encoding="UTF-8"?> +<svg fill="none" version="1.1" viewBox="0 0 71 71" xmlns="http://www.w3.org/2000/svg"> + <g transform="translate(0 8.0294)" clip-path="url(#clip0)"> + <path d="m60.104 4.8978c-4.5253-2.0764-9.378-3.6062-14.452-4.4824-0.0924-0.01691-0.1847 0.025349-0.2323 0.10987-0.6241 1.11-1.3154 2.5581-1.7995 3.6963-5.4572-0.817-10.886-0.817-16.232 0-0.4842-1.1635-1.2006-2.5863-1.8275-3.6963-0.0476-0.0817-0.1399-0.12396-0.2323-0.10987-5.071 0.87338-9.9237 2.4032-14.452 4.4824-0.0392 0.0169-0.0728 0.0451-0.0951 0.0817-9.2046 13.751-11.726 27.165-10.489 40.412 0.005597 0.0648 0.041978 0.1268 0.092353 0.1662 6.0729 4.4598 11.956 7.1673 17.729 8.9619 0.0924 0.0282 0.1903-0.0056 0.2491-0.0817 1.3657-1.865 2.5831-3.8315 3.6269-5.8995 0.0616-0.1211 0.0028-0.2648-0.1231-0.3127-1.931-0.7325-3.7697-1.6256-5.5384-2.6398-0.1399-0.0817-0.1511-0.2818-0.0224-0.3776 0.3722-0.2789 0.7445-0.5691 1.0999-0.8621 0.0643-0.0535 0.1539-0.0648 0.2295-0.031 11.62 5.3051 24.199 5.3051 35.682 0 0.0756-0.0366 0.1652-0.0253 0.2323 0.0282 0.3555 0.293 0.7277 0.586 1.1027 0.8649 0.1287 0.0958 0.1203 0.2959-0.0196 0.3776-1.7687 1.0339-3.6074 1.9073-5.5412 2.637-0.1259 0.0479-0.1819 0.1944-0.1203 0.3155 1.0662 2.0651 2.2836 4.0316 3.6241 5.8967 0.056 0.0789 0.1567 0.1127 0.2491 0.0845 5.8014-1.7946 11.684-4.5021 17.757-8.9619 0.0532-0.0394 0.0868-0.0986 0.0924-0.1634 1.4804-15.315-2.4796-28.618-10.498-40.412-0.0196-0.0394-0.0531-0.0676-0.0923-0.0845zm-36.379 32.428c-3.4983 0-6.3808-3.2117-6.3808-7.156s2.8266-7.156 6.3808-7.156c3.5821 0 6.4367 3.2399 6.3807 7.156 0 3.9443-2.8266 7.156-6.3807 7.156zm23.592 0c-3.4982 0-6.3807-3.2117-6.3807-7.156s2.8265-7.156 6.3807-7.156c3.5822 0 6.4367 3.2399 6.3808 7.156 0 3.9443-2.7986 7.156-6.3808 7.156z" fill="#5865f2"/> + </g> + <defs> + <clipPath id="clip0"> + <rect width="71" height="55" fill="#fff"/> + </clipPath> + </defs> </svg> diff --git a/launcher/tasks/SequentialTask.cpp b/launcher/tasks/SequentialTask.cpp index a66b9d78..1573e476 100644 --- a/launcher/tasks/SequentialTask.cpp +++ b/launcher/tasks/SequentialTask.cpp @@ -1,7 +1,23 @@ #include "SequentialTask.h" -SequentialTask::SequentialTask(QObject *parent) : Task(parent), m_currentIndex(-1) +SequentialTask::SequentialTask(QObject* parent, const QString& task_name) : Task(parent), m_name(task_name), m_currentIndex(-1) {} + +SequentialTask::~SequentialTask() +{ + for(auto task : m_queue){ + if(task) + task->deleteLater(); + } +} + +auto SequentialTask::getStepProgress() const -> qint64 +{ + return m_stepProgress; +} + +auto SequentialTask::getStepTotalProgress() const -> qint64 { + return m_stepTotalProgress; } void SequentialTask::addTask(Task::Ptr task) @@ -15,16 +31,24 @@ void SequentialTask::executeTask() startNext(); } +bool SequentialTask::abort() +{ + bool succeeded = true; + for (auto& task : m_queue) { + if (!task->abort()) succeeded = false; + } + + return succeeded; +} + void SequentialTask::startNext() { - if (m_currentIndex != -1) - { + if (m_currentIndex != -1) { Task::Ptr previous = m_queue[m_currentIndex]; disconnect(previous.get(), 0, this, 0); } m_currentIndex++; - if (m_queue.isEmpty() || m_currentIndex >= m_queue.size()) - { + if (m_queue.isEmpty() || m_currentIndex >= m_queue.size()) { emitSucceeded(); return; } @@ -33,23 +57,27 @@ void SequentialTask::startNext() connect(next.get(), SIGNAL(status(QString)), this, SLOT(subTaskStatus(QString))); connect(next.get(), SIGNAL(progress(qint64, qint64)), this, SLOT(subTaskProgress(qint64, qint64))); connect(next.get(), SIGNAL(succeeded()), this, SLOT(startNext())); + + setStatus(tr("Executing task %1 out of %2").arg(m_currentIndex + 1).arg(m_queue.size())); next->start(); } -void SequentialTask::subTaskFailed(const QString &msg) +void SequentialTask::subTaskFailed(const QString& msg) { emitFailed(msg); } -void SequentialTask::subTaskStatus(const QString &msg) +void SequentialTask::subTaskStatus(const QString& msg) { - setStatus(msg); + setStepStatus(m_queue[m_currentIndex]->getStatus()); } void SequentialTask::subTaskProgress(qint64 current, qint64 total) { - if(total == 0) - { + if (total == 0) { setProgress(0, 100); return; } - setProgress(current, total); + setProgress(m_currentIndex, m_queue.count()); + + m_stepProgress = current; + m_stepTotalProgress = total; } diff --git a/launcher/tasks/SequentialTask.h b/launcher/tasks/SequentialTask.h index 027744f3..5b3c0111 100644 --- a/launcher/tasks/SequentialTask.h +++ b/launcher/tasks/SequentialTask.h @@ -9,13 +9,21 @@ class SequentialTask : public Task { Q_OBJECT public: - explicit SequentialTask(QObject *parent = 0); - virtual ~SequentialTask() {}; + explicit SequentialTask(QObject *parent = nullptr, const QString& task_name = ""); + virtual ~SequentialTask(); + + inline auto isMultiStep() const -> bool override { return m_queue.size() > 1; }; + auto getStepProgress() const -> qint64 override; + auto getStepTotalProgress() const -> qint64 override; + + inline auto getStepStatus() const -> QString override { return m_step_status; } void addTask(Task::Ptr task); -protected: - void executeTask(); +protected slots: + void executeTask() override; +public slots: + bool abort() override; private slots: @@ -24,7 +32,19 @@ slots: void subTaskStatus(const QString &msg); void subTaskProgress(qint64 current, qint64 total); +signals: + void stepStatus(QString status); + private: + void setStepStatus(QString status) { m_step_status = status; }; + +private: + QString m_name; + QString m_step_status; + QQueue<Task::Ptr > m_queue; int m_currentIndex; + + qint64 m_stepProgress = 0; + qint64 m_stepTotalProgress = 100; }; diff --git a/launcher/tasks/Task.h b/launcher/tasks/Task.h index 9cf08dbd..344a024e 100644 --- a/launcher/tasks/Task.h +++ b/launcher/tasks/Task.h @@ -21,29 +21,27 @@ #include "QObjectPtr.h" -class Task : public QObject -{ +class Task : public QObject { Q_OBJECT -public: + public: using Ptr = shared_qobject_ptr<Task>; - enum class State - { - Inactive, - Running, - Succeeded, - Failed, - AbortedByUser - }; + enum class State { Inactive, Running, Succeeded, Failed, AbortedByUser }; -public: - explicit Task(QObject *parent = 0); - virtual ~Task() {}; + public: + explicit Task(QObject* parent = 0); + virtual ~Task() = default; bool isRunning() const; bool isFinished() const; bool wasSuccessful() const; + /*! + * MultiStep tasks are combinations of multiple tasks into a single logical task. + * The main usage of this is in SequencialTask. + */ + virtual auto isMultiStep() const -> bool { return false; } + /*! * Returns the string that was passed to emitFailed as the error message when the task failed. * If the task hasn't failed, returns an empty string. @@ -54,52 +52,45 @@ public: virtual bool canAbort() const { return false; } - QString getStatus() - { - return m_status; - } + QString getStatus() { return m_status; } + virtual auto getStepStatus() const -> QString { return m_status; } - qint64 getProgress() - { - return m_progress; - } + qint64 getProgress() { return m_progress; } + qint64 getTotalProgress() { return m_progressTotal; } + virtual auto getStepProgress() const -> qint64 { return 0; } + virtual auto getStepTotalProgress() const -> qint64 { return 100; } - qint64 getTotalProgress() - { - return m_progressTotal; - } + protected: + void logWarning(const QString& line); -protected: - void logWarning(const QString & line); - -private: + private: QString describe(); -signals: + signals: void started(); - void progress(qint64 current, qint64 total); + virtual void progress(qint64 current, qint64 total); void finished(); void succeeded(); void failed(QString reason); void status(QString status); -public slots: + public slots: virtual void start(); virtual bool abort() { return false; }; -protected: + protected: virtual void executeTask() = 0; -protected slots: + protected slots: virtual void emitSucceeded(); virtual void emitAborted(); virtual void emitFailed(QString reason); -public slots: - void setStatus(const QString &status); + public slots: + void setStatus(const QString& status); void setProgress(qint64 current, qint64 total); -private: + private: State m_state = State::Inactive; QStringList m_Warnings; QString m_failReason = ""; @@ -107,4 +98,3 @@ private: int m_progress = 0; int m_progressTotal = 100; }; - diff --git a/launcher/tasks/Task_test.cpp b/launcher/tasks/Task_test.cpp new file mode 100644 index 00000000..9b6cc2e5 --- /dev/null +++ b/launcher/tasks/Task_test.cpp @@ -0,0 +1,68 @@ +#include <QTest> +#include "TestUtil.h" + +#include "Task.h" + +/* Does nothing. Only used for testing. */ +class BasicTask : public Task { + Q_OBJECT + + friend class TaskTest; + + private: + void executeTask() override {}; +}; + +/* Does nothing. Only used for testing. */ +class BasicTask_MultiStep : public Task { + Q_OBJECT + + friend class TaskTest; + + private: + auto isMultiStep() const -> bool override { return true; } + + void executeTask() override {}; +}; + +class TaskTest : public QObject { + Q_OBJECT + + private slots: + void test_SetStatus_NoMultiStep(){ + BasicTask t; + QString status {"test status"}; + + t.setStatus(status); + + QCOMPARE(t.getStatus(), status); + QCOMPARE(t.getStepStatus(), status); + } + + void test_SetStatus_MultiStep(){ + BasicTask_MultiStep t; + QString status {"test status"}; + + t.setStatus(status); + + QCOMPARE(t.getStatus(), status); + // Even though it is multi step, it does not override the getStepStatus method, + // so it should remain the same. + QCOMPARE(t.getStepStatus(), status); + } + + void test_SetProgress(){ + BasicTask t; + int current = 42; + int total = 207; + + t.setProgress(current, total); + + QCOMPARE(t.getProgress(), current); + QCOMPARE(t.getTotalProgress(), total); + } +}; + +QTEST_GUILESS_MAIN(TaskTest) + +#include "Task_test.moc" diff --git a/launcher/ui/dialogs/AboutDialog.ui b/launcher/ui/dialogs/AboutDialog.ui index f9665c30..70c5009d 100644 --- a/launcher/ui/dialogs/AboutDialog.ui +++ b/launcher/ui/dialogs/AboutDialog.ui @@ -80,7 +80,7 @@ </font> </property> <property name="text"> - <string notr="true">PolyMC</string> + <string notr="true">Launcher</string> </property> <property name="alignment"> <set>Qt::AlignCenter</set> diff --git a/launcher/ui/dialogs/ModDownloadDialog.cpp b/launcher/ui/dialogs/ModDownloadDialog.cpp index a53f93e8..d02ea476 100644 --- a/launcher/ui/dialogs/ModDownloadDialog.cpp +++ b/launcher/ui/dialogs/ModDownloadDialog.cpp @@ -22,7 +22,9 @@ ModDownloadDialog::ModDownloadDialog(const std::shared_ptr<ModFolderModel> &mods : QDialog(parent), mods(mods), m_instance(instance) { setObjectName(QStringLiteral("ModDownloadDialog")); - resize(400, 347); + + resize(std::max(0.5*parent->width(), 400.0), std::max(0.75*parent->height(), 400.0)); + m_verticalLayout = new QVBoxLayout(this); m_verticalLayout->setObjectName(QStringLiteral("verticalLayout")); @@ -80,7 +82,7 @@ void ModDownloadDialog::confirm() tr("Confirm mods to download") ); - for(auto task : keys){ + for(auto& task : keys){ confirm_dialog->appendMod(task, modTask.find(task).value()->getFilename()); } diff --git a/launcher/ui/dialogs/ProgressDialog.cpp b/launcher/ui/dialogs/ProgressDialog.cpp index 4b092859..648bd88b 100644 --- a/launcher/ui/dialogs/ProgressDialog.cpp +++ b/launcher/ui/dialogs/ProgressDialog.cpp @@ -81,6 +81,12 @@ int ProgressDialog::execWithTask(Task *task) connect(task, SIGNAL(status(QString)), SLOT(changeStatus(const QString &))); connect(task, SIGNAL(progress(qint64, qint64)), SLOT(changeProgress(qint64, qint64))); + m_is_multi_step = task->isMultiStep(); + if(!m_is_multi_step){ + ui->globalStatusLabel->setHidden(true); + ui->globalProgressBar->setHidden(true); + } + // if this didn't connect to an already running task, invoke start if(!task->isRunning()) { @@ -152,14 +158,24 @@ void ProgressDialog::onTaskSucceeded() void ProgressDialog::changeStatus(const QString &status) { - ui->statusLabel->setText(status); + ui->statusLabel->setText(task->getStepStatus()); + ui->globalStatusLabel->setText(status); updateSize(); } void ProgressDialog::changeProgress(qint64 current, qint64 total) { - ui->taskProgressBar->setMaximum(total); - ui->taskProgressBar->setValue(current); + ui->globalProgressBar->setMaximum(total); + 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) diff --git a/launcher/ui/dialogs/ProgressDialog.h b/launcher/ui/dialogs/ProgressDialog.h index b28ad4fa..0b4b78a4 100644 --- a/launcher/ui/dialogs/ProgressDialog.h +++ b/launcher/ui/dialogs/ProgressDialog.h @@ -19,6 +19,7 @@ #include <memory> class Task; +class SequentialTask; namespace Ui { @@ -35,7 +36,7 @@ public: void updateSize(); - int execWithTask(Task *task); + int execWithTask(Task* task); int execWithTask(std::unique_ptr<Task> &&task); int execWithTask(std::unique_ptr<Task> &task); @@ -68,4 +69,6 @@ private: Ui::ProgressDialog *ui; Task *task; + + bool m_is_multi_step = false; }; diff --git a/launcher/ui/dialogs/ProgressDialog.ui b/launcher/ui/dialogs/ProgressDialog.ui index 04b8fef3..bf119a78 100644 --- a/launcher/ui/dialogs/ProgressDialog.ui +++ b/launcher/ui/dialogs/ProgressDialog.ui @@ -2,14 +2,6 @@ <ui version="4.0"> <class>ProgressDialog</class> <widget class="QDialog" name="ProgressDialog"> - <property name="geometry"> - <rect> - <x>0</x> - <y>0</y> - <width>400</width> - <height>100</height> - </rect> - </property> <property name="minimumSize"> <size> <width>400</width> @@ -26,7 +18,27 @@ <string>Please wait...</string> </property> <layout class="QGridLayout" name="gridLayout"> + <item row="4" column="0"> + <widget class="QPushButton" name="skipButton"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Expanding" vsizetype="Expanding"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="text"> + <string>Skip</string> + </property> + </widget> + </item> <item row="0" column="0"> + <widget class="QLabel" name="globalStatusLabel"> + <property name="text"> + <string>Global Task Status...</string> + </property> + </widget> + </item> + <item row="2" column="0"> <widget class="QLabel" name="statusLabel"> <property name="text"> <string>Task Status...</string> @@ -36,7 +48,7 @@ </property> </widget> </item> - <item row="1" column="0"> + <item row="3" column="0"> <widget class="QProgressBar" name="taskProgressBar"> <property name="value"> <number>24</number> @@ -46,16 +58,13 @@ </property> </widget> </item> - <item row="2" column="0"> - <widget class="QPushButton" name="skipButton"> - <property name="sizePolicy"> - <sizepolicy hsizetype="Expanding" vsizetype="Expanding"> - <horstretch>0</horstretch> - <verstretch>0</verstretch> - </sizepolicy> + <item row="1" column="0"> + <widget class="QProgressBar" name="globalProgressBar"> + <property name="enabled"> + <bool>true</bool> </property> - <property name="text"> - <string>Skip</string> + <property name="value"> + <number>24</number> </property> </widget> </item> diff --git a/launcher/ui/dialogs/UpdateDialog.ui b/launcher/ui/dialogs/UpdateDialog.ui index bd94a554..5eb9d88a 100644 --- a/launcher/ui/dialogs/UpdateDialog.ui +++ b/launcher/ui/dialogs/UpdateDialog.ui @@ -11,7 +11,7 @@ </rect> </property> <property name="windowTitle"> - <string>PolyMC Update</string> + <string>Launcher Update</string> </property> <property name="windowIcon"> <iconset> diff --git a/launcher/ui/pages/global/MinecraftPage.ui b/launcher/ui/pages/global/MinecraftPage.ui index decc9b8b..c18ab34b 100644 --- a/launcher/ui/pages/global/MinecraftPage.ui +++ b/launcher/ui/pages/global/MinecraftPage.ui @@ -173,20 +173,20 @@ <item> <widget class="QCheckBox" name="closeAfterLaunchCheck"> <property name="toolTip"> - <string><html><head/><body><p>PolyMC will automatically reopen when the game crashes or exits.</p></body></html></string> + <string><html><head/><body><p>The launcher will automatically reopen when the game crashes or exits.</p></body></html></string> </property> <property name="text"> - <string>Close PolyMC after game window opens</string> + <string>Close the launcher after game window opens</string> </property> </widget> </item> <item> <widget class="QCheckBox" name="quitAfterGameStopCheck"> <property name="toolTip"> - <string><html><head/><body><p>PolyMC will automatically exit if the game crashes or exists.</p></body></html></string> + <string><html><head/><body><p>The launcher will automatically quit after the game exits or crashes.</p></body></html></string> </property> <property name="text"> - <string>Quit PolyMC after game window stops</string> + <string>Quit the launcher after game window closes</string> </property> </widget> </item> diff --git a/launcher/ui/pages/instance/InstanceSettingsPage.cpp b/launcher/ui/pages/instance/InstanceSettingsPage.cpp index a5985741..a48c4d69 100644 --- a/launcher/ui/pages/instance/InstanceSettingsPage.cpp +++ b/launcher/ui/pages/instance/InstanceSettingsPage.cpp @@ -179,7 +179,6 @@ void InstanceSettingsPage::applySettings() if(javaArgs) { m_settings->set("JvmArgs", ui->jvmArgsTextBox->toPlainText().replace("\n", " ")); - JavaCommon::checkJVMArgs(m_settings->get("JvmArgs").toString(), this->parentWidget()); } else { diff --git a/launcher/ui/pages/instance/ModFolderPage.cpp b/launcher/ui/pages/instance/ModFolderPage.cpp index 599f0e11..8113fe85 100644 --- a/launcher/ui/pages/instance/ModFolderPage.cpp +++ b/launcher/ui/pages/instance/ModFolderPage.cpp @@ -56,8 +56,11 @@ #include "minecraft/VersionFilterData.h" #include "minecraft/PackProfile.h" +#include "modplatform/ModAPI.h" + #include "Version.h" #include "ui/dialogs/ProgressDialog.h" +#include "tasks/SequentialTask.h" namespace { // FIXME: wasteful @@ -387,32 +390,31 @@ void ModFolderPage::on_actionInstall_mods_triggered() if(m_inst->typeName() != "Minecraft"){ return; //this is a null instance or a legacy instance } - bool hasFabric = !((MinecraftInstance *)m_inst)->getPackProfile()->getComponentVersion("net.fabricmc.fabric-loader").isEmpty(); - bool hasForge = !((MinecraftInstance *)m_inst)->getPackProfile()->getComponentVersion("net.minecraftforge").isEmpty(); - if (!hasFabric && !hasForge) { + auto profile = ((MinecraftInstance *)m_inst)->getPackProfile(); + if (profile->getModLoader() == ModAPI::Unspecified) { QMessageBox::critical(this,tr("Error"),tr("Please install a mod loader first!")); return; } ModDownloadDialog mdownload(m_mods, this, m_inst); - if(mdownload.exec()) { - for(auto task : mdownload.getTasks()){ - connect(task, &Task::failed, [this, task](QString reason) { - task->deleteLater(); - CustomMessageBox::selectable(this, tr("Error"), reason, QMessageBox::Critical)->show(); - }); - connect(task, &Task::succeeded, [this, task]() { - QStringList warnings = task->warnings(); - if (warnings.count()) { - CustomMessageBox::selectable(this, tr("Warnings"), warnings.join('\n'), - QMessageBox::Warning)->show(); - } - task->deleteLater(); - }); - ProgressDialog loadDialog(this); - loadDialog.setSkipButton(true, tr("Abort")); - loadDialog.execWithTask(task); - m_mods->update(); + if (mdownload.exec()) { + SequentialTask* tasks = new SequentialTask(this); + connect(tasks, &Task::failed, [this, tasks](QString reason) { + CustomMessageBox::selectable(this, tr("Error"), reason, QMessageBox::Critical)->show(); + tasks->deleteLater(); + }); + connect(tasks, &Task::succeeded, [this, tasks]() { + QStringList warnings = tasks->warnings(); + if (warnings.count()) { CustomMessageBox::selectable(this, tr("Warnings"), warnings.join('\n'), QMessageBox::Warning)->show(); } + tasks->deleteLater(); + }); + + for (auto task : mdownload.getTasks()) { + tasks->addTask(task); } + ProgressDialog loadDialog(this); + loadDialog.setSkipButton(true, tr("Abort")); + loadDialog.execWithTask(tasks); + m_mods->update(); } } diff --git a/launcher/ui/pages/instance/VersionPage.cpp b/launcher/ui/pages/instance/VersionPage.cpp index ed37dd1a..23e2367b 100644 --- a/launcher/ui/pages/instance/VersionPage.cpp +++ b/launcher/ui/pages/instance/VersionPage.cpp @@ -243,6 +243,9 @@ void VersionPage::updateVersionControls() bool supportsFabric = minecraftVersion >= Version("1.14"); ui->actionInstall_Fabric->setEnabled(controlsEnabled && supportsFabric); + bool supportsQuilt = minecraftVersion >= Version("1.14"); + ui->actionInstall_Quilt->setEnabled(controlsEnabled && supportsQuilt); + bool supportsLiteLoader = minecraftVersion <= Version("1.12.2"); ui->actionInstall_LiteLoader->setEnabled(controlsEnabled && supportsLiteLoader); @@ -392,7 +395,7 @@ void VersionPage::on_actionChange_version_triggered() return; } VersionSelectDialog vselect(list.get(), tr("Change %1 version").arg(name), this); - if (uid == "net.fabricmc.intermediary") + if (uid == "net.fabricmc.intermediary" || uid == "org.quiltmc.hashed") { vselect.setEmptyString(tr("No intermediary mappings versions are currently available.")); vselect.setEmptyErrorString(tr("Couldn't load or download the intermediary mappings version lists!")); @@ -498,6 +501,33 @@ void VersionPage::on_actionInstall_Fabric_triggered() } } +void VersionPage::on_actionInstall_Quilt_triggered() +{ + auto vlist = APPLICATION->metadataIndex()->get("org.quiltmc.quilt-loader"); + if(!vlist) + { + return; + } + VersionSelectDialog vselect(vlist.get(), tr("Select Quilt Loader version"), this); + vselect.setEmptyString(tr("No Quilt Loader versions are currently available.")); + vselect.setEmptyErrorString(tr("Couldn't load or download the Quilt Loader version lists!")); + + auto currentVersion = m_profile->getComponentVersion("org.quiltmc.quilt-loader"); + if(!currentVersion.isEmpty()) + { + vselect.setCurrentVersion(currentVersion); + } + + if (vselect.exec() && vselect.selectedVersion()) + { + auto vsn = vselect.selectedVersion(); + m_profile->setComponentVersion("org.quiltmc.quilt-loader", vsn->descriptor()); + m_profile->resolve(Net::Mode::Online); + preselect(m_profile->rowCount(QModelIndex())-1); + m_container->refreshContainer(); + } +} + void VersionPage::on_actionAdd_Empty_triggered() { NewComponentDialog compdialog(QString(), QString(), this); diff --git a/launcher/ui/pages/instance/VersionPage.h b/launcher/ui/pages/instance/VersionPage.h index 2d37af43..979311fc 100644 --- a/launcher/ui/pages/instance/VersionPage.h +++ b/launcher/ui/pages/instance/VersionPage.h @@ -73,6 +73,7 @@ private slots: void on_actionChange_version_triggered(); void on_actionInstall_Forge_triggered(); void on_actionInstall_Fabric_triggered(); + void on_actionInstall_Quilt_triggered(); void on_actionAdd_Empty_triggered(); void on_actionInstall_LiteLoader_triggered(); void on_actionReload_triggered(); diff --git a/launcher/ui/pages/instance/VersionPage.ui b/launcher/ui/pages/instance/VersionPage.ui index a4990ff3..489f7218 100644 --- a/launcher/ui/pages/instance/VersionPage.ui +++ b/launcher/ui/pages/instance/VersionPage.ui @@ -107,6 +107,7 @@ <addaction name="separator"/> <addaction name="actionInstall_Forge"/> <addaction name="actionInstall_Fabric"/> + <addaction name="actionInstall_Quilt"/> <addaction name="actionInstall_LiteLoader"/> <addaction name="actionInstall_mods"/> <addaction name="separator"/> @@ -192,6 +193,14 @@ <string>Install the Fabric Loader package.</string> </property> </action> + <action name="actionInstall_Quilt"> + <property name="text"> + <string>Install Quilt</string> + </property> + <property name="toolTip"> + <string>Install the Quilt Loader package.</string> + </property> + </action> <action name="actionInstall_LiteLoader"> <property name="text"> <string>Install LiteLoader</string> diff --git a/launcher/ui/pages/modplatform/ModModel.cpp b/launcher/ui/pages/modplatform/ModModel.cpp index 01b5d247..da0331b5 100644 --- a/launcher/ui/pages/modplatform/ModModel.cpp +++ b/launcher/ui/pages/modplatform/ModModel.cpp @@ -61,21 +61,22 @@ auto ListModel::data(const QModelIndex& index, int role) const -> QVariant void ListModel::requestModVersions(ModPlatform::IndexedPack const& current) { + auto profile = (dynamic_cast<MinecraftInstance*>((dynamic_cast<ModPage*>(parent()))->m_instance))->getPackProfile(); + m_parent->apiProvider()->getVersions(this, - { current.addonId.toString(), getMineVersions(), hasFabric() ? ModAPI::ModLoaderType::Fabric : ModAPI::ModLoaderType::Forge }); + { current.addonId.toString(), getMineVersions(), profile->getModLoader() }); } void ListModel::performPaginatedSearch() { + auto profile = (dynamic_cast<MinecraftInstance*>((dynamic_cast<ModPage*>(parent()))->m_instance))->getPackProfile(); + m_parent->apiProvider()->searchMods(this, - { nextSearchOffset, currentSearchTerm, getSorts()[currentSort], hasFabric() ? ModAPI::Fabric : ModAPI::Forge, getMineVersions().at(0) }); + { nextSearchOffset, currentSearchTerm, getSorts()[currentSort], profile->getModLoader(), getMineVersions() }); } -void ListModel::searchWithTerm(const QString& term, const int sort) +void ListModel::refresh() { - if (currentSearchTerm == term && currentSearchTerm.isNull() == term.isNull() && currentSort == sort) { return; } - currentSearchTerm = term; - currentSort = sort; if (jobPtr) { jobPtr->abort(); searchState = ResetRequested; @@ -90,6 +91,20 @@ void ListModel::searchWithTerm(const QString& term, const int sort) performPaginatedSearch(); } +void ListModel::searchWithTerm(const QString& term, const int sort, const bool filter_changed) +{ + if (currentSearchTerm == term + && currentSearchTerm.isNull() == term.isNull() + && currentSort == sort + && !filter_changed) + { return; } + + currentSearchTerm = term; + currentSort = sort; + + refresh(); +} + void ListModel::getLogo(const QString& logo, const QString& logoUrl, LogoCallback callback) { if (m_logoMap.contains(logo)) { @@ -218,17 +233,8 @@ void ListModel::versionRequestSucceeded(QJsonDocument doc, QString addonId) } // namespace ModPlatform /******** Helpers ********/ -auto ModPlatform::ListModel::hasFabric() const -> bool -{ - return !(dynamic_cast<MinecraftInstance*>((dynamic_cast<ModPage*>(parent()))->m_instance)) - ->getPackProfile() - ->getComponentVersion("net.fabricmc.fabric-loader") - .isEmpty(); -} -auto ModPlatform::ListModel::getMineVersions() const -> QList<QString> +auto ModPlatform::ListModel::getMineVersions() const -> std::list<Version> { - return { (dynamic_cast<MinecraftInstance*>((dynamic_cast<ModPage*>(parent()))->m_instance)) - ->getPackProfile() - ->getComponentVersion("net.minecraft") }; + return m_parent->getFilter()->versions; } diff --git a/launcher/ui/pages/modplatform/ModModel.h b/launcher/ui/pages/modplatform/ModModel.h index 64cfa71e..d460cff2 100644 --- a/launcher/ui/pages/modplatform/ModModel.h +++ b/launcher/ui/pages/modplatform/ModModel.h @@ -7,6 +7,7 @@ #include "net/NetJob.h" class ModPage; +class Version; namespace ModPlatform { @@ -33,7 +34,8 @@ class ListModel : public QAbstractListModel { /* Ask the API for more information */ void fetchMore(const QModelIndex& parent) override; - void searchWithTerm(const QString& term, const int sort); + void refresh(); + void searchWithTerm(const QString& term, const int sort, const bool filter_changed); void requestModVersions(const ModPlatform::IndexedPack& current); virtual void loadIndexedPack(ModPlatform::IndexedPack& m, QJsonObject& obj) = 0; @@ -62,8 +64,7 @@ class ListModel : public QAbstractListModel { void requestLogo(QString file, QString url); - inline auto hasFabric() const -> bool; - inline auto getMineVersions() const -> QList<QString>; + inline auto getMineVersions() const -> std::list<Version>; protected: ModPage* m_parent; diff --git a/launcher/ui/pages/modplatform/ModPage.cpp b/launcher/ui/pages/modplatform/ModPage.cpp index 3a116d3c..29f6b601 100644 --- a/launcher/ui/pages/modplatform/ModPage.cpp +++ b/launcher/ui/pages/modplatform/ModPage.cpp @@ -2,21 +2,39 @@ #include "ui_ModPage.h" #include <QKeyEvent> +#include <memory> #include "minecraft/MinecraftInstance.h" #include "minecraft/PackProfile.h" #include "ui/dialogs/ModDownloadDialog.h" ModPage::ModPage(ModDownloadDialog* dialog, BaseInstance* instance, ModAPI* api) - : QWidget(dialog), m_instance(instance), ui(new Ui::ModPage), dialog(dialog), api(api) + : QWidget(dialog) + , m_instance(instance) + , ui(new Ui::ModPage) + , dialog(dialog) + , filter_widget(static_cast<MinecraftInstance*>(instance)->getPackProfile()->getComponentVersion("net.minecraft"), this) + , api(api) { ui->setupUi(this); connect(ui->searchButton, &QPushButton::clicked, this, &ModPage::triggerSearch); + connect(ui->modFilterButton, &QPushButton::clicked, this, &ModPage::filterMods); ui->searchEdit->installEventFilter(this); ui->versionSelectionBox->view()->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); ui->versionSelectionBox->view()->parentWidget()->setMaximumHeight(300); + ui->gridLayout_3->addWidget(&filter_widget, 0, 0, 1, ui->gridLayout_3->columnCount()); + + filter_widget.setInstance(static_cast<MinecraftInstance*>(m_instance)); + m_filter = filter_widget.getFilter(); + + connect(&filter_widget, &ModFilterWidget::filterChanged, this, [&]{ + ui->searchButton->setStyleSheet("text-decoration: underline"); + }); + connect(&filter_widget, &ModFilterWidget::filterUnchanged, this, [&]{ + ui->searchButton->setStyleSheet("text-decoration: none"); + }); } ModPage::~ModPage() @@ -49,9 +67,24 @@ auto ModPage::eventFilter(QObject* watched, QEvent* event) -> bool /******** Callbacks to events in the UI (set up in the derived classes) ********/ +void ModPage::filterMods() +{ + filter_widget.setHidden(!filter_widget.isHidden()); +} + void ModPage::triggerSearch() { - listModel->searchWithTerm(ui->searchEdit->text(), ui->sortByBox->currentIndex()); + auto changed = filter_widget.changed(); + m_filter = filter_widget.getFilter(); + + if(changed){ + ui->packView->clearSelection(); + ui->packDescription->clear(); + ui->versionSelectionBox->clear(); + updateSelectionButton(); + } + + listModel->searchWithTerm(ui->searchEdit->text(), ui->sortByBox->currentIndex(), changed); } void ModPage::onSelectionChanged(QModelIndex first, QModelIndex second) @@ -68,7 +101,7 @@ void ModPage::onSelectionChanged(QModelIndex first, QModelIndex second) text = name; else text = "<a href=\"" + current.websiteUrl + "\">" + name + "</a>"; - + if (!current.authors.empty()) { auto authorToStr = [](ModPlatform::ModpackAuthor& author) -> QString { if (author.url.isEmpty()) { return author.name; } @@ -128,27 +161,35 @@ void ModPage::onModSelected() void ModPage::retranslate() { - ui->retranslateUi(this); + ui->retranslateUi(this); } -void ModPage::updateModVersions() +void ModPage::updateModVersions(int prev_count) { auto packProfile = (dynamic_cast<MinecraftInstance*>(m_instance))->getPackProfile(); QString mcVersion = packProfile->getComponentVersion("net.minecraft"); - QString loaderString = (packProfile->getComponentVersion("net.minecraftforge").isEmpty()) ? "fabric" : "forge"; + + QString loaderString = ModAPI::getModLoaderString(packProfile->getModLoader()); for (int i = 0; i < current.versions.size(); i++) { auto version = current.versions[i]; - //NOTE: Flame doesn't care about loaderString, so passing it changes nothing. - if (!validateVersion(version, mcVersion, loaderString)) { - continue; + bool valid = false; + for(auto& mcVer : m_filter->versions){ + //NOTE: Flame doesn't care about loaderString, so passing it changes nothing. + if (validateVersion(version, mcVer.toString(), loaderString)) { + valid = true; + break; + } } - ui->versionSelectionBox->addItem(version.version, QVariant(i)); + if(valid || m_filter->versions.size() == 0) + ui->versionSelectionBox->addItem(version.version, QVariant(i)); + } + if (ui->versionSelectionBox->count() == 0 && prev_count != 0) { + ui->versionSelectionBox->addItem(tr("No valid version found!"), QVariant(-1)); + ui->modSelectionButton->setText(tr("Cannot select invalid version :(")); } - if (ui->versionSelectionBox->count() == 0) { ui->versionSelectionBox->addItem(tr("No valid version found!"), QVariant(-1)); } - ui->modSelectionButton->setText(tr("Cannot select invalid version :(")); updateSelectionButton(); } diff --git a/launcher/ui/pages/modplatform/ModPage.h b/launcher/ui/pages/modplatform/ModPage.h index 0cd13f37..85aaede9 100644 --- a/launcher/ui/pages/modplatform/ModPage.h +++ b/launcher/ui/pages/modplatform/ModPage.h @@ -7,6 +7,7 @@ #include "modplatform/ModIndex.h" #include "ui/pages/BasePage.h" #include "ui/pages/modplatform/ModModel.h" +#include "ui/widgets/ModFilterWidget.h" class ModDownloadDialog; @@ -39,9 +40,10 @@ class ModPage : public QWidget, public BasePage { virtual auto validateVersion(ModPlatform::IndexedVersion& ver, QString mineVer, QString loaderVer = "") const -> bool = 0; auto apiProvider() const -> const ModAPI* { return api.get(); }; + auto getFilter() const -> const std::shared_ptr<ModFilterWidget::Filter> { return m_filter; } auto getCurrent() -> ModPlatform::IndexedPack& { return current; } - void updateModVersions(); + void updateModVersions(int prev_count = -1); void openedImpl() override; auto eventFilter(QObject* watched, QEvent* event) -> bool override; @@ -52,6 +54,7 @@ class ModPage : public QWidget, public BasePage { void updateSelectionButton(); protected slots: + virtual void filterMods(); void triggerSearch(); void onSelectionChanged(QModelIndex first, QModelIndex second); void onVersionSelectionChanged(QString data); @@ -60,6 +63,10 @@ class ModPage : public QWidget, public BasePage { protected: Ui::ModPage* ui = nullptr; ModDownloadDialog* dialog = nullptr; + + ModFilterWidget filter_widget; + std::shared_ptr<ModFilterWidget::Filter> m_filter; + ModPlatform::ListModel* listModel = nullptr; ModPlatform::IndexedPack current; diff --git a/launcher/ui/pages/modplatform/ModPage.ui b/launcher/ui/pages/modplatform/ModPage.ui index 508f1bac..afcd9bb7 100644 --- a/launcher/ui/pages/modplatform/ModPage.ui +++ b/launcher/ui/pages/modplatform/ModPage.ui @@ -11,7 +11,7 @@ </rect> </property> <layout class="QGridLayout" name="gridLayout"> - <item row="1" column="0" colspan="2"> + <item row="1" column="0" colspan="4"> <layout class="QGridLayout" name="gridLayout_3"> <item row="1" column="2"> <widget class="QTextBrowser" name="packDescription"> @@ -41,7 +41,7 @@ </item> </layout> </item> - <item row="0" column="1"> + <item row="0" column="3"> <widget class="QPushButton" name="searchButton"> <property name="text"> <string>Search</string> @@ -51,12 +51,12 @@ <item row="0" column="0"> <widget class="QLineEdit" name="searchEdit"> <property name="placeholderText"> - <string>Search and filter...</string> + <string>Search for mods...</string> </property> </widget> </item> - <item row="2" column="0" colspan="2"> - <layout class="QGridLayout" name="gridLayout_4" columnstretch="0,0,0,0"> + <item row="2" column="0" colspan="4"> + <layout class="QGridLayout" name="gridLayout_4" columnstretch="0,0,0"> <item row="0" column="2"> <widget class="QComboBox" name="versionSelectionBox"/> </item> @@ -82,6 +82,20 @@ </item> </layout> </item> + <item row="0" column="1"> + <widget class="QPushButton" name="modFilterButton"> + <property name="text"> + <string>Filter options</string> + </property> + </widget> + </item> + <item row="0" column="2"> + <widget class="Line" name="line"> + <property name="orientation"> + <enum>Qt::Vertical</enum> + </property> + </widget> + </item> </layout> </widget> <tabstops> diff --git a/launcher/ui/pages/modplatform/VanillaPage.cpp b/launcher/ui/pages/modplatform/VanillaPage.cpp index c691128f..207d0130 100644 --- a/launcher/ui/pages/modplatform/VanillaPage.cpp +++ b/launcher/ui/pages/modplatform/VanillaPage.cpp @@ -44,6 +44,7 @@ #include "ui/dialogs/NewInstanceDialog.h" #include "Filter.h" #include "InstanceCreationTask.h" +#include "Version.h" VanillaPage::VanillaPage(NewInstanceDialog *dialog, QWidget *parent) : QWidget(parent), dialog(dialog), ui(new Ui::VanillaPage) @@ -59,6 +60,15 @@ VanillaPage::VanillaPage(NewInstanceDialog *dialog, QWidget *parent) connect(ui->releaseFilter, &QCheckBox::stateChanged, this, &VanillaPage::filterChanged); connect(ui->experimentsFilter, &QCheckBox::stateChanged, this, &VanillaPage::filterChanged); connect(ui->refreshBtn, &QPushButton::clicked, this, &VanillaPage::refresh); + + connect(ui->loaderVersionList, &VersionSelectWidget::selectedVersionChanged, this, &VanillaPage::setSelectedLoaderVersion); + connect(ui->noneFilter, &QRadioButton::toggled, this, &VanillaPage::loaderFilterChanged); + connect(ui->forgeFilter, &QRadioButton::toggled, this, &VanillaPage::loaderFilterChanged); + connect(ui->fabricFilter, &QRadioButton::toggled, this, &VanillaPage::loaderFilterChanged); + connect(ui->quiltFilter, &QRadioButton::toggled, this, &VanillaPage::loaderFilterChanged); + connect(ui->liteLoaderFilter, &QRadioButton::toggled, this, &VanillaPage::loaderFilterChanged); + connect(ui->loaderRefreshBtn, &QPushButton::clicked, this, &VanillaPage::loaderRefresh); + } void VanillaPage::openedImpl() @@ -80,6 +90,13 @@ void VanillaPage::refresh() ui->versionList->loadList(); } +void VanillaPage::loaderRefresh() +{ + if(ui->noneFilter->isChecked()) + return; + ui->loaderVersionList->loadList(); +} + void VanillaPage::filterChanged() { QStringList out; @@ -99,6 +116,52 @@ void VanillaPage::filterChanged() ui->versionList->setFilter(BaseVersionList::TypeRole, new RegexpFilter(regexp, false)); } +void VanillaPage::loaderFilterChanged() +{ + auto minecraftVersion = m_selectedVersion->descriptor(); + if(ui->noneFilter->isChecked()) + { + ui->loaderVersionList->setExactFilter(BaseVersionList::ParentVersionRole, "AAA"); // empty list + ui->loaderVersionList->setEmptyString(tr("No mod loader is selected.")); + ui->loaderVersionList->setEmptyMode(VersionListView::String); + return; + } + else if(ui->forgeFilter->isChecked()) + { + ui->loaderVersionList->setExactFilter(BaseVersionList::ParentVersionRole, minecraftVersion); + m_selectedLoader = "net.minecraftforge"; + } + else if(ui->fabricFilter->isChecked()) + { + // FIXME: dirty hack because the launcher is unaware of Fabric's dependencies + if (Version(minecraftVersion) >= Version("1.14")) // Fabric/Quilt supported + ui->loaderVersionList->setExactFilter(BaseVersionList::ParentVersionRole, ""); + else // Fabric/Quilt unsupported + ui->loaderVersionList->setExactFilter(BaseVersionList::ParentVersionRole, "AAA"); // clear list + m_selectedLoader = "net.fabricmc.fabric-loader"; + } + else if(ui->quiltFilter->isChecked()) + { + // FIXME: dirty hack because the launcher is unaware of Quilt's dependencies (same as Fabric) + if (Version(minecraftVersion) >= Version("1.14")) // Fabric/Quilt supported + ui->loaderVersionList->setExactFilter(BaseVersionList::ParentVersionRole, ""); + else // Fabric/Quilt unsupported + ui->loaderVersionList->setExactFilter(BaseVersionList::ParentVersionRole, "AAA"); // clear list + m_selectedLoader = "org.quiltmc.quilt-loader"; + } + else if(ui->liteLoaderFilter->isChecked()) + { + ui->loaderVersionList->setExactFilter(BaseVersionList::ParentVersionRole, minecraftVersion); + m_selectedLoader = "com.mumfrey.liteloader"; + } + + auto vlist = APPLICATION->metadataIndex()->get(m_selectedLoader); + ui->loaderVersionList->initialize(vlist.get()); + ui->loaderVersionList->selectRecommended(); + suggestCurrent(); + ui->loaderVersionList->setEmptyString(tr("No versions are currently available for Minecraft %1").arg(minecraftVersion)); +} + VanillaPage::~VanillaPage() { delete ui; @@ -119,6 +182,16 @@ BaseVersionPtr VanillaPage::selectedVersion() const return m_selectedVersion; } +BaseVersionPtr VanillaPage::selectedLoaderVersion() const +{ + return m_selectedLoaderVersion; +} + +QString VanillaPage::selectedLoader() const +{ + return m_selectedLoader; +} + void VanillaPage::suggestCurrent() { if (!isOpened) @@ -132,7 +205,15 @@ void VanillaPage::suggestCurrent() return; } - dialog->setSuggestedPack(m_selectedVersion->descriptor(), new InstanceCreationTask(m_selectedVersion)); + // List is empty if either no mod loader is selected, or no versions are available + if(!ui->loaderVersionList->hasVersions()) + dialog->setSuggestedPack(m_selectedVersion->descriptor(), new InstanceCreationTask(m_selectedVersion)); + else + { + dialog->setSuggestedPack(m_selectedVersion->descriptor(), + new InstanceCreationTask(m_selectedVersion, m_selectedLoader, + m_selectedLoaderVersion)); + } dialog->setSuggestedIcon("default"); } @@ -140,4 +221,11 @@ void VanillaPage::setSelectedVersion(BaseVersionPtr version) { m_selectedVersion = version; suggestCurrent(); + loaderFilterChanged(); +} + +void VanillaPage::setSelectedLoaderVersion(BaseVersionPtr version) +{ + m_selectedLoaderVersion = version; + suggestCurrent(); } diff --git a/launcher/ui/pages/modplatform/VanillaPage.h b/launcher/ui/pages/modplatform/VanillaPage.h index 4e7479df..7193597d 100644 --- a/launcher/ui/pages/modplatform/VanillaPage.h +++ b/launcher/ui/pages/modplatform/VanillaPage.h @@ -77,15 +77,20 @@ public: void openedImpl() override; BaseVersionPtr selectedVersion() const; + BaseVersionPtr selectedLoaderVersion() const; + QString selectedLoader() const; public slots: void setSelectedVersion(BaseVersionPtr version); + void setSelectedLoaderVersion(BaseVersionPtr version); private slots: void filterChanged(); + void loaderFilterChanged(); private: void refresh(); + void loaderRefresh(); void suggestCurrent(); private: @@ -94,4 +99,6 @@ private: Ui::VanillaPage *ui = nullptr; bool m_versionSetByUser = false; BaseVersionPtr m_selectedVersion; + BaseVersionPtr m_selectedLoaderVersion; + QString m_selectedLoader; }; diff --git a/launcher/ui/pages/modplatform/VanillaPage.ui b/launcher/ui/pages/modplatform/VanillaPage.ui index 870ff161..43110927 100644 --- a/launcher/ui/pages/modplatform/VanillaPage.ui +++ b/launcher/ui/pages/modplatform/VanillaPage.ui @@ -33,113 +33,231 @@ <string notr="true"/> </attribute> <layout class="QGridLayout" name="gridLayout_2"> - <item row="0" column="1"> - <layout class="QVBoxLayout" name="verticalLayout"> - <item> - <widget class="QLabel" name="label"> - <property name="text"> - <string>Filter</string> - </property> - <property name="alignment"> - <set>Qt::AlignCenter</set> - </property> - </widget> - </item> - <item> - <widget class="QCheckBox" name="releaseFilter"> - <property name="text"> - <string>Releases</string> - </property> - <property name="checkable"> - <bool>true</bool> - </property> - <property name="checked"> - <bool>true</bool> - </property> - </widget> - </item> - <item> - <widget class="QCheckBox" name="snapshotFilter"> - <property name="text"> - <string>Snapshots</string> - </property> - <property name="checkable"> - <bool>true</bool> - </property> - </widget> - </item> - <item> - <widget class="QCheckBox" name="oldSnapshotFilter"> - <property name="text"> - <string>Old Snapshots</string> - </property> - <property name="checkable"> - <bool>true</bool> - </property> - </widget> - </item> + <item row="2" column="0"> + <widget class="Line" name="line"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Minimum" vsizetype="Fixed"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + </widget> + </item> + <item row="0" column="0"> + <layout class="QHBoxLayout" name="minecraftLayout"> <item> - <widget class="QCheckBox" name="betaFilter"> - <property name="text"> - <string>Betas</string> - </property> - <property name="checkable"> - <bool>true</bool> + <widget class="VersionSelectWidget" name="versionList" native="true"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Expanding" vsizetype="Expanding"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> </property> </widget> </item> <item> - <widget class="QCheckBox" name="alphaFilter"> - <property name="text"> - <string>Alphas</string> - </property> - <property name="checkable"> - <bool>true</bool> - </property> - </widget> + <layout class="QVBoxLayout" name="verticalLayout"> + <item> + <widget class="QLabel" name="label"> + <property name="text"> + <string>Filter</string> + </property> + <property name="alignment"> + <set>Qt::AlignCenter</set> + </property> + </widget> + </item> + <item> + <widget class="QCheckBox" name="releaseFilter"> + <property name="text"> + <string>Releases</string> + </property> + <property name="checkable"> + <bool>true</bool> + </property> + <property name="checked"> + <bool>true</bool> + </property> + </widget> + </item> + <item> + <widget class="QCheckBox" name="snapshotFilter"> + <property name="text"> + <string>Snapshots</string> + </property> + <property name="checkable"> + <bool>true</bool> + </property> + </widget> + </item> + <item> + <widget class="QCheckBox" name="oldSnapshotFilter"> + <property name="text"> + <string>Old Snapshots</string> + </property> + <property name="checkable"> + <bool>true</bool> + </property> + </widget> + </item> + <item> + <widget class="QCheckBox" name="betaFilter"> + <property name="text"> + <string>Betas</string> + </property> + <property name="checkable"> + <bool>true</bool> + </property> + </widget> + </item> + <item> + <widget class="QCheckBox" name="alphaFilter"> + <property name="text"> + <string>Alphas</string> + </property> + <property name="checkable"> + <bool>true</bool> + </property> + </widget> + </item> + <item> + <widget class="QCheckBox" name="experimentsFilter"> + <property name="text"> + <string>Experiments</string> + </property> + <property name="checkable"> + <bool>true</bool> + </property> + </widget> + </item> + <item> + <spacer name="verticalSpacer"> + <property name="orientation"> + <enum>Qt::Vertical</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>20</width> + <height>40</height> + </size> + </property> + </spacer> + </item> + <item> + <widget class="QPushButton" name="refreshBtn"> + <property name="text"> + <string>Refresh</string> + </property> + </widget> + </item> + </layout> </item> + </layout> + </item> + <item row="4" column="0"> + <layout class="QHBoxLayout" name="loaderLayout"> <item> - <widget class="QCheckBox" name="experimentsFilter"> - <property name="text"> - <string>Experiments</string> - </property> - <property name="checkable"> - <bool>true</bool> + <widget class="VersionSelectWidget" name="loaderVersionList" native="true"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Expanding" vsizetype="Expanding"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> </property> </widget> </item> <item> - <spacer name="verticalSpacer"> - <property name="orientation"> - <enum>Qt::Vertical</enum> - </property> - <property name="sizeHint" stdset="0"> - <size> - <width>20</width> - <height>40</height> - </size> - </property> - </spacer> - </item> - <item> - <widget class="QPushButton" name="refreshBtn"> - <property name="text"> - <string>Refresh</string> - </property> - </widget> + <layout class="QVBoxLayout" name="verticalLayout_2"> + <item> + <widget class="QLabel" name="loaderLabel"> + <property name="text"> + <string>Mod Loader</string> + </property> + <property name="alignment"> + <set>Qt::AlignCenter</set> + </property> + </widget> + </item> + <item> + <widget class="QRadioButton" name="noneFilter"> + <property name="text"> + <string>None</string> + </property> + <property name="checked"> + <bool>true</bool> + </property> + <attribute name="buttonGroup"> + <string notr="true">loaderBtnGroup</string> + </attribute> + </widget> + </item> + <item> + <widget class="QRadioButton" name="forgeFilter"> + <property name="text"> + <string>Forge</string> + </property> + <attribute name="buttonGroup"> + <string notr="true">loaderBtnGroup</string> + </attribute> + </widget> + </item> + <item> + <widget class="QRadioButton" name="fabricFilter"> + <property name="text"> + <string>Fabric</string> + </property> + <attribute name="buttonGroup"> + <string notr="true">loaderBtnGroup</string> + </attribute> + </widget> + </item> + <item> + <widget class="QRadioButton" name="quiltFilter"> + <property name="text"> + <string>Quilt</string> + </property> + <attribute name="buttonGroup"> + <string notr="true">loaderBtnGroup</string> + </attribute> + </widget> + </item> + <item> + <widget class="QRadioButton" name="liteLoaderFilter"> + <property name="text"> + <string>LiteLoader</string> + </property> + <attribute name="buttonGroup"> + <string notr="true">loaderBtnGroup</string> + </attribute> + </widget> + </item> + <item> + <spacer name="verticalSpacer_2"> + <property name="orientation"> + <enum>Qt::Vertical</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>20</width> + <height>40</height> + </size> + </property> + </spacer> + </item> + <item> + <widget class="QPushButton" name="loaderRefreshBtn"> + <property name="text"> + <string>Refresh</string> + </property> + </widget> + </item> + </layout> </item> </layout> </item> - <item row="0" column="0"> - <widget class="VersionSelectWidget" name="versionList" native="true"> - <property name="sizePolicy"> - <sizepolicy hsizetype="Expanding" vsizetype="Expanding"> - <horstretch>0</horstretch> - <verstretch>0</verstretch> - </sizepolicy> - </property> - </widget> - </item> </layout> </widget> </widget> @@ -166,4 +284,7 @@ </tabstops> <resources/> <connections/> + <buttongroups> + <buttongroup name="loaderBtnGroup"/> + </buttongroups> </ui> diff --git a/launcher/ui/pages/modplatform/flame/FlameModPage.h b/launcher/ui/pages/modplatform/flame/FlameModPage.h index dc58fd7f..d96a0720 100644 --- a/launcher/ui/pages/modplatform/flame/FlameModPage.h +++ b/launcher/ui/pages/modplatform/flame/FlameModPage.h @@ -49,7 +49,7 @@ class FlameModPage : public ModPage { inline auto displayName() const -> QString override { return "CurseForge"; } inline auto icon() const -> QIcon override { return APPLICATION->getThemedIcon("flame"); } inline auto id() const -> QString override { return "curseforge"; } - inline auto helpPage() const -> QString override { return "Flame-platform"; } + inline auto helpPage() const -> QString override { return "Mod-platform"; } inline auto debugName() const -> QString override { return "Flame"; } inline auto metaEntryBase() const -> QString override { return "FlameMods"; }; diff --git a/launcher/ui/pages/modplatform/modrinth/ModrinthPage.h b/launcher/ui/pages/modplatform/modrinth/ModrinthPage.h index aa5ed793..0bde43eb 100644 --- a/launcher/ui/pages/modplatform/modrinth/ModrinthPage.h +++ b/launcher/ui/pages/modplatform/modrinth/ModrinthPage.h @@ -49,7 +49,7 @@ class ModrinthPage : public ModPage { inline auto displayName() const -> QString override { return "Modrinth"; } inline auto icon() const -> QIcon override { return APPLICATION->getThemedIcon("modrinth"); } inline auto id() const -> QString override { return "modrinth"; } - inline auto helpPage() const -> QString override { return "Modrinth-platform"; } + inline auto helpPage() const -> QString override { return "Mod-platform"; } inline auto debugName() const -> QString override { return "Modrinth"; } inline auto metaEntryBase() const -> QString override { return "ModrinthPacks"; }; diff --git a/launcher/ui/pages/modplatform/technic/TechnicData.h b/launcher/ui/pages/modplatform/technic/TechnicData.h index 50fd75e8..cd2ea8e1 100644 --- a/launcher/ui/pages/modplatform/technic/TechnicData.h +++ b/launcher/ui/pages/modplatform/technic/TechnicData.h @@ -1,22 +1,43 @@ -/* Copyright 2020-2021 MultiMC Contributors +// SPDX-License-Identifier: GPL-3.0-only +/* + * PolyMC - Minecraft Launcher + * Copyright (c) 2021-2022 Jamie Mansfield <jmansfield@cadixdev.org> * - * 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 + * 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. * - * 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 - * 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. + * 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 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 <QList> #include <QString> +#include <QVector> namespace Technic { struct Modpack { @@ -36,6 +57,11 @@ struct Modpack { QString websiteUrl; QString author; QString description; + QString currentVersion; + + bool versionsLoaded = false; + QString recommended; + QVector<QString> versions; }; } diff --git a/launcher/ui/pages/modplatform/technic/TechnicModel.cpp b/launcher/ui/pages/modplatform/technic/TechnicModel.cpp index 0167f746..9c9d1e75 100644 --- a/launcher/ui/pages/modplatform/technic/TechnicModel.cpp +++ b/launcher/ui/pages/modplatform/technic/TechnicModel.cpp @@ -1,20 +1,41 @@ -/* Copyright 2020-2021 MultiMC Contributors +// SPDX-License-Identifier: GPL-3.0-only +/* + * PolyMC - Minecraft Launcher + * Copyright (c) 2021 Jamie Mansfield <jmansfield@cadixdev.org> * - * 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 + * 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. * - * 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 - * 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. + * 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 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 "TechnicModel.h" #include "Application.h" +#include "BuildConfig.h" #include "Json.h" #include <QIcon> @@ -94,13 +115,24 @@ void Technic::ListModel::performSearch() NetJob *netJob = new NetJob("Technic::Search", APPLICATION->network()); QString searchUrl = ""; if (currentSearchTerm.isEmpty()) { - searchUrl = "https://api.technicpack.net/trending?build=multimc"; + searchUrl = QString("%1trending?build=%2") + .arg(BuildConfig.TECHNIC_API_BASE_URL, BuildConfig.TECHNIC_API_BUILD); + searchMode = List; } - else - { + else if (currentSearchTerm.startsWith("http://api.technicpack.net/modpack/")) { + searchUrl = QString("https://%1?build=%2") + .arg(currentSearchTerm.mid(7), BuildConfig.TECHNIC_API_BUILD); + searchMode = Single; + } + else if (currentSearchTerm.startsWith("https://api.technicpack.net/modpack/")) { + searchUrl = QString("%1?build=%2").arg(currentSearchTerm, BuildConfig.TECHNIC_API_BUILD); + searchMode = Single; + } + else { searchUrl = QString( - "https://api.technicpack.net/search?build=multimc&q=%1" - ).arg(currentSearchTerm); + "%1search?build=%2&q=%3" + ).arg(BuildConfig.TECHNIC_API_BASE_URL, BuildConfig.TECHNIC_API_BUILD, currentSearchTerm); + searchMode = List; } netJob->addNetAction(Net::Download::makeByteArray(QUrl(searchUrl), &response)); jobPtr = netJob; @@ -125,26 +157,58 @@ void Technic::ListModel::searchRequestFinished() QList<Modpack> newList; try { auto root = Json::requireObject(doc); - auto objs = Json::requireArray(root, "modpacks"); - for (auto technicPack: objs) { - Modpack pack; - auto technicPackObject = Json::requireObject(technicPack); - pack.name = Json::requireString(technicPackObject, "name"); - pack.slug = Json::requireString(technicPackObject, "slug"); - if (pack.slug == "vanilla") - continue; - - auto rawURL = Json::ensureString(technicPackObject, "iconUrl", "null"); - if(rawURL == "null") { - pack.logoUrl = "null"; - pack.logoName = "null"; + + switch (searchMode) { + case List: { + auto objs = Json::requireArray(root, "modpacks"); + for (auto technicPack: objs) { + Modpack pack; + auto technicPackObject = Json::requireObject(technicPack); + pack.name = Json::requireString(technicPackObject, "name"); + pack.slug = Json::requireString(technicPackObject, "slug"); + if (pack.slug == "vanilla") + continue; + + auto rawURL = Json::ensureString(technicPackObject, "iconUrl", "null"); + if(rawURL == "null") { + pack.logoUrl = "null"; + pack.logoName = "null"; + } + else { + pack.logoUrl = rawURL; + pack.logoName = rawURL.section(QLatin1Char('/'), -1).section(QLatin1Char('.'), 0, 0); + } + pack.broken = false; + newList.append(pack); + } + break; } - else { - pack.logoUrl = rawURL; - pack.logoName = rawURL.section(QLatin1Char('/'), -1).section(QLatin1Char('.'), 0, 0); + case Single: { + if (root.contains("error")) { + // Invalid API url + break; + } + + Modpack pack; + pack.name = Json::requireString(root, "displayName"); + pack.slug = Json::requireString(root, "name"); + + if (root.contains("icon")) { + auto iconObj = Json::requireObject(root, "icon"); + auto iconUrl = Json::requireString(iconObj, "url"); + + pack.logoUrl = iconUrl; + pack.logoName = iconUrl.section(QLatin1Char('/'), -1).section(QLatin1Char('.'), 0, 0); + } + else { + pack.logoUrl = "null"; + pack.logoName = "null"; + } + + pack.broken = false; + newList.append(pack); + break; } - pack.broken = false; - newList.append(pack); } } catch (const JSONValidationError &err) diff --git a/launcher/ui/pages/modplatform/technic/TechnicModel.h b/launcher/ui/pages/modplatform/technic/TechnicModel.h index e80e6e7c..5eea124c 100644 --- a/launcher/ui/pages/modplatform/technic/TechnicModel.h +++ b/launcher/ui/pages/modplatform/technic/TechnicModel.h @@ -1,16 +1,36 @@ -/* Copyright 2020-2021 MultiMC Contributors +// SPDX-License-Identifier: GPL-3.0-only +/* + * PolyMC - Minecraft Launcher + * Copyright (c) 2021 Jamie Mansfield <jmansfield@cadixdev.org> * - * 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 + * 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. * - * 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 - * 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. + * 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 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 @@ -63,6 +83,10 @@ private: ResetRequested, Finished } searchState = None; + enum SearchMode { + List, + Single, + } searchMode = List; NetJob::Ptr jobPtr; QByteArray response; }; diff --git a/launcher/ui/pages/modplatform/technic/TechnicPage.cpp b/launcher/ui/pages/modplatform/technic/TechnicPage.cpp index c3807269..b8c1e00a 100644 --- a/launcher/ui/pages/modplatform/technic/TechnicPage.cpp +++ b/launcher/ui/pages/modplatform/technic/TechnicPage.cpp @@ -1,7 +1,7 @@ // SPDX-License-Identifier: GPL-3.0-only /* * PolyMC - Minecraft Launcher - * Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org> + * Copyright (c) 2021-2022 Jamie Mansfield <jmansfield@cadixdev.org> * * 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 @@ -40,12 +40,14 @@ #include "ui/dialogs/NewInstanceDialog.h" +#include "BuildConfig.h" #include "TechnicModel.h" #include "modplatform/technic/SingleZipPackInstallTask.h" #include "modplatform/technic/SolderPackInstallTask.h" #include "Json.h" #include "Application.h" +#include "modplatform/technic/SolderPackManifest.h" TechnicPage::TechnicPage(NewInstanceDialog* dialog, QWidget *parent) : QWidget(parent), ui(new Ui::TechnicPage), dialog(dialog) @@ -55,7 +57,9 @@ TechnicPage::TechnicPage(NewInstanceDialog* dialog, QWidget *parent) ui->searchEdit->installEventFilter(this); model = new Technic::ListModel(this); ui->packView->setModel(model); + connect(ui->packView->selectionModel(), &QItemSelectionModel::currentChanged, this, &TechnicPage::onSelectionChanged); + connect(ui->versionSelectionBox, &QComboBox::currentTextChanged, this, &TechnicPage::onVersionSelectionChanged); } bool TechnicPage::eventFilter(QObject* watched, QEvent* event) @@ -98,13 +102,14 @@ void TechnicPage::triggerSearch() { void TechnicPage::onSelectionChanged(QModelIndex first, QModelIndex second) { + ui->versionSelectionBox->clear(); + if(!first.isValid()) { if(isOpened) { dialog->setSuggestedPack(); } - //ui->frame->clear(); return; } @@ -137,17 +142,19 @@ void TechnicPage::suggestCurrent() } NetJob *netJob = new NetJob(QString("Technic::PackMeta(%1)").arg(current.name), APPLICATION->network()); - std::shared_ptr<QByteArray> response = std::make_shared<QByteArray>(); QString slug = current.slug; - netJob->addNetAction(Net::Download::makeByteArray(QString("https://api.technicpack.net/modpack/%1?build=multimc").arg(slug), response.get())); - QObject::connect(netJob, &NetJob::succeeded, this, [this, response, slug] + netJob->addNetAction(Net::Download::makeByteArray(QString("%1modpack/%2?build=%3").arg(BuildConfig.TECHNIC_API_BASE_URL, slug, BuildConfig.TECHNIC_API_BUILD), &response)); + QObject::connect(netJob, &NetJob::succeeded, this, [this, slug] { + jobPtr.reset(); + if (current.slug != slug) { return; } - QJsonParseError parse_error; - QJsonDocument doc = QJsonDocument::fromJson(*response, &parse_error); + + QJsonParseError parse_error {}; + QJsonDocument doc = QJsonDocument::fromJson(response, &parse_error); QJsonObject obj = doc.object(); if(parse_error.error != QJsonParseError::NoError) { @@ -189,10 +196,14 @@ void TechnicPage::suggestCurrent() current.websiteUrl = Json::ensureString(obj, "platformUrl", QString(), "__placeholder__"); current.author = Json::ensureString(obj, "user", QString(), "__placeholder__"); current.description = Json::ensureString(obj, "description", QString(), "__placeholder__"); + current.currentVersion = Json::ensureString(obj, "version", QString(), "__placeholder__"); current.metadataLoaded = true; + metadataLoaded(); }); - netJob->start(); + + jobPtr = netJob; + jobPtr->start(); } // expects current.metadataLoaded to be true @@ -202,25 +213,119 @@ void TechnicPage::metadataLoaded() QString name = current.name; if (current.websiteUrl.isEmpty()) - // This allows injecting HTML here. - text = name; + text = name.toHtmlEscaped(); else - // URL not properly escaped for inclusion in HTML. The name allows for injecting HTML. - text = "<a href=\"" + current.websiteUrl + "\">" + name + "</a>"; + text = "<a href=\"" + current.websiteUrl.toHtmlEscaped() + "\">" + name.toHtmlEscaped() + "</a>"; + if (!current.author.isEmpty()) { - // This allows injecting HTML here - text += tr(" by ") + current.author; + text += "<br>" + tr(" by ") + current.author.toHtmlEscaped(); + } + + text += "<br><br>"; + + ui->packDescription->setHtml(text + current.description); + + // Strip trailing forward-slashes from Solder URL's + if (current.isSolder) { + while (current.url.endsWith('/')) current.url.chop(1); + } + + // Display versions from Solder + if (!current.isSolder) { + // If the pack isn't a Solder pack, it only has the single version + ui->versionSelectionBox->addItem(current.currentVersion); + } + else if (current.versionsLoaded) { + // reverse foreach, so that the newest versions are first + for (auto i = current.versions.size(); i--;) { + ui->versionSelectionBox->addItem(current.versions.at(i)); + } + ui->versionSelectionBox->setCurrentText(current.recommended); + } + else { + // For now, until the versions are pulled from the Solder instance, display the current + // version so we can display something quicker + ui->versionSelectionBox->addItem(current.currentVersion); + + auto* netJob = new NetJob(QString("Technic::SolderMeta(%1)").arg(current.name), APPLICATION->network()); + auto url = QString("%1/modpack/%2").arg(current.url, current.slug); + netJob->addNetAction(Net::Download::makeByteArray(QUrl(url), &response)); + + QObject::connect(netJob, &NetJob::succeeded, this, &TechnicPage::onSolderLoaded); + + jobPtr = netJob; + jobPtr->start(); + } + + selectVersion(); +} + +void TechnicPage::selectVersion() { + if (!isOpened) { + return; + } + if (current.broken) { + dialog->setSuggestedPack(); + return; } - ui->frame->setModText(text); - ui->frame->setModDescription(current.description); if (!current.isSolder) { - dialog->setSuggestedPack(current.name, new Technic::SingleZipPackInstallTask(current.url, current.minecraftVersion)); + dialog->setSuggestedPack(current.name + " " + selectedVersion, new Technic::SingleZipPackInstallTask(current.url, current.minecraftVersion)); } else { - while (current.url.endsWith('/')) current.url.chop(1); - dialog->setSuggestedPack(current.name, new Technic::SolderPackInstallTask(APPLICATION->network(), current.url + "/modpack/" + current.slug, current.minecraftVersion)); + dialog->setSuggestedPack(current.name + " " + selectedVersion, new Technic::SolderPackInstallTask(APPLICATION->network(), current.url, current.slug, selectedVersion, current.minecraftVersion)); + } +} + +void TechnicPage::onSolderLoaded() { + jobPtr.reset(); + + auto fallback = [this]() { + current.versionsLoaded = true; + + current.versions.clear(); + current.versions.append(current.currentVersion); + }; + + current.versions.clear(); + + QJsonParseError parse_error {}; + auto doc = QJsonDocument::fromJson(response, &parse_error); + if (parse_error.error != QJsonParseError::NoError) { + qWarning() << "Error while parsing JSON response from Solder at " << parse_error.offset << " reason: " << parse_error.errorString(); + qWarning() << response; + fallback(); + return; + } + auto obj = doc.object(); + + TechnicSolder::Pack pack; + try { + TechnicSolder::loadPack(pack, obj); + } + catch (const JSONValidationError& err) { + qCritical() << "Couldn't parse Solder pack metadata:" << err.cause(); + fallback(); + return; + } + + current.versionsLoaded = true; + current.recommended = pack.recommended; + current.versions.append(pack.builds); + + // Finally, let's reload :) + ui->versionSelectionBox->clear(); + metadataLoaded(); +} + +void TechnicPage::onVersionSelectionChanged(QString data) { + if (data.isNull() || data.isEmpty()) { + selectedVersion = ""; + return; } + + selectedVersion = data; + selectVersion(); } diff --git a/launcher/ui/pages/modplatform/technic/TechnicPage.h b/launcher/ui/pages/modplatform/technic/TechnicPage.h index bf4baa58..f4a3b61d 100644 --- a/launcher/ui/pages/modplatform/technic/TechnicPage.h +++ b/launcher/ui/pages/modplatform/technic/TechnicPage.h @@ -1,7 +1,7 @@ // SPDX-License-Identifier: GPL-3.0-only /* * PolyMC - Minecraft Launcher - * Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org> + * Copyright (c) 2021-2022 Jamie Mansfield <jmansfield@cadixdev.org> * * 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 @@ -39,6 +39,7 @@ #include "ui/pages/BasePage.h" #include <Application.h> +#include "net/NetJob.h" #include "tasks/Task.h" #include "TechnicData.h" @@ -86,14 +87,22 @@ public: private: void suggestCurrent(); void metadataLoaded(); + void selectVersion(); private slots: void triggerSearch(); void onSelectionChanged(QModelIndex first, QModelIndex second); + void onSolderLoaded(); + void onVersionSelectionChanged(QString data); private: Ui::TechnicPage *ui = nullptr; NewInstanceDialog* dialog = nullptr; Technic::ListModel* model = nullptr; + Technic::Modpack current; + QString selectedVersion; + + NetJob::Ptr jobPtr; + QByteArray response; }; diff --git a/launcher/ui/pages/modplatform/technic/TechnicPage.ui b/launcher/ui/pages/modplatform/technic/TechnicPage.ui index 62ab6154..ca6a9b7e 100644 --- a/launcher/ui/pages/modplatform/technic/TechnicPage.ui +++ b/launcher/ui/pages/modplatform/technic/TechnicPage.ui @@ -10,86 +10,76 @@ <height>405</height> </rect> </property> - <layout class="QVBoxLayout" name="verticalLayout"> - <item> - <widget class="QWidget" name="widget" native="true"> - <layout class="QHBoxLayout" name="horizontalLayout"> - <property name="leftMargin"> - <number>0</number> - </property> - <property name="topMargin"> - <number>0</number> - </property> - <property name="rightMargin"> - <number>0</number> - </property> - <property name="bottomMargin"> - <number>0</number> - </property> - <item> - <widget class="QLineEdit" name="searchEdit"> - <property name="placeholderText"> - <string>Search and filter...</string> - </property> - </widget> - </item> - <item> - <widget class="QPushButton" name="searchButton"> - <property name="text"> - <string>Search</string> - </property> - </widget> - </item> - </layout> - </widget> + <layout class="QGridLayout" name="gridLayout"> + <item row="3" column="0" colspan="2"> + <layout class="QGridLayout" name="gridLayout_3"> + <item row="0" column="2"> + <widget class="QComboBox" name="versionSelectionBox"/> + </item> + <item row="0" column="1"> + <widget class="QLabel" name="label"> + <property name="text"> + <string>Version selected:</string> + </property> + <property name="alignment"> + <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set> + </property> + </widget> + </item> + <item row="0" column="0"> + <spacer name="horizontalSpacer"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeType"> + <enum>QSizePolicy::Preferred</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>1</width> + <height>1</height> + </size> + </property> + </spacer> + </item> + </layout> </item> - <item> - <widget class="QListView" name="packView"> - <property name="horizontalScrollBarPolicy"> - <enum>Qt::ScrollBarAlwaysOff</enum> - </property> - <property name="alternatingRowColors"> - <bool>true</bool> - </property> - <property name="iconSize"> - <size> - <width>48</width> - <height>48</height> - </size> + <item row="2" column="0" colspan="2"> + <layout class="QGridLayout" name="gridLayout_2"> + <item row="0" column="0"> + <widget class="QListView" name="packView"> + <property name="alternatingRowColors"> + <bool>true</bool> + </property> + <property name="iconSize"> + <size> + <width>48</width> + <height>48</height> + </size> + </property> + </widget> + </item> + <item row="0" column="1"> + <widget class="QTextBrowser" name="packDescription"/> + </item> + </layout> + </item> + <item row="1" column="0"> + <widget class="QLineEdit" name="searchEdit"> + <property name="placeholderText"> + <string>Search and filter...</string> </property> </widget> </item> - <item> - <widget class="MCModInfoFrame" name="frame"> - <property name="sizePolicy"> - <sizepolicy hsizetype="Preferred" vsizetype="Minimum"> - <horstretch>0</horstretch> - <verstretch>0</verstretch> - </sizepolicy> - </property> - <property name="frameShape"> - <enum>QFrame::StyledPanel</enum> - </property> - <property name="frameShadow"> - <enum>QFrame::Raised</enum> + <item row="1" column="1"> + <widget class="QPushButton" name="searchButton"> + <property name="text"> + <string>Search</string> </property> </widget> </item> </layout> </widget> - <customwidgets> - <customwidget> - <class>MCModInfoFrame</class> - <extends>QFrame</extends> - <header>ui/widgets/MCModInfoFrame.h</header> - <container>1</container> - </customwidget> - </customwidgets> - <tabstops> - <tabstop>searchEdit</tabstop> - <tabstop>searchButton</tabstop> - <tabstop>packView</tabstop> - </tabstops> <resources/> <connections/> </ui> diff --git a/launcher/ui/widgets/CustomCommands.ui b/launcher/ui/widgets/CustomCommands.ui index dbd54431..650a9cc1 100644 --- a/launcher/ui/widgets/CustomCommands.ui +++ b/launcher/ui/widgets/CustomCommands.ui @@ -74,7 +74,7 @@ <item> <widget class="QLabel" name="labelCustomCmdsDescription"> <property name="text"> - <string><html><head/><body><p>Pre-launch command runs before the instance launches and post-exit command runs after it exits.</p><p>Both will be run in the launcher's working folder with extra environment variables:</p><ul><li>$INST_NAME - Name of the instance</li><li>$INST_ID - ID of the instance (its folder name)</li><li>$INST_DIR - absolute path of the instance</li><li>$INST_MC_DIR - absolute path of Minecraft</li><li>$INST_JAVA - Java binary used for launch</li><li>$INST_JAVA_ARGS - command-line parameters used for launch</li></ul><p>Wrapper command allows launching using an extra wrapper program (like 'optirun' on Linux)</p></body></html></string> + <string><html><head/><body><p>Pre-launch command runs before the instance launches and post-exit command runs after it exits.</p><p>Both will be run in the launcher's working folder with extra environment variables:</p><ul><li>$INST_NAME - Name of the instance</li><li>$INST_ID - ID of the instance (its folder name)</li><li>$INST_DIR - absolute path of the instance</li><li>$INST_MC_DIR - absolute path of Minecraft</li><li>$INST_JAVA - Java binary used for launch</li><li>$INST_JAVA_ARGS - command-line parameters used for launch (warning: will not work correctly if arguments contain spaces)</li></ul><p>Wrapper command allows launching using an extra wrapper program (like 'optirun' on Linux)</p></body></html></string> </property> <property name="alignment"> <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop</set> diff --git a/launcher/ui/widgets/ModFilterWidget.cpp b/launcher/ui/widgets/ModFilterWidget.cpp new file mode 100644 index 00000000..ffc8d05d --- /dev/null +++ b/launcher/ui/widgets/ModFilterWidget.cpp @@ -0,0 +1,109 @@ +#include "ModFilterWidget.h" +#include "ui_ModFilterWidget.h" + +ModFilterWidget::ModFilterWidget(Version def, QWidget* parent) + : QTabWidget(parent), m_filter(new Filter()), ui(new Ui::ModFilterWidget) +{ + ui->setupUi(this); + + m_mcVersion_buttons.addButton(ui->strictVersionButton, VersionButtonID::Strict); + ui->strictVersionButton->click(); + m_mcVersion_buttons.addButton(ui->majorVersionButton, VersionButtonID::Major); + m_mcVersion_buttons.addButton(ui->allVersionsButton, VersionButtonID::All); + //m_mcVersion_buttons.addButton(ui->betweenVersionsButton, VersionButtonID::Between); + + connect(&m_mcVersion_buttons, SIGNAL(idClicked(int)), this, SLOT(onVersionFilterChanged(int))); + + m_filter->versions.push_front(def); + + setHidden(true); +} + +void ModFilterWidget::setInstance(MinecraftInstance* instance) +{ + m_instance = instance; + + auto mcVersionSplit = mcVersionStr().split("."); + + ui->strictVersionButton->setText( + tr("Strict match (= %1)").arg(mcVersionStr())); + ui->majorVersionButton->setText( + tr("Major version match (= %1.%2.x)").arg(mcVersionSplit[0], mcVersionSplit[1])); + ui->allVersionsButton->setText( + tr("Any version")); + //ui->betweenVersionsButton->setText( + // tr("Between two versions")); +} + +auto ModFilterWidget::getFilter() -> std::shared_ptr<Filter> +{ + m_last_version_id = m_version_id; + emit filterUnchanged(); + return m_filter; +} + +void ModFilterWidget::disableVersionButton(VersionButtonID id) +{ + switch(id){ + case(VersionButtonID::Strict): + ui->strictVersionButton->setEnabled(false); + break; + case(VersionButtonID::Major): + ui->majorVersionButton->setEnabled(false); + break; + case(VersionButtonID::All): + ui->allVersionsButton->setEnabled(false); + break; + case(VersionButtonID::Between): + // ui->betweenVersionsButton->setEnabled(false); + break; + default: + break; + } +} + +void ModFilterWidget::onVersionFilterChanged(int id) +{ + //ui->lowerVersionComboBox->setEnabled(id == VersionButtonID::Between); + //ui->upperVersionComboBox->setEnabled(id == VersionButtonID::Between); + + auto versionSplit = mcVersionStr().split("."); + int index = 0; + + auto cast_id = (VersionButtonID) id; + if (cast_id != m_version_id) { + m_version_id = cast_id; + } else { + return; + } + + m_filter->versions.clear(); + + switch(cast_id){ + case(VersionButtonID::Strict): + m_filter->versions.push_front(mcVersion()); + break; + case(VersionButtonID::Major): + for(auto i = Version(QString("%1.%2").arg(versionSplit[0], versionSplit[1])); i <= mcVersion(); index++){ + m_filter->versions.push_front(i); + i = Version(QString("%1.%2.%3").arg(versionSplit[0], versionSplit[1], QString("%1").arg(index))); + } + break; + case(VersionButtonID::All): + // Empty list to avoid enumerating all versions :P + break; + case(VersionButtonID::Between): + // TODO + break; + } + + if(changed()) + emit filterChanged(); + else + emit filterUnchanged(); +} + +ModFilterWidget::~ModFilterWidget() +{ + delete ui; +} diff --git a/launcher/ui/widgets/ModFilterWidget.h b/launcher/ui/widgets/ModFilterWidget.h new file mode 100644 index 00000000..334fc672 --- /dev/null +++ b/launcher/ui/widgets/ModFilterWidget.h @@ -0,0 +1,69 @@ +#pragma once + +#include <QTabWidget> +#include <QButtonGroup> + +#include "Version.h" +#include "minecraft/MinecraftInstance.h" +#include "minecraft/PackProfile.h" + +class MinecraftInstance; + +namespace Ui { +class ModFilterWidget; +} + +class ModFilterWidget : public QTabWidget +{ + Q_OBJECT +public: + enum VersionButtonID { + Strict = 0, + Major = 1, + All = 2, + Between = 3 + }; + + struct Filter { + std::list<Version> versions; + + bool operator==(const Filter& other) const { return versions == other.versions; } + bool operator!=(const Filter& other) const { return !(*this == other); } + }; + + std::shared_ptr<Filter> m_filter; + +public: + explicit ModFilterWidget(Version def, QWidget* parent = nullptr); + ~ModFilterWidget(); + + void setInstance(MinecraftInstance* instance); + + /// By default all buttons are enabled + void disableVersionButton(VersionButtonID); + + auto getFilter() -> std::shared_ptr<Filter>; + auto changed() const -> bool { return m_last_version_id != m_version_id; } + +private: + inline auto mcVersionStr() const -> QString { return m_instance ? m_instance->getPackProfile()->getComponentVersion("net.minecraft") : ""; } + inline auto mcVersion() const -> Version { return { mcVersionStr() }; } + +private slots: + void onVersionFilterChanged(int id); + +public: signals: + void filterChanged(); + void filterUnchanged(); + +private: + Ui::ModFilterWidget* ui; + + MinecraftInstance* m_instance = nullptr; + + QButtonGroup m_mcVersion_buttons; + + /* Used to tell if the filter was changed since the last getFilter() call */ + VersionButtonID m_last_version_id = VersionButtonID::Strict; + VersionButtonID m_version_id = VersionButtonID::Strict; +}; diff --git a/launcher/ui/widgets/ModFilterWidget.ui b/launcher/ui/widgets/ModFilterWidget.ui new file mode 100644 index 00000000..ad1090e2 --- /dev/null +++ b/launcher/ui/widgets/ModFilterWidget.ui @@ -0,0 +1,54 @@ +<?xml version="1.0" encoding="UTF-8"?> +<ui version="4.0"> + <class>ModFilterWidget</class> + <widget class="QTabWidget" name="ModFilterWidget"> + <property name="geometry"> + <rect> + <x>0</x> + <y>0</y> + <width>400</width> + <height>300</height> + </rect> + </property> + <property name="sizePolicy"> + <sizepolicy hsizetype="Expanding" vsizetype="Minimum"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <widget class="QWidget" name="VersionPage"> + <attribute name="title"> + <string>Minecraft versions</string> + </attribute> + <layout class="QGridLayout" name="gridLayout"> + <item row="0" column="0"> + <layout class="QFormLayout" name="formLayout"> + <item row="2" column="0"> + <widget class="QRadioButton" name="allVersionsButton"> + <property name="text"> + <string>allVersions</string> + </property> + </widget> + </item> + <item row="0" column="0"> + <widget class="QRadioButton" name="strictVersionButton"> + <property name="text"> + <string>strictVersion</string> + </property> + </widget> + </item> + <item row="1" column="0"> + <widget class="QRadioButton" name="majorVersionButton"> + <property name="text"> + <string>majorVersion</string> + </property> + </widget> + </item> + </layout> + </item> + </layout> + </widget> + </widget> + <resources/> + <connections/> +</ui> diff --git a/launcher/ui/widgets/VersionSelectWidget.cpp b/launcher/ui/widgets/VersionSelectWidget.cpp index 1209f118..cc4fc6a2 100644 --- a/launcher/ui/widgets/VersionSelectWidget.cpp +++ b/launcher/ui/widgets/VersionSelectWidget.cpp @@ -4,7 +4,6 @@ #include <QVBoxLayout> #include <QHeaderView> -#include "VersionListView.h" #include "VersionProxyModel.h" #include "ui/dialogs/CustomMessageBox.h" @@ -57,6 +56,11 @@ void VersionSelectWidget::setEmptyErrorString(QString emptyErrorString) listView->setEmptyErrorString(emptyErrorString); } +void VersionSelectWidget::setEmptyMode(VersionListView::EmptyMode mode) +{ + listView->setEmptyMode(mode); +} + VersionSelectWidget::~VersionSelectWidget() { } diff --git a/launcher/ui/widgets/VersionSelectWidget.h b/launcher/ui/widgets/VersionSelectWidget.h index 0a649408..f56daa8a 100644 --- a/launcher/ui/widgets/VersionSelectWidget.h +++ b/launcher/ui/widgets/VersionSelectWidget.h @@ -18,6 +18,7 @@ #include <QWidget> #include <QSortFilterProxyModel> #include "BaseVersionList.h" +#include "VersionListView.h" class VersionProxyModel; class VersionListView; @@ -49,6 +50,7 @@ public: void setFilter(BaseVersionList::ModelRoles role, Filter *filter); void setEmptyString(QString emptyString); void setEmptyErrorString(QString emptyErrorString); + void setEmptyMode(VersionListView::EmptyMode mode); void setResizeOn(int column); signals: |