Merge remote-tracking branch 'upstream/develop' into sysprops
Signed-off-by: TheKodeToad <TheKodeToad@proton.me>
This commit is contained in:
@ -46,8 +46,8 @@
|
||||
#include "AssetsUtils.h"
|
||||
#include "BuildConfig.h"
|
||||
#include "FileSystem.h"
|
||||
#include "net/ApiDownload.h"
|
||||
#include "net/ChecksumValidator.h"
|
||||
#include "net/Download.h"
|
||||
|
||||
#include "Application.h"
|
||||
|
||||
@ -279,7 +279,7 @@ NetAction::Ptr AssetObject::getDownloadAction()
|
||||
{
|
||||
QFileInfo objectFile(getLocalPath());
|
||||
if ((!objectFile.isFile()) || (objectFile.size() != size)) {
|
||||
auto objectDL = Net::Download::makeFile(getUrl(), objectFile.filePath());
|
||||
auto objectDL = Net::ApiDownload::makeFile(getUrl(), objectFile.filePath());
|
||||
if (hash.size()) {
|
||||
auto rawHash = QByteArray::fromHex(hash.toLatin1());
|
||||
objectDL->addValidator(new Net::ChecksumValidator(QCryptographicHash::Sha1, rawHash));
|
||||
|
@ -25,7 +25,8 @@ class Component : public QObject, public ProblemProvider {
|
||||
Component(PackProfile* parent, std::shared_ptr<Meta::Version> version);
|
||||
Component(PackProfile* parent, const QString& uid, std::shared_ptr<VersionFile> file);
|
||||
|
||||
virtual ~Component(){};
|
||||
virtual ~Component() {}
|
||||
|
||||
void applyTo(LaunchProfile* profile);
|
||||
|
||||
bool isEnabled();
|
||||
|
@ -2,14 +2,14 @@
|
||||
|
||||
#include "Component.h"
|
||||
#include "ComponentUpdateTask_p.h"
|
||||
#include "OneSixVersionFormat.h"
|
||||
#include "PackProfile.h"
|
||||
#include "PackProfile_p.h"
|
||||
#include "Version.h"
|
||||
#include "cassert"
|
||||
#include "meta/Index.h"
|
||||
#include "meta/Version.h"
|
||||
#include "meta/VersionList.h"
|
||||
#include "minecraft/OneSixVersionFormat.h"
|
||||
#include "minecraft/ProfileUtils.h"
|
||||
#include "net/Mode.h"
|
||||
|
||||
#include "Application.h"
|
||||
|
@ -41,7 +41,7 @@
|
||||
|
||||
class LaunchProfile : public ProblemProvider {
|
||||
public:
|
||||
virtual ~LaunchProfile(){};
|
||||
virtual ~LaunchProfile() {}
|
||||
|
||||
public: /* application of profile variables from patches */
|
||||
void applyMinecraftVersion(const QString& id);
|
||||
|
@ -38,8 +38,8 @@
|
||||
|
||||
#include <BuildConfig.h>
|
||||
#include <FileSystem.h>
|
||||
#include <net/ApiDownload.h>
|
||||
#include <net/ChecksumValidator.h>
|
||||
#include <net/Download.h>
|
||||
|
||||
void Library::getApplicableFiles(const RuntimeContext& runtimeContext,
|
||||
QStringList& jar,
|
||||
@ -115,12 +115,12 @@ QList<NetAction::Ptr> Library::getDownloads(const RuntimeContext& runtimeContext
|
||||
|
||||
if (sha1.size()) {
|
||||
auto rawSha1 = QByteArray::fromHex(sha1.toLatin1());
|
||||
auto dl = Net::Download::makeCached(url, entry, options);
|
||||
auto dl = Net::ApiDownload::makeCached(url, entry, options);
|
||||
dl->addValidator(new Net::ChecksumValidator(QCryptographicHash::Sha1, rawSha1));
|
||||
qDebug() << "Checksummed Download for:" << rawName().serialize() << "storage:" << storage << "url:" << url;
|
||||
out.append(dl);
|
||||
} else {
|
||||
out.append(Net::Download::makeCached(url, entry, options));
|
||||
out.append(Net::ApiDownload::makeCached(url, entry, options));
|
||||
qDebug() << "Download for:" << rawName().serialize() << "storage:" << storage << "url:" << url;
|
||||
}
|
||||
return true;
|
||||
|
@ -3,8 +3,7 @@
|
||||
* Prism Launcher - Minecraft Launcher
|
||||
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
|
||||
* Copyright (C) 2022 Jamie Mansfield <jmansfield@cadixdev.org>
|
||||
* Copyright (C) 2022 TheKodeToad <TheKodeToad@proton.me>
|
||||
* Copyright (c) 2023 seth <getchoo at tuta dot io>
|
||||
* Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me>
|
||||
*
|
||||
* 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
|
||||
@ -88,6 +87,10 @@
|
||||
#include "minecraft/gameoptions/GameOptions.h"
|
||||
#include "minecraft/update/FoldersTask.h"
|
||||
|
||||
#include "tools/BaseProfiler.h"
|
||||
|
||||
#include <QActionGroup>
|
||||
|
||||
#ifdef Q_OS_LINUX
|
||||
#include "MangoHud.h"
|
||||
#endif
|
||||
@ -166,7 +169,9 @@ void MinecraftInstance::loadSpecificSettings()
|
||||
// Native library workarounds
|
||||
auto nativeLibraryWorkaroundsOverride = m_settings->registerSetting("OverrideNativeWorkarounds", false);
|
||||
m_settings->registerOverride(global_settings->getSetting("UseNativeOpenAL"), nativeLibraryWorkaroundsOverride);
|
||||
m_settings->registerOverride(global_settings->getSetting("CustomOpenALPath"), nativeLibraryWorkaroundsOverride);
|
||||
m_settings->registerOverride(global_settings->getSetting("UseNativeGLFW"), nativeLibraryWorkaroundsOverride);
|
||||
m_settings->registerOverride(global_settings->getSetting("CustomGLFWPath"), nativeLibraryWorkaroundsOverride);
|
||||
|
||||
// Peformance related options
|
||||
auto performanceOverride = m_settings->registerSetting("OverridePerformance", false);
|
||||
@ -179,9 +184,9 @@ void MinecraftInstance::loadSpecificSettings()
|
||||
m_settings->registerOverride(global_settings->getSetting("CloseAfterLaunch"), miscellaneousOverride);
|
||||
m_settings->registerOverride(global_settings->getSetting("QuitAfterGameStop"), miscellaneousOverride);
|
||||
|
||||
// Mod loader specific options
|
||||
auto modLoaderSettings = m_settings->registerSetting("OverrideModLoaderSettings", false);
|
||||
m_settings->registerOverride(global_settings->getSetting("DisableQuiltBeacon"), modLoaderSettings);
|
||||
// Legacy-related options
|
||||
auto legacySettings = m_settings->registerSetting("OverrideLegacySettings", false);
|
||||
m_settings->registerOverride(global_settings->getSetting("OnlineFixes"), legacySettings);
|
||||
|
||||
m_settings->set("InstanceType", "OneSix");
|
||||
}
|
||||
@ -194,6 +199,12 @@ void MinecraftInstance::loadSpecificSettings()
|
||||
m_settings->registerSetting("UseAccountForInstance", false);
|
||||
m_settings->registerSetting("InstanceAccountId", "");
|
||||
|
||||
m_settings->registerSetting("ExportName", "");
|
||||
m_settings->registerSetting("ExportVersion", "1.0.0");
|
||||
m_settings->registerSetting("ExportSummary", "");
|
||||
m_settings->registerSetting("ExportAuthor", "");
|
||||
m_settings->registerSetting("ExportOptionalFiles", true);
|
||||
|
||||
qDebug() << "Instance-type specific settings were loaded!";
|
||||
|
||||
setSpecificSettingsLoaded(true);
|
||||
@ -229,6 +240,50 @@ QSet<QString> MinecraftInstance::traits() const
|
||||
return profile->getTraits();
|
||||
}
|
||||
|
||||
// FIXME: move UI code out of MinecraftInstance
|
||||
void MinecraftInstance::populateLaunchMenu(QMenu* menu)
|
||||
{
|
||||
QAction* normalLaunch = menu->addAction(tr("&Launch"));
|
||||
normalLaunch->setShortcut(QKeySequence::Open);
|
||||
QAction* normalLaunchOffline = menu->addAction(tr("Launch &Offline"));
|
||||
normalLaunchOffline->setShortcut(QKeySequence(tr("Ctrl+Shift+O")));
|
||||
QAction* normalLaunchDemo = menu->addAction(tr("Launch &Demo"));
|
||||
normalLaunchDemo->setShortcut(QKeySequence(tr("Ctrl+Alt+O")));
|
||||
|
||||
normalLaunchDemo->setEnabled(supportsDemo());
|
||||
|
||||
connect(normalLaunch, &QAction::triggered, [this] { APPLICATION->launch(shared_from_this()); });
|
||||
connect(normalLaunchOffline, &QAction::triggered, [this] { APPLICATION->launch(shared_from_this(), false, false); });
|
||||
connect(normalLaunchDemo, &QAction::triggered, [this] { APPLICATION->launch(shared_from_this(), false, true); });
|
||||
|
||||
QString profilersTitle = tr("Profilers");
|
||||
menu->addSeparator()->setText(profilersTitle);
|
||||
|
||||
auto profilers = new QActionGroup(menu);
|
||||
profilers->setExclusive(true);
|
||||
connect(profilers, &QActionGroup::triggered, [this](QAction* action) {
|
||||
settings()->set("Profiler", action->data());
|
||||
emit profilerChanged();
|
||||
});
|
||||
|
||||
QAction* noProfilerAction = menu->addAction(tr("&No Profiler"));
|
||||
noProfilerAction->setData("");
|
||||
noProfilerAction->setCheckable(true);
|
||||
noProfilerAction->setChecked(true);
|
||||
profilers->addAction(noProfilerAction);
|
||||
|
||||
for (auto profiler = APPLICATION->profilers().begin(); profiler != APPLICATION->profilers().end(); profiler++) {
|
||||
QAction* profilerAction = menu->addAction(profiler.value()->name());
|
||||
profilers->addAction(profilerAction);
|
||||
profilerAction->setData(profiler.key());
|
||||
profilerAction->setCheckable(true);
|
||||
profilerAction->setChecked(settings()->get("Profiler").toString() == profiler.key());
|
||||
|
||||
QString error;
|
||||
profilerAction->setEnabled(profiler.value()->check(&error));
|
||||
}
|
||||
}
|
||||
|
||||
QString MinecraftInstance::gameRoot() const
|
||||
{
|
||||
QFileInfo mcDir(FS::PathCombine(instanceRoot(), "minecraft"));
|
||||
@ -260,7 +315,7 @@ QString MinecraftInstance::getLocalLibraryPath() const
|
||||
bool MinecraftInstance::supportsDemo() const
|
||||
{
|
||||
Version instance_ver{ getPackProfile()->getComponentVersion("net.minecraft") };
|
||||
// Demo mode was introduced in 1.3.1: https://minecraft.fandom.com/wiki/Demo_mode#History
|
||||
// Demo mode was introduced in 1.3.1: https://minecraft.wiki/w/Demo_mode#History
|
||||
// FIXME: Due to Version constraints atm, this can't handle well non-release versions
|
||||
return instance_ver >= Version("1.3.1");
|
||||
}
|
||||
@ -385,10 +440,31 @@ QStringList MinecraftInstance::extraArguments()
|
||||
}
|
||||
|
||||
{
|
||||
const auto loaders = version->getModLoaders();
|
||||
if (loaders.has_value() && loaders.value() & ResourceAPI::Quilt && settings()->get("DisableQuiltBeacon").toBool())
|
||||
list.append("-Dloader.disable_beacon=true");
|
||||
QString openALPath;
|
||||
QString glfwPath;
|
||||
|
||||
if (settings()->get("UseNativeOpenAL").toBool()) {
|
||||
openALPath = APPLICATION->m_detectedOpenALPath;
|
||||
auto customPath = settings()->get("CustomOpenALPath").toString();
|
||||
if (!customPath.isEmpty())
|
||||
openALPath = customPath;
|
||||
}
|
||||
if (settings()->get("UseNativeGLFW").toBool()) {
|
||||
glfwPath = APPLICATION->m_detectedGLFWPath;
|
||||
auto customPath = settings()->get("CustomGLFWPath").toString();
|
||||
if (!customPath.isEmpty())
|
||||
glfwPath = customPath;
|
||||
}
|
||||
|
||||
QFileInfo openALInfo(openALPath);
|
||||
QFileInfo glfwInfo(glfwPath);
|
||||
|
||||
if (!openALPath.isEmpty() && openALInfo.exists())
|
||||
list.append("-Dorg.lwjgl.openal.libname=" + openALInfo.absoluteFilePath());
|
||||
if (!glfwPath.isEmpty() && glfwInfo.exists())
|
||||
list.append("-Dorg.lwjgl.glfw.libname=" + glfwInfo.absoluteFilePath());
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
@ -441,20 +517,28 @@ QStringList MinecraftInstance::javaArguments()
|
||||
|
||||
args << "-Duser.language=en";
|
||||
|
||||
if (javaVersion.isModular() && shouldApplyOnlineFixes())
|
||||
// allow reflective access to java.net - required by the skin fix
|
||||
args << "--add-opens"
|
||||
<< "java.base/java.net=ALL-UNNAMED";
|
||||
|
||||
return args;
|
||||
}
|
||||
|
||||
QString MinecraftInstance::getLauncher()
|
||||
{
|
||||
auto profile = m_components->getProfile();
|
||||
|
||||
// use legacy launcher if the traits are set
|
||||
if (profile->getTraits().contains("legacyLaunch") || profile->getTraits().contains("alphaLaunch"))
|
||||
if (traits().contains("legacyLaunch") || traits().contains("alphaLaunch"))
|
||||
return "legacy";
|
||||
|
||||
return "standard";
|
||||
}
|
||||
|
||||
bool MinecraftInstance::shouldApplyOnlineFixes()
|
||||
{
|
||||
return traits().contains("legacyServices") && settings()->get("OnlineFixes").toBool();
|
||||
}
|
||||
|
||||
QMap<QString, QString> MinecraftInstance::getVariables()
|
||||
{
|
||||
QMap<QString, QString> out;
|
||||
@ -651,6 +735,9 @@ QString MinecraftInstance::createLaunchScript(AuthSessionPtr session, MinecraftS
|
||||
launchScript += "traits " + trait + "\n";
|
||||
}
|
||||
|
||||
if (shouldApplyOnlineFixes())
|
||||
launchScript += "onlineFixes true\n";
|
||||
|
||||
launchScript += "launcher " + getLauncher() + "\n";
|
||||
|
||||
// qDebug() << "Generated launch script:" << launchScript;
|
||||
@ -791,9 +878,6 @@ QMap<QString, QString> MinecraftInstance::createCensorFilterFromSession(AuthSess
|
||||
if (sessionRef.access_token != "0") {
|
||||
addToFilter(sessionRef.access_token, tr("<ACCESS TOKEN>"));
|
||||
}
|
||||
if (sessionRef.client_token.size()) {
|
||||
addToFilter(sessionRef.client_token, tr("<CLIENT TOKEN>"));
|
||||
}
|
||||
addToFilter(sessionRef.uuid, tr("<PROFILE ID>"));
|
||||
|
||||
return filter;
|
||||
@ -875,13 +959,16 @@ QString MinecraftInstance::getStatusbarDescription()
|
||||
if (m_settings->get("ShowGameTime").toBool()) {
|
||||
if (lastTimePlayed() > 0) {
|
||||
QDateTime lastLaunchTime = QDateTime::fromMSecsSinceEpoch(lastLaunch());
|
||||
description.append(tr(", last played on %1 for %2")
|
||||
.arg(QLocale().toString(lastLaunchTime, QLocale::ShortFormat))
|
||||
.arg(Time::prettifyDuration(lastTimePlayed())));
|
||||
description.append(
|
||||
tr(", last played on %1 for %2")
|
||||
.arg(QLocale().toString(lastLaunchTime, QLocale::ShortFormat))
|
||||
.arg(Time::prettifyDuration(lastTimePlayed(), APPLICATION->settings()->get("ShowGameTimeWithoutDays").toBool())));
|
||||
}
|
||||
|
||||
if (totalTimePlayed() > 0) {
|
||||
description.append(tr(", total played for %1").arg(Time::prettifyDuration(totalTimePlayed())));
|
||||
description.append(
|
||||
tr(", total played for %1")
|
||||
.arg(Time::prettifyDuration(totalTimePlayed(), APPLICATION->settings()->get("ShowGameTimeWithoutDays").toBool())));
|
||||
}
|
||||
}
|
||||
if (hasCrashed()) {
|
||||
|
@ -2,7 +2,7 @@
|
||||
/*
|
||||
* Prism Launcher - Minecraft Launcher
|
||||
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
|
||||
* Copyright (C) 2022 TheKodeToad <TheKodeToad@proton.me>
|
||||
* Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me>
|
||||
*
|
||||
* 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
|
||||
@ -70,6 +70,8 @@ class MinecraftInstance : public BaseInstance {
|
||||
|
||||
bool canExport() const override { return true; }
|
||||
|
||||
void populateLaunchMenu(QMenu* menu) override;
|
||||
|
||||
////// Directories and files //////
|
||||
QString jarModsDir() const;
|
||||
QString resourcePacksDir() const;
|
||||
@ -127,6 +129,7 @@ class MinecraftInstance : public BaseInstance {
|
||||
/// get arguments passed to java
|
||||
QStringList javaArguments();
|
||||
QString getLauncher();
|
||||
bool shouldApplyOnlineFixes();
|
||||
|
||||
/// get variables for launch command variable substitution/environment
|
||||
QMap<QString, QString> getVariables() override;
|
||||
|
@ -19,8 +19,8 @@ struct MojangDownloadInfo {
|
||||
};
|
||||
|
||||
struct MojangLibraryDownloadInfo {
|
||||
MojangLibraryDownloadInfo(MojangDownloadInfo::Ptr artifact) : artifact(artifact){};
|
||||
MojangLibraryDownloadInfo(){};
|
||||
MojangLibraryDownloadInfo(MojangDownloadInfo::Ptr artifact_) : artifact(artifact_) {}
|
||||
MojangLibraryDownloadInfo() {}
|
||||
|
||||
// types
|
||||
typedef std::shared_ptr<MojangLibraryDownloadInfo> Ptr;
|
||||
@ -47,18 +47,18 @@ struct MojangAssetIndexInfo : public MojangDownloadInfo {
|
||||
// methods
|
||||
MojangAssetIndexInfo() {}
|
||||
|
||||
MojangAssetIndexInfo(QString id)
|
||||
MojangAssetIndexInfo(QString id_)
|
||||
{
|
||||
this->id = id;
|
||||
this->id = id_;
|
||||
// HACK: ignore assets from other version files than Minecraft
|
||||
// workaround for stupid assets issue caused by amazon:
|
||||
// https://www.theregister.co.uk/2017/02/28/aws_is_awol_as_s3_goes_haywire/
|
||||
if (id == "legacy") {
|
||||
if (id_ == "legacy") {
|
||||
url = "https://piston-meta.mojang.com/mc/assets/legacy/c0fd82e8ce9fbc93119e40d96d5a4e62cfa3f729/legacy.json";
|
||||
}
|
||||
// HACK
|
||||
else {
|
||||
url = "https://s3.amazonaws.com/Minecraft.Download/indexes/" + id + ".json";
|
||||
url = "https://s3.amazonaws.com/Minecraft.Download/indexes/" + id_ + ".json";
|
||||
}
|
||||
known = false;
|
||||
}
|
||||
|
@ -350,7 +350,7 @@ QJsonDocument OneSixVersionFormat::versionFileToJson(const VersionFilePtr& patch
|
||||
}
|
||||
}
|
||||
|
||||
LibraryPtr OneSixVersionFormat::plusJarModFromJson(ProblemContainer& problems,
|
||||
LibraryPtr OneSixVersionFormat::plusJarModFromJson([[maybe_unused]] ProblemContainer& problems,
|
||||
const QJsonObject& libObj,
|
||||
const QString& filename,
|
||||
const QString& originalName)
|
||||
|
@ -58,14 +58,14 @@
|
||||
#include "ComponentUpdateTask.h"
|
||||
#include "PackProfile.h"
|
||||
#include "PackProfile_p.h"
|
||||
#include "minecraft/mod/Mod.h"
|
||||
#include "modplatform/ModIndex.h"
|
||||
|
||||
#include "Application.h"
|
||||
#include "modplatform/ResourceAPI.h"
|
||||
|
||||
static const QMap<QString, ResourceAPI::ModLoaderType> modloaderMapping{ { "net.minecraftforge", ResourceAPI::Forge },
|
||||
{ "net.fabricmc.fabric-loader", ResourceAPI::Fabric },
|
||||
{ "org.quiltmc.quilt-loader", ResourceAPI::Quilt },
|
||||
{ "com.mumfrey.liteloader", ResourceAPI::LiteLoader } };
|
||||
static const QMap<QString, ModPlatform::ModLoaderType> modloaderMapping{ { "net.neoforged", ModPlatform::NeoForge },
|
||||
{ "net.minecraftforge", ModPlatform::Forge },
|
||||
{ "net.fabricmc.fabric-loader", ModPlatform::Fabric },
|
||||
{ "org.quiltmc.quilt-loader", ModPlatform::Quilt },
|
||||
{ "com.mumfrey.liteloader", ModPlatform::LiteLoader } };
|
||||
|
||||
PackProfile::PackProfile(MinecraftInstance* instance) : QAbstractListModel()
|
||||
{
|
||||
@ -204,10 +204,10 @@ static bool loadPackProfile(PackProfile* parent,
|
||||
}
|
||||
auto orderArray = Json::requireArray(obj.value("components"));
|
||||
for (auto item : orderArray) {
|
||||
auto obj = Json::requireObject(item, "Component must be an object.");
|
||||
container.append(componentFromJsonV1(parent, componentJsonPattern, obj));
|
||||
auto comp_obj = Json::requireObject(item, "Component must be an object.");
|
||||
container.append(componentFromJsonV1(parent, componentJsonPattern, comp_obj));
|
||||
}
|
||||
} catch (const JSONValidationError& err) {
|
||||
} catch ([[maybe_unused]] const JSONValidationError& err) {
|
||||
qCritical() << "Couldn't parse" << componentsFile.fileName() << ": bad file format";
|
||||
container.clear();
|
||||
return false;
|
||||
@ -377,7 +377,7 @@ void PackProfile::insertComponent(size_t index, ComponentPtr component)
|
||||
qWarning() << "Attempt to add a component that is already present!";
|
||||
return;
|
||||
}
|
||||
beginInsertRows(QModelIndex(), index, index);
|
||||
beginInsertRows(QModelIndex(), static_cast<int>(index), static_cast<int>(index));
|
||||
d->components.insert(index, component);
|
||||
d->componentIndex[id] = component;
|
||||
endInsertRows();
|
||||
@ -389,7 +389,7 @@ void PackProfile::componentDataChanged()
|
||||
{
|
||||
auto objPtr = qobject_cast<Component*>(sender());
|
||||
if (!objPtr) {
|
||||
qWarning() << "PackProfile got dataChenged signal from a non-Component!";
|
||||
qWarning() << "PackProfile got dataChanged signal from a non-Component!";
|
||||
return;
|
||||
}
|
||||
if (objPtr->getID() == "net.minecraft") {
|
||||
@ -405,7 +405,7 @@ void PackProfile::componentDataChanged()
|
||||
}
|
||||
index++;
|
||||
}
|
||||
qWarning() << "PackProfile got dataChenged signal from a Component which does not belong to it!";
|
||||
qWarning() << "PackProfile got dataChanged signal from a Component which does not belong to it!";
|
||||
}
|
||||
|
||||
bool PackProfile::remove(const int index)
|
||||
@ -483,9 +483,9 @@ ComponentPtr PackProfile::getComponent(const QString& id)
|
||||
return (*iter);
|
||||
}
|
||||
|
||||
ComponentPtr PackProfile::getComponent(int index)
|
||||
ComponentPtr PackProfile::getComponent(size_t index)
|
||||
{
|
||||
if (index < 0 || index >= d->components.size()) {
|
||||
if (index >= static_cast<size_t>(d->components.size())) {
|
||||
return nullptr;
|
||||
}
|
||||
return d->components[index];
|
||||
@ -547,7 +547,7 @@ QVariant PackProfile::data(const QModelIndex& index, int role) const
|
||||
return QVariant();
|
||||
}
|
||||
|
||||
bool PackProfile::setData(const QModelIndex& index, const QVariant& value, int role)
|
||||
bool PackProfile::setData(const QModelIndex& index, [[maybe_unused]] const QVariant& value, int role)
|
||||
{
|
||||
if (!index.isValid() || index.row() < 0 || index.row() >= rowCount(index.parent())) {
|
||||
return false;
|
||||
@ -989,12 +989,12 @@ void PackProfile::disableInteraction(bool disable)
|
||||
}
|
||||
}
|
||||
|
||||
std::optional<ResourceAPI::ModLoaderTypes> PackProfile::getModLoaders()
|
||||
std::optional<ModPlatform::ModLoaderTypes> PackProfile::getModLoaders()
|
||||
{
|
||||
ResourceAPI::ModLoaderTypes result;
|
||||
ModPlatform::ModLoaderTypes result;
|
||||
bool has_any_loader = false;
|
||||
|
||||
QMapIterator<QString, ResourceAPI::ModLoaderType> i(modloaderMapping);
|
||||
QMapIterator<QString, ModPlatform::ModLoaderType> i(modloaderMapping);
|
||||
|
||||
while (i.hasNext()) {
|
||||
i.next();
|
||||
@ -1008,3 +1008,17 @@ std::optional<ResourceAPI::ModLoaderTypes> PackProfile::getModLoaders()
|
||||
return {};
|
||||
return result;
|
||||
}
|
||||
|
||||
std::optional<ModPlatform::ModLoaderTypes> PackProfile::getSupportedModLoaders()
|
||||
{
|
||||
auto loadersOpt = getModLoaders();
|
||||
if (!loadersOpt.has_value())
|
||||
return loadersOpt;
|
||||
auto loaders = loadersOpt.value();
|
||||
// TODO: remove this or add version condition once Quilt drops official Fabric support
|
||||
if (loaders & ModPlatform::Quilt)
|
||||
loaders |= ModPlatform::Fabric;
|
||||
if (getComponentVersion("net.minecraft") == "1.20.1" && (loaders & ModPlatform::NeoForge))
|
||||
loaders |= ModPlatform::Forge;
|
||||
return loaders;
|
||||
}
|
||||
|
@ -44,14 +44,11 @@
|
||||
#include <QList>
|
||||
#include <QString>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
|
||||
#include "BaseVersion.h"
|
||||
#include "Component.h"
|
||||
#include "LaunchProfile.h"
|
||||
#include "Library.h"
|
||||
#include "MojangDownloadInfo.h"
|
||||
#include "ProfileUtils.h"
|
||||
#include "modplatform/ResourceAPI.h"
|
||||
#include "modplatform/ModIndex.h"
|
||||
#include "net/Mode.h"
|
||||
|
||||
class MinecraftInstance;
|
||||
@ -140,13 +137,15 @@ class PackProfile : public QAbstractListModel {
|
||||
ComponentPtr getComponent(const QString& id);
|
||||
|
||||
/// get the profile component by index
|
||||
ComponentPtr getComponent(int index);
|
||||
ComponentPtr getComponent(size_t index);
|
||||
|
||||
/// Add the component to the internal list of patches
|
||||
// todo(merged): is this the best approach
|
||||
void appendComponent(ComponentPtr component);
|
||||
|
||||
std::optional<ResourceAPI::ModLoaderTypes> getModLoaders();
|
||||
std::optional<ModPlatform::ModLoaderTypes> getModLoaders();
|
||||
// this returns aditional loaders(Quilt supports fabric and NeoForge supports Forge)
|
||||
std::optional<ModPlatform::ModLoaderTypes> getSupportedModLoaders();
|
||||
|
||||
private:
|
||||
void scheduleSave();
|
||||
|
@ -82,7 +82,7 @@ bool readOverrideOrders(QString path, PatchOrder& order)
|
||||
for (auto item : orderArray) {
|
||||
order.append(Json::requireString(item));
|
||||
}
|
||||
} catch (const JSONValidationError& err) {
|
||||
} catch ([[maybe_unused]] const JSONValidationError& err) {
|
||||
qCritical() << "Couldn't parse" << orderFile.fileName() << ": bad file format";
|
||||
qWarning() << "Ignoring overriden order";
|
||||
order.clear();
|
||||
|
@ -55,7 +55,7 @@ class Rule {
|
||||
|
||||
public:
|
||||
Rule(RuleAction result) : m_result(result) {}
|
||||
virtual ~Rule(){};
|
||||
virtual ~Rule() {}
|
||||
virtual QJsonObject toJson() = 0;
|
||||
RuleAction apply(const Library* parent, const RuntimeContext& runtimeContext)
|
||||
{
|
||||
|
@ -368,11 +368,11 @@ optional<QString> read_string(nbt::value& parent, const char* name)
|
||||
}
|
||||
auto& tag_str = namedValue.as<nbt::tag_string>();
|
||||
return QString::fromStdString(tag_str.get());
|
||||
} catch (const std::out_of_range& e) {
|
||||
} catch ([[maybe_unused]] const std::out_of_range& e) {
|
||||
// fallback for old world formats
|
||||
qWarning() << "String NBT tag" << name << "could not be found.";
|
||||
return nullopt;
|
||||
} catch (const std::bad_cast& e) {
|
||||
} catch ([[maybe_unused]] const std::bad_cast& e) {
|
||||
// type mismatch
|
||||
qWarning() << "NBT tag" << name << "could not be converted to string.";
|
||||
return nullopt;
|
||||
@ -388,11 +388,11 @@ optional<int64_t> read_long(nbt::value& parent, const char* name)
|
||||
}
|
||||
auto& tag_str = namedValue.as<nbt::tag_long>();
|
||||
return tag_str.get();
|
||||
} catch (const std::out_of_range& e) {
|
||||
} catch ([[maybe_unused]] const std::out_of_range& e) {
|
||||
// fallback for old world formats
|
||||
qWarning() << "Long NBT tag" << name << "could not be found.";
|
||||
return nullopt;
|
||||
} catch (const std::bad_cast& e) {
|
||||
} catch ([[maybe_unused]] const std::bad_cast& e) {
|
||||
// type mismatch
|
||||
qWarning() << "NBT tag" << name << "could not be converted to long.";
|
||||
return nullopt;
|
||||
@ -408,11 +408,11 @@ optional<int> read_int(nbt::value& parent, const char* name)
|
||||
}
|
||||
auto& tag_str = namedValue.as<nbt::tag_int>();
|
||||
return tag_str.get();
|
||||
} catch (const std::out_of_range& e) {
|
||||
} catch ([[maybe_unused]] const std::out_of_range& e) {
|
||||
// fallback for old world formats
|
||||
qWarning() << "Int NBT tag" << name << "could not be found.";
|
||||
return nullopt;
|
||||
} catch (const std::bad_cast& e) {
|
||||
} catch ([[maybe_unused]] const std::bad_cast& e) {
|
||||
// type mismatch
|
||||
qWarning() << "NBT tag" << name << "could not be converted to int.";
|
||||
return nullopt;
|
||||
|
@ -255,7 +255,7 @@ QVariant WorldList::data(const QModelIndex& index, int role) const
|
||||
}
|
||||
}
|
||||
|
||||
QVariant WorldList::headerData(int section, Qt::Orientation orientation, int role) const
|
||||
QVariant WorldList::headerData(int section, [[maybe_unused]] Qt::Orientation orientation, int role) const
|
||||
{
|
||||
switch (role) {
|
||||
case Qt::DisplayRole:
|
||||
@ -294,7 +294,6 @@ QVariant WorldList::headerData(int section, Qt::Orientation orientation, int rol
|
||||
default:
|
||||
return QVariant();
|
||||
}
|
||||
return QVariant();
|
||||
}
|
||||
|
||||
QStringList WorldList::mimeTypes() const
|
||||
@ -339,19 +338,19 @@ QMimeData* WorldList::mimeData(const QModelIndexList& indexes) const
|
||||
if (indexes.size() == 0)
|
||||
return new QMimeData();
|
||||
|
||||
QList<World> worlds;
|
||||
QList<World> worlds_;
|
||||
for (auto idx : indexes) {
|
||||
if (idx.column() != 0)
|
||||
continue;
|
||||
int row = idx.row();
|
||||
if (row < 0 || row >= this->worlds.size())
|
||||
continue;
|
||||
worlds.append(this->worlds[row]);
|
||||
worlds_.append(this->worlds[row]);
|
||||
}
|
||||
if (!worlds.size()) {
|
||||
if (!worlds_.size()) {
|
||||
return new QMimeData();
|
||||
}
|
||||
return new WorldMimeData(worlds);
|
||||
return new WorldMimeData(worlds_);
|
||||
}
|
||||
|
||||
Qt::ItemFlags WorldList::flags(const QModelIndex& index) const
|
||||
|
@ -278,67 +278,6 @@ bool entitlementFromJSONV3(const QJsonObject& parent, MinecraftEntitlement& out)
|
||||
|
||||
} // namespace
|
||||
|
||||
bool AccountData::resumeStateFromV2(QJsonObject data)
|
||||
{
|
||||
// The JSON object must at least have a username for it to be valid.
|
||||
if (!data.value("username").isString()) {
|
||||
qCritical() << "Can't load Mojang account info from JSON object. Username field is missing or of the wrong type.";
|
||||
return false;
|
||||
}
|
||||
|
||||
QString userName = data.value("username").toString("");
|
||||
QString clientToken = data.value("clientToken").toString("");
|
||||
QString accessToken = data.value("accessToken").toString("");
|
||||
|
||||
QJsonArray profileArray = data.value("profiles").toArray();
|
||||
if (profileArray.size() < 1) {
|
||||
qCritical() << "Can't load Mojang account with username \"" << userName << "\". No profiles found.";
|
||||
return false;
|
||||
}
|
||||
|
||||
struct AccountProfile {
|
||||
QString id;
|
||||
QString name;
|
||||
bool legacy;
|
||||
};
|
||||
|
||||
QList<AccountProfile> profiles;
|
||||
int currentProfileIndex = 0;
|
||||
int index = -1;
|
||||
QString currentProfile = data.value("activeProfile").toString("");
|
||||
for (QJsonValue profileVal : profileArray) {
|
||||
index++;
|
||||
QJsonObject profileObject = profileVal.toObject();
|
||||
QString id = profileObject.value("id").toString("");
|
||||
QString name = profileObject.value("name").toString("");
|
||||
bool legacy = profileObject.value("legacy").toBool(false);
|
||||
if (id.isEmpty() || name.isEmpty()) {
|
||||
qWarning() << "Unable to load a profile" << name << "because it was missing an ID or a name.";
|
||||
continue;
|
||||
}
|
||||
if (id == currentProfile) {
|
||||
currentProfileIndex = index;
|
||||
}
|
||||
profiles.append({ id, name, legacy });
|
||||
}
|
||||
auto& profile = profiles[currentProfileIndex];
|
||||
|
||||
type = AccountType::Mojang;
|
||||
legacy = profile.legacy;
|
||||
|
||||
minecraftProfile.id = profile.id;
|
||||
minecraftProfile.name = profile.name;
|
||||
minecraftProfile.validity = Katabasis::Validity::Assumed;
|
||||
|
||||
yggdrasilToken.token = accessToken;
|
||||
yggdrasilToken.extra["clientToken"] = clientToken;
|
||||
yggdrasilToken.extra["userName"] = userName;
|
||||
yggdrasilToken.validity = Katabasis::Validity::Assumed;
|
||||
|
||||
validity_ = minecraftProfile.validity;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool AccountData::resumeStateFromV3(QJsonObject data)
|
||||
{
|
||||
auto typeV = data.value("type");
|
||||
@ -349,8 +288,6 @@ bool AccountData::resumeStateFromV3(QJsonObject data)
|
||||
auto typeS = typeV.toString();
|
||||
if (typeS == "MSA") {
|
||||
type = AccountType::MSA;
|
||||
} else if (typeS == "Mojang") {
|
||||
type = AccountType::Mojang;
|
||||
} else if (typeS == "Offline") {
|
||||
type = AccountType::Offline;
|
||||
} else {
|
||||
@ -358,11 +295,6 @@ bool AccountData::resumeStateFromV3(QJsonObject data)
|
||||
return false;
|
||||
}
|
||||
|
||||
if (type == AccountType::Mojang) {
|
||||
legacy = data.value("legacy").toBool(false);
|
||||
canMigrateToMSA = data.value("canMigrateToMSA").toBool(false);
|
||||
}
|
||||
|
||||
if (type == AccountType::MSA) {
|
||||
auto clientIDV = data.value("msa-client-id");
|
||||
if (clientIDV.isString()) {
|
||||
@ -395,15 +327,7 @@ bool AccountData::resumeStateFromV3(QJsonObject data)
|
||||
QJsonObject AccountData::saveState() const
|
||||
{
|
||||
QJsonObject output;
|
||||
if (type == AccountType::Mojang) {
|
||||
output["type"] = "Mojang";
|
||||
if (legacy) {
|
||||
output["legacy"] = true;
|
||||
}
|
||||
if (canMigrateToMSA) {
|
||||
output["canMigrateToMSA"] = true;
|
||||
}
|
||||
} else if (type == AccountType::MSA) {
|
||||
if (type == AccountType::MSA) {
|
||||
output["type"] = "MSA";
|
||||
output["msa-client-id"] = msaClientID;
|
||||
tokenToJSONV3(output, msaToken, "msa");
|
||||
@ -420,51 +344,11 @@ QJsonObject AccountData::saveState() const
|
||||
return output;
|
||||
}
|
||||
|
||||
QString AccountData::userName() const
|
||||
{
|
||||
if (type == AccountType::MSA) {
|
||||
return QString();
|
||||
}
|
||||
return yggdrasilToken.extra["userName"].toString();
|
||||
}
|
||||
|
||||
QString AccountData::accessToken() const
|
||||
{
|
||||
return yggdrasilToken.token;
|
||||
}
|
||||
|
||||
QString AccountData::clientToken() const
|
||||
{
|
||||
if (type != AccountType::Mojang) {
|
||||
return QString();
|
||||
}
|
||||
return yggdrasilToken.extra["clientToken"].toString();
|
||||
}
|
||||
|
||||
void AccountData::setClientToken(QString clientToken)
|
||||
{
|
||||
if (type != AccountType::Mojang) {
|
||||
return;
|
||||
}
|
||||
yggdrasilToken.extra["clientToken"] = clientToken;
|
||||
}
|
||||
|
||||
void AccountData::generateClientTokenIfMissing()
|
||||
{
|
||||
if (yggdrasilToken.extra.contains("clientToken")) {
|
||||
return;
|
||||
}
|
||||
invalidateClientToken();
|
||||
}
|
||||
|
||||
void AccountData::invalidateClientToken()
|
||||
{
|
||||
if (type != AccountType::Mojang) {
|
||||
return;
|
||||
}
|
||||
yggdrasilToken.extra["clientToken"] = QUuid::createUuid().toString().remove(QRegularExpression("[{-}]"));
|
||||
}
|
||||
|
||||
QString AccountData::profileId() const
|
||||
{
|
||||
return minecraftProfile.id;
|
||||
@ -482,9 +366,6 @@ QString AccountData::profileName() const
|
||||
QString AccountData::accountDisplayString() const
|
||||
{
|
||||
switch (type) {
|
||||
case AccountType::Mojang: {
|
||||
return userName();
|
||||
}
|
||||
case AccountType::Offline: {
|
||||
return QObject::tr("<Offline>");
|
||||
}
|
||||
|
@ -71,27 +71,17 @@ struct MinecraftProfile {
|
||||
Katabasis::Validity validity = Katabasis::Validity::None;
|
||||
};
|
||||
|
||||
enum class AccountType { MSA, Mojang, Offline };
|
||||
enum class AccountType { MSA, Offline };
|
||||
|
||||
enum class AccountState { Unchecked, Offline, Working, Online, Disabled, Errored, Expired, Gone };
|
||||
|
||||
struct AccountData {
|
||||
QJsonObject saveState() const;
|
||||
bool resumeStateFromV2(QJsonObject data);
|
||||
bool resumeStateFromV3(QJsonObject data);
|
||||
|
||||
//! userName for Mojang accounts, gamertag for MSA
|
||||
QString accountDisplayString() const;
|
||||
|
||||
//! Only valid for Mojang accounts. MSA does not preserve this information
|
||||
QString userName() const;
|
||||
|
||||
//! Only valid for Mojang accounts.
|
||||
QString clientToken() const;
|
||||
void setClientToken(QString clientToken);
|
||||
void invalidateClientToken();
|
||||
void generateClientTokenIfMissing();
|
||||
|
||||
//! Yggdrasil access token, as passed to the game.
|
||||
QString accessToken() const;
|
||||
|
||||
@ -101,8 +91,6 @@ struct AccountData {
|
||||
QString lastError() const;
|
||||
|
||||
AccountType type = AccountType::MSA;
|
||||
bool legacy = false;
|
||||
bool canMigrateToMSA = false;
|
||||
|
||||
QString msaClientID;
|
||||
Katabasis::Token msaToken;
|
||||
|
@ -54,7 +54,7 @@
|
||||
|
||||
#include <chrono>
|
||||
|
||||
enum AccountListVersion { MojangOnly = 2, MojangMSA = 3 };
|
||||
enum AccountListVersion { MojangMSA = 3 };
|
||||
|
||||
AccountList::AccountList(QObject* parent) : QAbstractListModel(parent)
|
||||
{
|
||||
@ -320,17 +320,6 @@ QVariant AccountList::data(const QModelIndex& index, int role) const
|
||||
}
|
||||
}
|
||||
|
||||
case MigrationColumn: {
|
||||
if (account->isMSA() || account->isOffline()) {
|
||||
return tr("N/A", "Can Migrate");
|
||||
}
|
||||
if (account->canMigrate()) {
|
||||
return tr("Yes", "Can Migrate");
|
||||
} else {
|
||||
return tr("No", "Can Migrate");
|
||||
}
|
||||
}
|
||||
|
||||
default:
|
||||
return QVariant();
|
||||
}
|
||||
@ -353,7 +342,7 @@ QVariant AccountList::data(const QModelIndex& index, int role) const
|
||||
}
|
||||
}
|
||||
|
||||
QVariant AccountList::headerData(int section, Qt::Orientation orientation, int role) const
|
||||
QVariant AccountList::headerData(int section, [[maybe_unused]] Qt::Orientation orientation, int role) const
|
||||
{
|
||||
switch (role) {
|
||||
case Qt::DisplayRole:
|
||||
@ -366,8 +355,6 @@ QVariant AccountList::headerData(int section, Qt::Orientation orientation, int r
|
||||
return tr("Type");
|
||||
case StatusColumn:
|
||||
return tr("Status");
|
||||
case MigrationColumn:
|
||||
return tr("Can Migrate?");
|
||||
default:
|
||||
return QVariant();
|
||||
}
|
||||
@ -379,11 +366,9 @@ QVariant AccountList::headerData(int section, Qt::Orientation orientation, int r
|
||||
case NameColumn:
|
||||
return tr("User name of the account.");
|
||||
case TypeColumn:
|
||||
return tr("Type of the account - Mojang or MSA.");
|
||||
return tr("Type of the account (MSA or Offline)");
|
||||
case StatusColumn:
|
||||
return tr("Current status of the account.");
|
||||
case MigrationColumn:
|
||||
return tr("Can this account migrate to a Microsoft account?");
|
||||
default:
|
||||
return QVariant();
|
||||
}
|
||||
@ -415,7 +400,7 @@ Qt::ItemFlags AccountList::flags(const QModelIndex& index) const
|
||||
|
||||
bool AccountList::setData(const QModelIndex& idx, const QVariant& value, int role)
|
||||
{
|
||||
if (idx.row() < 0 || idx.row() >= rowCount(idx) || !idx.isValid()) {
|
||||
if (idx.row() < 0 || idx.row() >= rowCount(idx.parent()) || !idx.isValid()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@ -423,7 +408,8 @@ bool AccountList::setData(const QModelIndex& idx, const QVariant& value, int rol
|
||||
if (value == Qt::Checked) {
|
||||
MinecraftAccountPtr account = at(idx.row());
|
||||
setDefaultAccount(account);
|
||||
}
|
||||
} else if (m_defaultAccount == at(idx.row()))
|
||||
setDefaultAccount(nullptr);
|
||||
}
|
||||
|
||||
emit dataChanged(idx, index(idx.row(), columnCount(QModelIndex()) - 1));
|
||||
@ -472,9 +458,6 @@ bool AccountList::loadList()
|
||||
// Make sure the format version matches.
|
||||
auto listVersion = root.value("formatVersion").toVariant().toInt();
|
||||
switch (listVersion) {
|
||||
case AccountListVersion::MojangOnly: {
|
||||
return loadV2(root);
|
||||
} break;
|
||||
case AccountListVersion::MojangMSA: {
|
||||
return loadV3(root);
|
||||
} break;
|
||||
@ -488,36 +471,6 @@ bool AccountList::loadList()
|
||||
}
|
||||
}
|
||||
|
||||
bool AccountList::loadV2(QJsonObject& root)
|
||||
{
|
||||
beginResetModel();
|
||||
auto defaultUserName = root.value("activeAccount").toString("");
|
||||
QJsonArray accounts = root.value("accounts").toArray();
|
||||
for (QJsonValue accountVal : accounts) {
|
||||
QJsonObject accountObj = accountVal.toObject();
|
||||
MinecraftAccountPtr account = MinecraftAccount::loadFromJsonV2(accountObj);
|
||||
if (account.get() != nullptr) {
|
||||
auto profileId = account->profileId();
|
||||
if (!profileId.size()) {
|
||||
continue;
|
||||
}
|
||||
if (findAccountByProfileId(profileId) != -1) {
|
||||
continue;
|
||||
}
|
||||
connect(account.get(), &MinecraftAccount::changed, this, &AccountList::accountChanged);
|
||||
connect(account.get(), &MinecraftAccount::activityChanged, this, &AccountList::accountActivityChanged);
|
||||
m_accounts.append(account);
|
||||
if (defaultUserName.size() && account->mojangUserName() == defaultUserName) {
|
||||
m_defaultAccount = account;
|
||||
}
|
||||
} else {
|
||||
qWarning() << "Failed to load an account.";
|
||||
}
|
||||
}
|
||||
endResetModel();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool AccountList::loadV3(QJsonObject& root)
|
||||
{
|
||||
beginResetModel();
|
||||
|
@ -55,7 +55,6 @@ class AccountList : public QAbstractListModel {
|
||||
// TODO: Add icon column.
|
||||
ProfileNameColumn = 0,
|
||||
NameColumn,
|
||||
MigrationColumn,
|
||||
TypeColumn,
|
||||
StatusColumn,
|
||||
|
||||
@ -97,7 +96,6 @@ class AccountList : public QAbstractListModel {
|
||||
void setListFilePath(QString path, bool autosave = false);
|
||||
|
||||
bool loadList();
|
||||
bool loadV2(QJsonObject& root);
|
||||
bool loadV3(QJsonObject& root);
|
||||
bool saveList();
|
||||
|
||||
|
@ -24,10 +24,6 @@ struct AuthSession {
|
||||
GoneOrMigrated
|
||||
} status = Undetermined;
|
||||
|
||||
// client token
|
||||
QString client_token;
|
||||
// account user name
|
||||
QString username;
|
||||
// combined session ID
|
||||
QString session;
|
||||
// volatile auth token
|
||||
|
@ -37,6 +37,7 @@
|
||||
|
||||
#include "MinecraftAccount.h"
|
||||
|
||||
#include <QColor>
|
||||
#include <QCryptographicHash>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
@ -50,7 +51,6 @@
|
||||
#include <QPainter>
|
||||
|
||||
#include "flows/MSA.h"
|
||||
#include "flows/Mojang.h"
|
||||
#include "flows/Offline.h"
|
||||
|
||||
MinecraftAccount::MinecraftAccount(QObject* parent) : QObject(parent)
|
||||
@ -58,15 +58,6 @@ MinecraftAccount::MinecraftAccount(QObject* parent) : QObject(parent)
|
||||
data.internalId = QUuid::createUuid().toString().remove(QRegularExpression("[{}-]"));
|
||||
}
|
||||
|
||||
MinecraftAccountPtr MinecraftAccount::loadFromJsonV2(const QJsonObject& json)
|
||||
{
|
||||
MinecraftAccountPtr account(new MinecraftAccount());
|
||||
if (account->data.resumeStateFromV2(json)) {
|
||||
return account;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
MinecraftAccountPtr MinecraftAccount::loadFromJsonV3(const QJsonObject& json)
|
||||
{
|
||||
MinecraftAccountPtr account(new MinecraftAccount());
|
||||
@ -76,15 +67,6 @@ MinecraftAccountPtr MinecraftAccount::loadFromJsonV3(const QJsonObject& json)
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
MinecraftAccountPtr MinecraftAccount::createFromUsername(const QString& username)
|
||||
{
|
||||
auto account = makeShared<MinecraftAccount>();
|
||||
account->data.type = AccountType::Mojang;
|
||||
account->data.yggdrasilToken.extra["userName"] = username;
|
||||
account->data.yggdrasilToken.extra["clientToken"] = QUuid::createUuid().toString().remove(QRegularExpression("[{}-]"));
|
||||
return account;
|
||||
}
|
||||
|
||||
MinecraftAccountPtr MinecraftAccount::createBlankMSA()
|
||||
{
|
||||
MinecraftAccountPtr account(new MinecraftAccount());
|
||||
@ -126,24 +108,17 @@ QPixmap MinecraftAccount::getFace() const
|
||||
return QPixmap();
|
||||
}
|
||||
QPixmap skin = QPixmap(8, 8);
|
||||
#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
|
||||
skin.fill(QColorConstants::Transparent);
|
||||
#else
|
||||
skin.fill(QColor(0, 0, 0, 0));
|
||||
#endif
|
||||
QPainter painter(&skin);
|
||||
painter.drawPixmap(0, 0, skinTexture.copy(8, 8, 8, 8));
|
||||
painter.drawPixmap(0, 0, skinTexture.copy(40, 8, 8, 8));
|
||||
return skin.scaled(64, 64, Qt::KeepAspectRatio);
|
||||
}
|
||||
|
||||
shared_qobject_ptr<AccountTask> MinecraftAccount::login(QString password)
|
||||
{
|
||||
Q_ASSERT(m_currentTask.get() == nullptr);
|
||||
|
||||
m_currentTask.reset(new MojangLogin(&data, password));
|
||||
connect(m_currentTask.get(), &Task::succeeded, this, &MinecraftAccount::authSucceeded);
|
||||
connect(m_currentTask.get(), &Task::failed, this, &MinecraftAccount::authFailed);
|
||||
connect(m_currentTask.get(), &Task::aborted, this, [this] { authFailed(tr("Aborted")); });
|
||||
emit activityChanged(true);
|
||||
return m_currentTask;
|
||||
}
|
||||
|
||||
shared_qobject_ptr<AccountTask> MinecraftAccount::loginMSA()
|
||||
{
|
||||
Q_ASSERT(m_currentTask.get() == nullptr);
|
||||
@ -176,10 +151,8 @@ shared_qobject_ptr<AccountTask> MinecraftAccount::refresh()
|
||||
|
||||
if (data.type == AccountType::MSA) {
|
||||
m_currentTask.reset(new MSASilent(&data));
|
||||
} else if (data.type == AccountType::Offline) {
|
||||
m_currentTask.reset(new OfflineRefresh(&data));
|
||||
} else {
|
||||
m_currentTask.reset(new MojangRefresh(&data));
|
||||
m_currentTask.reset(new OfflineRefresh(&data));
|
||||
}
|
||||
|
||||
connect(m_currentTask.get(), &Task::succeeded, this, &MinecraftAccount::authSucceeded);
|
||||
@ -290,13 +263,8 @@ void MinecraftAccount::fillSession(AuthSessionPtr session)
|
||||
}
|
||||
}
|
||||
|
||||
// the user name. you have to have an user name
|
||||
// FIXME: not with MSA
|
||||
session->username = data.userName();
|
||||
// volatile auth token
|
||||
session->access_token = data.accessToken();
|
||||
// the semi-permanent client token
|
||||
session->client_token = data.clientToken();
|
||||
// profile name
|
||||
session->player_name = data.profileName();
|
||||
// profile ID
|
||||
|
@ -85,13 +85,10 @@ class MinecraftAccount : public QObject, public Usable {
|
||||
//! Default constructor
|
||||
explicit MinecraftAccount(QObject* parent = 0);
|
||||
|
||||
static MinecraftAccountPtr createFromUsername(const QString& username);
|
||||
|
||||
static MinecraftAccountPtr createBlankMSA();
|
||||
|
||||
static MinecraftAccountPtr createOffline(const QString& username);
|
||||
|
||||
static MinecraftAccountPtr loadFromJsonV2(const QJsonObject& json);
|
||||
static MinecraftAccountPtr loadFromJsonV3(const QJsonObject& json);
|
||||
|
||||
static QUuid uuidFromUsername(QString username);
|
||||
@ -100,12 +97,6 @@ class MinecraftAccount : public QObject, public Usable {
|
||||
QJsonObject saveToJson() const;
|
||||
|
||||
public: /* manipulation */
|
||||
/**
|
||||
* Attempt to login. Empty password means we use the token.
|
||||
* If the attempt fails because we already are performing some task, it returns false.
|
||||
*/
|
||||
shared_qobject_ptr<AccountTask> login(QString password);
|
||||
|
||||
shared_qobject_ptr<AccountTask> loginMSA();
|
||||
|
||||
shared_qobject_ptr<AccountTask> loginOffline();
|
||||
@ -119,8 +110,6 @@ class MinecraftAccount : public QObject, public Usable {
|
||||
|
||||
QString accountDisplayString() const { return data.accountDisplayString(); }
|
||||
|
||||
QString mojangUserName() const { return data.userName(); }
|
||||
|
||||
QString accessToken() const { return data.accessToken(); }
|
||||
|
||||
QString profileId() const { return data.profileId(); }
|
||||
@ -129,8 +118,6 @@ class MinecraftAccount : public QObject, public Usable {
|
||||
|
||||
bool isActive() const;
|
||||
|
||||
bool canMigrate() const { return data.canMigrateToMSA; }
|
||||
|
||||
bool isMSA() const { return data.type == AccountType::MSA; }
|
||||
|
||||
bool isOffline() const { return data.type == AccountType::Offline; }
|
||||
@ -142,12 +129,6 @@ class MinecraftAccount : public QObject, public Usable {
|
||||
QString typeString() const
|
||||
{
|
||||
switch (data.type) {
|
||||
case AccountType::Mojang: {
|
||||
if (data.legacy) {
|
||||
return "legacy";
|
||||
}
|
||||
return "mojang";
|
||||
} break;
|
||||
case AccountType::MSA: {
|
||||
return "msa";
|
||||
} break;
|
||||
|
@ -113,16 +113,16 @@ bool parseXTokenResponse(QByteArray& data, Katabasis::Token& output, QString nam
|
||||
if (!item.isObject()) {
|
||||
continue;
|
||||
}
|
||||
auto obj = item.toObject();
|
||||
if (obj.contains("uhs")) {
|
||||
auto obj_ = item.toObject();
|
||||
if (obj_.contains("uhs")) {
|
||||
foundUHS = true;
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
// consume all 'display claims' ... whatever that means
|
||||
for (auto iter = obj.begin(); iter != obj.end(); iter++) {
|
||||
for (auto iter = obj_.begin(); iter != obj_.end(); iter++) {
|
||||
QString claim;
|
||||
if (!getString(obj.value(iter.key()), claim)) {
|
||||
if (!getString(obj_.value(iter.key()), claim)) {
|
||||
qWarning() << "display claim " << iter.key() << " is not a string...";
|
||||
return false;
|
||||
}
|
||||
|
@ -1,342 +0,0 @@
|
||||
/* 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 "Yggdrasil.h"
|
||||
#include "AccountData.h"
|
||||
|
||||
#include <QByteArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QNetworkReply>
|
||||
#include <QObject>
|
||||
#include <QString>
|
||||
|
||||
#include <QDebug>
|
||||
|
||||
#include "Application.h"
|
||||
|
||||
Yggdrasil::Yggdrasil(AccountData* data, QObject* parent) : AccountTask(data, parent)
|
||||
{
|
||||
changeState(AccountTaskState::STATE_CREATED);
|
||||
}
|
||||
|
||||
void Yggdrasil::sendRequest(QUrl endpoint, QByteArray content)
|
||||
{
|
||||
changeState(AccountTaskState::STATE_WORKING);
|
||||
|
||||
QNetworkRequest netRequest(endpoint);
|
||||
netRequest.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
|
||||
m_netReply = APPLICATION->network()->post(netRequest, content);
|
||||
connect(m_netReply, &QNetworkReply::finished, this, &Yggdrasil::processReply);
|
||||
connect(m_netReply, &QNetworkReply::uploadProgress, this, &Yggdrasil::refreshTimers);
|
||||
connect(m_netReply, &QNetworkReply::downloadProgress, this, &Yggdrasil::refreshTimers);
|
||||
connect(m_netReply, &QNetworkReply::sslErrors, this, &Yggdrasil::sslErrors);
|
||||
timeout_keeper.setSingleShot(true);
|
||||
timeout_keeper.start(timeout_max);
|
||||
counter.setSingleShot(false);
|
||||
counter.start(time_step);
|
||||
progress(0, timeout_max);
|
||||
connect(&timeout_keeper, &QTimer::timeout, this, &Yggdrasil::abortByTimeout);
|
||||
connect(&counter, &QTimer::timeout, this, &Yggdrasil::heartbeat);
|
||||
}
|
||||
|
||||
void Yggdrasil::executeTask() {}
|
||||
|
||||
void Yggdrasil::refresh()
|
||||
{
|
||||
start();
|
||||
/*
|
||||
* {
|
||||
* "clientToken": "client identifier"
|
||||
* "accessToken": "current access token to be refreshed"
|
||||
* "selectedProfile": // specifying this causes errors
|
||||
* {
|
||||
* "id": "profile ID"
|
||||
* "name": "profile name"
|
||||
* }
|
||||
* "requestUser": true/false // request the user structure
|
||||
* }
|
||||
*/
|
||||
QJsonObject req;
|
||||
req.insert("clientToken", m_data->clientToken());
|
||||
req.insert("accessToken", m_data->accessToken());
|
||||
/*
|
||||
{
|
||||
auto currentProfile = m_account->currentProfile();
|
||||
QJsonObject profile;
|
||||
profile.insert("id", currentProfile->id());
|
||||
profile.insert("name", currentProfile->name());
|
||||
req.insert("selectedProfile", profile);
|
||||
}
|
||||
*/
|
||||
req.insert("requestUser", false);
|
||||
QJsonDocument doc(req);
|
||||
|
||||
QUrl reqUrl("https://authserver.mojang.com/refresh");
|
||||
QByteArray requestData = doc.toJson();
|
||||
|
||||
sendRequest(reqUrl, requestData);
|
||||
}
|
||||
|
||||
void Yggdrasil::login(QString password)
|
||||
{
|
||||
start();
|
||||
/*
|
||||
* {
|
||||
* "agent": { // optional
|
||||
* "name": "Minecraft", // So far this is the only encountered value
|
||||
* "version": 1 // This number might be increased
|
||||
* // by the vanilla client in the future
|
||||
* },
|
||||
* "username": "mojang account name", // Can be an email address or player name for
|
||||
* // unmigrated accounts
|
||||
* "password": "mojang account password",
|
||||
* "clientToken": "client identifier", // optional
|
||||
* "requestUser": true/false // request the user structure
|
||||
* }
|
||||
*/
|
||||
QJsonObject req;
|
||||
|
||||
{
|
||||
QJsonObject agent;
|
||||
// C++ makes string literals void* for some stupid reason, so we have to tell it
|
||||
// QString... Thanks Obama.
|
||||
agent.insert("name", QString("Minecraft"));
|
||||
agent.insert("version", 1);
|
||||
req.insert("agent", agent);
|
||||
}
|
||||
|
||||
req.insert("username", m_data->userName());
|
||||
req.insert("password", password);
|
||||
req.insert("requestUser", false);
|
||||
|
||||
// If we already have a client token, give it to the server.
|
||||
// Otherwise, let the server give us one.
|
||||
|
||||
m_data->generateClientTokenIfMissing();
|
||||
req.insert("clientToken", m_data->clientToken());
|
||||
|
||||
QJsonDocument doc(req);
|
||||
|
||||
QUrl reqUrl("https://authserver.mojang.com/authenticate");
|
||||
QNetworkRequest netRequest(reqUrl);
|
||||
QByteArray requestData = doc.toJson();
|
||||
|
||||
sendRequest(reqUrl, requestData);
|
||||
}
|
||||
|
||||
void Yggdrasil::refreshTimers(qint64, qint64)
|
||||
{
|
||||
timeout_keeper.stop();
|
||||
timeout_keeper.start(timeout_max);
|
||||
progress(count = 0, timeout_max);
|
||||
}
|
||||
|
||||
void Yggdrasil::heartbeat()
|
||||
{
|
||||
count += time_step;
|
||||
progress(count, timeout_max);
|
||||
}
|
||||
|
||||
bool Yggdrasil::abort()
|
||||
{
|
||||
progress(timeout_max, timeout_max);
|
||||
// TODO: actually use this in a meaningful way
|
||||
m_aborted = Yggdrasil::BY_USER;
|
||||
m_netReply->abort();
|
||||
return true;
|
||||
}
|
||||
|
||||
void Yggdrasil::abortByTimeout()
|
||||
{
|
||||
progress(timeout_max, timeout_max);
|
||||
// TODO: actually use this in a meaningful way
|
||||
m_aborted = Yggdrasil::BY_TIMEOUT;
|
||||
m_netReply->abort();
|
||||
}
|
||||
|
||||
void Yggdrasil::sslErrors(QList<QSslError> errors)
|
||||
{
|
||||
int i = 1;
|
||||
for (auto error : errors) {
|
||||
qCritical() << "LOGIN SSL Error #" << i << " : " << error.errorString();
|
||||
auto cert = error.certificate();
|
||||
qCritical() << "Certificate in question:\n" << cert.toText();
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
void Yggdrasil::processResponse(QJsonObject responseData)
|
||||
{
|
||||
// Read the response data. We need to get the client token, access token, and the selected
|
||||
// profile.
|
||||
qDebug() << "Processing authentication response.";
|
||||
|
||||
// qDebug() << responseData;
|
||||
// If we already have a client token, make sure the one the server gave us matches our
|
||||
// existing one.
|
||||
QString clientToken = responseData.value("clientToken").toString("");
|
||||
if (clientToken.isEmpty()) {
|
||||
// Fail if the server gave us an empty client token
|
||||
changeState(AccountTaskState::STATE_FAILED_HARD, tr("Authentication server didn't send a client token."));
|
||||
return;
|
||||
}
|
||||
if (m_data->clientToken().isEmpty()) {
|
||||
m_data->setClientToken(clientToken);
|
||||
} else if (clientToken != m_data->clientToken()) {
|
||||
changeState(AccountTaskState::STATE_FAILED_HARD,
|
||||
tr("Authentication server attempted to change the client token. This isn't supported."));
|
||||
return;
|
||||
}
|
||||
|
||||
// Now, we set the access token.
|
||||
qDebug() << "Getting access token.";
|
||||
QString accessToken = responseData.value("accessToken").toString("");
|
||||
if (accessToken.isEmpty()) {
|
||||
// Fail if the server didn't give us an access token.
|
||||
changeState(AccountTaskState::STATE_FAILED_HARD, tr("Authentication server didn't send an access token."));
|
||||
return;
|
||||
}
|
||||
// Set the access token.
|
||||
m_data->yggdrasilToken.token = accessToken;
|
||||
m_data->yggdrasilToken.validity = Katabasis::Validity::Certain;
|
||||
m_data->yggdrasilToken.issueInstant = QDateTime::currentDateTimeUtc();
|
||||
|
||||
// Get UUID here since we need it for later
|
||||
auto profile = responseData.value("selectedProfile");
|
||||
if (!profile.isObject()) {
|
||||
changeState(AccountTaskState::STATE_FAILED_HARD, tr("Authentication server didn't send a selected profile."));
|
||||
return;
|
||||
}
|
||||
|
||||
auto profileObj = profile.toObject();
|
||||
for (auto i = profileObj.constBegin(); i != profileObj.constEnd(); ++i) {
|
||||
if (i.key() == "name" && i.value().isString()) {
|
||||
m_data->minecraftProfile.name = i->toString();
|
||||
} else if (i.key() == "id" && i.value().isString()) {
|
||||
m_data->minecraftProfile.id = i->toString();
|
||||
}
|
||||
}
|
||||
|
||||
if (m_data->minecraftProfile.id.isEmpty()) {
|
||||
changeState(AccountTaskState::STATE_FAILED_HARD, tr("Authentication server didn't send a UUID in selected profile."));
|
||||
return;
|
||||
}
|
||||
|
||||
// We've made it through the minefield of possible errors. Return true to indicate that
|
||||
// we've succeeded.
|
||||
qDebug() << "Finished reading authentication response.";
|
||||
changeState(AccountTaskState::STATE_SUCCEEDED);
|
||||
}
|
||||
|
||||
void Yggdrasil::processReply()
|
||||
{
|
||||
changeState(AccountTaskState::STATE_WORKING);
|
||||
|
||||
switch (m_netReply->error()) {
|
||||
case QNetworkReply::NoError:
|
||||
break;
|
||||
case QNetworkReply::TimeoutError:
|
||||
changeState(AccountTaskState::STATE_FAILED_SOFT, tr("Authentication operation timed out."));
|
||||
return;
|
||||
case QNetworkReply::OperationCanceledError:
|
||||
changeState(AccountTaskState::STATE_FAILED_SOFT, tr("Authentication operation cancelled."));
|
||||
return;
|
||||
case QNetworkReply::SslHandshakeFailedError:
|
||||
changeState(AccountTaskState::STATE_FAILED_SOFT,
|
||||
tr("<b>SSL Handshake failed.</b><br/>There might be a few causes for it:<br/>"
|
||||
"<ul>"
|
||||
"<li>You use Windows and need to update your root certificates, please install any outstanding updates.</li>"
|
||||
"<li>Some device on your network is interfering with SSL traffic. In that case, "
|
||||
"you have bigger worries than Minecraft not starting.</li>"
|
||||
"<li>Possibly something else. Check the log file for details</li>"
|
||||
"</ul>"));
|
||||
return;
|
||||
// used for invalid credentials and similar errors. Fall through.
|
||||
case QNetworkReply::ContentAccessDenied:
|
||||
case QNetworkReply::ContentOperationNotPermittedError:
|
||||
break;
|
||||
case QNetworkReply::ContentGoneError: {
|
||||
changeState(AccountTaskState::STATE_FAILED_GONE,
|
||||
tr("The Mojang account no longer exists. It may have been migrated to a Microsoft account."));
|
||||
return;
|
||||
}
|
||||
default:
|
||||
changeState(AccountTaskState::STATE_FAILED_SOFT, tr("Authentication operation failed due to a network error: %1 (%2)")
|
||||
.arg(m_netReply->errorString())
|
||||
.arg(m_netReply->error()));
|
||||
return;
|
||||
}
|
||||
|
||||
// Try to parse the response regardless of the response code.
|
||||
// Sometimes the auth server will give more information and an error code.
|
||||
QJsonParseError jsonError;
|
||||
QByteArray replyData = m_netReply->readAll();
|
||||
QJsonDocument doc = QJsonDocument::fromJson(replyData, &jsonError);
|
||||
// Check the response code.
|
||||
int responseCode = m_netReply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
|
||||
|
||||
if (responseCode == 200) {
|
||||
// If the response code was 200, then there shouldn't be an error. Make sure
|
||||
// anyways.
|
||||
// Also, sometimes an empty reply indicates success. If there was no data received,
|
||||
// pass an empty json object to the processResponse function.
|
||||
if (jsonError.error == QJsonParseError::NoError || replyData.size() == 0) {
|
||||
processResponse(replyData.size() > 0 ? doc.object() : QJsonObject());
|
||||
return;
|
||||
} else {
|
||||
changeState(AccountTaskState::STATE_FAILED_SOFT,
|
||||
tr("Failed to parse authentication server response JSON response: %1 at offset %2.")
|
||||
.arg(jsonError.errorString())
|
||||
.arg(jsonError.offset));
|
||||
qCritical() << replyData;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// If the response code was not 200, then Yggdrasil may have given us information
|
||||
// about the error.
|
||||
// If we can parse the response, then get information from it. Otherwise just say
|
||||
// there was an unknown error.
|
||||
if (jsonError.error == QJsonParseError::NoError) {
|
||||
// We were able to parse the server's response. Woo!
|
||||
// Call processError. If a subclass has overridden it then they'll handle their
|
||||
// stuff there.
|
||||
qDebug() << "The request failed, but the server gave us an error message. Processing error.";
|
||||
processError(doc.object());
|
||||
} else {
|
||||
// The server didn't say anything regarding the error. Give the user an unknown
|
||||
// error.
|
||||
qDebug() << "The request failed and the server gave no error message. Unknown error.";
|
||||
changeState(
|
||||
AccountTaskState::STATE_FAILED_SOFT,
|
||||
tr("An unknown error occurred when trying to communicate with the authentication server: %1").arg(m_netReply->errorString()));
|
||||
}
|
||||
}
|
||||
|
||||
void Yggdrasil::processError(QJsonObject responseData)
|
||||
{
|
||||
QJsonValue errorVal = responseData.value("error");
|
||||
QJsonValue errorMessageValue = responseData.value("errorMessage");
|
||||
QJsonValue causeVal = responseData.value("cause");
|
||||
|
||||
if (errorVal.isString() && errorMessageValue.isString()) {
|
||||
m_error = std::shared_ptr<Error>(new Error{ errorVal.toString(""), errorMessageValue.toString(""), causeVal.toString("") });
|
||||
changeState(AccountTaskState::STATE_FAILED_HARD, m_error->m_errorMessageVerbose);
|
||||
} else {
|
||||
// Error is not in standard format. Don't set m_error and return unknown error.
|
||||
changeState(AccountTaskState::STATE_FAILED_HARD, tr("An unknown Yggdrasil error occurred."));
|
||||
}
|
||||
}
|
@ -1,92 +0,0 @@
|
||||
/* Copyright 2013-2021 MultiMC Contributors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "AccountTask.h"
|
||||
|
||||
#include <qsslerror.h>
|
||||
#include <QJsonObject>
|
||||
#include <QString>
|
||||
#include <QTimer>
|
||||
|
||||
#include "MinecraftAccount.h"
|
||||
|
||||
class QNetworkAccessManager;
|
||||
class QNetworkReply;
|
||||
|
||||
/**
|
||||
* A Yggdrasil task is a task that performs an operation on a given mojang account.
|
||||
*/
|
||||
class Yggdrasil : public AccountTask {
|
||||
Q_OBJECT
|
||||
public:
|
||||
explicit Yggdrasil(AccountData* data, QObject* parent = 0);
|
||||
virtual ~Yggdrasil() = default;
|
||||
|
||||
void refresh();
|
||||
void login(QString password);
|
||||
|
||||
struct Error {
|
||||
QString m_errorMessageShort;
|
||||
QString m_errorMessageVerbose;
|
||||
QString m_cause;
|
||||
};
|
||||
std::shared_ptr<Error> m_error;
|
||||
|
||||
enum AbortedBy { BY_NOTHING, BY_USER, BY_TIMEOUT } m_aborted = BY_NOTHING;
|
||||
|
||||
protected:
|
||||
void executeTask() override;
|
||||
|
||||
/**
|
||||
* Processes the response received from the server.
|
||||
* If an error occurred, this should emit a failed signal.
|
||||
* If Yggdrasil gave an error response, it should call setError() first, and then return false.
|
||||
* Otherwise, it should return true.
|
||||
* Note: If the response from the server was blank, and the HTTP code was 200, this function is called with
|
||||
* an empty QJsonObject.
|
||||
*/
|
||||
void processResponse(QJsonObject responseData);
|
||||
|
||||
/**
|
||||
* Processes an error response received from the server.
|
||||
* The default implementation will read data from Yggdrasil's standard error response format and set it as this task's Error.
|
||||
* \returns a QString error message that will be passed to emitFailed.
|
||||
*/
|
||||
virtual void processError(QJsonObject responseData);
|
||||
|
||||
protected slots:
|
||||
void processReply();
|
||||
void refreshTimers(qint64, qint64);
|
||||
void heartbeat();
|
||||
void sslErrors(QList<QSslError>);
|
||||
void abortByTimeout();
|
||||
|
||||
public slots:
|
||||
virtual bool abort() override;
|
||||
|
||||
private:
|
||||
void sendRequest(QUrl endpoint, QByteArray content);
|
||||
|
||||
protected:
|
||||
QNetworkReply* m_netReply = nullptr;
|
||||
QTimer timeout_keeper;
|
||||
QTimer counter;
|
||||
int count = 0; // num msec since time reset
|
||||
|
||||
const int timeout_max = 30000;
|
||||
const int time_step = 50;
|
||||
};
|
@ -12,7 +12,6 @@
|
||||
#include "minecraft/auth/AccountData.h"
|
||||
#include "minecraft/auth/AccountTask.h"
|
||||
#include "minecraft/auth/AuthStep.h"
|
||||
#include "minecraft/auth/Yggdrasil.h"
|
||||
|
||||
class AuthFlow : public AccountTask {
|
||||
Q_OBJECT
|
||||
|
@ -1,22 +0,0 @@
|
||||
#include "Mojang.h"
|
||||
|
||||
#include "minecraft/auth/steps/GetSkinStep.h"
|
||||
#include "minecraft/auth/steps/MigrationEligibilityStep.h"
|
||||
#include "minecraft/auth/steps/MinecraftProfileStepMojang.h"
|
||||
#include "minecraft/auth/steps/YggdrasilStep.h"
|
||||
|
||||
MojangRefresh::MojangRefresh(AccountData* data, QObject* parent) : AuthFlow(data, parent)
|
||||
{
|
||||
m_steps.append(makeShared<YggdrasilStep>(m_data, QString()));
|
||||
m_steps.append(makeShared<MinecraftProfileStepMojang>(m_data));
|
||||
m_steps.append(makeShared<MigrationEligibilityStep>(m_data));
|
||||
m_steps.append(makeShared<GetSkinStep>(m_data));
|
||||
}
|
||||
|
||||
MojangLogin::MojangLogin(AccountData* data, QString password, QObject* parent) : AuthFlow(data, parent), m_password(password)
|
||||
{
|
||||
m_steps.append(makeShared<YggdrasilStep>(m_data, m_password));
|
||||
m_steps.append(makeShared<MinecraftProfileStepMojang>(m_data));
|
||||
m_steps.append(makeShared<MigrationEligibilityStep>(m_data));
|
||||
m_steps.append(makeShared<GetSkinStep>(m_data));
|
||||
}
|
@ -1,17 +0,0 @@
|
||||
#pragma once
|
||||
#include "AuthFlow.h"
|
||||
|
||||
class MojangRefresh : public AuthFlow {
|
||||
Q_OBJECT
|
||||
public:
|
||||
explicit MojangRefresh(AccountData* data, QObject* parent = 0);
|
||||
};
|
||||
|
||||
class MojangLogin : public AuthFlow {
|
||||
Q_OBJECT
|
||||
public:
|
||||
explicit MojangLogin(AccountData* data, QString password, QObject* parent = 0);
|
||||
|
||||
private:
|
||||
QString m_password;
|
||||
};
|
@ -36,7 +36,9 @@ void EntitlementsStep::rehydrate()
|
||||
// NOOP, for now. We only save bools and there's nothing to check.
|
||||
}
|
||||
|
||||
void EntitlementsStep::onRequestDone(QNetworkReply::NetworkError error, QByteArray data, QList<QNetworkReply::RawHeaderPair> headers)
|
||||
void EntitlementsStep::onRequestDone([[maybe_unused]] QNetworkReply::NetworkError error,
|
||||
QByteArray data,
|
||||
[[maybe_unused]] QList<QNetworkReply::RawHeaderPair> headers)
|
||||
{
|
||||
auto requestor = qobject_cast<AuthRequest*>(QObject::sender());
|
||||
requestor->deleteLater();
|
||||
|
@ -1,45 +0,0 @@
|
||||
#include "MigrationEligibilityStep.h"
|
||||
|
||||
#include <QNetworkRequest>
|
||||
|
||||
#include "minecraft/auth/AuthRequest.h"
|
||||
#include "minecraft/auth/Parsers.h"
|
||||
|
||||
MigrationEligibilityStep::MigrationEligibilityStep(AccountData* data) : AuthStep(data) {}
|
||||
|
||||
MigrationEligibilityStep::~MigrationEligibilityStep() noexcept = default;
|
||||
|
||||
QString MigrationEligibilityStep::describe()
|
||||
{
|
||||
return tr("Checking for migration eligibility.");
|
||||
}
|
||||
|
||||
void MigrationEligibilityStep::perform()
|
||||
{
|
||||
auto url = QUrl("https://api.minecraftservices.com/rollout/v1/msamigration");
|
||||
QNetworkRequest request = QNetworkRequest(url);
|
||||
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
|
||||
request.setRawHeader("Authorization", QString("Bearer %1").arg(m_data->yggdrasilToken.token).toUtf8());
|
||||
|
||||
AuthRequest* requestor = new AuthRequest(this);
|
||||
connect(requestor, &AuthRequest::finished, this, &MigrationEligibilityStep::onRequestDone);
|
||||
requestor->get(request);
|
||||
}
|
||||
|
||||
void MigrationEligibilityStep::rehydrate()
|
||||
{
|
||||
// NOOP, for now. We only save bools and there's nothing to check.
|
||||
}
|
||||
|
||||
void MigrationEligibilityStep::onRequestDone(QNetworkReply::NetworkError error,
|
||||
QByteArray data,
|
||||
QList<QNetworkReply::RawHeaderPair> headers)
|
||||
{
|
||||
auto requestor = qobject_cast<AuthRequest*>(QObject::sender());
|
||||
requestor->deleteLater();
|
||||
|
||||
if (error == QNetworkReply::NoError) {
|
||||
Parsers::parseRolloutResponse(data, m_data->canMigrateToMSA);
|
||||
}
|
||||
emit finished(AccountTaskState::STATE_WORKING, tr("Got migration flags"));
|
||||
}
|
@ -1,21 +0,0 @@
|
||||
#pragma once
|
||||
#include <QObject>
|
||||
|
||||
#include "QObjectPtr.h"
|
||||
#include "minecraft/auth/AuthStep.h"
|
||||
|
||||
class MigrationEligibilityStep : public AuthStep {
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit MigrationEligibilityStep(AccountData* data);
|
||||
virtual ~MigrationEligibilityStep() noexcept;
|
||||
|
||||
void perform() override;
|
||||
void rehydrate() override;
|
||||
|
||||
QString describe() override;
|
||||
|
||||
private slots:
|
||||
void onRequestDone(QNetworkReply::NetworkError, QByteArray, QList<QNetworkReply::RawHeaderPair>);
|
||||
};
|
@ -41,10 +41,6 @@ void MinecraftProfileStep::onRequestDone(QNetworkReply::NetworkError error, QByt
|
||||
qCDebug(authCredentials()) << data;
|
||||
if (error == QNetworkReply::ContentNotFoundError) {
|
||||
// NOTE: Succeed even if we do not have a profile. This is a valid account state.
|
||||
if (m_data->type == AccountType::Mojang) {
|
||||
m_data->minecraftEntitlement.canPlayMinecraft = false;
|
||||
m_data->minecraftEntitlement.ownsMinecraft = false;
|
||||
}
|
||||
m_data->minecraftProfile = MinecraftProfile();
|
||||
emit finished(AccountTaskState::STATE_SUCCEEDED, tr("Account has no Minecraft profile."));
|
||||
return;
|
||||
@ -73,10 +69,5 @@ void MinecraftProfileStep::onRequestDone(QNetworkReply::NetworkError error, QByt
|
||||
return;
|
||||
}
|
||||
|
||||
if (m_data->type == AccountType::Mojang) {
|
||||
auto validProfile = m_data->minecraftProfile.validity == Katabasis::Validity::Certain;
|
||||
m_data->minecraftEntitlement.canPlayMinecraft = validProfile;
|
||||
m_data->minecraftEntitlement.ownsMinecraft = validProfile;
|
||||
}
|
||||
emit finished(AccountTaskState::STATE_WORKING, tr("Minecraft Java profile acquisition succeeded."));
|
||||
}
|
||||
|
@ -1,87 +0,0 @@
|
||||
#include "MinecraftProfileStepMojang.h"
|
||||
|
||||
#include <QNetworkRequest>
|
||||
|
||||
#include "Logging.h"
|
||||
#include "minecraft/auth/AuthRequest.h"
|
||||
#include "minecraft/auth/Parsers.h"
|
||||
#include "net/NetUtils.h"
|
||||
|
||||
MinecraftProfileStepMojang::MinecraftProfileStepMojang(AccountData* data) : AuthStep(data) {}
|
||||
|
||||
MinecraftProfileStepMojang::~MinecraftProfileStepMojang() noexcept = default;
|
||||
|
||||
QString MinecraftProfileStepMojang::describe()
|
||||
{
|
||||
return tr("Fetching the Minecraft profile.");
|
||||
}
|
||||
|
||||
void MinecraftProfileStepMojang::perform()
|
||||
{
|
||||
if (m_data->minecraftProfile.id.isEmpty()) {
|
||||
emit finished(AccountTaskState::STATE_FAILED_HARD, tr("A UUID is required to get the profile."));
|
||||
return;
|
||||
}
|
||||
|
||||
// use session server instead of profile due to profile endpoint being locked for locked Mojang accounts
|
||||
QUrl url = QUrl("https://sessionserver.mojang.com/session/minecraft/profile/" + m_data->minecraftProfile.id);
|
||||
QNetworkRequest req = QNetworkRequest(url);
|
||||
AuthRequest* request = new AuthRequest(this);
|
||||
connect(request, &AuthRequest::finished, this, &MinecraftProfileStepMojang::onRequestDone);
|
||||
request->get(req);
|
||||
}
|
||||
|
||||
void MinecraftProfileStepMojang::rehydrate()
|
||||
{
|
||||
// NOOP, for now. We only save bools and there's nothing to check.
|
||||
}
|
||||
|
||||
void MinecraftProfileStepMojang::onRequestDone(QNetworkReply::NetworkError error,
|
||||
QByteArray data,
|
||||
QList<QNetworkReply::RawHeaderPair> headers)
|
||||
{
|
||||
auto requestor = qobject_cast<AuthRequest*>(QObject::sender());
|
||||
requestor->deleteLater();
|
||||
|
||||
qCDebug(authCredentials()) << data;
|
||||
if (error == QNetworkReply::ContentNotFoundError) {
|
||||
// NOTE: Succeed even if we do not have a profile. This is a valid account state.
|
||||
if (m_data->type == AccountType::Mojang) {
|
||||
m_data->minecraftEntitlement.canPlayMinecraft = false;
|
||||
m_data->minecraftEntitlement.ownsMinecraft = false;
|
||||
}
|
||||
m_data->minecraftProfile = MinecraftProfile();
|
||||
emit finished(AccountTaskState::STATE_SUCCEEDED, tr("Account has no Minecraft profile."));
|
||||
return;
|
||||
}
|
||||
if (error != QNetworkReply::NoError) {
|
||||
qWarning() << "Error getting profile:";
|
||||
qWarning() << " HTTP Status: " << requestor->httpStatus_;
|
||||
qWarning() << " Internal error no.: " << error;
|
||||
qWarning() << " Error string: " << requestor->errorString_;
|
||||
|
||||
qWarning() << " Response:";
|
||||
qWarning() << QString::fromUtf8(data);
|
||||
|
||||
if (Net::isApplicationError(error)) {
|
||||
emit finished(AccountTaskState::STATE_FAILED_SOFT,
|
||||
tr("Minecraft Java profile acquisition failed: %1").arg(requestor->errorString_));
|
||||
} else {
|
||||
emit finished(AccountTaskState::STATE_OFFLINE,
|
||||
tr("Minecraft Java profile acquisition failed: %1").arg(requestor->errorString_));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!Parsers::parseMinecraftProfileMojang(data, m_data->minecraftProfile)) {
|
||||
m_data->minecraftProfile = MinecraftProfile();
|
||||
emit finished(AccountTaskState::STATE_FAILED_SOFT, tr("Minecraft Java profile response could not be parsed"));
|
||||
return;
|
||||
}
|
||||
|
||||
if (m_data->type == AccountType::Mojang) {
|
||||
auto validProfile = m_data->minecraftProfile.validity == Katabasis::Validity::Certain;
|
||||
m_data->minecraftEntitlement.canPlayMinecraft = validProfile;
|
||||
m_data->minecraftEntitlement.ownsMinecraft = validProfile;
|
||||
}
|
||||
emit finished(AccountTaskState::STATE_WORKING, tr("Minecraft Java profile acquisition succeeded."));
|
||||
}
|
@ -1,21 +0,0 @@
|
||||
#pragma once
|
||||
#include <QObject>
|
||||
|
||||
#include "QObjectPtr.h"
|
||||
#include "minecraft/auth/AuthStep.h"
|
||||
|
||||
class MinecraftProfileStepMojang : public AuthStep {
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit MinecraftProfileStepMojang(AccountData* data);
|
||||
virtual ~MinecraftProfileStepMojang() noexcept;
|
||||
|
||||
void perform() override;
|
||||
void rehydrate() override;
|
||||
|
||||
QString describe() override;
|
||||
|
||||
private slots:
|
||||
void onRequestDone(QNetworkReply::NetworkError, QByteArray, QList<QNetworkReply::RawHeaderPair>);
|
||||
};
|
@ -38,7 +38,7 @@ void XboxUserStep::perform()
|
||||
QNetworkRequest request = QNetworkRequest(QUrl("https://user.auth.xboxlive.com/user/authenticate"));
|
||||
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
|
||||
request.setRawHeader("Accept", "application/json");
|
||||
// set contract-verison header (prevent err 400 bad-request?)
|
||||
// set contract-version header (prevent err 400 bad-request?)
|
||||
// https://learn.microsoft.com/en-us/gaming/gdk/_content/gc/reference/live/rest/additional/httpstandardheaders
|
||||
request.setRawHeader("x-xbl-contract-version", "1");
|
||||
|
||||
|
@ -1,57 +0,0 @@
|
||||
#include "YggdrasilStep.h"
|
||||
|
||||
#include "minecraft/auth/AuthRequest.h"
|
||||
#include "minecraft/auth/Parsers.h"
|
||||
#include "minecraft/auth/Yggdrasil.h"
|
||||
|
||||
YggdrasilStep::YggdrasilStep(AccountData* data, QString password) : AuthStep(data), m_password(password)
|
||||
{
|
||||
m_yggdrasil = new Yggdrasil(m_data, this);
|
||||
|
||||
connect(m_yggdrasil, &Task::failed, this, &YggdrasilStep::onAuthFailed);
|
||||
connect(m_yggdrasil, &Task::succeeded, this, &YggdrasilStep::onAuthSucceeded);
|
||||
connect(m_yggdrasil, &Task::aborted, this, &YggdrasilStep::onAuthFailed);
|
||||
}
|
||||
|
||||
YggdrasilStep::~YggdrasilStep() noexcept = default;
|
||||
|
||||
QString YggdrasilStep::describe()
|
||||
{
|
||||
return tr("Logging in with Mojang account.");
|
||||
}
|
||||
|
||||
void YggdrasilStep::rehydrate()
|
||||
{
|
||||
// NOOP, for now.
|
||||
}
|
||||
|
||||
void YggdrasilStep::perform()
|
||||
{
|
||||
if (m_password.size()) {
|
||||
m_yggdrasil->login(m_password);
|
||||
} else {
|
||||
m_yggdrasil->refresh();
|
||||
}
|
||||
}
|
||||
|
||||
void YggdrasilStep::onAuthSucceeded()
|
||||
{
|
||||
emit finished(AccountTaskState::STATE_WORKING, tr("Logged in with Mojang"));
|
||||
}
|
||||
|
||||
void YggdrasilStep::onAuthFailed()
|
||||
{
|
||||
// TODO: hook these in again, expand to MSA
|
||||
// m_error = m_yggdrasil->m_error;
|
||||
// m_aborted = m_yggdrasil->m_aborted;
|
||||
|
||||
auto state = m_yggdrasil->taskState();
|
||||
QString errorMessage = tr("Mojang user authentication failed.");
|
||||
|
||||
// NOTE: soft error in the first step means 'offline'
|
||||
if (state == AccountTaskState::STATE_FAILED_SOFT) {
|
||||
state = AccountTaskState::STATE_OFFLINE;
|
||||
errorMessage = tr("Mojang user authentication ended with a network error.");
|
||||
}
|
||||
emit finished(state, errorMessage);
|
||||
}
|
@ -1,28 +0,0 @@
|
||||
#pragma once
|
||||
#include <QObject>
|
||||
|
||||
#include "QObjectPtr.h"
|
||||
#include "minecraft/auth/AuthStep.h"
|
||||
|
||||
class Yggdrasil;
|
||||
|
||||
class YggdrasilStep : public AuthStep {
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit YggdrasilStep(AccountData* data, QString password);
|
||||
virtual ~YggdrasilStep() noexcept;
|
||||
|
||||
void perform() override;
|
||||
void rehydrate() override;
|
||||
|
||||
QString describe() override;
|
||||
|
||||
private slots:
|
||||
void onAuthSucceeded();
|
||||
void onAuthFailed();
|
||||
|
||||
private:
|
||||
Yggdrasil* m_yggdrasil = nullptr;
|
||||
QString m_password;
|
||||
};
|
@ -97,12 +97,11 @@ QVariant GameOptions::data(const QModelIndex& index, int role) const
|
||||
default:
|
||||
return QVariant();
|
||||
}
|
||||
return QVariant();
|
||||
}
|
||||
|
||||
int GameOptions::rowCount(const QModelIndex&) const
|
||||
{
|
||||
return contents.size();
|
||||
return static_cast<int>(contents.size());
|
||||
}
|
||||
|
||||
int GameOptions::columnCount(const QModelIndex&) const
|
||||
|
@ -39,7 +39,7 @@ static QString replaceSuffix(QString target, const QString& suffix, const QStrin
|
||||
return target + replacement;
|
||||
}
|
||||
|
||||
static bool unzipNatives(QString source, QString targetFolder, bool applyJnilibHack, bool nativeOpenAL, bool nativeGLFW)
|
||||
static bool unzipNatives(QString source, QString targetFolder, bool applyJnilibHack)
|
||||
{
|
||||
QuaZip zip(source);
|
||||
if (!zip.open(QuaZip::mdUnzip)) {
|
||||
@ -52,12 +52,6 @@ static bool unzipNatives(QString source, QString targetFolder, bool applyJnilibH
|
||||
do {
|
||||
QString name = zip.getCurrentFileName();
|
||||
auto lowercase = name.toLower();
|
||||
if (nativeGLFW && name.contains("glfw")) {
|
||||
continue;
|
||||
}
|
||||
if (nativeOpenAL && name.contains("openal")) {
|
||||
continue;
|
||||
}
|
||||
if (applyJnilibHack) {
|
||||
name = replaceSuffix(name, ".jnilib", ".dylib");
|
||||
}
|
||||
@ -83,14 +77,12 @@ void ExtractNatives::executeTask()
|
||||
return;
|
||||
}
|
||||
auto settings = minecraftInstance->settings();
|
||||
bool nativeOpenAL = settings->get("UseNativeOpenAL").toBool();
|
||||
bool nativeGLFW = settings->get("UseNativeGLFW").toBool();
|
||||
|
||||
auto outputPath = minecraftInstance->getNativePath();
|
||||
auto javaVersion = minecraftInstance->getJavaVersion();
|
||||
bool jniHackEnabled = javaVersion.major() >= 8;
|
||||
for (const auto& source : toExtract) {
|
||||
if (!unzipNatives(source, outputPath, jniHackEnabled, nativeOpenAL, nativeGLFW)) {
|
||||
if (!unzipNatives(source, outputPath, jniHackEnabled)) {
|
||||
const char* reason = QT_TR_NOOP("Couldn't extract native jar '%1' to destination '%2'");
|
||||
emit logLine(QString(reason).arg(source, outputPath), MessageLevel::Fatal);
|
||||
emitFailed(tr(reason).arg(source, outputPath));
|
||||
|
@ -53,7 +53,7 @@ LauncherPartLaunch::LauncherPartLaunch(LaunchTask* parent) : LaunchStep(parent)
|
||||
auto instance = parent->instance();
|
||||
if (instance->settings()->get("CloseAfterLaunch").toBool()) {
|
||||
std::shared_ptr<QMetaObject::Connection> connection{ new QMetaObject::Connection };
|
||||
*connection = connect(&m_process, &LoggedProcess::log, this, [=](QStringList lines, MessageLevel::Enum level) {
|
||||
*connection = connect(&m_process, &LoggedProcess::log, this, [=](QStringList lines, [[maybe_unused]] MessageLevel::Enum level) {
|
||||
qDebug() << lines;
|
||||
if (lines.filter(QRegularExpression(".*Setting user.+", QRegularExpression::CaseInsensitiveOption)).length() != 0) {
|
||||
APPLICATION->closeAllWindows();
|
||||
@ -105,6 +105,17 @@ void LauncherPartLaunch::executeTask()
|
||||
auto instance = m_parent->instance();
|
||||
std::shared_ptr<MinecraftInstance> minecraftInstance = std::dynamic_pointer_cast<MinecraftInstance>(instance);
|
||||
|
||||
QString legacyJarPath;
|
||||
if (minecraftInstance->getLauncher() == "legacy" || minecraftInstance->shouldApplyOnlineFixes()) {
|
||||
legacyJarPath = APPLICATION->getJarPath("NewLaunchLegacy.jar");
|
||||
if (legacyJarPath.isEmpty()) {
|
||||
const char* reason = QT_TR_NOOP("Legacy launcher library could not be found. Please check your installation.");
|
||||
emit logLine(tr(reason), MessageLevel::Fatal);
|
||||
emitFailed(tr(reason));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
m_launchScript = minecraftInstance->createLaunchScript(m_session, m_serverToJoin);
|
||||
QStringList args = minecraftInstance->javaArguments();
|
||||
QString allArgs = args.join(", ");
|
||||
@ -120,6 +131,9 @@ void LauncherPartLaunch::executeTask()
|
||||
auto classPath = minecraftInstance->getClassPath();
|
||||
classPath.prepend(jarPath);
|
||||
|
||||
if (!legacyJarPath.isEmpty())
|
||||
classPath.prepend(legacyJarPath);
|
||||
|
||||
auto natPath = minecraftInstance->getNativePath();
|
||||
#ifdef Q_OS_WIN
|
||||
if (!fitsInLocal8bit(natPath)) {
|
||||
|
@ -28,7 +28,7 @@
|
||||
#include "Version.h"
|
||||
|
||||
// Values taken from:
|
||||
// https://minecraft.fandom.com/wiki/Tutorials/Creating_a_data_pack#%22pack_format%22
|
||||
// https://minecraft.wiki/w/Tutorials/Creating_a_data_pack#%22pack_format%22
|
||||
static const QMap<int, std::pair<Version, Version>> s_pack_format_versions = {
|
||||
{ 4, { Version("1.13"), Version("1.14.4") } }, { 5, { Version("1.15"), Version("1.16.1") } },
|
||||
{ 6, { Version("1.16.2"), Version("1.16.5") } }, { 7, { Version("1.17"), Version("1.17.1") } },
|
||||
|
@ -63,7 +63,7 @@ class DataPack : public Resource {
|
||||
mutable QMutex m_data_lock;
|
||||
|
||||
/* The 'version' of a data pack, as defined in the pack.mcmeta file.
|
||||
* See https://minecraft.fandom.com/wiki/Data_pack#pack.mcmeta
|
||||
* See https://minecraft.wiki/w/Data_pack#pack.mcmeta
|
||||
*/
|
||||
int m_pack_format = 0;
|
||||
|
||||
|
@ -31,6 +31,7 @@ class Mod;
|
||||
class Metadata {
|
||||
public:
|
||||
using ModStruct = Packwiz::V1::Mod;
|
||||
using ModSide = Packwiz::V1::Side;
|
||||
|
||||
static auto create(QDir& index_dir, ModPlatform::IndexedPack& mod_pack, ModPlatform::IndexedVersion& mod_version) -> ModStruct
|
||||
{
|
||||
|
@ -132,17 +132,23 @@ auto Mod::destroy(QDir& index_dir, bool preserve_metadata, bool attempt_trash) -
|
||||
if (!preserve_metadata) {
|
||||
qDebug() << QString("Destroying metadata for '%1' on purpose").arg(name());
|
||||
|
||||
if (metadata()) {
|
||||
Metadata::remove(index_dir, metadata()->slug);
|
||||
} else {
|
||||
auto n = name();
|
||||
Metadata::remove(index_dir, n);
|
||||
}
|
||||
destroyMetadata(index_dir);
|
||||
}
|
||||
|
||||
return Resource::destroy(attempt_trash);
|
||||
}
|
||||
|
||||
void Mod::destroyMetadata(QDir& index_dir)
|
||||
{
|
||||
if (metadata()) {
|
||||
Metadata::remove(index_dir, metadata()->slug);
|
||||
} else {
|
||||
auto n = name();
|
||||
Metadata::remove(index_dir, n);
|
||||
}
|
||||
m_local_details.metadata = nullptr;
|
||||
}
|
||||
|
||||
auto Mod::details() const -> const ModDetails&
|
||||
{
|
||||
return m_local_details;
|
||||
@ -246,7 +252,8 @@ void Mod::setIcon(QImage new_image) const
|
||||
PixmapCache::remove(m_pack_image_cache_key.key);
|
||||
|
||||
// scale the image to avoid flooding the pixmapcache
|
||||
auto pixmap = QPixmap::fromImage(new_image.scaled({ 64, 64 }, Qt::AspectRatioMode::KeepAspectRatioByExpanding));
|
||||
auto pixmap =
|
||||
QPixmap::fromImage(new_image.scaled({ 64, 64 }, Qt::AspectRatioMode::KeepAspectRatioByExpanding, Qt::SmoothTransformation));
|
||||
|
||||
m_pack_image_cache_key.key = PixmapCache::insert(pixmap);
|
||||
m_pack_image_cache_key.was_ever_used = true;
|
||||
@ -259,7 +266,7 @@ QPixmap Mod::icon(QSize size, Qt::AspectRatioMode mode) const
|
||||
if (PixmapCache::find(m_pack_image_cache_key.key, &cached_image)) {
|
||||
if (size.isNull())
|
||||
return cached_image;
|
||||
return cached_image.scaled(size, mode);
|
||||
return cached_image.scaled(size, mode, Qt::SmoothTransformation);
|
||||
}
|
||||
|
||||
// No valid image we can get
|
||||
|
@ -72,7 +72,7 @@ class Mod : public Resource {
|
||||
auto metaurl() const -> QString;
|
||||
|
||||
/** Get the intneral path to the mod's icon file*/
|
||||
QString iconPath() const { return m_local_details.icon_file; };
|
||||
QString iconPath() const { return m_local_details.icon_file; }
|
||||
/** Gets the icon of the mod, converted to a QPixmap for drawing, and scaled to size. */
|
||||
[[nodiscard]] QPixmap icon(QSize size, Qt::AspectRatioMode mode = Qt::AspectRatioMode::IgnoreAspectRatio) const;
|
||||
/** Thread-safe. */
|
||||
@ -93,6 +93,8 @@ class Mod : public Resource {
|
||||
|
||||
// Delete all the files of this mod
|
||||
auto destroy(QDir& index_dir, bool preserve_metadata = false, bool attempt_trash = true) -> bool;
|
||||
// Delete the metadata only
|
||||
void destroyMetadata(QDir& index_dir);
|
||||
|
||||
void finishResolvingWithDetails(ModDetails&& details);
|
||||
|
||||
|
@ -60,17 +60,17 @@ struct ModLicense {
|
||||
|
||||
ModLicense(const QString license)
|
||||
{
|
||||
// FIXME: come up with a better license parseing.
|
||||
// FIXME: come up with a better license parsing.
|
||||
// handle SPDX identifiers? https://spdx.org/licenses/
|
||||
auto parts = license.split(' ');
|
||||
QStringList notNameParts = {};
|
||||
for (auto part : parts) {
|
||||
auto url = QUrl(part);
|
||||
auto _url = QUrl(part);
|
||||
if (part.startsWith("(") && part.endsWith(")"))
|
||||
url = QUrl(part.mid(1, part.size() - 2));
|
||||
_url = QUrl(part.mid(1, part.size() - 2));
|
||||
|
||||
if (url.isValid() && !url.scheme().isEmpty() && !url.host().isEmpty()) {
|
||||
this->url = url.toString();
|
||||
if (_url.isValid() && !_url.scheme().isEmpty() && !_url.host().isEmpty()) {
|
||||
this->url = _url.toString();
|
||||
notNameParts.append(part);
|
||||
continue;
|
||||
}
|
||||
@ -89,13 +89,9 @@ struct ModLicense {
|
||||
}
|
||||
}
|
||||
|
||||
ModLicense(const QString name, const QString id, const QString url, const QString description)
|
||||
{
|
||||
this->name = name;
|
||||
this->id = id;
|
||||
this->url = url;
|
||||
this->description = description;
|
||||
}
|
||||
ModLicense(const QString& name_, const QString& id_, const QString& url_, const QString& description_)
|
||||
: name(name_), id(id_), url(url_), description(description_)
|
||||
{}
|
||||
|
||||
ModLicense(const ModLicense& other) : name(other.name), id(other.id), url(other.url), description(other.description) {}
|
||||
|
||||
|
@ -51,8 +51,13 @@
|
||||
|
||||
#include "Application.h"
|
||||
|
||||
#include "Json.h"
|
||||
#include "minecraft/mod/tasks/LocalModParseTask.h"
|
||||
#include "minecraft/mod/tasks/LocalModUpdateTask.h"
|
||||
#include "minecraft/mod/tasks/ModFolderLoadTask.h"
|
||||
#include "modplatform/ModIndex.h"
|
||||
#include "modplatform/flame/FlameAPI.h"
|
||||
#include "modplatform/flame/FlameModIndex.h"
|
||||
|
||||
ModFolderModel::ModFolderModel(const QString& dir, BaseInstance* instance, bool is_indexed, bool create_dir)
|
||||
: ResourceFolderModel(QDir(dir), instance, nullptr, create_dir), m_is_indexed(is_indexed)
|
||||
@ -62,6 +67,7 @@ ModFolderModel::ModFolderModel(const QString& dir, BaseInstance* instance, bool
|
||||
m_column_sort_keys = { SortType::ENABLED, SortType::NAME, SortType::NAME, SortType::VERSION, SortType::DATE, SortType::PROVIDER };
|
||||
m_column_resize_modes = { QHeaderView::ResizeToContents, QHeaderView::Interactive, QHeaderView::Stretch,
|
||||
QHeaderView::ResizeToContents, QHeaderView::ResizeToContents, QHeaderView::ResizeToContents };
|
||||
m_columnsHideable = { false, true, false, true, true, true };
|
||||
}
|
||||
|
||||
QVariant ModFolderModel::data(const QModelIndex& index, int role) const
|
||||
@ -137,7 +143,7 @@ QVariant ModFolderModel::data(const QModelIndex& index, int role) const
|
||||
}
|
||||
}
|
||||
|
||||
QVariant ModFolderModel::headerData(int section, Qt::Orientation orientation, int role) const
|
||||
QVariant ModFolderModel::headerData(int section, [[maybe_unused]] Qt::Orientation orientation, int role) const
|
||||
{
|
||||
switch (role) {
|
||||
case Qt::DisplayRole:
|
||||
@ -227,6 +233,25 @@ bool ModFolderModel::deleteMods(const QModelIndexList& indexes)
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ModFolderModel::deleteModsMetadata(const QModelIndexList& indexes)
|
||||
{
|
||||
if (indexes.isEmpty())
|
||||
return true;
|
||||
|
||||
for (auto i : indexes) {
|
||||
if (i.column() != 0) {
|
||||
continue;
|
||||
}
|
||||
auto m = at(i.row());
|
||||
auto index_dir = indexDir();
|
||||
m->destroyMetadata(index_dir);
|
||||
}
|
||||
|
||||
update();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ModFolderModel::isValid()
|
||||
{
|
||||
return m_dir.exists() && m_dir.isReadable();
|
||||
@ -308,3 +333,47 @@ void ModFolderModel::onParseSucceeded(int ticket, QString mod_id)
|
||||
|
||||
emit dataChanged(index(row), index(row, columnCount(QModelIndex()) - 1));
|
||||
}
|
||||
|
||||
static const FlameAPI flameAPI;
|
||||
bool ModFolderModel::installMod(QString file_path, ModPlatform::IndexedVersion& vers)
|
||||
{
|
||||
if (vers.addonId.isValid()) {
|
||||
ModPlatform::IndexedPack pack{
|
||||
vers.addonId,
|
||||
ModPlatform::ResourceProvider::FLAME,
|
||||
};
|
||||
|
||||
QEventLoop loop;
|
||||
|
||||
auto response = std::make_shared<QByteArray>();
|
||||
auto job = flameAPI.getProject(vers.addonId.toString(), response);
|
||||
|
||||
QObject::connect(job.get(), &Task::failed, [&loop] { loop.quit(); });
|
||||
QObject::connect(job.get(), &Task::aborted, &loop, &QEventLoop::quit);
|
||||
QObject::connect(job.get(), &Task::succeeded, [response, this, &vers, &loop, &pack] {
|
||||
QJsonParseError parse_error{};
|
||||
QJsonDocument doc = QJsonDocument::fromJson(*response, &parse_error);
|
||||
if (parse_error.error != QJsonParseError::NoError) {
|
||||
qWarning() << "Error while parsing JSON response for mod info at " << parse_error.offset
|
||||
<< " reason: " << parse_error.errorString();
|
||||
qDebug() << *response;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
auto obj = Json::requireObject(Json::requireObject(doc), "data");
|
||||
FlameMod::loadIndexedPack(pack, obj);
|
||||
} catch (const JSONValidationError& e) {
|
||||
qDebug() << doc;
|
||||
qWarning() << "Error while reading mod info: " << e.cause();
|
||||
}
|
||||
LocalModUpdateTask update_metadata(indexDir(), pack, vers);
|
||||
QObject::connect(&update_metadata, &Task::finished, &loop, &QEventLoop::quit);
|
||||
update_metadata.start();
|
||||
});
|
||||
|
||||
job->start();
|
||||
|
||||
loop.exec();
|
||||
}
|
||||
return ResourceFolderModel::installResource(file_path);
|
||||
}
|
||||
|
@ -48,6 +48,7 @@
|
||||
|
||||
#include "minecraft/mod/tasks/LocalModParseTask.h"
|
||||
#include "minecraft/mod/tasks/ModFolderLoadTask.h"
|
||||
#include "modplatform/ModIndex.h"
|
||||
|
||||
class LegacyInstance;
|
||||
class BaseInstance;
|
||||
@ -75,10 +76,12 @@ class ModFolderModel : public ResourceFolderModel {
|
||||
[[nodiscard]] Task* createParseTask(Resource&) override;
|
||||
|
||||
bool installMod(QString file_path) { return ResourceFolderModel::installResource(file_path); }
|
||||
bool installMod(QString file_path, ModPlatform::IndexedVersion& vers);
|
||||
bool uninstallMod(const QString& filename, bool preserve_metadata = false);
|
||||
|
||||
/// Deletes all the selected mods
|
||||
bool deleteMods(const QModelIndexList& indexes);
|
||||
bool deleteModsMetadata(const QModelIndexList& indexes);
|
||||
|
||||
bool isValid();
|
||||
|
||||
|
@ -33,6 +33,10 @@ ResourceFolderModel::ResourceFolderModel(QDir dir, BaseInstance* instance, QObje
|
||||
|
||||
connect(&m_watcher, &QFileSystemWatcher::directoryChanged, this, &ResourceFolderModel::directoryChanged);
|
||||
connect(&m_helper_thread_task, &ConcurrentTask::finished, this, [this] { m_helper_thread_task.clear(); });
|
||||
#ifndef LAUNCHER_TEST
|
||||
// in tests the application macro doesn't work
|
||||
m_helper_thread_task.setMaxConcurrent(APPLICATION->settings()->get("NumberOfConcurrentTasks").toInt());
|
||||
#endif
|
||||
}
|
||||
|
||||
ResourceFolderModel::~ResourceFolderModel()
|
||||
@ -447,7 +451,7 @@ QVariant ResourceFolderModel::data(const QModelIndex& index, int role) const
|
||||
}
|
||||
}
|
||||
|
||||
bool ResourceFolderModel::setData(const QModelIndex& index, const QVariant& value, int role)
|
||||
bool ResourceFolderModel::setData(const QModelIndex& index, [[maybe_unused]] const QVariant& value, int role)
|
||||
{
|
||||
int row = index.row();
|
||||
if (row < 0 || row >= rowCount(index.parent()) || !index.isValid())
|
||||
@ -471,7 +475,7 @@ bool ResourceFolderModel::setData(const QModelIndex& index, const QVariant& valu
|
||||
return false;
|
||||
}
|
||||
|
||||
QVariant ResourceFolderModel::headerData(int section, Qt::Orientation orientation, int role) const
|
||||
QVariant ResourceFolderModel::headerData(int section, [[maybe_unused]] Qt::Orientation orientation, int role) const
|
||||
{
|
||||
switch (role) {
|
||||
case Qt::DisplayRole:
|
||||
@ -551,6 +555,9 @@ QMenu* ResourceFolderModel::createHeaderContextMenu(QTreeView* tree)
|
||||
menu->addSeparator()->setText(tr("Show / Hide Columns"));
|
||||
|
||||
for (int col = 0; col < columnCount(); ++col) {
|
||||
// Skip creating actions for columns that should not be hidden
|
||||
if (!m_columnsHideable.at(col))
|
||||
continue;
|
||||
auto act = new QAction(menu);
|
||||
setupHeaderAction(act, col);
|
||||
|
||||
@ -584,7 +591,8 @@ SortType ResourceFolderModel::columnToSortKey(size_t column) const
|
||||
}
|
||||
|
||||
/* Standard Proxy Model for createFilterProxyModel */
|
||||
[[nodiscard]] bool ResourceFolderModel::ProxyModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const
|
||||
[[nodiscard]] bool ResourceFolderModel::ProxyModel::filterAcceptsRow(int source_row,
|
||||
[[maybe_unused]] const QModelIndex& source_parent) const
|
||||
{
|
||||
auto* model = qobject_cast<ResourceFolderModel*>(sourceModel());
|
||||
if (!model)
|
||||
|
@ -49,8 +49,8 @@ class ResourceFolderModel : public QAbstractListModel {
|
||||
bool stopWatching(const QStringList paths);
|
||||
|
||||
/* Helper methods for subclasses, using a predetermined list of paths. */
|
||||
virtual bool startWatching() { return startWatching({ m_dir.absolutePath() }); };
|
||||
virtual bool stopWatching() { return stopWatching({ m_dir.absolutePath() }); };
|
||||
virtual bool startWatching() { return startWatching({ m_dir.absolutePath() }); }
|
||||
virtual bool stopWatching() { return stopWatching({ m_dir.absolutePath() }); }
|
||||
|
||||
/** Given a path in the system, install that resource, moving it to its place in the
|
||||
* instance file hierarchy.
|
||||
@ -78,7 +78,7 @@ class ResourceFolderModel : public QAbstractListModel {
|
||||
/** Creates a new parse task, if needed, for 'res' and start it.*/
|
||||
virtual void resolveResource(Resource* res);
|
||||
|
||||
[[nodiscard]] size_t size() const { return m_resources.size(); };
|
||||
[[nodiscard]] qsizetype size() const { return m_resources.size(); }
|
||||
[[nodiscard]] bool empty() const { return size() == 0; }
|
||||
[[nodiscard]] Resource& at(int index) { return *m_resources.at(index); }
|
||||
[[nodiscard]] Resource const& at(int index) const { return *m_resources.at(index); }
|
||||
@ -97,10 +97,10 @@ class ResourceFolderModel : public QAbstractListModel {
|
||||
|
||||
/* Basic columns */
|
||||
enum Columns { ACTIVE_COLUMN = 0, NAME_COLUMN, DATE_COLUMN, NUM_COLUMNS };
|
||||
QStringList columnNames(bool translated = true) const { return translated ? m_column_names_translated : m_column_names; };
|
||||
QStringList columnNames(bool translated = true) const { return translated ? m_column_names_translated : m_column_names; }
|
||||
|
||||
[[nodiscard]] int rowCount(const QModelIndex& parent = {}) const override { return parent.isValid() ? 0 : static_cast<int>(size()); }
|
||||
[[nodiscard]] int columnCount(const QModelIndex& parent = {}) const override { return parent.isValid() ? 0 : NUM_COLUMNS; };
|
||||
[[nodiscard]] int columnCount(const QModelIndex& parent = {}) const override { return parent.isValid() ? 0 : NUM_COLUMNS; }
|
||||
|
||||
[[nodiscard]] Qt::DropActions supportedDropActions() const override;
|
||||
|
||||
@ -159,7 +159,7 @@ class ResourceFolderModel : public QAbstractListModel {
|
||||
* This task should load and parse all heavy info needed by a resource, such as parsing a manifest. It gets executed
|
||||
* in the background, so it slowly updates the UI as tasks get done.
|
||||
*/
|
||||
[[nodiscard]] virtual Task* createParseTask(Resource&) { return nullptr; };
|
||||
[[nodiscard]] virtual Task* createParseTask(Resource&) { return nullptr; }
|
||||
|
||||
/** Standard implementation of the model update logic.
|
||||
*
|
||||
@ -203,6 +203,7 @@ class ResourceFolderModel : public QAbstractListModel {
|
||||
QStringList m_column_names_translated = { tr("Enable"), tr("Name"), tr("Last Modified") };
|
||||
QList<QHeaderView::ResizeMode> m_column_resize_modes = { QHeaderView::ResizeToContents, QHeaderView::Stretch,
|
||||
QHeaderView::ResizeToContents };
|
||||
QList<bool> m_columnsHideable = { false, false, true };
|
||||
|
||||
QDir m_dir;
|
||||
BaseInstance* m_instance;
|
||||
@ -224,15 +225,15 @@ class ResourceFolderModel : public QAbstractListModel {
|
||||
|
||||
/* A macro to define useful functions to handle Resource* -> T* more easily on derived classes */
|
||||
#define RESOURCE_HELPERS(T) \
|
||||
[[nodiscard]] T* operator[](size_t index) \
|
||||
[[nodiscard]] T* operator[](int index) \
|
||||
{ \
|
||||
return static_cast<T*>(m_resources[index].get()); \
|
||||
} \
|
||||
[[nodiscard]] T* at(size_t index) \
|
||||
[[nodiscard]] T* at(int index) \
|
||||
{ \
|
||||
return static_cast<T*>(m_resources[index].get()); \
|
||||
} \
|
||||
[[nodiscard]] const T* at(size_t index) const \
|
||||
[[nodiscard]] const T* at(int index) const \
|
||||
{ \
|
||||
return static_cast<const T*>(m_resources.at(index).get()); \
|
||||
} \
|
||||
@ -329,7 +330,8 @@ void ResourceFolderModel::applyUpdates(QSet<QString>& current_set, QSet<QString>
|
||||
|
||||
// When you have a Qt build with assertions turned on, proceeding here will abort the application
|
||||
if (added_set.size() > 0) {
|
||||
beginInsertRows(QModelIndex(), m_resources.size(), m_resources.size() + added_set.size() - 1);
|
||||
beginInsertRows(QModelIndex(), static_cast<int>(m_resources.size()),
|
||||
static_cast<int>(m_resources.size() + added_set.size() - 1));
|
||||
|
||||
for (auto& added : added_set) {
|
||||
auto res = new_resources[added];
|
||||
|
@ -11,7 +11,7 @@
|
||||
#include "minecraft/mod/tasks/LocalResourcePackParseTask.h"
|
||||
|
||||
// Values taken from:
|
||||
// https://minecraft.fandom.com/wiki/Tutorials/Creating_a_resource_pack#Formatting_pack.mcmeta
|
||||
// https://minecraft.wiki/w/Tutorials/Creating_a_resource_pack#Formatting_pack.mcmeta
|
||||
static const QMap<int, std::pair<Version, Version>> s_pack_format_versions = {
|
||||
{ 1, { Version("1.6.1"), Version("1.8.9") } }, { 2, { Version("1.9"), Version("1.10.2") } },
|
||||
{ 3, { Version("1.11"), Version("1.12.2") } }, { 4, { Version("1.13"), Version("1.14.4") } },
|
||||
@ -50,7 +50,8 @@ void ResourcePack::setImage(QImage new_image) const
|
||||
PixmapCache::instance().remove(m_pack_image_cache_key.key);
|
||||
|
||||
// scale the image to avoid flooding the pixmapcache
|
||||
auto pixmap = QPixmap::fromImage(new_image.scaled({ 64, 64 }, Qt::AspectRatioMode::KeepAspectRatioByExpanding));
|
||||
auto pixmap =
|
||||
QPixmap::fromImage(new_image.scaled({ 64, 64 }, Qt::AspectRatioMode::KeepAspectRatioByExpanding, Qt::SmoothTransformation));
|
||||
|
||||
m_pack_image_cache_key.key = PixmapCache::instance().insert(pixmap);
|
||||
m_pack_image_cache_key.was_ever_used = true;
|
||||
@ -68,7 +69,7 @@ QPixmap ResourcePack::image(QSize size, Qt::AspectRatioMode mode) const
|
||||
if (PixmapCache::instance().find(m_pack_image_cache_key.key, &cached_image)) {
|
||||
if (size.isNull())
|
||||
return cached_image;
|
||||
return cached_image.scaled(size, mode);
|
||||
return cached_image.scaled(size, mode, Qt::SmoothTransformation);
|
||||
}
|
||||
|
||||
// No valid image we can get
|
||||
|
@ -51,7 +51,7 @@ class ResourcePack : public Resource {
|
||||
mutable QMutex m_data_lock;
|
||||
|
||||
/* The 'version' of a resource pack, as defined in the pack.mcmeta file.
|
||||
* See https://minecraft.fandom.com/wiki/Tutorials/Creating_a_resource_pack#Formatting_pack.mcmeta
|
||||
* See https://minecraft.wiki/w/Tutorials/Creating_a_resource_pack#Formatting_pack.mcmeta
|
||||
*/
|
||||
int m_pack_format = 0;
|
||||
|
||||
|
@ -54,6 +54,7 @@ ResourcePackFolderModel::ResourcePackFolderModel(const QString& dir, BaseInstanc
|
||||
m_column_sort_keys = { SortType::ENABLED, SortType::NAME, SortType::NAME, SortType::PACK_FORMAT, SortType::DATE };
|
||||
m_column_resize_modes = { QHeaderView::ResizeToContents, QHeaderView::Interactive, QHeaderView::Stretch, QHeaderView::ResizeToContents,
|
||||
QHeaderView::ResizeToContents };
|
||||
m_columnsHideable = { false, true, false, true, true };
|
||||
}
|
||||
|
||||
QVariant ResourcePackFolderModel::data(const QModelIndex& index, int role) const
|
||||
@ -128,7 +129,7 @@ QVariant ResourcePackFolderModel::data(const QModelIndex& index, int role) const
|
||||
}
|
||||
}
|
||||
|
||||
QVariant ResourcePackFolderModel::headerData(int section, Qt::Orientation orientation, int role) const
|
||||
QVariant ResourcePackFolderModel::headerData(int section, [[maybe_unused]] Qt::Orientation orientation, int role) const
|
||||
{
|
||||
switch (role) {
|
||||
case Qt::DisplayRole:
|
||||
@ -165,7 +166,6 @@ QVariant ResourcePackFolderModel::headerData(int section, Qt::Orientation orient
|
||||
default:
|
||||
return {};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
int ResourcePackFolderModel::columnCount(const QModelIndex& parent) const
|
||||
|
@ -22,7 +22,7 @@
|
||||
|
||||
#include "ShaderPack.h"
|
||||
|
||||
#include "minecraft/mod/tasks/LocalShaderPackParseTask.h"
|
||||
#include <QRegularExpression>
|
||||
|
||||
void ShaderPack::setPackFormat(ShaderPackFormat new_format)
|
||||
{
|
||||
@ -35,3 +35,8 @@ bool ShaderPack::valid() const
|
||||
{
|
||||
return m_pack_format != ShaderPackFormat::INVALID;
|
||||
}
|
||||
|
||||
bool ShaderPack::applyFilter(QRegularExpression filter) const
|
||||
{
|
||||
return valid() && Resource::applyFilter(filter);
|
||||
}
|
||||
|
@ -54,6 +54,7 @@ class ShaderPack : public Resource {
|
||||
void setPackFormat(ShaderPackFormat new_format);
|
||||
|
||||
bool valid() const override;
|
||||
[[nodiscard]] bool applyFilter(QRegularExpression filter) const override;
|
||||
|
||||
protected:
|
||||
mutable QMutex m_data_lock;
|
||||
|
@ -1,6 +1,9 @@
|
||||
#pragma once
|
||||
|
||||
#include "ResourceFolderModel.h"
|
||||
#include "minecraft/mod/ShaderPack.h"
|
||||
#include "minecraft/mod/tasks/BasicFolderLoadTask.h"
|
||||
#include "minecraft/mod/tasks/LocalShaderPackParseTask.h"
|
||||
|
||||
class ShaderPackFolderModel : public ResourceFolderModel {
|
||||
Q_OBJECT
|
||||
@ -9,4 +12,14 @@ class ShaderPackFolderModel : public ResourceFolderModel {
|
||||
explicit ShaderPackFolderModel(const QString& dir, BaseInstance* instance) : ResourceFolderModel(QDir(dir), instance) {}
|
||||
|
||||
virtual QString id() const override { return "shaderpacks"; }
|
||||
|
||||
[[nodiscard]] Task* createUpdateTask() override
|
||||
{
|
||||
return new BasicFolderLoadTask(m_dir, [](QFileInfo const& entry) { return makeShared<ShaderPack>(entry); });
|
||||
}
|
||||
|
||||
[[nodiscard]] Task* createParseTask(Resource& resource) override
|
||||
{
|
||||
return new LocalShaderPackParseTask(m_next_resolution_ticket, static_cast<ShaderPack&>(resource));
|
||||
}
|
||||
};
|
||||
|
@ -44,7 +44,8 @@ void TexturePack::setImage(QImage new_image) const
|
||||
PixmapCache::remove(m_pack_image_cache_key.key);
|
||||
|
||||
// scale the image to avoid flooding the pixmapcache
|
||||
auto pixmap = QPixmap::fromImage(new_image.scaled({ 64, 64 }, Qt::AspectRatioMode::KeepAspectRatioByExpanding));
|
||||
auto pixmap =
|
||||
QPixmap::fromImage(new_image.scaled({ 64, 64 }, Qt::AspectRatioMode::KeepAspectRatioByExpanding, Qt::SmoothTransformation));
|
||||
|
||||
m_pack_image_cache_key.key = PixmapCache::insert(pixmap);
|
||||
m_pack_image_cache_key.was_ever_used = true;
|
||||
@ -56,7 +57,7 @@ QPixmap TexturePack::image(QSize size, Qt::AspectRatioMode mode) const
|
||||
if (PixmapCache::find(m_pack_image_cache_key.key, &cached_image)) {
|
||||
if (size.isNull())
|
||||
return cached_image;
|
||||
return cached_image.scaled(size, mode);
|
||||
return cached_image.scaled(size, mode, Qt::SmoothTransformation);
|
||||
}
|
||||
|
||||
// No valid image we can get
|
||||
|
@ -49,6 +49,7 @@ TexturePackFolderModel::TexturePackFolderModel(const QString& dir, BaseInstance*
|
||||
m_column_sort_keys = { SortType::ENABLED, SortType::NAME, SortType::NAME, SortType::DATE };
|
||||
m_column_resize_modes = { QHeaderView::ResizeToContents, QHeaderView::Interactive, QHeaderView::Stretch,
|
||||
QHeaderView::ResizeToContents };
|
||||
m_columnsHideable = { false, true, false, true };
|
||||
}
|
||||
|
||||
Task* TexturePackFolderModel::createUpdateTask()
|
||||
@ -113,7 +114,7 @@ QVariant TexturePackFolderModel::data(const QModelIndex& index, int role) const
|
||||
}
|
||||
}
|
||||
|
||||
QVariant TexturePackFolderModel::headerData(int section, Qt::Orientation orientation, int role) const
|
||||
QVariant TexturePackFolderModel::headerData(int section, [[maybe_unused]] Qt::Orientation orientation, int role) const
|
||||
{
|
||||
switch (role) {
|
||||
case Qt::DisplayRole:
|
||||
|
@ -39,9 +39,9 @@ static Version mcVersion(BaseInstance* inst)
|
||||
return static_cast<MinecraftInstance*>(inst)->getPackProfile()->getComponent("net.minecraft")->getVersion();
|
||||
}
|
||||
|
||||
static ResourceAPI::ModLoaderTypes mcLoaders(BaseInstance* inst)
|
||||
static ModPlatform::ModLoaderTypes mcLoaders(BaseInstance* inst)
|
||||
{
|
||||
return static_cast<MinecraftInstance*>(inst)->getPackProfile()->getModLoaders().value();
|
||||
return static_cast<MinecraftInstance*>(inst)->getPackProfile()->getSupportedModLoaders().value();
|
||||
}
|
||||
|
||||
GetModDependenciesTask::GetModDependenciesTask(QObject* parent,
|
||||
@ -61,7 +61,7 @@ GetModDependenciesTask::GetModDependenciesTask(QObject* parent,
|
||||
if (auto meta = mod->metadata(); meta)
|
||||
m_mods.append(meta);
|
||||
prepare();
|
||||
};
|
||||
}
|
||||
|
||||
void GetModDependenciesTask::prepare()
|
||||
{
|
||||
@ -75,7 +75,7 @@ void GetModDependenciesTask::prepare()
|
||||
ModPlatform::Dependency GetModDependenciesTask::getOverride(const ModPlatform::Dependency& dep,
|
||||
const ModPlatform::ResourceProvider providerName)
|
||||
{
|
||||
if (auto isQuilt = m_loaderType & ResourceAPI::Quilt; isQuilt || m_loaderType & ResourceAPI::Fabric) {
|
||||
if (auto isQuilt = m_loaderType & ModPlatform::Quilt; isQuilt || m_loaderType & ModPlatform::Fabric) {
|
||||
auto overide = ModPlatform::getOverrideDeps();
|
||||
auto over = std::find_if(overide.cbegin(), overide.cend(), [dep, providerName, isQuilt](auto o) {
|
||||
return o.provider == providerName && dep.addonId == (isQuilt ? o.fabric : o.quilt);
|
||||
@ -94,7 +94,7 @@ QList<ModPlatform::Dependency> GetModDependenciesTask::getDependenciesForVersion
|
||||
for (auto ver_dep : version.dependencies) {
|
||||
if (ver_dep.type != ModPlatform::DependencyType::REQUIRED)
|
||||
continue;
|
||||
|
||||
ver_dep = getOverride(ver_dep, providerName);
|
||||
auto isOnlyVersion = providerName == ModPlatform::ResourceProvider::MODRINTH && ver_dep.addonId.toString().isEmpty();
|
||||
if (auto dep = std::find_if(c_dependencies.begin(), c_dependencies.end(),
|
||||
[&ver_dep, isOnlyVersion](const ModPlatform::Dependency& i) {
|
||||
@ -127,10 +127,10 @@ QList<ModPlatform::Dependency> GetModDependenciesTask::getDependenciesForVersion
|
||||
dep != m_pack_dependencies.end()) // check loaded dependencies
|
||||
continue;
|
||||
|
||||
c_dependencies.append(getOverride(ver_dep, providerName));
|
||||
c_dependencies.append(ver_dep);
|
||||
}
|
||||
return c_dependencies;
|
||||
};
|
||||
}
|
||||
|
||||
Task::Ptr GetModDependenciesTask::getProjectInfoTask(std::shared_ptr<PackDependency> pDep)
|
||||
{
|
||||
@ -181,7 +181,7 @@ Task::Ptr GetModDependenciesTask::prepareDependencyTask(const ModPlatform::Depen
|
||||
ResourceAPI::DependencySearchArgs args = { dep, m_version, m_loaderType };
|
||||
ResourceAPI::DependencySearchCallbacks callbacks;
|
||||
|
||||
callbacks.on_succeed = [dep, provider, pDep, level, this](auto& doc, auto& pack) {
|
||||
callbacks.on_succeed = [dep, provider, pDep, level, this](auto& doc, [[maybe_unused]] auto& pack) {
|
||||
try {
|
||||
QJsonArray arr;
|
||||
if (dep.version.length() != 0 && doc.isObject()) {
|
||||
@ -191,7 +191,7 @@ Task::Ptr GetModDependenciesTask::prepareDependencyTask(const ModPlatform::Depen
|
||||
}
|
||||
pDep->version = provider.mod->loadDependencyVersions(dep, arr);
|
||||
if (!pDep->version.addonId.isValid()) {
|
||||
if (m_loaderType & ResourceAPI::Quilt) { // falback for quilt
|
||||
if (m_loaderType & ModPlatform::Quilt) { // falback for quilt
|
||||
auto overide = ModPlatform::getOverrideDeps();
|
||||
auto over = std::find_if(overide.cbegin(), overide.cend(),
|
||||
[dep, provider](auto o) { return o.provider == provider.name && dep.addonId == o.quilt; });
|
||||
@ -201,6 +201,7 @@ Task::Ptr GetModDependenciesTask::prepareDependencyTask(const ModPlatform::Depen
|
||||
return;
|
||||
}
|
||||
}
|
||||
removePack(dep.addonId);
|
||||
qWarning() << "Error while reading mod version empty ";
|
||||
qDebug() << doc;
|
||||
return;
|
||||
@ -215,27 +216,27 @@ Task::Ptr GetModDependenciesTask::prepareDependencyTask(const ModPlatform::Depen
|
||||
return;
|
||||
}
|
||||
if (level == 0) {
|
||||
qWarning() << "Dependency cycle exeeded";
|
||||
qWarning() << "Dependency cycle exceeded";
|
||||
return;
|
||||
}
|
||||
if (dep.addonId.toString().isEmpty() && !pDep->version.addonId.toString().isEmpty()) {
|
||||
pDep->pack->addonId = pDep->version.addonId;
|
||||
auto dep = getOverride({ pDep->version.addonId, pDep->dependency.type }, provider.name);
|
||||
if (dep.addonId != pDep->version.addonId) {
|
||||
auto dep_ = getOverride({ pDep->version.addonId, pDep->dependency.type }, provider.name);
|
||||
if (dep_.addonId != pDep->version.addonId) {
|
||||
removePack(pDep->version.addonId);
|
||||
addTask(prepareDependencyTask(dep, provider.name, level));
|
||||
addTask(prepareDependencyTask(dep_, provider.name, level));
|
||||
} else
|
||||
addTask(getProjectInfoTask(pDep));
|
||||
}
|
||||
for (auto dep : getDependenciesForVersion(pDep->version, provider.name)) {
|
||||
addTask(prepareDependencyTask(dep, provider.name, level - 1));
|
||||
for (auto dep_ : getDependenciesForVersion(pDep->version, provider.name)) {
|
||||
addTask(prepareDependencyTask(dep_, provider.name, level - 1));
|
||||
}
|
||||
};
|
||||
|
||||
auto version = provider.api->getDependencyVersion(std::move(args), std::move(callbacks));
|
||||
tasks->addTask(version);
|
||||
return tasks;
|
||||
};
|
||||
}
|
||||
|
||||
void GetModDependenciesTask::removePack(const QVariant addonId)
|
||||
{
|
||||
@ -250,3 +251,32 @@ void GetModDependenciesTask::removePack(const QVariant addonId)
|
||||
++it;
|
||||
#endif
|
||||
}
|
||||
|
||||
QHash<QString, QStringList> GetModDependenciesTask::getRequiredBy()
|
||||
{
|
||||
QHash<QString, QStringList> rby;
|
||||
auto fullList = m_selected + m_pack_dependencies;
|
||||
for (auto& mod : fullList) {
|
||||
auto addonId = mod->pack->addonId;
|
||||
auto provider = mod->pack->provider;
|
||||
auto version = mod->version.fileId;
|
||||
auto req = QStringList();
|
||||
for (auto& smod : fullList) {
|
||||
if (provider != smod->pack->provider)
|
||||
continue;
|
||||
auto deps = smod->version.dependencies;
|
||||
if (auto dep = std::find_if(deps.begin(), deps.end(),
|
||||
[addonId, provider, version](const ModPlatform::Dependency& d) {
|
||||
return d.type == ModPlatform::DependencyType::REQUIRED &&
|
||||
(provider == ModPlatform::ResourceProvider::MODRINTH && d.addonId.toString().isEmpty()
|
||||
? version == d.version
|
||||
: d.addonId == addonId);
|
||||
});
|
||||
dep != deps.end()) {
|
||||
req.append(smod->pack->name);
|
||||
}
|
||||
}
|
||||
rby[addonId.toString()] = req;
|
||||
}
|
||||
return rby;
|
||||
}
|
@ -62,6 +62,7 @@ class GetModDependenciesTask : public SequentialTask {
|
||||
QList<std::shared_ptr<PackDependency>> selected);
|
||||
|
||||
auto getDependecies() const -> QList<std::shared_ptr<PackDependency>> { return m_pack_dependencies; }
|
||||
QHash<QString, QStringList> getRequiredBy();
|
||||
|
||||
protected slots:
|
||||
Task::Ptr prepareDependencyTask(const ModPlatform::Dependency&, const ModPlatform::ResourceProvider, int);
|
||||
@ -80,5 +81,5 @@ class GetModDependenciesTask : public SequentialTask {
|
||||
Provider m_modrinth_provider;
|
||||
|
||||
Version m_version;
|
||||
ResourceAPI::ModLoaderTypes m_loaderType;
|
||||
ModPlatform::ModLoaderTypes m_loaderType;
|
||||
};
|
||||
|
@ -133,7 +133,7 @@ bool processZIP(DataPack& pack, ProcessingLevel level)
|
||||
return true;
|
||||
}
|
||||
|
||||
// https://minecraft.fandom.com/wiki/Data_pack#pack.mcmeta
|
||||
// https://minecraft.wiki/w/Data_pack#pack.mcmeta
|
||||
bool processMCMeta(DataPack& pack, QByteArray&& raw_data)
|
||||
{
|
||||
try {
|
||||
|
@ -104,14 +104,15 @@ ModDetails ReadMCModTOML(QByteArray contents)
|
||||
#if TOML_EXCEPTIONS
|
||||
try {
|
||||
tomlData = toml::parse(contents.toStdString());
|
||||
} catch (const toml::parse_error& err) {
|
||||
} catch ([[maybe_unused]] const toml::parse_error& err) {
|
||||
return {};
|
||||
}
|
||||
#else
|
||||
tomlData = toml::parse(contents.toStdString());
|
||||
if (!tomlData) {
|
||||
toml::parse_result result = toml::parse(contents.toStdString());
|
||||
if (!result) {
|
||||
return {};
|
||||
}
|
||||
tomlData = result.table();
|
||||
#endif
|
||||
|
||||
// array defined by [[mods]]
|
||||
@ -151,8 +152,8 @@ ModDetails ReadMCModTOML(QByteArray contents)
|
||||
QString authors = "";
|
||||
if (auto authorsDatum = tomlData["authors"].as_string()) {
|
||||
authors = QString::fromStdString(authorsDatum->get());
|
||||
} else if (auto authorsDatum = (*modsTable)["authors"].as_string()) {
|
||||
authors = QString::fromStdString(authorsDatum->get());
|
||||
} else if (auto authorsDatumMods = (*modsTable)["authors"].as_string()) {
|
||||
authors = QString::fromStdString(authorsDatumMods->get());
|
||||
}
|
||||
if (!authors.isEmpty()) {
|
||||
details.authors.append(authors);
|
||||
@ -161,8 +162,8 @@ ModDetails ReadMCModTOML(QByteArray contents)
|
||||
QString homeurl = "";
|
||||
if (auto homeurlDatum = tomlData["displayURL"].as_string()) {
|
||||
homeurl = QString::fromStdString(homeurlDatum->get());
|
||||
} else if (auto homeurlDatum = (*modsTable)["displayURL"].as_string()) {
|
||||
homeurl = QString::fromStdString(homeurlDatum->get());
|
||||
} else if (auto homeurlDatumMods = (*modsTable)["displayURL"].as_string()) {
|
||||
homeurl = QString::fromStdString(homeurlDatumMods->get());
|
||||
}
|
||||
// fix up url.
|
||||
if (!homeurl.isEmpty() && !homeurl.startsWith("http://") && !homeurl.startsWith("https://") && !homeurl.startsWith("ftp://")) {
|
||||
@ -173,16 +174,16 @@ ModDetails ReadMCModTOML(QByteArray contents)
|
||||
QString issueTrackerURL = "";
|
||||
if (auto issueTrackerURLDatum = tomlData["issueTrackerURL"].as_string()) {
|
||||
issueTrackerURL = QString::fromStdString(issueTrackerURLDatum->get());
|
||||
} else if (auto issueTrackerURLDatum = (*modsTable)["issueTrackerURL"].as_string()) {
|
||||
issueTrackerURL = QString::fromStdString(issueTrackerURLDatum->get());
|
||||
} else if (auto issueTrackerURLDatumMods = (*modsTable)["issueTrackerURL"].as_string()) {
|
||||
issueTrackerURL = QString::fromStdString(issueTrackerURLDatumMods->get());
|
||||
}
|
||||
details.issue_tracker = issueTrackerURL;
|
||||
|
||||
QString license = "";
|
||||
if (auto licenseDatum = tomlData["license"].as_string()) {
|
||||
license = QString::fromStdString(licenseDatum->get());
|
||||
} else if (auto licenseDatum = (*modsTable)["license"].as_string()) {
|
||||
license = QString::fromStdString(licenseDatum->get());
|
||||
} else if (auto licenseDatumMods = (*modsTable)["license"].as_string()) {
|
||||
license = QString::fromStdString(licenseDatumMods->get());
|
||||
}
|
||||
if (!license.isEmpty())
|
||||
details.licenses.append(ModLicense(license));
|
||||
@ -190,8 +191,8 @@ ModDetails ReadMCModTOML(QByteArray contents)
|
||||
QString logoFile = "";
|
||||
if (auto logoFileDatum = tomlData["logoFile"].as_string()) {
|
||||
logoFile = QString::fromStdString(logoFileDatum->get());
|
||||
} else if (auto logoFileDatum = (*modsTable)["logoFile"].as_string()) {
|
||||
logoFile = QString::fromStdString(logoFileDatum->get());
|
||||
} else if (auto logoFileDatumMods = (*modsTable)["logoFile"].as_string()) {
|
||||
logoFile = QString::fromStdString(logoFileDatumMods->get());
|
||||
}
|
||||
details.icon_file = logoFile;
|
||||
|
||||
@ -458,7 +459,7 @@ bool process(Mod& mod, ProcessingLevel level)
|
||||
}
|
||||
}
|
||||
|
||||
bool processZIP(Mod& mod, ProcessingLevel level)
|
||||
bool processZIP(Mod& mod, [[maybe_unused]] ProcessingLevel level)
|
||||
{
|
||||
ModDetails details;
|
||||
|
||||
@ -591,7 +592,7 @@ bool processZIP(Mod& mod, ProcessingLevel level)
|
||||
return false; // no valid mod found in archive
|
||||
}
|
||||
|
||||
bool processFolder(Mod& mod, ProcessingLevel level)
|
||||
bool processFolder(Mod& mod, [[maybe_unused]] ProcessingLevel level)
|
||||
{
|
||||
ModDetails details;
|
||||
|
||||
@ -612,7 +613,7 @@ bool processFolder(Mod& mod, ProcessingLevel level)
|
||||
return false; // no valid mcmod.info file found
|
||||
}
|
||||
|
||||
bool processLitemod(Mod& mod, ProcessingLevel level)
|
||||
bool processLitemod(Mod& mod, [[maybe_unused]] ProcessingLevel level)
|
||||
{
|
||||
ModDetails details;
|
||||
|
||||
|
@ -178,7 +178,7 @@ bool processZIP(ResourcePack& pack, ProcessingLevel level)
|
||||
return true;
|
||||
}
|
||||
|
||||
// https://minecraft.fandom.com/wiki/Tutorials/Creating_a_resource_pack#Formatting_pack.mcmeta
|
||||
// https://minecraft.wiki/w/Tutorials/Creating_a_resource_pack#Formatting_pack.mcmeta
|
||||
bool processMCMeta(ResourcePack& pack, QByteArray&& raw_data)
|
||||
{
|
||||
try {
|
||||
|
@ -122,7 +122,7 @@ void ModFolderLoadTask::getFromMetadata()
|
||||
auto metadata = Metadata::get(m_index_dir, entry);
|
||||
|
||||
if (!metadata.isValid()) {
|
||||
return;
|
||||
continue;
|
||||
}
|
||||
|
||||
auto* mod = new Mod(m_mods_dir, metadata);
|
||||
|
@ -42,7 +42,7 @@
|
||||
|
||||
CapeChange::CapeChange(QObject* parent, QString token, QString cape) : Task(parent), m_capeId(cape), m_token(token) {}
|
||||
|
||||
void CapeChange::setCape(QString& cape)
|
||||
void CapeChange::setCape([[maybe_unused]] QString& cape)
|
||||
{
|
||||
QNetworkRequest request(QUrl("https://api.minecraftservices.com/minecraft/profile/capes/active"));
|
||||
auto requestString = QString("{\"capeId\":\"%1\"}").arg(m_capeId);
|
||||
|
@ -7,6 +7,8 @@
|
||||
|
||||
#include "Application.h"
|
||||
|
||||
#include "net/ApiDownload.h"
|
||||
|
||||
AssetUpdateTask::AssetUpdateTask(MinecraftInstance* inst)
|
||||
{
|
||||
m_inst = inst;
|
||||
@ -29,7 +31,7 @@ void AssetUpdateTask::executeTask()
|
||||
entry->setStale(true);
|
||||
auto hexSha1 = assets->sha1.toLatin1();
|
||||
qDebug() << "Asset index SHA1:" << hexSha1;
|
||||
auto dl = Net::Download::makeCached(indexUrl, entry);
|
||||
auto dl = Net::ApiDownload::makeCached(indexUrl, entry);
|
||||
auto rawSha1 = QByteArray::fromHex(assets->sha1.toLatin1());
|
||||
dl->addValidator(new Net::ChecksumValidator(QCryptographicHash::Sha1, rawSha1));
|
||||
job->addNetAction(dl);
|
||||
|
@ -8,6 +8,8 @@
|
||||
#include "Application.h"
|
||||
#include "BuildConfig.h"
|
||||
|
||||
#include "net/ApiDownload.h"
|
||||
|
||||
FMLLibrariesTask::FMLLibrariesTask(MinecraftInstance* inst)
|
||||
{
|
||||
m_inst = inst;
|
||||
@ -62,7 +64,7 @@ void FMLLibrariesTask::executeTask()
|
||||
for (auto& lib : fmlLibsToProcess) {
|
||||
auto entry = metacache->resolveEntry("fmllibs", lib.filename);
|
||||
QString urlString = BuildConfig.FMLLIBS_BASE_URL + lib.filename;
|
||||
dljob->addNetAction(Net::Download::makeCached(QUrl(urlString), entry, options));
|
||||
dljob->addNetAction(Net::ApiDownload::makeCached(QUrl(urlString), entry, options));
|
||||
}
|
||||
|
||||
connect(dljob.get(), &NetJob::succeeded, this, &FMLLibrariesTask::fmllibsFinished);
|
||||
|
Reference in New Issue
Block a user