id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
29,104
OverrideUtils.cpp
PrismLauncher_PrismLauncher/launcher/modplatform/helpers/OverrideUtils.cpp
#include "OverrideUtils.h" #include <QDirIterator> #include "FileSystem.h" namespace Override { void createOverrides(const QString& name, const QString& parent_folder, const QString& override_path) { QString file_path(FS::PathCombine(parent_folder, name + ".txt")); if (QFile::exists(file_path)) FS::deletePath(file_path); FS::ensureFilePathExists(file_path); QFile file(file_path); file.open(QFile::WriteOnly); QDirIterator override_iterator(override_path, QDirIterator::Subdirectories); while (override_iterator.hasNext()) { auto override_file_path = override_iterator.next(); QFileInfo info(override_file_path); if (info.isFile()) { // Absolute path with temp directory -> relative path override_file_path = override_file_path.split(name).last().remove(0, 1); file.write(override_file_path.toUtf8()); file.write("\n"); } } file.close(); } QStringList readOverrides(const QString& name, const QString& parent_folder) { QString file_path(FS::PathCombine(parent_folder, name + ".txt")); QFile file(file_path); if (!file.exists()) return {}; QStringList previous_overrides; file.open(QFile::ReadOnly); QString entry; do { entry = file.readLine(); previous_overrides.append(entry.trimmed()); } while (!entry.isEmpty()); file.close(); return previous_overrides; } } // namespace Override
1,491
C++
.cpp
42
29.619048
101
0.671089
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,105
HashUtils.cpp
PrismLauncher_PrismLauncher/launcher/modplatform/helpers/HashUtils.cpp
#include "HashUtils.h" #include <QBuffer> #include <QDebug> #include <QFile> #include <QtConcurrentRun> #include <MurmurHash2.h> namespace Hashing { Hasher::Ptr createHasher(QString file_path, ModPlatform::ResourceProvider provider) { switch (provider) { case ModPlatform::ResourceProvider::MODRINTH: return makeShared<Hasher>(file_path, ModPlatform::ProviderCapabilities::hashType(ModPlatform::ResourceProvider::MODRINTH).first()); case ModPlatform::ResourceProvider::FLAME: return makeShared<Hasher>(file_path, Algorithm::Murmur2); default: qCritical() << "[Hashing]" << "Unrecognized mod platform!"; return nullptr; } } Hasher::Ptr createHasher(QString file_path, QString type) { return makeShared<Hasher>(file_path, type); } class QIODeviceReader : public Murmur2::Reader { public: QIODeviceReader(QIODevice* device) : m_device(device) {} virtual ~QIODeviceReader() = default; virtual int read(char* s, int n) { return m_device->read(s, n); } virtual bool eof() { return m_device->atEnd(); } virtual void goToBeginning() { m_device->seek(0); } virtual void close() { m_device->close(); } private: QIODevice* m_device; }; QString algorithmToString(Algorithm type) { switch (type) { case Algorithm::Md4: return "md4"; case Algorithm::Md5: return "md5"; case Algorithm::Sha1: return "sha1"; case Algorithm::Sha256: return "sha256"; case Algorithm::Sha512: return "sha512"; case Algorithm::Murmur2: return "murmur2"; // case Algorithm::Unknown: default: break; } return "unknown"; } Algorithm algorithmFromString(QString type) { if (type == "md4") return Algorithm::Md4; if (type == "md5") return Algorithm::Md5; if (type == "sha1") return Algorithm::Sha1; if (type == "sha256") return Algorithm::Sha256; if (type == "sha512") return Algorithm::Sha512; if (type == "murmur2") return Algorithm::Murmur2; return Algorithm::Unknown; } QString hash(QIODevice* device, Algorithm type) { if (!device->isOpen() && !device->open(QFile::ReadOnly)) return ""; QCryptographicHash::Algorithm alg = QCryptographicHash::Sha1; switch (type) { case Algorithm::Md4: alg = QCryptographicHash::Algorithm::Md4; break; case Algorithm::Md5: alg = QCryptographicHash::Algorithm::Md5; break; case Algorithm::Sha1: alg = QCryptographicHash::Algorithm::Sha1; break; case Algorithm::Sha256: alg = QCryptographicHash::Algorithm::Sha256; break; case Algorithm::Sha512: alg = QCryptographicHash::Algorithm::Sha512; break; case Algorithm::Murmur2: { // CF-specific auto should_filter_out = [](char c) { return (c == 9 || c == 10 || c == 13 || c == 32); }; auto reader = std::make_unique<QIODeviceReader>(device); auto result = QString::number(Murmur2::hash(reader.get(), 4 * MiB, should_filter_out)); device->close(); return result; } case Algorithm::Unknown: device->close(); return ""; } QCryptographicHash hash(alg); if (!hash.addData(device)) qCritical() << "Failed to read JAR to create hash!"; Q_ASSERT(hash.result().length() == hash.hashLength(alg)); auto result = hash.result().toHex(); device->close(); return result; } QString hash(QString fileName, Algorithm type) { QFile file(fileName); return hash(&file, type); } QString hash(QByteArray data, Algorithm type) { QBuffer buff(&data); return hash(&buff, type); } void Hasher::executeTask() { m_future = QtConcurrent::run( QThreadPool::globalInstance(), [](QString fileName, Algorithm type) { return hash(fileName, type); }, m_path, m_alg); connect(&m_watcher, &QFutureWatcher<QString>::finished, this, [this] { if (m_future.isCanceled()) { emitAborted(); } else if (m_result = m_future.result(); m_result.isEmpty()) { emitFailed("Empty hash!"); } else { emitSucceeded(); emit resultsReady(m_result); } }); m_watcher.setFuture(m_future); } bool Hasher::abort() { if (m_future.isRunning()) { m_future.cancel(); // NOTE: Here we don't do `emitAborted()` because it will be done when `m_build_zip_future` actually cancels, which may not // occur immediately. return true; } return false; } } // namespace Hashing
4,838
C++
.cpp
149
25.456376
132
0.610957
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,106
FlamePackIndex.cpp
PrismLauncher_PrismLauncher/launcher/modplatform/flame/FlamePackIndex.cpp
#include "FlamePackIndex.h" #include <QFileInfo> #include <QUrl> #include "Json.h" #include "modplatform/ModIndex.h" void Flame::loadIndexedPack(Flame::IndexedPack& pack, QJsonObject& obj) { pack.addonId = Json::requireInteger(obj, "id"); pack.name = Json::requireString(obj, "name"); pack.description = Json::ensureString(obj, "summary", ""); auto logo = Json::requireObject(obj, "logo"); pack.logoUrl = Json::requireString(logo, "thumbnailUrl"); pack.logoName = Json::requireString(obj, "slug") + "." + QFileInfo(QUrl(pack.logoUrl).fileName()).suffix(); auto authors = Json::requireArray(obj, "authors"); for (auto authorIter : authors) { auto author = Json::requireObject(authorIter); Flame::ModpackAuthor packAuthor; packAuthor.name = Json::requireString(author, "name"); packAuthor.url = Json::requireString(author, "url"); pack.authors.append(packAuthor); } int defaultFileId = Json::requireInteger(obj, "mainFileId"); bool found = false; // check if there are some files before adding the pack auto files = Json::requireArray(obj, "latestFiles"); for (auto fileIter : files) { auto file = Json::requireObject(fileIter); int id = Json::requireInteger(file, "id"); // NOTE: for now, ignore everything that's not the default... if (id != defaultFileId) { continue; } auto versionArray = Json::requireArray(file, "gameVersions"); if (versionArray.size() < 1) { continue; } found = true; break; } if (!found) { throw JSONValidationError(QString("Pack with no good file, skipping: %1").arg(pack.name)); } loadIndexedInfo(pack, obj); } void Flame::loadIndexedInfo(IndexedPack& pack, QJsonObject& obj) { auto links_obj = Json::ensureObject(obj, "links"); pack.extra.websiteUrl = Json::ensureString(links_obj, "websiteUrl"); if (pack.extra.websiteUrl.endsWith('/')) pack.extra.websiteUrl.chop(1); pack.extra.issuesUrl = Json::ensureString(links_obj, "issuesUrl"); if (pack.extra.issuesUrl.endsWith('/')) pack.extra.issuesUrl.chop(1); pack.extra.sourceUrl = Json::ensureString(links_obj, "sourceUrl"); if (pack.extra.sourceUrl.endsWith('/')) pack.extra.sourceUrl.chop(1); pack.extra.wikiUrl = Json::ensureString(links_obj, "wikiUrl"); if (pack.extra.wikiUrl.endsWith('/')) pack.extra.wikiUrl.chop(1); pack.extraInfoLoaded = true; } void Flame::loadIndexedPackVersions(Flame::IndexedPack& pack, QJsonArray& arr) { QVector<Flame::IndexedVersion> unsortedVersions; for (auto versionIter : arr) { auto version = Json::requireObject(versionIter); Flame::IndexedVersion file; file.addonId = pack.addonId; file.fileId = Json::requireInteger(version, "id"); auto versionArray = Json::requireArray(version, "gameVersions"); if (versionArray.size() < 1) { continue; } for (auto mcVer : versionArray) { auto str = mcVer.toString(); if (str.contains('.')) file.mcVersion.append(str); if (auto loader = str.toLower(); loader == "neoforge") file.loaders |= ModPlatform::NeoForge; else if (loader == "forge") file.loaders |= ModPlatform::Forge; else if (loader == "cauldron") file.loaders |= ModPlatform::Cauldron; else if (loader == "liteloader") file.loaders |= ModPlatform::LiteLoader; else if (loader == "fabric") file.loaders |= ModPlatform::Fabric; else if (loader == "quilt") file.loaders |= ModPlatform::Quilt; } // pick the latest version supported file.version = Json::requireString(version, "displayName"); ModPlatform::IndexedVersionType::VersionType ver_type; switch (Json::requireInteger(version, "releaseType")) { case 1: ver_type = ModPlatform::IndexedVersionType::VersionType::Release; break; case 2: ver_type = ModPlatform::IndexedVersionType::VersionType::Beta; break; case 3: ver_type = ModPlatform::IndexedVersionType::VersionType::Alpha; break; default: ver_type = ModPlatform::IndexedVersionType::VersionType::Unknown; } file.version_type = ModPlatform::IndexedVersionType(ver_type); file.downloadUrl = Json::ensureString(version, "downloadUrl"); // only add if we have a download URL (third party distribution is enabled) if (!file.downloadUrl.isEmpty()) { unsortedVersions.append(file); } } auto orderSortPredicate = [](const IndexedVersion& a, const IndexedVersion& b) -> bool { return a.fileId > b.fileId; }; std::sort(unsortedVersions.begin(), unsortedVersions.end(), orderSortPredicate); pack.versions = unsortedVersions; pack.versionsLoaded = true; }
5,155
C++
.cpp
118
35.127119
123
0.631159
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,107
FlameCheckUpdate.cpp
PrismLauncher_PrismLauncher/launcher/modplatform/flame/FlameCheckUpdate.cpp
#include "FlameCheckUpdate.h" #include "Application.h" #include "FlameAPI.h" #include "FlameModIndex.h" #include <MurmurHash2.h> #include <memory> #include "Json.h" #include "ResourceDownloadTask.h" #include "minecraft/mod/ModFolderModel.h" #include "minecraft/mod/tasks/GetModDependenciesTask.h" #include "net/ApiDownload.h" static FlameAPI api; bool FlameCheckUpdate::abort() { m_was_aborted = true; if (m_net_job) return m_net_job->abort(); return true; } ModPlatform::IndexedPack FlameCheckUpdate::getProjectInfo(ModPlatform::IndexedVersion& ver_info) { ModPlatform::IndexedPack pack; QEventLoop loop; auto get_project_job = new NetJob("Flame::GetProjectJob", APPLICATION->network()); auto response = std::make_shared<QByteArray>(); auto url = QString("https://api.curseforge.com/v1/mods/%1").arg(ver_info.addonId.toString()); auto dl = Net::ApiDownload::makeByteArray(url, response); get_project_job->addNetAction(dl); QObject::connect(get_project_job, &NetJob::succeeded, [response, &pack]() { QJsonParseError parse_error{}; QJsonDocument doc = QJsonDocument::fromJson(*response, &parse_error); if (parse_error.error != QJsonParseError::NoError) { qWarning() << "Error while parsing JSON response from FlameCheckUpdate at " << parse_error.offset << " reason: " << parse_error.errorString(); qWarning() << *response; return; } try { auto doc_obj = Json::requireObject(doc); auto data_obj = Json::requireObject(doc_obj, "data"); FlameMod::loadIndexedPack(pack, data_obj); } catch (Json::JsonException& e) { qWarning() << e.cause(); qDebug() << doc; } }); connect(get_project_job, &NetJob::failed, this, &FlameCheckUpdate::emitFailed); QObject::connect(get_project_job, &NetJob::finished, [&loop, get_project_job] { get_project_job->deleteLater(); loop.quit(); }); get_project_job->start(); loop.exec(); return pack; } ModPlatform::IndexedVersion FlameCheckUpdate::getFileInfo(int addonId, int fileId) { ModPlatform::IndexedVersion ver; QEventLoop loop; auto get_file_info_job = new NetJob("Flame::GetFileInfoJob", APPLICATION->network()); auto response = std::make_shared<QByteArray>(); auto url = QString("https://api.curseforge.com/v1/mods/%1/files/%2").arg(QString::number(addonId), QString::number(fileId)); auto dl = Net::ApiDownload::makeByteArray(url, response); get_file_info_job->addNetAction(dl); QObject::connect(get_file_info_job, &NetJob::succeeded, [response, &ver]() { QJsonParseError parse_error{}; QJsonDocument doc = QJsonDocument::fromJson(*response, &parse_error); if (parse_error.error != QJsonParseError::NoError) { qWarning() << "Error while parsing JSON response from FlameCheckUpdate at " << parse_error.offset << " reason: " << parse_error.errorString(); qWarning() << *response; return; } try { auto doc_obj = Json::requireObject(doc); auto data_obj = Json::requireObject(doc_obj, "data"); ver = FlameMod::loadIndexedPackVersion(data_obj); } catch (Json::JsonException& e) { qWarning() << e.cause(); qDebug() << doc; } }); connect(get_file_info_job, &NetJob::failed, this, &FlameCheckUpdate::emitFailed); QObject::connect(get_file_info_job, &NetJob::finished, [&loop, get_file_info_job] { get_file_info_job->deleteLater(); loop.quit(); }); get_file_info_job->start(); loop.exec(); return ver; } /* Check for update: * - Get latest version available * - Compare hash of the latest version with the current hash * - If equal, no updates, else, there's updates, so add to the list * */ void FlameCheckUpdate::executeTask() { setStatus(tr("Preparing resources for CurseForge...")); int i = 0; for (auto* resource : m_resources) { setStatus(tr("Getting API response from CurseForge for '%1'...").arg(resource->name())); setProgress(i++, m_resources.size()); auto latest_vers = api.getLatestVersions({ { resource->metadata()->project_id.toString() }, m_game_versions }); // Check if we were aborted while getting the latest version if (m_was_aborted) { aborted(); return; } auto latest_ver = api.getLatestVersion(latest_vers, m_loaders_list, resource->metadata()->loaders); setStatus(tr("Parsing the API response from CurseForge for '%1'...").arg(resource->name())); if (!latest_ver.has_value() || !latest_ver->addonId.isValid()) { QString reason; if (dynamic_cast<Mod*>(resource) != nullptr) reason = tr("No valid version found for this resource. It's probably unavailable for the current game " "version / mod loader."); else reason = tr("No valid version found for this resource. It's probably unavailable for the current game version."); emit checkFailed(resource, reason); continue; } if (latest_ver->downloadUrl.isEmpty() && latest_ver->fileId != resource->metadata()->file_id) { auto pack = getProjectInfo(latest_ver.value()); auto recover_url = QString("%1/download/%2").arg(pack.websiteUrl, latest_ver->fileId.toString()); emit checkFailed(resource, tr("Resource has a new update available, but is not downloadable using CurseForge."), recover_url); continue; } // Fake pack with the necessary info to pass to the download task :) auto pack = std::make_shared<ModPlatform::IndexedPack>(); pack->name = resource->name(); pack->slug = resource->metadata()->slug; pack->addonId = resource->metadata()->project_id; pack->provider = ModPlatform::ResourceProvider::FLAME; if (!latest_ver->hash.isEmpty() && (resource->metadata()->hash != latest_ver->hash || resource->status() == ResourceStatus::NOT_INSTALLED)) { auto old_version = resource->metadata()->version_number; if (old_version.isEmpty()) { if (resource->status() == ResourceStatus::NOT_INSTALLED) old_version = tr("Not installed"); else old_version = tr("Unknown"); } auto download_task = makeShared<ResourceDownloadTask>(pack, latest_ver.value(), m_resource_model); m_updates.emplace_back(pack->name, resource->metadata()->hash, old_version, latest_ver->version, latest_ver->version_type, api.getModFileChangelog(latest_ver->addonId.toInt(), latest_ver->fileId.toInt()), ModPlatform::ResourceProvider::FLAME, download_task, resource->enabled()); } m_deps.append(std::make_shared<GetModDependenciesTask::PackDependency>(pack, latest_ver.value())); } emitSucceeded(); }
7,228
C++
.cpp
152
38.848684
138
0.629119
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,108
PackManifest.cpp
PrismLauncher_PrismLauncher/launcher/modplatform/flame/PackManifest.cpp
#include "PackManifest.h" #include "Json.h" static void loadFileV1(Flame::File& f, QJsonObject& file) { f.projectId = Json::requireInteger(file, "projectID"); f.fileId = Json::requireInteger(file, "fileID"); f.required = Json::ensureBoolean(file, QString("required"), true); } static void loadModloaderV1(Flame::Modloader& m, QJsonObject& modLoader) { m.id = Json::requireString(modLoader, "id"); m.primary = Json::ensureBoolean(modLoader, QString("primary"), false); } static void loadMinecraftV1(Flame::Minecraft& m, QJsonObject& minecraft) { m.version = Json::requireString(minecraft, "version"); // extra libraries... apparently only used for a custom Minecraft launcher in the 1.2.5 FTB retro pack // intended use is likely hardcoded in the 'Flame' client, the manifest says nothing m.libraries = Json::ensureString(minecraft, QString("libraries"), QString()); auto arr = Json::ensureArray(minecraft, "modLoaders", QJsonArray()); for (QJsonValueRef item : arr) { auto obj = Json::requireObject(item); Flame::Modloader loader; loadModloaderV1(loader, obj); m.modLoaders.append(loader); } } static void loadManifestV1(Flame::Manifest& pack, QJsonObject& manifest) { auto mc = Json::requireObject(manifest, "minecraft"); loadMinecraftV1(pack.minecraft, mc); pack.name = Json::ensureString(manifest, QString("name"), "Unnamed"); pack.version = Json::ensureString(manifest, QString("version"), QString()); pack.author = Json::ensureString(manifest, QString("author"), "Anonymous"); auto arr = Json::ensureArray(manifest, "files", QJsonArray()); for (auto item : arr) { auto obj = Json::requireObject(item); Flame::File file; loadFileV1(file, obj); pack.files.insert(file.fileId, file); } pack.overrides = Json::ensureString(manifest, "overrides", "overrides"); pack.is_loaded = true; } void Flame::loadManifest(Flame::Manifest& m, const QString& filepath) { auto doc = Json::requireDocument(filepath); auto obj = Json::requireObject(doc); m.manifestType = Json::requireString(obj, "manifestType"); if (m.manifestType != "minecraftModpack") { throw JSONValidationError("Not a modpack manifest!"); } m.manifestVersion = Json::requireInteger(obj, "manifestVersion"); if (m.manifestVersion != 1) { throw JSONValidationError(QString("Unknown manifest version (%1)").arg(m.manifestVersion)); } loadManifestV1(m, obj); }
2,530
C++
.cpp
58
38.896552
106
0.70122
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,109
FlamePackExportTask.cpp
PrismLauncher_PrismLauncher/launcher/modplatform/flame/FlamePackExportTask.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me> * Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "FlamePackExportTask.h" #include <QJsonArray> #include <QJsonObject> #include <QCryptographicHash> #include <QFileInfo> #include <QMessageBox> #include <QtConcurrentRun> #include <algorithm> #include <iterator> #include <memory> #include "Application.h" #include "Json.h" #include "MMCZip.h" #include "minecraft/PackProfile.h" #include "minecraft/mod/ModFolderModel.h" #include "modplatform/ModIndex.h" #include "modplatform/flame/FlameModIndex.h" #include "modplatform/helpers/HashUtils.h" #include "tasks/Task.h" const QString FlamePackExportTask::TEMPLATE = "<li><a href=\"{url}\">{name}{authors}</a></li>\n"; const QStringList FlamePackExportTask::FILE_EXTENSIONS({ "jar", "zip" }); FlamePackExportTask::FlamePackExportTask(const QString& name, const QString& version, const QString& author, bool optionalFiles, InstancePtr instance, const QString& output, MMCZip::FilterFunction filter) : name(name) , version(version) , author(author) , optionalFiles(optionalFiles) , instance(instance) , mcInstance(dynamic_cast<MinecraftInstance*>(instance.get())) , gameRoot(instance->gameRoot()) , output(output) , filter(filter) {} void FlamePackExportTask::executeTask() { setStatus(tr("Searching for files...")); setProgress(0, 5); collectFiles(); } bool FlamePackExportTask::abort() { if (task) { task->abort(); emitAborted(); return true; } return false; } void FlamePackExportTask::collectFiles() { setAbortable(false); QCoreApplication::processEvents(); files.clear(); if (!MMCZip::collectFileListRecursively(instance->gameRoot(), nullptr, &files, filter)) { emitFailed(tr("Could not search for files")); return; } pendingHashes.clear(); resolvedFiles.clear(); if (mcInstance != nullptr) { mcInstance->loaderModList()->update(); connect(mcInstance->loaderModList().get(), &ModFolderModel::updateFinished, this, &FlamePackExportTask::collectHashes); } else collectHashes(); } void FlamePackExportTask::collectHashes() { setAbortable(true); setStatus(tr("Finding file hashes...")); setProgress(1, 5); auto allMods = mcInstance->loaderModList()->allMods(); ConcurrentTask::Ptr hashingTask(new ConcurrentTask("MakeHashesTask", APPLICATION->settings()->get("NumberOfConcurrentTasks").toInt())); task.reset(hashingTask); for (const QFileInfo& file : files) { const QString relative = gameRoot.relativeFilePath(file.absoluteFilePath()); // require sensible file types if (!std::any_of(FILE_EXTENSIONS.begin(), FILE_EXTENSIONS.end(), [&relative](const QString& extension) { return relative.endsWith('.' + extension) || relative.endsWith('.' + extension + ".disabled"); })) continue; if (relative.startsWith("resourcepacks/") && (relative.endsWith(".zip") || relative.endsWith(".zip.disabled"))) { // is resourcepack auto hashTask = Hashing::createHasher(file.absoluteFilePath(), ModPlatform::ResourceProvider::FLAME); connect(hashTask.get(), &Hashing::Hasher::resultsReady, [this, relative, file](QString hash) { if (m_state == Task::State::Running) { pendingHashes.insert(hash, { relative, file.absoluteFilePath(), relative.endsWith(".zip") }); } }); connect(hashTask.get(), &Task::failed, this, &FlamePackExportTask::emitFailed); hashingTask->addTask(hashTask); continue; } if (auto modIter = std::find_if(allMods.begin(), allMods.end(), [&file](Mod* mod) { return mod->fileinfo() == file; }); modIter != allMods.end()) { const Mod* mod = *modIter; if (!mod || mod->type() == ResourceType::FOLDER) { continue; } if (mod->metadata() && mod->metadata()->provider == ModPlatform::ResourceProvider::FLAME) { resolvedFiles.insert(mod->fileinfo().absoluteFilePath(), { mod->metadata()->project_id.toInt(), mod->metadata()->file_id.toInt(), mod->enabled(), true, mod->metadata()->name, mod->metadata()->slug, mod->authors().join(", ") }); continue; } auto hashTask = Hashing::createHasher(mod->fileinfo().absoluteFilePath(), ModPlatform::ResourceProvider::FLAME); connect(hashTask.get(), &Hashing::Hasher::resultsReady, [this, mod](QString hash) { if (m_state == Task::State::Running) { pendingHashes.insert(hash, { mod->name(), mod->fileinfo().absoluteFilePath(), mod->enabled(), true }); } }); connect(hashTask.get(), &Task::failed, this, &FlamePackExportTask::emitFailed); hashingTask->addTask(hashTask); } } auto progressStep = std::make_shared<TaskStepProgress>(); connect(hashingTask.get(), &Task::finished, this, [this, progressStep] { progressStep->state = TaskStepState::Succeeded; stepProgress(*progressStep); }); connect(hashingTask.get(), &Task::succeeded, this, &FlamePackExportTask::makeApiRequest); connect(hashingTask.get(), &Task::failed, this, [this, progressStep](QString reason) { progressStep->state = TaskStepState::Failed; stepProgress(*progressStep); emitFailed(reason); }); connect(hashingTask.get(), &Task::stepProgress, this, &FlamePackExportTask::propagateStepProgress); connect(hashingTask.get(), &Task::progress, this, [this, progressStep](qint64 current, qint64 total) { progressStep->update(current, total); stepProgress(*progressStep); }); connect(hashingTask.get(), &Task::status, this, [this, progressStep](QString status) { progressStep->status = status; stepProgress(*progressStep); }); hashingTask->start(); } void FlamePackExportTask::makeApiRequest() { if (pendingHashes.isEmpty()) { buildZip(); return; } setStatus(tr("Finding versions for hashes...")); setProgress(2, 5); auto response = std::make_shared<QByteArray>(); QList<uint> fingerprints; for (auto& murmur : pendingHashes.keys()) { fingerprints.push_back(murmur.toUInt()); } task.reset(api.matchFingerprints(fingerprints, response)); connect(task.get(), &Task::succeeded, this, [this, response] { QJsonParseError parseError{}; QJsonDocument doc = QJsonDocument::fromJson(*response, &parseError); if (parseError.error != QJsonParseError::NoError) { qWarning() << "Error while parsing JSON response from CurseForge::CurrentVersions at " << parseError.offset << " reason: " << parseError.errorString(); qWarning() << *response; emitFailed(parseError.errorString()); return; } try { auto docObj = Json::requireObject(doc); auto dataObj = Json::requireObject(docObj, "data"); auto dataArr = Json::requireArray(dataObj, "exactMatches"); if (dataArr.isEmpty()) { qWarning() << "No matches found for fingerprint search!"; getProjectsInfo(); return; } for (auto match : dataArr) { auto matchObj = Json::ensureObject(match, {}); auto fileObj = Json::ensureObject(matchObj, "file", {}); if (matchObj.isEmpty() || fileObj.isEmpty()) { qWarning() << "Fingerprint match is empty!"; return; } auto fingerprint = QString::number(Json::ensureVariant(fileObj, "fileFingerprint").toUInt()); auto mod = pendingHashes.find(fingerprint); if (mod == pendingHashes.end()) { qWarning() << "Invalid fingerprint from the API response."; continue; } setStatus(tr("Parsing API response from CurseForge for '%1'...").arg(mod->name)); if (Json::ensureBoolean(fileObj, "isAvailable", false, "isAvailable")) resolvedFiles.insert(mod->path, { Json::requireInteger(fileObj, "modId"), Json::requireInteger(fileObj, "id"), mod->enabled, mod->isMod }); } } catch (Json::JsonException& e) { qDebug() << e.cause(); qDebug() << doc; } pendingHashes.clear(); getProjectsInfo(); }); connect(task.get(), &Task::failed, this, &FlamePackExportTask::getProjectsInfo); task->start(); } void FlamePackExportTask::getProjectsInfo() { setStatus(tr("Finding project info from CurseForge...")); setProgress(3, 5); QStringList addonIds; for (const auto& resolved : resolvedFiles) { if (resolved.slug.isEmpty()) { addonIds << QString::number(resolved.addonId); } } auto response = std::make_shared<QByteArray>(); Task::Ptr projTask; if (addonIds.isEmpty()) { buildZip(); return; } else if (addonIds.size() == 1) { projTask = api.getProject(*addonIds.begin(), response); } else { projTask = api.getProjects(addonIds, response); } connect(projTask.get(), &Task::succeeded, this, [this, response, addonIds] { QJsonParseError parseError{}; auto doc = QJsonDocument::fromJson(*response, &parseError); if (parseError.error != QJsonParseError::NoError) { qWarning() << "Error while parsing JSON response from CurseForge projects task at " << parseError.offset << " reason: " << parseError.errorString(); qWarning() << *response; emitFailed(parseError.errorString()); return; } try { QJsonArray entries; if (addonIds.size() == 1) entries = { Json::requireObject(Json::requireObject(doc), "data") }; else entries = Json::requireArray(Json::requireObject(doc), "data"); for (auto entry : entries) { auto entryObj = Json::requireObject(entry); try { setStatus(tr("Parsing API response from CurseForge for '%1'...").arg(Json::requireString(entryObj, "name"))); ModPlatform::IndexedPack pack; FlameMod::loadIndexedPack(pack, entryObj); for (auto key : resolvedFiles.keys()) { auto val = resolvedFiles.value(key); if (val.addonId == pack.addonId) { val.name = pack.name; val.slug = pack.slug; QStringList authors; for (auto author : pack.authors) authors << author.name; val.authors = authors.join(", "); resolvedFiles[key] = val; } } } catch (Json::JsonException& e) { qDebug() << e.cause(); qDebug() << entries; } } } catch (Json::JsonException& e) { qDebug() << e.cause(); qDebug() << doc; } buildZip(); }); connect(projTask.get(), &Task::failed, this, &FlamePackExportTask::emitFailed); task.reset(projTask); task->start(); } void FlamePackExportTask::buildZip() { setStatus(tr("Adding files...")); setProgress(4, 5); auto zipTask = makeShared<MMCZip::ExportToZipTask>(output, gameRoot, files, "overrides/", true, false); zipTask->addExtraFile("manifest.json", generateIndex()); zipTask->addExtraFile("modlist.html", generateHTML()); QStringList exclude; std::transform(resolvedFiles.keyBegin(), resolvedFiles.keyEnd(), std::back_insert_iterator(exclude), [this](QString file) { return gameRoot.relativeFilePath(file); }); zipTask->setExcludeFiles(exclude); auto progressStep = std::make_shared<TaskStepProgress>(); connect(zipTask.get(), &Task::finished, this, [this, progressStep] { progressStep->state = TaskStepState::Succeeded; stepProgress(*progressStep); }); connect(zipTask.get(), &Task::succeeded, this, &FlamePackExportTask::emitSucceeded); connect(zipTask.get(), &Task::aborted, this, &FlamePackExportTask::emitAborted); connect(zipTask.get(), &Task::failed, this, [this, progressStep](QString reason) { progressStep->state = TaskStepState::Failed; stepProgress(*progressStep); emitFailed(reason); }); connect(zipTask.get(), &Task::stepProgress, this, &FlamePackExportTask::propagateStepProgress); connect(zipTask.get(), &Task::progress, this, [this, progressStep](qint64 current, qint64 total) { progressStep->update(current, total); stepProgress(*progressStep); }); connect(zipTask.get(), &Task::status, this, [this, progressStep](QString status) { progressStep->status = status; stepProgress(*progressStep); }); task.reset(zipTask); zipTask->start(); } QByteArray FlamePackExportTask::generateIndex() { QJsonObject obj; obj["manifestType"] = "minecraftModpack"; obj["manifestVersion"] = 1; obj["name"] = name; obj["version"] = version; obj["author"] = author; obj["overrides"] = "overrides"; if (mcInstance) { QJsonObject version; auto profile = mcInstance->getPackProfile(); // collect all supported components const ComponentPtr minecraft = profile->getComponent("net.minecraft"); const ComponentPtr quilt = profile->getComponent("org.quiltmc.quilt-loader"); const ComponentPtr fabric = profile->getComponent("net.fabricmc.fabric-loader"); const ComponentPtr forge = profile->getComponent("net.minecraftforge"); const ComponentPtr neoforge = profile->getComponent("net.neoforged"); // convert all available components to mrpack dependencies if (minecraft != nullptr) version["version"] = minecraft->m_version; QString id; if (quilt != nullptr) id = "quilt-" + quilt->m_version; else if (fabric != nullptr) id = "fabric-" + fabric->m_version; else if (forge != nullptr) id = "forge-" + forge->m_version; else if (neoforge != nullptr) { id = "neoforge-"; if (minecraft->m_version == "1.20.1") id += "1.20.1-"; id += neoforge->m_version; } version["modLoaders"] = QJsonArray(); if (!id.isEmpty()) { QJsonObject loader; loader["id"] = id; loader["primary"] = true; version["modLoaders"] = QJsonArray({ loader }); } obj["minecraft"] = version; } QJsonArray files; for (auto mod : resolvedFiles) { QJsonObject file; file["projectID"] = mod.addonId; file["fileID"] = mod.version; file["required"] = mod.enabled || !optionalFiles; files << file; } obj["files"] = files; return QJsonDocument(obj).toJson(QJsonDocument::Compact); } QByteArray FlamePackExportTask::generateHTML() { QString content = ""; for (auto mod : resolvedFiles) { if (mod.isMod) { content += QString(TEMPLATE) .replace("{name}", mod.name.toHtmlEscaped()) .replace("{url}", ModPlatform::getMetaURL(ModPlatform::ResourceProvider::FLAME, mod.addonId).toHtmlEscaped()) .replace("{authors}", !mod.authors.isEmpty() ? QString(" (by %1)").arg(mod.authors).toHtmlEscaped() : ""); } } content = "<ul>" + content + "</ul>"; return content.toUtf8(); }
17,155
C++
.cpp
392
34.048469
139
0.60055
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,110
FlameInstanceCreationTask.cpp
PrismLauncher_PrismLauncher/launcher/modplatform/flame/FlameInstanceCreationTask.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 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 "FlameInstanceCreationTask.h" #include "QObjectPtr.h" #include "minecraft/mod/tasks/LocalResourceUpdateTask.h" #include "modplatform/flame/FileResolvingTask.h" #include "modplatform/flame/FlameAPI.h" #include "modplatform/flame/FlameModIndex.h" #include "modplatform/flame/PackManifest.h" #include "Application.h" #include "FileSystem.h" #include "InstanceList.h" #include "Json.h" #include "minecraft/MinecraftInstance.h" #include "minecraft/PackProfile.h" #include "modplatform/helpers/OverrideUtils.h" #include "settings/INISettingsObject.h" #include "tasks/ConcurrentTask.h" #include "ui/dialogs/BlockedModsDialog.h" #include "ui/dialogs/CustomMessageBox.h" #include <QDebug> #include <QFileInfo> #include "meta/Index.h" #include "minecraft/World.h" #include "minecraft/mod/tasks/LocalResourceParse.h" #include "net/ApiDownload.h" #include "ui/pages/modplatform/OptionalModDialog.h" static const FlameAPI api; bool FlameCreationTask::abort() { if (!canAbort()) return false; m_abort = true; if (m_process_update_file_info_job) m_process_update_file_info_job->abort(); if (m_files_job) m_files_job->abort(); if (m_mod_id_resolver) m_mod_id_resolver->abort(); return Task::abort(); } bool FlameCreationTask::updateInstance() { auto instance_list = APPLICATION->instances(); // FIXME: How to handle situations when there's more than one install already for a given modpack? InstancePtr inst; if (auto original_id = originalInstanceID(); !original_id.isEmpty()) { inst = instance_list->getInstanceById(original_id); Q_ASSERT(inst); } else { inst = instance_list->getInstanceByManagedName(originalName()); if (!inst) { inst = instance_list->getInstanceById(originalName()); if (!inst) return false; } } QString index_path(FS::PathCombine(m_stagingPath, "manifest.json")); try { Flame::loadManifest(m_pack, index_path); } catch (const JSONValidationError& e) { setError(tr("Could not understand pack manifest:\n") + e.cause()); return false; } auto version_id = inst->getManagedPackVersionName(); auto version_str = !version_id.isEmpty() ? tr(" (version %1)").arg(version_id) : ""; if (shouldConfirmUpdate()) { auto should_update = askIfShouldUpdate(m_parent, version_str); if (should_update == ShouldUpdate::SkipUpdating) return false; if (should_update == ShouldUpdate::Cancel) { m_abort = true; return false; } } QDir old_inst_dir(inst->instanceRoot()); QString old_index_folder(FS::PathCombine(old_inst_dir.absolutePath(), "flame")); QString old_index_path(FS::PathCombine(old_index_folder, "manifest.json")); QFileInfo old_index_file(old_index_path); if (old_index_file.exists()) { Flame::Manifest old_pack; Flame::loadManifest(old_pack, old_index_path); auto& old_files = old_pack.files; auto& files = m_pack.files; // Remove repeated files, we don't need to download them! auto files_iterator = files.begin(); while (files_iterator != files.end()) { auto const& file = files_iterator; auto old_file = old_files.find(file.key()); if (old_file != old_files.end()) { // We found a match, but is it a different version? if (old_file->fileId == file->fileId) { qDebug() << "Removed file at" << file->targetFolder << "with id" << file->fileId << "from list of downloads"; old_files.remove(file.key()); files_iterator = files.erase(files_iterator); if (files_iterator != files.begin()) files_iterator--; } } files_iterator++; } QDir old_minecraft_dir(inst->gameRoot()); // We will remove all the previous overrides, to prevent duplicate files! // TODO: Currently 'overrides' will always override the stuff on update. How do we preserve unchanged overrides? // FIXME: We may want to do something about disabled mods. auto old_overrides = Override::readOverrides("overrides", old_index_folder); for (const auto& entry : old_overrides) { if (entry.isEmpty()) continue; qDebug() << "Scheduling" << entry << "for removal"; m_files_to_remove.append(old_minecraft_dir.absoluteFilePath(entry)); } // Remove remaining old files (we need to do an API request to know which ids are which files...) QStringList fileIds; for (auto& file : old_files) { fileIds.append(QString::number(file.fileId)); } auto raw_response = std::make_shared<QByteArray>(); auto job = api.getFiles(fileIds, raw_response); QEventLoop loop; connect(job.get(), &Task::succeeded, this, [this, raw_response, fileIds, old_inst_dir, &old_files, old_minecraft_dir] { // Parse the API response QJsonParseError parse_error{}; auto doc = QJsonDocument::fromJson(*raw_response, &parse_error); if (parse_error.error != QJsonParseError::NoError) { qWarning() << "Error while parsing JSON response from Flame files task at " << parse_error.offset << " reason: " << parse_error.errorString(); qWarning() << *raw_response; return; } try { QJsonArray entries; if (fileIds.size() == 1) entries = { Json::requireObject(Json::requireObject(doc), "data") }; else entries = Json::requireArray(Json::requireObject(doc), "data"); for (auto entry : entries) { auto entry_obj = Json::requireObject(entry); Flame::File file; // We don't care about blocked mods, we just need local data to delete the file file.version = FlameMod::loadIndexedPackVersion(entry_obj); auto id = Json::requireInteger(entry_obj, "id"); old_files.insert(id, file); } } catch (Json::JsonException& e) { qCritical() << e.cause() << e.what(); } // Delete the files for (auto& file : old_files) { if (file.version.fileName.isEmpty() || file.targetFolder.isEmpty()) continue; QString relative_path(FS::PathCombine(file.targetFolder, file.version.fileName)); qDebug() << "Scheduling" << relative_path << "for removal"; m_files_to_remove.append(old_minecraft_dir.absoluteFilePath(relative_path)); } }); connect(job.get(), &Task::failed, this, [](QString reason) { qCritical() << "Failed to get files: " << reason; }); connect(job.get(), &Task::finished, &loop, &QEventLoop::quit); m_process_update_file_info_job = job; job->start(); loop.exec(); m_process_update_file_info_job = nullptr; } else { // We don't have an old index file, so we may duplicate stuff! auto dialog = CustomMessageBox::selectable(m_parent, tr("No index file."), tr("We couldn't find a suitable index file for the older version. This may cause some " "of the files to be duplicated. Do you want to continue?"), QMessageBox::Warning, QMessageBox::Ok | QMessageBox::Cancel); if (dialog->exec() == QDialog::DialogCode::Rejected) { m_abort = true; return false; } } setOverride(true, inst->id()); qDebug() << "Will override instance!"; m_instance = inst; // We let it go through the createInstance() stage, just with a couple modifications for updating return false; } QString FlameCreationTask::getVersionForLoader(QString uid, QString loaderType, QString loaderVersion, QString mcVersion) { if (loaderVersion == "recommended") { auto vlist = APPLICATION->metadataIndex()->get(uid); if (!vlist) { setError(tr("Failed to get local metadata index for %1").arg(uid)); return {}; } if (!vlist->isLoaded()) { QEventLoop loadVersionLoop; auto task = vlist->getLoadTask(); connect(task.get(), &Task::finished, &loadVersionLoop, &QEventLoop::quit); if (!task->isRunning()) task->start(); loadVersionLoop.exec(); } for (auto version : vlist->versions()) { // first recommended build we find, we use. if (!version->isRecommended()) continue; auto reqs = version->requiredSet(); // filter by minecraft version, if the loader depends on a certain version. // not all mod loaders depend on a given Minecraft version, so we won't do this // filtering for those loaders. if (loaderType == "forge" || loaderType == "neoforge") { auto iter = std::find_if(reqs.begin(), reqs.end(), [mcVersion](const Meta::Require& req) { return req.uid == "net.minecraft" && req.equalsVersion == mcVersion; }); if (iter == reqs.end()) continue; } return version->descriptor(); } setError(tr("Failed to find version for %1 loader").arg(loaderType)); return {}; } if (loaderVersion.isEmpty()) { emitFailed(tr("No loader version set for modpack!")); return {}; } return loaderVersion; } bool FlameCreationTask::createInstance() { QEventLoop loop; QString parent_folder(FS::PathCombine(m_stagingPath, "flame")); try { QString index_path(FS::PathCombine(m_stagingPath, "manifest.json")); if (!m_pack.is_loaded) Flame::loadManifest(m_pack, index_path); // Keep index file in case we need it some other time (like when changing versions) QString new_index_place(FS::PathCombine(parent_folder, "manifest.json")); FS::ensureFilePathExists(new_index_place); FS::move(index_path, new_index_place); } catch (const JSONValidationError& e) { setError(tr("Could not understand pack manifest:\n") + e.cause()); return false; } if (!m_pack.overrides.isEmpty()) { QString overridePath = FS::PathCombine(m_stagingPath, m_pack.overrides); if (QFile::exists(overridePath)) { // Create a list of overrides in "overrides.txt" inside flame/ Override::createOverrides("overrides", parent_folder, overridePath); QString mcPath = FS::PathCombine(m_stagingPath, "minecraft"); if (!FS::move(overridePath, mcPath)) { setError(tr("Could not rename the overrides folder:\n") + m_pack.overrides); return false; } } else { logWarning( tr("The specified overrides folder (%1) is missing. Maybe the modpack was already used before?").arg(m_pack.overrides)); } } QString loaderType; QString loaderUid; QString loaderVersion; for (auto& loader : m_pack.minecraft.modLoaders) { auto id = loader.id; if (id.startsWith("neoforge-")) { id.remove("neoforge-"); if (id.startsWith("1.20.1-")) id.remove("1.20.1-"); // this is a mess for curseforge loaderType = "neoforge"; loaderUid = "net.neoforged"; } else if (id.startsWith("forge-")) { id.remove("forge-"); loaderType = "forge"; loaderUid = "net.minecraftforge"; } else if (id.startsWith("fabric-")) { id.remove("fabric-"); loaderType = "fabric"; loaderUid = "net.fabricmc.fabric-loader"; } else if (id.startsWith("quilt-")) { id.remove("quilt-"); loaderType = "quilt"; loaderUid = "org.quiltmc.quilt-loader"; } else { logWarning(tr("Unknown mod loader in manifest: %1").arg(id)); continue; } loaderVersion = id; } QString configPath = FS::PathCombine(m_stagingPath, "instance.cfg"); auto instanceSettings = std::make_shared<INISettingsObject>(configPath); MinecraftInstance instance(m_globalSettings, instanceSettings, m_stagingPath); auto mcVersion = m_pack.minecraft.version; // Hack to correct some 'special sauce'... if (mcVersion.endsWith('.')) { mcVersion.remove(QRegularExpression("[.]+$")); logWarning(tr("Mysterious trailing dots removed from Minecraft version while importing pack.")); } auto components = instance.getPackProfile(); components->buildingFromScratch(); components->setComponentVersion("net.minecraft", mcVersion, true); if (!loaderType.isEmpty()) { auto version = getVersionForLoader(loaderUid, loaderType, loaderVersion, mcVersion); if (version.isEmpty()) return false; components->setComponentVersion(loaderUid, version); } if (m_instIcon != "default") { instance.setIconKey(m_instIcon); } else { if (m_pack.name.contains("Direwolf20")) { instance.setIconKey("steve"); } else if (m_pack.name.contains("FTB") || m_pack.name.contains("Feed The Beast")) { instance.setIconKey("ftb_logo"); } else { instance.setIconKey("flame"); } } QString jarmodsPath = FS::PathCombine(m_stagingPath, "minecraft", "jarmods"); QFileInfo jarmodsInfo(jarmodsPath); if (jarmodsInfo.isDir()) { // install all the jar mods qDebug() << "Found jarmods:"; QDir jarmodsDir(jarmodsPath); QStringList jarMods; for (const auto& info : jarmodsDir.entryInfoList(QDir::NoDotAndDotDot | QDir::Files)) { qDebug() << info.fileName(); jarMods.push_back(info.absoluteFilePath()); } auto profile = instance.getPackProfile(); profile->installJarMods(jarMods); // nuke the original files FS::deletePath(jarmodsPath); } // Don't add managed info to packs without an ID (most likely imported from ZIP) if (!m_managed_id.isEmpty()) instance.setManagedPack("flame", m_managed_id, m_pack.name, m_managed_version_id, m_pack.version); else instance.setManagedPack("flame", "", name(), "", ""); instance.setName(name()); m_mod_id_resolver.reset(new Flame::FileResolvingTask(APPLICATION->network(), m_pack)); connect(m_mod_id_resolver.get(), &Flame::FileResolvingTask::succeeded, this, [this, &loop] { idResolverSucceeded(loop); }); connect(m_mod_id_resolver.get(), &Flame::FileResolvingTask::failed, [this, &loop](QString reason) { m_mod_id_resolver.reset(); setError(tr("Unable to resolve mod IDs:\n") + reason); loop.quit(); }); connect(m_mod_id_resolver.get(), &Flame::FileResolvingTask::aborted, &loop, &QEventLoop::quit); connect(m_mod_id_resolver.get(), &Flame::FileResolvingTask::progress, this, &FlameCreationTask::setProgress); connect(m_mod_id_resolver.get(), &Flame::FileResolvingTask::status, this, &FlameCreationTask::setStatus); connect(m_mod_id_resolver.get(), &Flame::FileResolvingTask::stepProgress, this, &FlameCreationTask::propagateStepProgress); connect(m_mod_id_resolver.get(), &Flame::FileResolvingTask::details, this, &FlameCreationTask::setDetails); m_mod_id_resolver->start(); loop.exec(); bool did_succeed = getError().isEmpty(); // Update information of the already installed instance, if any. if (m_instance && did_succeed) { setAbortable(false); auto inst = m_instance.value(); inst->copyManagedPack(instance); } return did_succeed; } void FlameCreationTask::idResolverSucceeded(QEventLoop& loop) { auto results = m_mod_id_resolver->getResults(); // first check for blocked mods QList<BlockedMod> blocked_mods; auto anyBlocked = false; for (const auto& result : results.files.values()) { if (result.version.fileName.endsWith(".zip")) { m_ZIP_resources.append(std::make_pair(result.version.fileName, result.targetFolder)); } if (result.version.downloadUrl.isEmpty()) { BlockedMod blocked_mod; blocked_mod.name = result.version.fileName; blocked_mod.websiteUrl = QString("%1/download/%2").arg(result.pack.websiteUrl, QString::number(result.fileId)); blocked_mod.hash = result.version.hash; blocked_mod.matched = false; blocked_mod.localPath = ""; blocked_mod.targetFolder = result.targetFolder; blocked_mods.append(blocked_mod); anyBlocked = true; } } if (anyBlocked) { qWarning() << "Blocked mods found, displaying mod list"; BlockedModsDialog message_dialog(m_parent, tr("Blocked mods found"), tr("The following files are not available for download in third party launchers.<br/>" "You will need to manually download them and add them to the instance."), blocked_mods); message_dialog.setModal(true); if (message_dialog.exec()) { qDebug() << "Post dialog blocked mods list: " << blocked_mods; copyBlockedMods(blocked_mods); setupDownloadJob(loop); } else { m_mod_id_resolver.reset(); setError("Canceled"); loop.quit(); } } else { setupDownloadJob(loop); } } void FlameCreationTask::setupDownloadJob(QEventLoop& loop) { m_files_job.reset(new NetJob(tr("Mod Download Flame"), APPLICATION->network())); auto results = m_mod_id_resolver->getResults().files; QStringList optionalFiles; for (auto& result : results) { if (!result.required) { optionalFiles << FS::PathCombine(result.targetFolder, result.version.fileName); } } QStringList selectedOptionalMods; if (!optionalFiles.empty()) { OptionalModDialog optionalModDialog(m_parent, optionalFiles); if (optionalModDialog.exec() == QDialog::Rejected) { emitAborted(); loop.quit(); return; } selectedOptionalMods = optionalModDialog.getResult(); } for (const auto& result : results) { auto fileName = result.version.fileName; fileName = FS::RemoveInvalidPathChars(fileName); auto relpath = FS::PathCombine(result.targetFolder, fileName); if (!result.required && !selectedOptionalMods.contains(relpath)) { relpath += ".disabled"; } relpath = FS::PathCombine("minecraft", relpath); auto path = FS::PathCombine(m_stagingPath, relpath); if (!result.version.downloadUrl.isEmpty()) { qDebug() << "Will download" << result.version.downloadUrl << "to" << path; auto dl = Net::ApiDownload::makeFile(result.version.downloadUrl, path); m_files_job->addNetAction(dl); } } connect(m_files_job.get(), &NetJob::finished, this, [this, &loop]() { m_files_job.reset(); validateZIPResources(loop); }); connect(m_files_job.get(), &NetJob::failed, [this](QString reason) { m_files_job.reset(); setError(reason); }); connect(m_files_job.get(), &NetJob::progress, this, [this](qint64 current, qint64 total) { setDetails(tr("%1 out of %2 complete").arg(current).arg(total)); setProgress(current, total); }); connect(m_files_job.get(), &NetJob::stepProgress, this, &FlameCreationTask::propagateStepProgress); setStatus(tr("Downloading mods...")); m_files_job->start(); } /// @brief copy the matched blocked mods to the instance staging area /// @param blocked_mods list of the blocked mods and their matched paths void FlameCreationTask::copyBlockedMods(QList<BlockedMod> const& blocked_mods) { setStatus(tr("Copying Blocked Mods...")); setAbortable(false); int i = 0; int total = blocked_mods.length(); setProgress(i, total); for (auto const& mod : blocked_mods) { if (!mod.matched) { qDebug() << mod.name << "was not matched to a local file, skipping copy"; continue; } auto destPath = FS::PathCombine(m_stagingPath, "minecraft", mod.targetFolder, mod.name); setStatus(tr("Copying Blocked Mods (%1 out of %2 are done)").arg(QString::number(i), QString::number(total))); qDebug() << "Will try to copy" << mod.localPath << "to" << destPath; if (!FS::copy(mod.localPath, destPath)()) { qDebug() << "Copy of" << mod.localPath << "to" << destPath << "Failed"; } i++; setProgress(i, total); } setAbortable(true); } void FlameCreationTask::validateZIPResources(QEventLoop& loop) { qDebug() << "Validating whether resources stored as .zip are in the right place"; QStringList zipMods; for (auto [fileName, targetFolder] : m_ZIP_resources) { qDebug() << "Checking" << fileName << "..."; auto localPath = FS::PathCombine(m_stagingPath, "minecraft", targetFolder, fileName); /// @brief check the target and move the the file /// @return path where file can now be found auto validatePath = [&localPath, this](QString fileName, QString targetFolder, QString realTarget) { if (targetFolder != realTarget) { qDebug() << "Target folder of" << fileName << "is incorrect, it belongs in" << realTarget; auto destPath = FS::PathCombine(m_stagingPath, "minecraft", realTarget, fileName); qDebug() << "Moving" << localPath << "to" << destPath; if (FS::move(localPath, destPath)) { return destPath; } } else { qDebug() << "Target folder of" << fileName << "is correct at" << targetFolder; } return localPath; }; auto installWorld = [this](QString worldPath) { qDebug() << "Installing World from" << worldPath; QFileInfo worldFileInfo(worldPath); World w(worldFileInfo); if (!w.isValid()) { qDebug() << "World at" << worldPath << "is not valid, skipping install."; } else { w.install(FS::PathCombine(m_stagingPath, "minecraft", "saves")); } }; QFileInfo localFileInfo(localPath); auto type = ResourceUtils::identify(localFileInfo); QString worldPath; switch (type) { case PackedResourceType::Mod: validatePath(fileName, targetFolder, "mods"); zipMods.push_back(fileName); break; case PackedResourceType::ResourcePack: validatePath(fileName, targetFolder, "resourcepacks"); break; case PackedResourceType::TexturePack: validatePath(fileName, targetFolder, "texturepacks"); break; case PackedResourceType::DataPack: validatePath(fileName, targetFolder, "datapacks"); break; case PackedResourceType::ShaderPack: // in theory flame API can't do this but who knows, that *may* change ? // better to handle it if it *does* occur in the future validatePath(fileName, targetFolder, "shaderpacks"); break; case PackedResourceType::WorldSave: worldPath = validatePath(fileName, targetFolder, "saves"); installWorld(worldPath); break; case PackedResourceType::UNKNOWN: default: qDebug() << "Can't Identify" << fileName << "at" << localPath << ", leaving it where it is."; break; } } // TODO make this work with other sorts of resource auto task = makeShared<ConcurrentTask>("CreateModMetadata", APPLICATION->settings()->get("NumberOfConcurrentTasks").toInt()); auto results = m_mod_id_resolver->getResults().files; auto folder = FS::PathCombine(m_stagingPath, "minecraft", "mods", ".index"); for (auto file : results) { if (file.targetFolder != "mods" || (file.version.fileName.endsWith(".zip") && !zipMods.contains(file.version.fileName))) { continue; } task->addTask(makeShared<LocalResourceUpdateTask>(folder, file.pack, file.version)); } connect(task.get(), &Task::finished, &loop, &QEventLoop::quit); m_process_update_file_info_job = task; task->start(); }
26,800
C++
.cpp
583
36.524871
138
0.614088
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,111
FileResolvingTask.cpp
PrismLauncher_PrismLauncher/launcher/modplatform/flame/FileResolvingTask.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2024 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "FileResolvingTask.h" #include <algorithm> #include "Json.h" #include "QObjectPtr.h" #include "modplatform/ModIndex.h" #include "modplatform/flame/FlameAPI.h" #include "modplatform/flame/FlameModIndex.h" #include "modplatform/modrinth/ModrinthAPI.h" #include "modplatform/modrinth/ModrinthPackIndex.h" #include "net/NetJob.h" #include "tasks/Task.h" static const FlameAPI flameAPI; static ModrinthAPI modrinthAPI; Flame::FileResolvingTask::FileResolvingTask(const shared_qobject_ptr<QNetworkAccessManager>& network, Flame::Manifest& toProcess) : m_network(network), m_manifest(toProcess) {} bool Flame::FileResolvingTask::abort() { bool aborted = true; if (m_task) { aborted = m_task->abort(); } return aborted ? Task::abort() : false; } void Flame::FileResolvingTask::executeTask() { if (m_manifest.files.isEmpty()) { // no file to resolve so leave it empty and emit success immediately emitSucceeded(); return; } setStatus(tr("Resolving mod IDs...")); setProgress(0, 3); m_result.reset(new QByteArray()); QStringList fileIds; for (auto file : m_manifest.files) { fileIds.push_back(QString::number(file.fileId)); } m_task = flameAPI.getFiles(fileIds, m_result); auto step_progress = std::make_shared<TaskStepProgress>(); connect(m_task.get(), &Task::finished, this, [this, step_progress]() { step_progress->state = TaskStepState::Succeeded; stepProgress(*step_progress); netJobFinished(); }); connect(m_task.get(), &Task::failed, this, [this, step_progress](QString reason) { step_progress->state = TaskStepState::Failed; stepProgress(*step_progress); emitFailed(reason); }); connect(m_task.get(), &Task::stepProgress, this, &FileResolvingTask::propagateStepProgress); connect(m_task.get(), &Task::progress, this, [this, step_progress](qint64 current, qint64 total) { qDebug() << "Resolve slug progress" << current << total; step_progress->update(current, total); stepProgress(*step_progress); }); connect(m_task.get(), &Task::status, this, [this, step_progress](QString status) { step_progress->status = status; stepProgress(*step_progress); }); m_task->start(); } void Flame::FileResolvingTask::netJobFinished() { setProgress(1, 3); // job to check modrinth for blocked projects QJsonDocument doc; QJsonArray array; try { doc = Json::requireDocument(*m_result); array = Json::requireArray(doc.object()["data"]); } catch (Json::JsonException& e) { qCritical() << "Non-JSON data returned from the CF API"; qCritical() << e.cause(); emitFailed(tr("Invalid data returned from the API.")); return; } QStringList hashes; for (QJsonValueRef file : array) { try { auto obj = Json::requireObject(file); auto version = FlameMod::loadIndexedPackVersion(obj); auto fileid = version.fileId.toInt(); m_manifest.files[fileid].version = version; auto url = QUrl(version.downloadUrl, QUrl::TolerantMode); if (!url.isValid() && "sha1" == version.hash_type && !version.hash.isEmpty()) { hashes.push_back(version.hash); } } catch (Json::JsonException& e) { qCritical() << "Non-JSON data returned from the CF API"; qCritical() << e.cause(); emitFailed(tr("Invalid data returned from the API.")); return; } } if (hashes.isEmpty()) { getFlameProjects(); return; } m_result.reset(new QByteArray()); m_task = modrinthAPI.currentVersions(hashes, "sha1", m_result); (dynamic_cast<NetJob*>(m_task.get()))->setAskRetry(false); auto step_progress = std::make_shared<TaskStepProgress>(); connect(m_task.get(), &Task::finished, this, [this, step_progress]() { step_progress->state = TaskStepState::Succeeded; stepProgress(*step_progress); QJsonParseError parse_error{}; QJsonDocument doc = QJsonDocument::fromJson(*m_result, &parse_error); if (parse_error.error != QJsonParseError::NoError) { qWarning() << "Error while parsing JSON response from Modrinth::CurrentVersions at " << parse_error.offset << " reason: " << parse_error.errorString(); qWarning() << *m_result; failed(parse_error.errorString()); return; } try { auto entries = Json::requireObject(doc); for (auto& out : m_manifest.files) { auto url = QUrl(out.version.downloadUrl, QUrl::TolerantMode); if (!url.isValid() && "sha1" == out.version.hash_type && !out.version.hash.isEmpty()) { try { auto entry = Json::requireObject(entries, out.version.hash); auto file = Modrinth::loadIndexedPackVersion(entry); // If there's more than one mod loader for this version, we can't know for sure // which file is relative to each loader, so it's best to not use any one and // let the user download it manually. if (!file.loaders || hasSingleModLoaderSelected(file.loaders)) { out.version.downloadUrl = file.downloadUrl; qDebug() << "Found alternative on modrinth " << out.version.fileName; } } catch (Json::JsonException& e) { qDebug() << e.cause(); qDebug() << entries; } } } } catch (Json::JsonException& e) { qDebug() << e.cause(); qDebug() << doc; } getFlameProjects(); }); connect(m_task.get(), &Task::failed, this, [this, step_progress](QString reason) { step_progress->state = TaskStepState::Failed; stepProgress(*step_progress); }); connect(m_task.get(), &Task::stepProgress, this, &FileResolvingTask::propagateStepProgress); connect(m_task.get(), &Task::progress, this, [this, step_progress](qint64 current, qint64 total) { qDebug() << "Resolve slug progress" << current << total; step_progress->update(current, total); stepProgress(*step_progress); }); connect(m_task.get(), &Task::status, this, [this, step_progress](QString status) { step_progress->status = status; stepProgress(*step_progress); }); m_task->start(); } void Flame::FileResolvingTask::getFlameProjects() { setProgress(2, 3); m_result.reset(new QByteArray()); QStringList addonIds; for (auto file : m_manifest.files) { addonIds.push_back(QString::number(file.projectId)); } m_task = flameAPI.getProjects(addonIds, m_result); auto step_progress = std::make_shared<TaskStepProgress>(); connect(m_task.get(), &Task::succeeded, this, [this, step_progress] { QJsonParseError parse_error{}; auto doc = QJsonDocument::fromJson(*m_result, &parse_error); if (parse_error.error != QJsonParseError::NoError) { qWarning() << "Error while parsing JSON response from Modrinth projects task at " << parse_error.offset << " reason: " << parse_error.errorString(); qWarning() << *m_result; return; } try { QJsonArray entries; entries = Json::requireArray(Json::requireObject(doc), "data"); for (auto entry : entries) { auto entry_obj = Json::requireObject(entry); auto id = Json::requireInteger(entry_obj, "id"); auto file = std::find_if(m_manifest.files.begin(), m_manifest.files.end(), [id](const Flame::File& file) { return file.projectId == id; }); if (file == m_manifest.files.end()) { continue; } setStatus(tr("Parsing API response from CurseForge for '%1'...").arg(file->version.fileName)); FlameMod::loadIndexedPack(file->pack, entry_obj); } } catch (Json::JsonException& e) { qDebug() << e.cause(); qDebug() << doc; } step_progress->state = TaskStepState::Succeeded; stepProgress(*step_progress); emitSucceeded(); }); connect(m_task.get(), &Task::failed, this, [this, step_progress](QString reason) { step_progress->state = TaskStepState::Failed; stepProgress(*step_progress); emitFailed(reason); }); connect(m_task.get(), &Task::stepProgress, this, &FileResolvingTask::propagateStepProgress); connect(m_task.get(), &Task::progress, this, [this, step_progress](qint64 current, qint64 total) { qDebug() << "Resolve slug progress" << current << total; step_progress->update(current, total); stepProgress(*step_progress); }); connect(m_task.get(), &Task::status, this, [this, step_progress](QString status) { step_progress->status = status; stepProgress(*step_progress); }); m_task->start(); }
10,100
C++
.cpp
232
34.87931
129
0.614251
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,112
FlameAPI.cpp
PrismLauncher_PrismLauncher/launcher/modplatform/flame/FlameAPI.cpp
// SPDX-FileCopyrightText: 2023 flowln <flowlnlnln@gmail.com> // // SPDX-License-Identifier: GPL-3.0-only #include "FlameAPI.h" #include <memory> #include <optional> #include "FlameModIndex.h" #include "Application.h" #include "Json.h" #include "modplatform/ModIndex.h" #include "net/ApiDownload.h" #include "net/ApiUpload.h" #include "net/NetJob.h" Task::Ptr FlameAPI::matchFingerprints(const QList<uint>& fingerprints, std::shared_ptr<QByteArray> response) { auto netJob = makeShared<NetJob>(QString("Flame::MatchFingerprints"), APPLICATION->network()); QJsonObject body_obj; QJsonArray fingerprints_arr; for (auto& fp : fingerprints) { fingerprints_arr.append(QString("%1").arg(fp)); } body_obj["fingerprints"] = fingerprints_arr; QJsonDocument body(body_obj); auto body_raw = body.toJson(); netJob->addNetAction(Net::ApiUpload::makeByteArray(QString("https://api.curseforge.com/v1/fingerprints"), response, body_raw)); return netJob; } QString FlameAPI::getModFileChangelog(int modId, int fileId) { QEventLoop lock; QString changelog; auto netJob = makeShared<NetJob>(QString("Flame::FileChangelog"), APPLICATION->network()); auto response = std::make_shared<QByteArray>(); netJob->addNetAction(Net::ApiDownload::makeByteArray( QString("https://api.curseforge.com/v1/mods/%1/files/%2/changelog") .arg(QString::fromStdString(std::to_string(modId)), QString::fromStdString(std::to_string(fileId))), response)); QObject::connect(netJob.get(), &NetJob::succeeded, [&netJob, response, &changelog] { QJsonParseError parse_error{}; QJsonDocument doc = QJsonDocument::fromJson(*response, &parse_error); if (parse_error.error != QJsonParseError::NoError) { qWarning() << "Error while parsing JSON response from Flame::FileChangelog at " << parse_error.offset << " reason: " << parse_error.errorString(); qWarning() << *response; netJob->failed(parse_error.errorString()); return; } changelog = Json::ensureString(doc.object(), "data"); }); QObject::connect(netJob.get(), &NetJob::finished, [&lock] { lock.quit(); }); netJob->start(); lock.exec(); return changelog; } QString FlameAPI::getModDescription(int modId) { QEventLoop lock; QString description; auto netJob = makeShared<NetJob>(QString("Flame::ModDescription"), APPLICATION->network()); auto response = std::make_shared<QByteArray>(); netJob->addNetAction(Net::ApiDownload::makeByteArray( QString("https://api.curseforge.com/v1/mods/%1/description").arg(QString::number(modId)), response)); QObject::connect(netJob.get(), &NetJob::succeeded, [&netJob, response, &description] { QJsonParseError parse_error{}; QJsonDocument doc = QJsonDocument::fromJson(*response, &parse_error); if (parse_error.error != QJsonParseError::NoError) { qWarning() << "Error while parsing JSON response from Flame::ModDescription at " << parse_error.offset << " reason: " << parse_error.errorString(); qWarning() << *response; netJob->failed(parse_error.errorString()); return; } description = Json::ensureString(doc.object(), "data"); }); QObject::connect(netJob.get(), &NetJob::finished, [&lock] { lock.quit(); }); netJob->start(); lock.exec(); return description; } QList<ModPlatform::IndexedVersion> FlameAPI::getLatestVersions(VersionSearchArgs&& args) { auto versions_url_optional = getVersionsURL(args); if (!versions_url_optional.has_value()) return {}; auto versions_url = versions_url_optional.value(); QEventLoop loop; auto netJob = makeShared<NetJob>(QString("Flame::GetLatestVersion(%1)").arg(args.pack.name), APPLICATION->network()); auto response = std::make_shared<QByteArray>(); QList<ModPlatform::IndexedVersion> ver; netJob->addNetAction(Net::ApiDownload::makeByteArray(versions_url, response)); QObject::connect(netJob.get(), &NetJob::succeeded, [response, args, &ver] { QJsonParseError parse_error{}; QJsonDocument doc = QJsonDocument::fromJson(*response, &parse_error); if (parse_error.error != QJsonParseError::NoError) { qWarning() << "Error while parsing JSON response from latest mod version at " << parse_error.offset << " reason: " << parse_error.errorString(); qWarning() << *response; return; } try { auto obj = Json::requireObject(doc); auto arr = Json::requireArray(obj, "data"); for (auto file : arr) { auto file_obj = Json::requireObject(file); ver.append(FlameMod::loadIndexedPackVersion(file_obj)); } } catch (Json::JsonException& e) { qCritical() << "Failed to parse response from a version request."; qCritical() << e.what(); qDebug() << doc; } }); QObject::connect(netJob.get(), &NetJob::finished, &loop, &QEventLoop::quit); netJob->start(); loop.exec(); return ver; } Task::Ptr FlameAPI::getProjects(QStringList addonIds, std::shared_ptr<QByteArray> response) const { auto netJob = makeShared<NetJob>(QString("Flame::GetProjects"), APPLICATION->network()); QJsonObject body_obj; QJsonArray addons_arr; for (auto& addonId : addonIds) { addons_arr.append(addonId); } body_obj["modIds"] = addons_arr; QJsonDocument body(body_obj); auto body_raw = body.toJson(); netJob->addNetAction(Net::ApiUpload::makeByteArray(QString("https://api.curseforge.com/v1/mods"), response, body_raw)); QObject::connect(netJob.get(), &NetJob::failed, [body_raw] { qDebug() << body_raw; }); return netJob; } Task::Ptr FlameAPI::getFiles(const QStringList& fileIds, std::shared_ptr<QByteArray> response) const { auto netJob = makeShared<NetJob>(QString("Flame::GetFiles"), APPLICATION->network()); QJsonObject body_obj; QJsonArray files_arr; for (auto& fileId : fileIds) { files_arr.append(fileId); } body_obj["fileIds"] = files_arr; QJsonDocument body(body_obj); auto body_raw = body.toJson(); netJob->addNetAction(Net::ApiUpload::makeByteArray(QString("https://api.curseforge.com/v1/mods/files"), response, body_raw)); QObject::connect(netJob.get(), &NetJob::failed, [body_raw] { qDebug() << body_raw; }); return netJob; } Task::Ptr FlameAPI::getFile(const QString& addonId, const QString& fileId, std::shared_ptr<QByteArray> response) const { auto netJob = makeShared<NetJob>(QString("Flame::GetFile"), APPLICATION->network()); netJob->addNetAction( Net::ApiDownload::makeByteArray(QUrl(QString("https://api.curseforge.com/v1/mods/%1/files/%2").arg(addonId, fileId)), response)); QObject::connect(netJob.get(), &NetJob::failed, [addonId, fileId] { qDebug() << "Flame API file failure" << addonId << fileId; }); return netJob; } QList<ResourceAPI::SortingMethod> FlameAPI::getSortingMethods() const { // https://docs.curseforge.com/?python#tocS_ModsSearchSortField return { { 1, "Featured", QObject::tr("Sort by Featured") }, { 2, "Popularity", QObject::tr("Sort by Popularity") }, { 3, "LastUpdated", QObject::tr("Sort by Last Updated") }, { 4, "Name", QObject::tr("Sort by Name") }, { 5, "Author", QObject::tr("Sort by Author") }, { 6, "TotalDownloads", QObject::tr("Sort by Downloads") }, { 7, "Category", QObject::tr("Sort by Category") }, { 8, "GameVersion", QObject::tr("Sort by Game Version") } }; } Task::Ptr FlameAPI::getCategories(std::shared_ptr<QByteArray> response, ModPlatform::ResourceType type) { auto netJob = makeShared<NetJob>(QString("Flame::GetCategories"), APPLICATION->network()); netJob->addNetAction(Net::ApiDownload::makeByteArray( QUrl(QString("https://api.curseforge.com/v1/categories?gameId=432&classId=%1").arg(getClassId(type))), response)); QObject::connect(netJob.get(), &Task::failed, [](QString msg) { qDebug() << "Flame failed to get categories:" << msg; }); return netJob; } Task::Ptr FlameAPI::getModCategories(std::shared_ptr<QByteArray> response) { return getCategories(response, ModPlatform::ResourceType::MOD); } QList<ModPlatform::Category> FlameAPI::loadModCategories(std::shared_ptr<QByteArray> response) { QList<ModPlatform::Category> categories; QJsonParseError parse_error{}; QJsonDocument doc = QJsonDocument::fromJson(*response, &parse_error); if (parse_error.error != QJsonParseError::NoError) { qWarning() << "Error while parsing JSON response from categories at " << parse_error.offset << " reason: " << parse_error.errorString(); qWarning() << *response; return categories; } try { auto obj = Json::requireObject(doc); auto arr = Json::requireArray(obj, "data"); for (auto val : arr) { auto cat = Json::requireObject(val); auto id = Json::requireInteger(cat, "id"); auto name = Json::requireString(cat, "name"); categories.push_back({ name, QString::number(id) }); } } catch (Json::JsonException& e) { qCritical() << "Failed to parse response from a version request."; qCritical() << e.what(); qDebug() << doc; } return categories; }; std::optional<ModPlatform::IndexedVersion> FlameAPI::getLatestVersion(QList<ModPlatform::IndexedVersion> versions, QList<ModPlatform::ModLoaderType> instanceLoaders, ModPlatform::ModLoaderTypes modLoaders) { // edge case: mod has installed for forge but the instance is fabric => fabric version will be prioritizated on update auto bestVersion = [&versions](ModPlatform::ModLoaderTypes loader) { std::optional<ModPlatform::IndexedVersion> ver; for (auto file_tmp : versions) { if (file_tmp.loaders & loader && (!ver.has_value() || file_tmp.date > ver->date)) { ver = file_tmp; } } return ver; }; for (auto l : instanceLoaders) { auto ver = bestVersion(l); if (ver.has_value()) { return ver; } } return bestVersion(modLoaders); }
10,627
C++
.cpp
228
39.201754
137
0.649318
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,113
FlameModIndex.cpp
PrismLauncher_PrismLauncher/launcher/modplatform/flame/FlameModIndex.cpp
#include "FlameModIndex.h" #include "FileSystem.h" #include "Json.h" #include "minecraft/MinecraftInstance.h" #include "minecraft/PackProfile.h" #include "modplatform/flame/FlameAPI.h" static FlameAPI api; void FlameMod::loadIndexedPack(ModPlatform::IndexedPack& pack, QJsonObject& obj) { pack.addonId = Json::requireInteger(obj, "id"); pack.provider = ModPlatform::ResourceProvider::FLAME; pack.name = Json::requireString(obj, "name"); pack.slug = Json::requireString(obj, "slug"); pack.websiteUrl = Json::ensureString(Json::ensureObject(obj, "links"), "websiteUrl", ""); pack.description = Json::ensureString(obj, "summary", ""); QJsonObject logo = Json::ensureObject(obj, "logo"); pack.logoName = Json::ensureString(logo, "title"); pack.logoUrl = Json::ensureString(logo, "thumbnailUrl"); if (pack.logoUrl.isEmpty()) { pack.logoUrl = Json::ensureString(logo, "url"); } auto authors = Json::ensureArray(obj, "authors"); for (auto authorIter : authors) { auto author = Json::requireObject(authorIter); ModPlatform::ModpackAuthor packAuthor; packAuthor.name = Json::requireString(author, "name"); packAuthor.url = Json::requireString(author, "url"); pack.authors.append(packAuthor); } pack.extraDataLoaded = false; loadURLs(pack, obj); } void FlameMod::loadURLs(ModPlatform::IndexedPack& pack, QJsonObject& obj) { auto links_obj = Json::ensureObject(obj, "links"); pack.extraData.issuesUrl = Json::ensureString(links_obj, "issuesUrl"); if (pack.extraData.issuesUrl.endsWith('/')) pack.extraData.issuesUrl.chop(1); pack.extraData.sourceUrl = Json::ensureString(links_obj, "sourceUrl"); if (pack.extraData.sourceUrl.endsWith('/')) pack.extraData.sourceUrl.chop(1); pack.extraData.wikiUrl = Json::ensureString(links_obj, "wikiUrl"); if (pack.extraData.wikiUrl.endsWith('/')) pack.extraData.wikiUrl.chop(1); if (!pack.extraData.body.isEmpty()) pack.extraDataLoaded = true; } void FlameMod::loadBody(ModPlatform::IndexedPack& pack, [[maybe_unused]] QJsonObject& obj) { pack.extraData.body = api.getModDescription(pack.addonId.toInt()); if (!pack.extraData.issuesUrl.isEmpty() || !pack.extraData.sourceUrl.isEmpty() || !pack.extraData.wikiUrl.isEmpty()) pack.extraDataLoaded = true; } static QString enumToString(int hash_algorithm) { switch (hash_algorithm) { default: case 1: return "sha1"; case 2: return "md5"; } } void FlameMod::loadIndexedPackVersions(ModPlatform::IndexedPack& pack, QJsonArray& arr, [[maybe_unused]] const shared_qobject_ptr<QNetworkAccessManager>& network, const BaseInstance* inst) { QVector<ModPlatform::IndexedVersion> unsortedVersions; for (auto versionIter : arr) { auto obj = versionIter.toObject(); auto file = loadIndexedPackVersion(obj); if (!file.addonId.isValid()) file.addonId = pack.addonId; if (file.fileId.isValid()) // Heuristic to check if the returned value is valid unsortedVersions.append(file); } auto orderSortPredicate = [](const ModPlatform::IndexedVersion& a, const ModPlatform::IndexedVersion& b) -> bool { // dates are in RFC 3339 format return a.date > b.date; }; std::sort(unsortedVersions.begin(), unsortedVersions.end(), orderSortPredicate); pack.versions = unsortedVersions; pack.versionsLoaded = true; } auto FlameMod::loadIndexedPackVersion(QJsonObject& obj, bool load_changelog) -> ModPlatform::IndexedVersion { auto versionArray = Json::requireArray(obj, "gameVersions"); if (versionArray.isEmpty()) { return {}; } ModPlatform::IndexedVersion file; for (auto mcVer : versionArray) { auto str = mcVer.toString(); if (str.contains('.')) file.mcVersion.append(str); if (auto loader = str.toLower(); loader == "neoforge") file.loaders |= ModPlatform::NeoForge; else if (loader == "forge") file.loaders |= ModPlatform::Forge; else if (loader == "cauldron") file.loaders |= ModPlatform::Cauldron; else if (loader == "liteloader") file.loaders |= ModPlatform::LiteLoader; else if (loader == "fabric") file.loaders |= ModPlatform::Fabric; else if (loader == "quilt") file.loaders |= ModPlatform::Quilt; else if (loader == "server" || loader == "client") { if (file.side.isEmpty()) file.side = loader; else if (file.side != loader) file.side = "both"; } } file.addonId = Json::requireInteger(obj, "modId"); file.fileId = Json::requireInteger(obj, "id"); file.date = Json::requireString(obj, "fileDate"); file.version = Json::requireString(obj, "displayName"); file.downloadUrl = Json::ensureString(obj, "downloadUrl"); file.fileName = Json::requireString(obj, "fileName"); file.fileName = FS::RemoveInvalidPathChars(file.fileName); ModPlatform::IndexedVersionType::VersionType ver_type; switch (Json::requireInteger(obj, "releaseType")) { case 1: ver_type = ModPlatform::IndexedVersionType::VersionType::Release; break; case 2: ver_type = ModPlatform::IndexedVersionType::VersionType::Beta; break; case 3: ver_type = ModPlatform::IndexedVersionType::VersionType::Alpha; break; default: ver_type = ModPlatform::IndexedVersionType::VersionType::Unknown; } file.version_type = ModPlatform::IndexedVersionType(ver_type); auto hash_list = Json::ensureArray(obj, "hashes"); for (auto h : hash_list) { auto hash_entry = Json::ensureObject(h); auto hash_types = ModPlatform::ProviderCapabilities::hashType(ModPlatform::ResourceProvider::FLAME); auto hash_algo = enumToString(Json::ensureInteger(hash_entry, "algo", 1, "algorithm")); if (hash_types.contains(hash_algo)) { file.hash = Json::requireString(hash_entry, "value"); file.hash_type = hash_algo; break; } } auto dependencies = Json::ensureArray(obj, "dependencies"); for (auto d : dependencies) { auto dep = Json::ensureObject(d); ModPlatform::Dependency dependency; dependency.addonId = Json::requireInteger(dep, "modId"); switch (Json::requireInteger(dep, "relationType")) { case 1: // EmbeddedLibrary dependency.type = ModPlatform::DependencyType::EMBEDDED; break; case 2: // OptionalDependency dependency.type = ModPlatform::DependencyType::OPTIONAL; break; case 3: // RequiredDependency dependency.type = ModPlatform::DependencyType::REQUIRED; break; case 4: // Tool dependency.type = ModPlatform::DependencyType::TOOL; break; case 5: // Incompatible dependency.type = ModPlatform::DependencyType::INCOMPATIBLE; break; case 6: // Include dependency.type = ModPlatform::DependencyType::INCLUDE; break; default: dependency.type = ModPlatform::DependencyType::UNKNOWN; break; } file.dependencies.append(dependency); } if (load_changelog) file.changelog = api.getModFileChangelog(file.addonId.toInt(), file.fileId.toInt()); return file; } ModPlatform::IndexedVersion FlameMod::loadDependencyVersions(const ModPlatform::Dependency& m, QJsonArray& arr, const BaseInstance* inst) { auto profile = (dynamic_cast<const MinecraftInstance*>(inst))->getPackProfile(); QString mcVersion = profile->getComponentVersion("net.minecraft"); auto loaders = profile->getSupportedModLoaders(); QVector<ModPlatform::IndexedVersion> versions; for (auto versionIter : arr) { auto obj = versionIter.toObject(); auto file = loadIndexedPackVersion(obj); if (!file.addonId.isValid()) file.addonId = m.addonId; if (file.fileId.isValid() && (!loaders.has_value() || !file.loaders || loaders.value() & file.loaders)) // Heuristic to check if the returned value is valid versions.append(file); } auto orderSortPredicate = [](const ModPlatform::IndexedVersion& a, const ModPlatform::IndexedVersion& b) -> bool { // dates are in RFC 3339 format return a.date > b.date; }; std::sort(versions.begin(), versions.end(), orderSortPredicate); if (versions.size() != 0) return versions.front(); return {}; }
8,996
C++
.cpp
206
35.286408
140
0.641128
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,114
PackInstallTask.cpp
PrismLauncher_PrismLauncher/launcher/modplatform/legacy_ftb/PackInstallTask.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 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 "PackInstallTask.h" #include <QtConcurrent> #include "BaseInstance.h" #include "FileSystem.h" #include "MMCZip.h" #include "minecraft/GradleSpecifier.h" #include "minecraft/MinecraftInstance.h" #include "minecraft/PackProfile.h" #include "settings/INISettingsObject.h" #include "Application.h" #include "BuildConfig.h" #include "net/ApiDownload.h" namespace LegacyFTB { PackInstallTask::PackInstallTask(shared_qobject_ptr<QNetworkAccessManager> network, Modpack pack, QString version) { m_pack = pack; m_version = version; m_network = network; } void PackInstallTask::executeTask() { downloadPack(); } void PackInstallTask::downloadPack() { setStatus(tr("Downloading zip for %1").arg(m_pack.name)); setProgress(1, 4); setAbortable(false); auto path = QString("%1/%2/%3").arg(m_pack.dir, m_version.replace(".", "_"), m_pack.file); auto entry = APPLICATION->metacache()->resolveEntry("FTBPacks", path); entry->setStale(true); archivePath = entry->getFullPath(); netJobContainer.reset(new NetJob("Download FTB Pack", m_network)); QString url; if (m_pack.type == PackType::Private) { url = QString(BuildConfig.LEGACY_FTB_CDN_BASE_URL + "privatepacks/%1").arg(path); } else { url = QString(BuildConfig.LEGACY_FTB_CDN_BASE_URL + "modpacks/%1").arg(path); } netJobContainer->addNetAction(Net::ApiDownload::makeCached(url, entry)); connect(netJobContainer.get(), &NetJob::succeeded, this, &PackInstallTask::unzip); connect(netJobContainer.get(), &NetJob::failed, this, &PackInstallTask::emitFailed); connect(netJobContainer.get(), &NetJob::stepProgress, this, &PackInstallTask::propagateStepProgress); connect(netJobContainer.get(), &NetJob::aborted, this, &PackInstallTask::emitAborted); netJobContainer->start(); setAbortable(true); progress(1, 4); } void PackInstallTask::unzip() { setStatus(tr("Extracting modpack")); setAbortable(false); progress(2, 4); QDir extractDir(m_stagingPath); m_packZip.reset(new QuaZip(archivePath)); if (!m_packZip->open(QuaZip::mdUnzip)) { emitFailed(tr("Failed to open modpack file %1!").arg(archivePath)); return; } #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) m_extractFuture = QtConcurrent::run(QThreadPool::globalInstance(), QOverload<QString, QString>::of(MMCZip::extractDir), archivePath, extractDir.absolutePath() + "/unzip"); #else m_extractFuture = QtConcurrent::run(QThreadPool::globalInstance(), MMCZip::extractDir, archivePath, extractDir.absolutePath() + "/unzip"); #endif connect(&m_extractFutureWatcher, &QFutureWatcher<QStringList>::finished, this, &PackInstallTask::onUnzipFinished); connect(&m_extractFutureWatcher, &QFutureWatcher<QStringList>::canceled, this, &PackInstallTask::onUnzipCanceled); m_extractFutureWatcher.setFuture(m_extractFuture); } void PackInstallTask::onUnzipFinished() { install(); } void PackInstallTask::onUnzipCanceled() { emitAborted(); } void PackInstallTask::install() { setStatus(tr("Installing modpack")); progress(3, 4); QDir unzipMcDir(m_stagingPath + "/unzip/minecraft"); if (unzipMcDir.exists()) { // ok, found minecraft dir, move contents to instance dir if (!FS::move(m_stagingPath + "/unzip/minecraft", m_stagingPath + "/minecraft")) { emitFailed(tr("Failed to move unpacked Minecraft!")); return; } } QString instanceConfigPath = FS::PathCombine(m_stagingPath, "instance.cfg"); auto instanceSettings = std::make_shared<INISettingsObject>(instanceConfigPath); instanceSettings->suspendSave(); MinecraftInstance instance(m_globalSettings, instanceSettings, m_stagingPath); auto components = instance.getPackProfile(); components->buildingFromScratch(); components->setComponentVersion("net.minecraft", m_pack.mcVersion, true); bool fallback = true; // handle different versions QFile packJson(m_stagingPath + "/minecraft/pack.json"); QDir jarmodDir = QDir(m_stagingPath + "/unzip/instMods"); if (packJson.exists()) { packJson.open(QIODevice::ReadOnly | QIODevice::Text); QJsonDocument doc = QJsonDocument::fromJson(packJson.readAll()); packJson.close(); // we only care about the libs QJsonArray libs = doc.object().value("libraries").toArray(); foreach (const QJsonValue& value, libs) { QString nameValue = value.toObject().value("name").toString(); if (!nameValue.startsWith("net.minecraftforge")) { continue; } GradleSpecifier forgeVersion(nameValue); components->setComponentVersion("net.minecraftforge", forgeVersion.version().replace(m_pack.mcVersion, "").replace("-", "")); packJson.remove(); fallback = false; break; } } if (jarmodDir.exists()) { qDebug() << "Found jarmods, installing..."; QStringList jarmods; for (auto info : jarmodDir.entryInfoList(QDir::NoDotAndDotDot | QDir::Files)) { qDebug() << "Jarmod:" << info.fileName(); jarmods.push_back(info.absoluteFilePath()); } components->installJarMods(jarmods); fallback = false; } // just nuke unzip directory, it s not needed anymore FS::deletePath(m_stagingPath + "/unzip"); if (fallback) { // TODO: Some fallback mechanism... or just keep failing! emitFailed(tr("No installation method found!")); return; } components->saveNow(); progress(4, 4); instance.setName(name()); if (m_instIcon == "default") { m_instIcon = "ftb_logo"; } instance.setIconKey(m_instIcon); instanceSettings->resumeSave(); emitSucceeded(); } bool PackInstallTask::abort() { if (!canAbort()) { return false; } netJobContainer->abort(); return InstanceTask::abort(); } } // namespace LegacyFTB
7,558
C++
.cpp
189
34.883598
137
0.6915
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,115
PackFetchTask.cpp
PrismLauncher_PrismLauncher/launcher/modplatform/legacy_ftb/PackFetchTask.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 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 "PackFetchTask.h" #include "PrivatePackManager.h" #include <QDomDocument> #include "Application.h" #include "BuildConfig.h" #include "net/ApiDownload.h" namespace LegacyFTB { void PackFetchTask::fetch() { publicPacks.clear(); thirdPartyPacks.clear(); jobPtr.reset(new NetJob("LegacyFTB::ModpackFetch", m_network)); QUrl publicPacksUrl = QUrl(BuildConfig.LEGACY_FTB_CDN_BASE_URL + "static/modpacks.xml"); qDebug() << "Downloading public version info from" << publicPacksUrl.toString(); jobPtr->addNetAction(Net::ApiDownload::makeByteArray(publicPacksUrl, publicModpacksXmlFileData)); QUrl thirdPartyUrl = QUrl(BuildConfig.LEGACY_FTB_CDN_BASE_URL + "static/thirdparty.xml"); qDebug() << "Downloading thirdparty version info from" << thirdPartyUrl.toString(); jobPtr->addNetAction(Net::Download::makeByteArray(thirdPartyUrl, thirdPartyModpacksXmlFileData)); QObject::connect(jobPtr.get(), &NetJob::succeeded, this, &PackFetchTask::fileDownloadFinished); QObject::connect(jobPtr.get(), &NetJob::failed, this, &PackFetchTask::fileDownloadFailed); QObject::connect(jobPtr.get(), &NetJob::aborted, this, &PackFetchTask::fileDownloadAborted); jobPtr->start(); } void PackFetchTask::fetchPrivate(const QStringList& toFetch) { QString privatePackBaseUrl = BuildConfig.LEGACY_FTB_CDN_BASE_URL + "static/%1.xml"; for (auto& packCode : toFetch) { auto data = std::make_shared<QByteArray>(); NetJob* job = new NetJob("Fetching private pack", m_network); job->addNetAction(Net::ApiDownload::makeByteArray(privatePackBaseUrl.arg(packCode), data)); job->setAskRetry(false); QObject::connect(job, &NetJob::succeeded, this, [this, job, data, packCode] { ModpackList packs; parseAndAddPacks(*data, PackType::Private, packs); foreach (Modpack currentPack, packs) { currentPack.packCode = packCode; emit privateFileDownloadFinished(currentPack); } job->deleteLater(); data->clear(); }); QObject::connect(job, &NetJob::failed, this, [this, job, packCode, data](QString reason) { emit privateFileDownloadFailed(reason, packCode); job->deleteLater(); data->clear(); }); QObject::connect(job, &NetJob::aborted, this, [this, job, data] { emit aborted(); job->deleteLater(); data->clear(); }); job->start(); } } void PackFetchTask::fileDownloadFinished() { jobPtr.reset(); QStringList failedLists; if (!parseAndAddPacks(*publicModpacksXmlFileData, PackType::Public, publicPacks)) { failedLists.append(tr("Public Packs")); } if (!parseAndAddPacks(*thirdPartyModpacksXmlFileData, PackType::ThirdParty, thirdPartyPacks)) { failedLists.append(tr("Third Party Packs")); } if (failedLists.size() > 0) { emit failed(tr("Failed to download some pack lists: %1").arg(failedLists.join("\n- "))); } else { emit finished(publicPacks, thirdPartyPacks); } } bool PackFetchTask::parseAndAddPacks(QByteArray& data, PackType packType, ModpackList& list) { QDomDocument doc; QString errorMsg = "Unknown error."; int errorLine = -1; int errorCol = -1; if (!doc.setContent(data, false, &errorMsg, &errorLine, &errorCol)) { auto fullErrMsg = QString("Failed to fetch modpack data: %1 %2:%3!").arg(errorMsg).arg(errorLine).arg(errorCol); qWarning() << fullErrMsg; data.clear(); return false; } QDomNodeList nodes = doc.elementsByTagName("modpack"); for (int i = 0; i < nodes.length(); i++) { QDomElement element = nodes.at(i).toElement(); Modpack modpack; modpack.name = element.attribute("name"); modpack.currentVersion = element.attribute("version"); modpack.mcVersion = element.attribute("mcVersion"); modpack.description = element.attribute("description"); modpack.mods = element.attribute("mods"); modpack.logo = element.attribute("logo"); modpack.oldVersions = element.attribute("oldVersions").split(";"); modpack.broken = false; modpack.bugged = false; // remove empty if the xml is bugged for (QString curr : modpack.oldVersions) { if (curr.isNull() || curr.isEmpty()) { modpack.oldVersions.removeAll(curr); modpack.bugged = true; qWarning() << "Removed some empty versions from" << modpack.name; } } if (modpack.oldVersions.size() < 1) { if (!modpack.currentVersion.isNull() && !modpack.currentVersion.isEmpty()) { modpack.oldVersions.append(modpack.currentVersion); qWarning() << "Added current version to oldVersions because oldVersions was empty! (" + modpack.name + ")"; } else { modpack.broken = true; qWarning() << "Broken pack:" << modpack.name << " => No valid version!"; } } modpack.author = element.attribute("author"); modpack.dir = element.attribute("dir"); modpack.file = element.attribute("url"); modpack.type = packType; list.append(modpack); } return true; } void PackFetchTask::fileDownloadFailed(QString reason) { qWarning() << "Fetching FTBPacks failed:" << reason; emit failed(reason); } void PackFetchTask::fileDownloadAborted() { emit aborted(); } } // namespace LegacyFTB
7,117
C++
.cpp
164
36.957317
123
0.669463
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,116
PrivatePackManager.cpp
PrismLauncher_PrismLauncher/launcher/modplatform/legacy_ftb/PrivatePackManager.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 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 "PrivatePackManager.h" #include <QDebug> #include "FileSystem.h" namespace LegacyFTB { void PrivatePackManager::load() { try { #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) auto foo = QString::fromUtf8(FS::read(m_filename)).split('\n', Qt::SkipEmptyParts); currentPacks = QSet<QString>(foo.begin(), foo.end()); #else currentPacks = QString::fromUtf8(FS::read(m_filename)).split('\n', QString::SkipEmptyParts).toSet(); #endif dirty = false; } catch (...) { currentPacks = {}; qWarning() << "Failed to read third party FTB pack codes from" << m_filename; } } void PrivatePackManager::save() const { if (!dirty) { return; } try { QStringList list = currentPacks.values(); FS::write(m_filename, list.join('\n').toUtf8()); dirty = false; } catch (...) { qWarning() << "Failed to write third party FTB pack codes to" << m_filename; } } } // namespace LegacyFTB
2,485
C++
.cpp
67
33.701493
108
0.689212
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,117
PackInstallTask.cpp
PrismLauncher_PrismLauncher/launcher/modplatform/import_ftb/PackInstallTask.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "PackInstallTask.h" #include <QtConcurrent> #include "BaseInstance.h" #include "FileSystem.h" #include "minecraft/MinecraftInstance.h" #include "minecraft/PackProfile.h" #include "modplatform/ResourceAPI.h" #include "modplatform/import_ftb/PackHelpers.h" #include "settings/INISettingsObject.h" namespace FTBImportAPP { void PackInstallTask::executeTask() { setStatus(tr("Copying files...")); setAbortable(false); progress(1, 2); m_copyFuture = QtConcurrent::run(QThreadPool::globalInstance(), [this] { FS::copy folderCopy(m_pack.path, FS::PathCombine(m_stagingPath, "minecraft")); folderCopy.followSymlinks(true); return folderCopy(); }); connect(&m_copyFutureWatcher, &QFutureWatcher<bool>::finished, this, &PackInstallTask::copySettings); connect(&m_copyFutureWatcher, &QFutureWatcher<bool>::canceled, this, &PackInstallTask::emitAborted); m_copyFutureWatcher.setFuture(m_copyFuture); } void PackInstallTask::copySettings() { setStatus(tr("Copying settings...")); progress(2, 2); QString instanceConfigPath = FS::PathCombine(m_stagingPath, "instance.cfg"); auto instanceSettings = std::make_shared<INISettingsObject>(instanceConfigPath); instanceSettings->suspendSave(); MinecraftInstance instance(m_globalSettings, instanceSettings, m_stagingPath); instance.settings()->set("InstanceType", "OneSix"); instance.settings()->set("totalTimePlayed", m_pack.totalPlayTime / 1000); if (m_pack.jvmArgs.isValid() && !m_pack.jvmArgs.toString().isEmpty()) { instance.settings()->set("OverrideJavaArgs", true); instance.settings()->set("JvmArgs", m_pack.jvmArgs.toString()); } auto components = instance.getPackProfile(); components->buildingFromScratch(); components->setComponentVersion("net.minecraft", m_pack.mcVersion, true); auto modloader = m_pack.loaderType; if (modloader.has_value()) switch (modloader.value()) { case ModPlatform::NeoForge: { components->setComponentVersion("net.neoforged", m_pack.version, true); break; } case ModPlatform::Forge: { components->setComponentVersion("net.minecraftforge", m_pack.version, true); break; } case ModPlatform::Fabric: { components->setComponentVersion("net.fabricmc.fabric-loader", m_pack.version, true); break; } case ModPlatform::Quilt: { components->setComponentVersion("org.quiltmc.quilt-loader", m_pack.version, true); break; } case ModPlatform::Cauldron: break; case ModPlatform::LiteLoader: break; } components->saveNow(); instance.setName(name()); if (m_instIcon == "default") m_instIcon = "ftb_logo"; instance.setIconKey(m_instIcon); instanceSettings->resumeSave(); emitSucceeded(); } } // namespace FTBImportAPP
3,797
C++
.cpp
91
35.362637
105
0.68508
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,118
PackHelpers.cpp
PrismLauncher_PrismLauncher/launcher/modplatform/import_ftb/PackHelpers.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "modplatform/import_ftb/PackHelpers.h" #include <QIcon> #include <QString> #include <QVariant> #include "FileSystem.h" #include "Json.h" namespace FTBImportAPP { Modpack parseDirectory(QString path) { Modpack modpack{ path }; auto instanceFile = QFileInfo(FS::PathCombine(path, "instance.json")); if (!instanceFile.exists() || !instanceFile.isFile()) return {}; try { auto doc = Json::requireDocument(instanceFile.absoluteFilePath(), "FTB_APP instance JSON file"); const auto root = doc.object(); modpack.uuid = Json::requireString(root, "uuid", "uuid"); modpack.id = Json::requireInteger(root, "id", "id"); modpack.versionId = Json::requireInteger(root, "versionId", "versionId"); modpack.name = Json::requireString(root, "name", "name"); modpack.version = Json::requireString(root, "version", "version"); modpack.mcVersion = Json::requireString(root, "mcVersion", "mcVersion"); modpack.jvmArgs = Json::ensureVariant(root, "jvmArgs", {}, "jvmArgs"); modpack.totalPlayTime = Json::requireInteger(root, "totalPlayTime", "totalPlayTime"); } catch (const Exception& e) { qDebug() << "Couldn't load ftb instance json: " << e.cause(); return {}; } auto versionsFile = QFileInfo(FS::PathCombine(path, "version.json")); if (!versionsFile.exists() || !versionsFile.isFile()) return {}; try { auto doc = Json::requireDocument(versionsFile.absoluteFilePath(), "FTB_APP version JSON file"); const auto root = doc.object(); auto targets = Json::requireArray(root, "targets", "targets"); for (auto target : targets) { auto obj = Json::requireObject(target, "target"); auto name = Json::requireString(obj, "name", "name"); auto version = Json::requireString(obj, "version", "version"); if (name == "neoforge") { modpack.loaderType = ModPlatform::NeoForge; modpack.version = version; break; } else if (name == "forge") { modpack.loaderType = ModPlatform::Forge; modpack.version = version; break; } else if (name == "fabric") { modpack.loaderType = ModPlatform::Fabric; modpack.version = version; break; } else if (name == "quilt") { modpack.loaderType = ModPlatform::Quilt; modpack.version = version; break; } } } catch (const Exception& e) { qDebug() << "Couldn't load ftb version json: " << e.cause(); return {}; } auto iconFile = QFileInfo(FS::PathCombine(path, "folder.jpg")); if (iconFile.exists() && iconFile.isFile()) { modpack.icon = QIcon(iconFile.absoluteFilePath()); } return modpack; } } // namespace FTBImportAPP
3,697
C++
.cpp
85
36.070588
104
0.631068
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,119
TechnicPackProcessor.cpp
PrismLauncher_PrismLauncher/launcher/modplatform/technic/TechnicPackProcessor.cpp
/* Copyright 2020-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "TechnicPackProcessor.h" #include <FileSystem.h> #include <Json.h> #include <minecraft/MinecraftInstance.h> #include <minecraft/PackProfile.h> #include <quazip/quazip.h> #include <quazip/quazipdir.h> #include <quazip/quazipfile.h> #include <settings/INISettingsObject.h> #include <memory> void Technic::TechnicPackProcessor::run(SettingsObjectPtr globalSettings, const QString& instName, const QString& instIcon, const QString& stagingPath, const QString& minecraftVersion, [[maybe_unused]] const bool isSolder) { QString minecraftPath = FS::PathCombine(stagingPath, "minecraft"); QString configPath = FS::PathCombine(stagingPath, "instance.cfg"); auto instanceSettings = std::make_shared<INISettingsObject>(configPath); MinecraftInstance instance(globalSettings, instanceSettings, stagingPath); instance.setName(instName); if (instIcon != "default") { instance.setIconKey(instIcon); } auto components = instance.getPackProfile(); components->buildingFromScratch(); QByteArray data; QString modpackJar = FS::PathCombine(minecraftPath, "bin", "modpack.jar"); QString versionJson = FS::PathCombine(minecraftPath, "bin", "version.json"); QString fmlMinecraftVersion; if (QFile::exists(modpackJar)) { QuaZip zipFile(modpackJar); if (!zipFile.open(QuaZip::mdUnzip)) { emit failed(tr("Unable to open \"bin/modpack.jar\" file!")); return; } QuaZipDir zipFileRoot(&zipFile, "/"); if (zipFileRoot.exists("/version.json")) { if (zipFileRoot.exists("/fmlversion.properties")) { zipFile.setCurrentFile("fmlversion.properties"); QuaZipFile file(&zipFile); if (!file.open(QIODevice::ReadOnly)) { emit failed(tr("Unable to open \"fmlversion.properties\"!")); return; } QByteArray fmlVersionData = file.readAll(); file.close(); INIFile iniFile; iniFile.loadFile(fmlVersionData); // If not present, this evaluates to a null string fmlMinecraftVersion = iniFile["fmlbuild.mcversion"].toString(); } zipFile.setCurrentFile("version.json", QuaZip::csSensitive); QuaZipFile file(&zipFile); if (!file.open(QIODevice::ReadOnly)) { emit failed(tr("Unable to open \"version.json\"!")); return; } data = file.readAll(); file.close(); } else { if (minecraftVersion.isEmpty()) { emit failed(tr("Could not find \"version.json\" inside \"bin/modpack.jar\", but Minecraft version is unknown")); return; } components->setComponentVersion("net.minecraft", minecraftVersion, true); components->installJarMods({ modpackJar }); // Forge for 1.4.7 and for 1.5.2 require extra libraries. // Figure out the forge version and add it as a component // (the code still comes from the jar mod installed above) if (zipFileRoot.exists("/forgeversion.properties")) { zipFile.setCurrentFile("forgeversion.properties", QuaZip::csSensitive); QuaZipFile file(&zipFile); if (!file.open(QIODevice::ReadOnly)) { // Really shouldn't happen, but error handling shall not be forgotten emit failed(tr("Unable to open \"forgeversion.properties\"")); return; } QByteArray forgeVersionData = file.readAll(); file.close(); INIFile iniFile; iniFile.loadFile(forgeVersionData); QString major, minor, revision, build; major = iniFile["forge.major.number"].toString(); minor = iniFile["forge.minor.number"].toString(); revision = iniFile["forge.revision.number"].toString(); build = iniFile["forge.build.number"].toString(); if (major.isEmpty() || minor.isEmpty() || revision.isEmpty() || build.isEmpty()) { emit failed(tr("Invalid \"forgeversion.properties\"!")); return; } components->setComponentVersion("net.minecraftforge", major + '.' + minor + '.' + revision + '.' + build); } components->saveNow(); emit succeeded(); return; } } else if (QFile::exists(versionJson)) { QFile file(versionJson); if (!file.open(QIODevice::ReadOnly)) { emit failed(tr("Unable to open \"version.json\"!")); return; } data = file.readAll(); file.close(); } else { // This is the "Vanilla" modpack, excluded by the search code components->setComponentVersion("net.minecraft", minecraftVersion, true); components->saveNow(); emit succeeded(); return; } try { QJsonDocument doc = Json::requireDocument(data); QJsonObject root = Json::requireObject(doc, "version.json"); QString packMinecraftVersion = Json::ensureString(root, "inheritsFrom", QString(), ""); if (packMinecraftVersion.isEmpty()) { if (fmlMinecraftVersion.isEmpty()) { emit failed(tr("Could not understand \"version.json\":\ninheritsFrom is missing")); return; } packMinecraftVersion = fmlMinecraftVersion; } components->setComponentVersion("net.minecraft", packMinecraftVersion, true); for (auto library : Json::ensureArray(root, "libraries", {})) { if (!library.isObject()) { continue; } auto libraryObject = Json::ensureObject(library, {}, ""); auto libraryName = Json::ensureString(libraryObject, "name", "", ""); if (libraryName.startsWith("net.neoforged.fancymodloader:")) { // it is neoforge // no easy way to get the version from the libs so use the arguments auto arguments = Json::ensureObject(root, "arguments", {}); bool isVersionArg = false; QString neoforgeVersion; for (auto arg : Json::ensureArray(arguments, "game", {})) { auto argument = Json::ensureString(arg, ""); if (isVersionArg) { neoforgeVersion = argument; break; } else { isVersionArg = "--fml.neoForgeVersion" == argument || "--fml.forgeVersion" == argument; } } if (!neoforgeVersion.isEmpty()) { components->setComponentVersion("net.neoforged", neoforgeVersion); } break; } else if ((libraryName.startsWith("net.minecraftforge:forge:") || libraryName.startsWith("net.minecraftforge:fmlloader:")) && libraryName.contains('-')) { QString libraryVersion = libraryName.section(':', 2); if (!libraryVersion.startsWith("1.7.10-")) { components->setComponentVersion("net.minecraftforge", libraryName.section('-', 1)); } else { // 1.7.10 versions sometimes look like 1.7.10-10.13.4.1614-1.7.10, this filters out the 10.13.4.1614 part components->setComponentVersion("net.minecraftforge", libraryName.section('-', 1, 1)); } break; } else { // <Technic library name prefix> -> <our component name> static QMap<QString, QString> loaderMap{ { "net.minecraftforge:minecraftforge:", "net.minecraftforge" }, { "net.fabricmc:fabric-loader:", "net.fabricmc.fabric-loader" }, { "org.quiltmc:quilt-loader:", "org.quiltmc.quilt-loader" } }; for (const auto& loader : loaderMap.keys()) { if (libraryName.startsWith(loader)) { components->setComponentVersion(loaderMap.value(loader), libraryName.section(':', 2)); break; } } } } } catch (const JSONValidationError& e) { emit failed(tr("Could not understand \"version.json\":\n") + e.cause()); return; } components->saveNow(); emit succeeded(); }
9,511
C++
.cpp
193
35.974093
138
0.569401
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,120
SolderPackManifest.cpp
PrismLauncher_PrismLauncher/launcher/modplatform/technic/SolderPackManifest.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "SolderPackManifest.h" #include "Json.h" namespace TechnicSolder { void loadPack(Pack& v, QJsonObject& obj) { v.recommended = Json::requireString(obj, "recommended"); v.latest = Json::requireString(obj, "latest"); auto builds = Json::requireArray(obj, "builds"); for (const auto buildRaw : builds) { auto build = Json::requireString(buildRaw); v.builds.append(build); } } static void loadPackBuildMod(PackBuildMod& b, QJsonObject& obj) { b.name = Json::requireString(obj, "name"); b.version = Json::ensureString(obj, "version", ""); b.md5 = Json::requireString(obj, "md5"); b.url = Json::requireString(obj, "url"); } void loadPackBuild(PackBuild& v, QJsonObject& obj) { v.minecraft = Json::requireString(obj, "minecraft"); auto mods = Json::requireArray(obj, "mods"); for (const auto modRaw : mods) { auto modObj = Json::requireObject(modRaw); PackBuildMod mod; loadPackBuildMod(mod, modObj); v.mods.append(mod); } } } // namespace TechnicSolder
1,813
C++
.cpp
49
33.469388
74
0.707123
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,121
SingleZipPackInstallTask.cpp
PrismLauncher_PrismLauncher/launcher/modplatform/technic/SingleZipPackInstallTask.cpp
/* 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 "SingleZipPackInstallTask.h" #include <QtConcurrent> #include "FileSystem.h" #include "MMCZip.h" #include "TechnicPackProcessor.h" #include "Application.h" #include "net/ApiDownload.h" Technic::SingleZipPackInstallTask::SingleZipPackInstallTask(const QUrl& sourceUrl, const QString& minecraftVersion) { m_sourceUrl = sourceUrl; m_minecraftVersion = minecraftVersion; } bool Technic::SingleZipPackInstallTask::abort() { if (m_abortable) { return m_filesNetJob->abort(); } return false; } void Technic::SingleZipPackInstallTask::executeTask() { setStatus(tr("Downloading modpack:\n%1").arg(m_sourceUrl.toString())); const QString path = m_sourceUrl.host() + '/' + m_sourceUrl.path(); auto entry = APPLICATION->metacache()->resolveEntry("general", path); entry->setStale(true); m_filesNetJob.reset(new NetJob(tr("Modpack download"), APPLICATION->network())); m_filesNetJob->addNetAction(Net::ApiDownload::makeCached(m_sourceUrl, entry)); m_archivePath = entry->getFullPath(); auto job = m_filesNetJob.get(); connect(job, &NetJob::succeeded, this, &Technic::SingleZipPackInstallTask::downloadSucceeded); connect(job, &NetJob::progress, this, &Technic::SingleZipPackInstallTask::downloadProgressChanged); connect(job, &NetJob::stepProgress, this, &Technic::SingleZipPackInstallTask::propagateStepProgress); connect(job, &NetJob::failed, this, &Technic::SingleZipPackInstallTask::downloadFailed); m_filesNetJob->start(); } void Technic::SingleZipPackInstallTask::downloadSucceeded() { m_abortable = false; setStatus(tr("Extracting modpack")); QDir extractDir(FS::PathCombine(m_stagingPath, "minecraft")); qDebug() << "Attempting to create instance from" << m_archivePath; // open the zip and find relevant files in it m_packZip.reset(new QuaZip(m_archivePath)); if (!m_packZip->open(QuaZip::mdUnzip)) { emitFailed(tr("Unable to open supplied modpack zip file.")); return; } m_extractFuture = QtConcurrent::run(QThreadPool::globalInstance(), MMCZip::extractSubDir, m_packZip.get(), QString(""), extractDir.absolutePath()); connect(&m_extractFutureWatcher, &QFutureWatcher<QStringList>::finished, this, &Technic::SingleZipPackInstallTask::extractFinished); connect(&m_extractFutureWatcher, &QFutureWatcher<QStringList>::canceled, this, &Technic::SingleZipPackInstallTask::extractAborted); m_extractFutureWatcher.setFuture(m_extractFuture); m_filesNetJob.reset(); } void Technic::SingleZipPackInstallTask::downloadFailed(QString reason) { m_abortable = false; emitFailed(reason); m_filesNetJob.reset(); } void Technic::SingleZipPackInstallTask::downloadProgressChanged(qint64 current, qint64 total) { m_abortable = true; setProgress(current / 2, total); } void Technic::SingleZipPackInstallTask::extractFinished() { m_packZip.reset(); if (!m_extractFuture.result()) { emitFailed(tr("Failed to extract modpack")); return; } QDir extractDir(m_stagingPath); qDebug() << "Fixing permissions for extracted pack files..."; QDirIterator it(extractDir, QDirIterator::Subdirectories); while (it.hasNext()) { auto filepath = it.next(); QFileInfo file(filepath); auto permissions = QFile::permissions(filepath); auto origPermissions = permissions; if (file.isDir()) { // Folder +rwx for current user permissions |= QFileDevice::Permission::ReadUser | QFileDevice::Permission::WriteUser | QFileDevice::Permission::ExeUser; } else { // File +rw for current user permissions |= QFileDevice::Permission::ReadUser | QFileDevice::Permission::WriteUser; } if (origPermissions != permissions) { if (!QFile::setPermissions(filepath, permissions)) { logWarning(tr("Could not fix permissions for %1").arg(filepath)); } else { qDebug() << "Fixed" << filepath; } } } auto packProcessor = makeShared<Technic::TechnicPackProcessor>(); connect(packProcessor.get(), &Technic::TechnicPackProcessor::succeeded, this, &Technic::SingleZipPackInstallTask::emitSucceeded); connect(packProcessor.get(), &Technic::TechnicPackProcessor::failed, this, &Technic::SingleZipPackInstallTask::emitFailed); packProcessor->run(m_globalSettings, name(), m_instIcon, m_stagingPath, m_minecraftVersion); } void Technic::SingleZipPackInstallTask::extractAborted() { emitFailed(tr("Instance import has been aborted.")); }
5,228
C++
.cpp
118
39.381356
137
0.722506
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,122
SolderPackInstallTask.cpp
PrismLauncher_PrismLauncher/launcher/modplatform/technic/SolderPackInstallTask.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2021-2022 Jamie Mansfield <jmansfield@cadixdev.org> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "SolderPackInstallTask.h" #include <FileSystem.h> #include <Json.h> #include <MMCZip.h> #include <QtConcurrentRun> #include "SolderPackManifest.h" #include "TechnicPackProcessor.h" #include "net/ApiDownload.h" #include "net/ChecksumValidator.h" Technic::SolderPackInstallTask::SolderPackInstallTask(shared_qobject_ptr<QNetworkAccessManager> network, const QUrl& solderUrl, const QString& pack, const QString& version, const QString& minecraftVersion) { m_solderUrl = solderUrl; m_pack = pack; m_version = version; m_network = network; m_minecraftVersion = minecraftVersion; } bool Technic::SolderPackInstallTask::abort() { if (m_abortable) { return m_filesNetJob->abort(); } return false; } void Technic::SolderPackInstallTask::executeTask() { setStatus(tr("Resolving modpack files")); m_filesNetJob.reset(new NetJob(tr("Resolving modpack files"), m_network)); auto sourceUrl = QString("%1/modpack/%2/%3").arg(m_solderUrl.toString(), m_pack, m_version); m_filesNetJob->addNetAction(Net::ApiDownload::makeByteArray(sourceUrl, m_response)); auto job = m_filesNetJob.get(); connect(job, &NetJob::succeeded, this, &Technic::SolderPackInstallTask::fileListSucceeded); connect(job, &NetJob::failed, this, &Technic::SolderPackInstallTask::downloadFailed); connect(job, &NetJob::aborted, this, &Technic::SolderPackInstallTask::downloadAborted); m_filesNetJob->start(); } void Technic::SolderPackInstallTask::fileListSucceeded() { setStatus(tr("Downloading modpack")); QJsonParseError parse_error{}; QJsonDocument doc = QJsonDocument::fromJson(*m_response, &parse_error); if (parse_error.error != QJsonParseError::NoError) { qWarning() << "Error while parsing JSON response from Solder at " << parse_error.offset << " reason: " << parse_error.errorString(); qWarning() << *m_response; return; } auto obj = doc.object(); TechnicSolder::PackBuild build; try { TechnicSolder::loadPackBuild(build, obj); } catch (const JSONValidationError& e) { emitFailed(tr("Could not understand pack manifest:\n") + e.cause()); m_filesNetJob.reset(); return; } if (!build.minecraft.isEmpty()) m_minecraftVersion = build.minecraft; m_filesNetJob.reset(new NetJob(tr("Downloading modpack"), m_network)); int i = 0; for (const auto& mod : build.mods) { auto path = FS::PathCombine(m_outputDir.path(), QString("%1").arg(i)); auto dl = Net::ApiDownload::makeFile(mod.url, path); if (!mod.md5.isEmpty()) { dl->addValidator(new Net::ChecksumValidator(QCryptographicHash::Md5, mod.md5)); } m_filesNetJob->addNetAction(dl); i++; } m_modCount = build.mods.size(); connect(m_filesNetJob.get(), &NetJob::succeeded, this, &Technic::SolderPackInstallTask::downloadSucceeded); connect(m_filesNetJob.get(), &NetJob::progress, this, &Technic::SolderPackInstallTask::downloadProgressChanged); connect(m_filesNetJob.get(), &NetJob::stepProgress, this, &Technic::SolderPackInstallTask::propagateStepProgress); connect(m_filesNetJob.get(), &NetJob::failed, this, &Technic::SolderPackInstallTask::downloadFailed); connect(m_filesNetJob.get(), &NetJob::aborted, this, &Technic::SolderPackInstallTask::downloadAborted); m_filesNetJob->start(); } void Technic::SolderPackInstallTask::downloadSucceeded() { m_abortable = false; setStatus(tr("Extracting modpack")); m_filesNetJob.reset(); m_extractFuture = QtConcurrent::run([this]() { int i = 0; QString extractDir = FS::PathCombine(m_stagingPath, "minecraft"); FS::ensureFolderPathExists(extractDir); while (m_modCount > i) { auto path = FS::PathCombine(m_outputDir.path(), QString("%1").arg(i)); if (!MMCZip::extractDir(path, extractDir)) { return false; } i++; } return true; }); connect(&m_extractFutureWatcher, &QFutureWatcher<QStringList>::finished, this, &Technic::SolderPackInstallTask::extractFinished); connect(&m_extractFutureWatcher, &QFutureWatcher<QStringList>::canceled, this, &Technic::SolderPackInstallTask::extractAborted); m_extractFutureWatcher.setFuture(m_extractFuture); } void Technic::SolderPackInstallTask::downloadFailed(QString reason) { m_abortable = false; emitFailed(reason); m_filesNetJob.reset(); } void Technic::SolderPackInstallTask::downloadProgressChanged(qint64 current, qint64 total) { m_abortable = true; setProgress(current / 2, total); } void Technic::SolderPackInstallTask::downloadAborted() { emitAborted(); m_filesNetJob.reset(); } void Technic::SolderPackInstallTask::extractFinished() { if (!m_extractFuture.result()) { emitFailed(tr("Failed to extract modpack")); return; } QDir extractDir(m_stagingPath); qDebug() << "Fixing permissions for extracted pack files..."; QDirIterator it(extractDir, QDirIterator::Subdirectories); while (it.hasNext()) { auto filepath = it.next(); QFileInfo file(filepath); auto permissions = QFile::permissions(filepath); auto origPermissions = permissions; if (file.isDir()) { // Folder +rwx for current user permissions |= QFileDevice::Permission::ReadUser | QFileDevice::Permission::WriteUser | QFileDevice::Permission::ExeUser; } else { // File +rw for current user permissions |= QFileDevice::Permission::ReadUser | QFileDevice::Permission::WriteUser; } if (origPermissions != permissions) { if (!QFile::setPermissions(filepath, permissions)) { logWarning(tr("Could not fix permissions for %1").arg(filepath)); } else { qDebug() << "Fixed" << filepath; } } } auto packProcessor = makeShared<Technic::TechnicPackProcessor>(); connect(packProcessor.get(), &Technic::TechnicPackProcessor::succeeded, this, &Technic::SolderPackInstallTask::emitSucceeded); connect(packProcessor.get(), &Technic::TechnicPackProcessor::failed, this, &Technic::SolderPackInstallTask::emitFailed); packProcessor->run(m_globalSettings, name(), m_instIcon, m_stagingPath, m_minecraftVersion, true); } void Technic::SolderPackInstallTask::extractAborted() { emitFailed(tr("Instance import has been aborted.")); }
8,232
C++
.cpp
190
37.126316
140
0.683429
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,123
INIFile.cpp
PrismLauncher_PrismLauncher/launcher/settings/INIFile.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2023 flowln <flowlnlnln@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "settings/INIFile.h" #include <FileSystem.h> #include <QDebug> #include <QFile> #include <QStringList> #include <QTemporaryFile> #include <QTextStream> #include <QSettings> INIFile::INIFile() {} bool INIFile::saveFile(QString fileName) { if (!contains("ConfigVersion")) insert("ConfigVersion", "1.2"); QSettings _settings_obj{ fileName, QSettings::Format::IniFormat }; _settings_obj.setFallbacksEnabled(false); _settings_obj.clear(); for (Iterator iter = begin(); iter != end(); iter++) _settings_obj.setValue(iter.key(), iter.value()); _settings_obj.sync(); if (auto status = _settings_obj.status(); status != QSettings::Status::NoError) { // Shouldn't be possible! Q_ASSERT(status != QSettings::Status::FormatError); if (status == QSettings::Status::AccessError) qCritical() << "An access error occurred (e.g. trying to write to a read-only file)."; return false; } return true; } QString unescape(QString orig) { QString out; QChar prev = QChar::Null; for (auto c : orig) { if (prev == '\\') { if (c == 'n') out += '\n'; else if (c == 't') out += '\t'; else if (c == '#') out += '#'; else out += c; prev = QChar::Null; } else { if (c == '\\') { prev = c; continue; } out += c; prev = QChar::Null; } } return out; } QString unquote(QString str) { if ((str.contains(QChar(';')) || str.contains(QChar('=')) || str.contains(QChar(','))) && str.endsWith("\"") && str.startsWith("\"")) { #if QT_VERSION < QT_VERSION_CHECK(6, 5, 0) str = str.remove(0, 1); str = str.remove(str.size() - 1, 1); #else str = str.removeFirst().removeLast(); #endif } return str; } bool parseOldFileFormat(QIODevice& device, QSettings::SettingsMap& map) { QTextStream in(device.readAll()); #if QT_VERSION <= QT_VERSION_CHECK(6, 0, 0) in.setCodec("UTF-8"); #endif QStringList lines = in.readAll().split('\n'); for (int i = 0; i < lines.count(); i++) { QString& lineRaw = lines[i]; // Ignore comments. int commentIndex = 0; QString line = lineRaw; // Search for comments until no more escaped # are available while ((commentIndex = line.indexOf('#', commentIndex + 1)) != -1) { if (commentIndex > 0 && line.at(commentIndex - 1) == '\\') { continue; } line = line.left(lineRaw.indexOf('#')).trimmed(); } int eqPos = line.indexOf('='); if (eqPos == -1) continue; QString key = line.left(eqPos).trimmed(); QString valueStr = line.right(line.length() - eqPos - 1).trimmed(); valueStr = unquote(unescape(valueStr)); QVariant value(valueStr); map.insert(key, value); } return true; } bool INIFile::loadFile(QString fileName) { QSettings _settings_obj{ fileName, QSettings::Format::IniFormat }; _settings_obj.setFallbacksEnabled(false); if (auto status = _settings_obj.status(); status != QSettings::Status::NoError) { if (status == QSettings::Status::AccessError) qCritical() << "An access error occurred (e.g. trying to write to a read-only file)."; if (status == QSettings::Status::FormatError) qCritical() << "A format error occurred (e.g. loading a malformed INI file)."; return false; } if (!_settings_obj.value("ConfigVersion").isValid()) { QFile file(fileName); if (!file.open(QIODevice::ReadOnly)) return false; QSettings::SettingsMap map; parseOldFileFormat(file, map); file.close(); for (auto&& key : map.keys()) insert(key, map.value(key)); insert("ConfigVersion", "1.2"); } else if (_settings_obj.value("ConfigVersion").toString() == "1.1") { for (auto&& key : _settings_obj.allKeys()) { if (auto valueStr = _settings_obj.value(key).toString(); (valueStr.contains(QChar(';')) || valueStr.contains(QChar('=')) || valueStr.contains(QChar(','))) && valueStr.endsWith("\"") && valueStr.startsWith("\"")) { insert(key, unquote(valueStr)); } else insert(key, _settings_obj.value(key)); } insert("ConfigVersion", "1.2"); } else for (auto&& key : _settings_obj.allKeys()) insert(key, _settings_obj.value(key)); return true; } bool INIFile::loadFile(QByteArray data) { QTemporaryFile file; if (!file.open()) return false; file.write(data); file.flush(); file.close(); auto loaded = loadFile(file.fileName()); file.remove(); return loaded; } QVariant INIFile::get(QString key, QVariant def) const { if (!this->contains(key)) return def; else return this->operator[](key); } void INIFile::set(QString key, QVariant val) { this->operator[](key) = val; }
6,739
C++
.cpp
190
29.221053
139
0.609042
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,124
OverrideSetting.cpp
PrismLauncher_PrismLauncher/launcher/settings/OverrideSetting.cpp
/* 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 "OverrideSetting.h" OverrideSetting::OverrideSetting(std::shared_ptr<Setting> other, std::shared_ptr<Setting> gate) : Setting(other->configKeys(), QVariant()) { Q_ASSERT(other); Q_ASSERT(gate); m_other = other; m_gate = gate; } bool OverrideSetting::isOverriding() const { return m_gate->get().toBool(); } QVariant OverrideSetting::defValue() const { return m_other->get(); } QVariant OverrideSetting::get() const { if (isOverriding()) { return Setting::get(); } return m_other->get(); } void OverrideSetting::reset() { Setting::reset(); } void OverrideSetting::set(QVariant value) { Setting::set(value); }
1,281
C++
.cpp
45
25.866667
138
0.727421
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
29,127
PassthroughSetting.cpp
PrismLauncher_PrismLauncher/launcher/settings/PassthroughSetting.cpp
/* 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 "PassthroughSetting.h" PassthroughSetting::PassthroughSetting(std::shared_ptr<Setting> other, std::shared_ptr<Setting> gate) : Setting(other->configKeys(), QVariant()) { Q_ASSERT(other); m_other = other; m_gate = gate; } bool PassthroughSetting::isOverriding() const { if (!m_gate) { return false; } return m_gate->get().toBool(); } QVariant PassthroughSetting::defValue() const { if (isOverriding()) { return m_other->get(); } return m_other->defValue(); } QVariant PassthroughSetting::get() const { if (isOverriding()) { return Setting::get(); } return m_other->get(); } void PassthroughSetting::reset() { if (isOverriding()) { Setting::reset(); } m_other->reset(); } void PassthroughSetting::set(QVariant value) { if (isOverriding()) { Setting::set(value); } m_other->set(value); }
1,523
C++
.cpp
57
23.333333
101
0.693626
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
29,129
POTranslator.cpp
PrismLauncher_PrismLauncher/launcher/translations/POTranslator.cpp
#include "POTranslator.h" #include <QDebug> #include "FileSystem.h" struct POEntry { QString text; bool fuzzy; }; struct POTranslatorPrivate { QString filename; QHash<QByteArray, POEntry> mapping; QHash<QByteArray, POEntry> mapping_disambiguatrion; bool loaded = false; void reload(); }; class ParserArray : public QByteArray { public: ParserArray(const QByteArray& in) : QByteArray(in) {} bool chomp(const char* data, int length) { if (startsWith(data)) { remove(0, length); return true; } return false; } bool chompString(QByteArray& appendHere) { QByteArray msg; bool escape = false; if (size() < 2) { qDebug() << "String fragment is too short"; return false; } if (!startsWith('"')) { qDebug() << "String fragment does not start with \""; return false; } if (!endsWith('"')) { qDebug() << "String fragment does not end with \", instead, there is" << at(size() - 1); return false; } for (int i = 1; i < size() - 1; i++) { char c = operator[](i); if (escape) { switch (c) { case 'r': msg += '\r'; break; case 'n': msg += '\n'; break; case 't': msg += '\t'; break; case 'v': msg += '\v'; break; case 'a': msg += '\a'; break; case 'b': msg += '\b'; break; case 'f': msg += '\f'; break; case '"': msg += '"'; break; case '\\': msg.append('\\'); break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': { int octal_start = i; while ((c = operator[](i)) >= '0' && c <= '7') { i++; if (i == length() - 1) { qDebug() << "Something went bad while parsing an octal escape string..."; return false; } } msg += mid(octal_start, i - octal_start).toUInt(0, 8); break; } case 'x': { // chomp the 'x' i++; int hex_start = i; while (isxdigit(operator[](i))) { i++; if (i == length() - 1) { qDebug() << "Something went bad while parsing a hex escape string..."; return false; } } msg += mid(hex_start, i - hex_start).toUInt(0, 16); break; } default: { qDebug() << "Invalid escape sequence character:" << c; return false; } } escape = false; } else if (c == '\\') { escape = true; } else { msg += c; } } if (escape) { qDebug() << "Unterminated escape sequence..."; return false; } appendHere += msg; return true; } }; void POTranslatorPrivate::reload() { QFile file(filename); if (!file.open(QFile::OpenMode::enum_type::ReadOnly | QFile::OpenMode::enum_type::Text)) { qDebug() << "Failed to open PO file:" << filename; return; } QByteArray context; QByteArray disambiguation; QByteArray id; QByteArray str; bool fuzzy = false; bool nextFuzzy = false; enum class Mode { First, MessageContext, MessageId, MessageString } mode = Mode::First; int lineNumber = 0; QHash<QByteArray, POEntry> newMapping; QHash<QByteArray, POEntry> newMapping_disambiguation; auto endEntry = [&]() { auto strStr = QString::fromUtf8(str); // NOTE: PO header has empty id. We skip it. if (!id.isEmpty()) { auto normalKey = context + "|" + id; newMapping.insert(normalKey, { strStr, fuzzy }); if (!disambiguation.isEmpty()) { auto disambiguationKey = context + "|" + id + "@" + disambiguation; newMapping_disambiguation.insert(disambiguationKey, { strStr, fuzzy }); } } context.clear(); disambiguation.clear(); id.clear(); str.clear(); fuzzy = nextFuzzy; nextFuzzy = false; }; while (!file.atEnd()) { ParserArray line = file.readLine(); if (line.endsWith('\n')) { line.resize(line.size() - 1); } if (line.endsWith('\r')) { line.resize(line.size() - 1); } if (!line.size()) { // NIL } else if (line[0] == '#') { if (line.contains(", fuzzy")) { nextFuzzy = true; } } else if (line.startsWith('"')) { QByteArray temp; QByteArray* out = &temp; switch (mode) { case Mode::First: qDebug() << "Unexpected escaped string during initial state... line:" << lineNumber; return; case Mode::MessageString: out = &str; break; case Mode::MessageContext: out = &context; break; case Mode::MessageId: out = &id; break; } if (!line.chompString(*out)) { qDebug() << "Badly formatted string on line:" << lineNumber; return; } } else if (line.chomp("msgctxt ", 8)) { switch (mode) { case Mode::First: break; case Mode::MessageString: endEntry(); break; case Mode::MessageContext: case Mode::MessageId: qDebug() << "Unexpected msgctxt line:" << lineNumber; return; } if (line.chompString(context)) { auto parts = context.split('|'); context = parts[0]; if (parts.size() > 1 && !parts[1].isEmpty()) { disambiguation = parts[1]; } mode = Mode::MessageContext; } } else if (line.chomp("msgid ", 6)) { switch (mode) { case Mode::MessageContext: case Mode::First: break; case Mode::MessageString: endEntry(); break; case Mode::MessageId: qDebug() << "Unexpected msgid line:" << lineNumber; return; } if (line.chompString(id)) { mode = Mode::MessageId; } } else if (line.chomp("msgstr ", 7)) { switch (mode) { case Mode::First: case Mode::MessageString: case Mode::MessageContext: qDebug() << "Unexpected msgstr line:" << lineNumber; return; case Mode::MessageId: break; } if (line.chompString(str)) { mode = Mode::MessageString; } } else { qDebug() << "I did not understand line: " << lineNumber << ":" << QString::fromUtf8(line); } lineNumber++; } endEntry(); mapping = std::move(newMapping); mapping_disambiguatrion = std::move(newMapping_disambiguation); loaded = true; } POTranslator::POTranslator(const QString& filename, QObject* parent) : QTranslator(parent) { d = new POTranslatorPrivate; d->filename = filename; d->reload(); } POTranslator::~POTranslator() { delete d; } QString POTranslator::translate(const char* context, const char* sourceText, const char* disambiguation, [[maybe_unused]] int n) const { if (disambiguation) { auto disambiguationKey = QByteArray(context) + "|" + QByteArray(sourceText) + "@" + QByteArray(disambiguation); auto iter = d->mapping_disambiguatrion.find(disambiguationKey); if (iter != d->mapping_disambiguatrion.end()) { auto& entry = *iter; if (entry.text.isEmpty()) { qDebug() << "Translation entry has no content:" << disambiguationKey; } if (entry.fuzzy) { qDebug() << "Translation entry is fuzzy:" << disambiguationKey << "->" << entry.text; } return entry.text; } } auto key = QByteArray(context) + "|" + QByteArray(sourceText); auto iter = d->mapping.find(key); if (iter != d->mapping.end()) { auto& entry = *iter; if (entry.text.isEmpty()) { qDebug() << "Translation entry has no content:" << key; } if (entry.fuzzy) { qDebug() << "Translation entry is fuzzy:" << key << "->" << entry.text; } return entry.text; } return QString(); } bool POTranslator::isEmpty() const { return !d->loaded; }
10,148
C++
.cpp
297
20.555556
134
0.431985
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,130
TranslationsModel.cpp
PrismLauncher_PrismLauncher/launcher/translations/TranslationsModel.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 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 "TranslationsModel.h" #include <QCoreApplication> #include <QDebug> #include <QDir> #include <QLibraryInfo> #include <QLocale> #include <QTranslator> #include <locale> #include "BuildConfig.h" #include "FileSystem.h" #include "Json.h" #include "net/ChecksumValidator.h" #include "net/NetJob.h" #include "POTranslator.h" #include "Application.h" const static QLatin1String defaultLangCode("en_US"); enum class FileType { NONE, QM, PO }; struct Language { Language() { updated = true; } Language(const QString& _key) { key = _key; locale = QLocale(key); updated = (key == defaultLangCode); } QString languageName() const { QString result; if (key == "ja_KANJI") { result = locale.nativeLanguageName() + u8" (漢字)"; } else if (key == "es_UY") { result = u8"español de Latinoamérica"; } else if (key == "en_NZ") { result = u8"New Zealand English"; // No idea why qt translates this to just english and not to New Zealand English } else if (key == "en@pirate") { result = u8"Tongue of the High Seas"; } else if (key == "en@uwu") { result = u8"Cute Engwish"; } else if (key == "tok") { result = u8"toki pona"; } else if (key == "nan") { result = u8"閩南語"; // Using traditional Chinese script. Not sure if we should use simplified instead? } else { result = locale.nativeLanguageName(); } if (result.isEmpty()) { result = key; } return result; } float percentTranslated() const { if (total == 0) { return 100.0f; } return 100.0f * float(translated) / float(total); } void setTranslationStats(unsigned _translated, unsigned _untranslated, unsigned _fuzzy) { translated = _translated; untranslated = _untranslated; fuzzy = _fuzzy; total = translated + untranslated + fuzzy; } bool isOfSameNameAs(const Language& other) const { return key == other.key; } bool isIdenticalTo(const Language& other) const { return (key == other.key && file_name == other.file_name && file_size == other.file_size && file_sha1 == other.file_sha1 && translated == other.translated && fuzzy == other.fuzzy && total == other.fuzzy && localFileType == other.localFileType); } Language& apply(Language& other) { if (!isOfSameNameAs(other)) { return *this; } file_name = other.file_name; file_size = other.file_size; file_sha1 = other.file_sha1; translated = other.translated; fuzzy = other.fuzzy; total = other.total; localFileType = other.localFileType; return *this; } QString key; QLocale locale; bool updated; QString file_name = QString(); std::size_t file_size = 0; QString file_sha1 = QString(); unsigned translated = 0; unsigned untranslated = 0; unsigned fuzzy = 0; unsigned total = 0; FileType localFileType = FileType::NONE; }; struct TranslationsModel::Private { QDir m_dir; // initial state is just english QVector<Language> m_languages = { Language(defaultLangCode) }; QString m_selectedLanguage = defaultLangCode; std::unique_ptr<QTranslator> m_qt_translator; std::unique_ptr<QTranslator> m_app_translator; Net::Download* m_index_task; QString m_downloadingTranslation; NetJob::Ptr m_dl_job; NetJob::Ptr m_index_job; QString m_nextDownload; std::unique_ptr<POTranslator> m_po_translator; QFileSystemWatcher* watcher; const QString m_system_locale = QLocale::system().name(); const QString m_system_language = m_system_locale.split('_').front(); bool no_language_set = false; }; TranslationsModel::TranslationsModel(QString path, QObject* parent) : QAbstractListModel(parent) { d.reset(new Private); d->m_dir.setPath(path); FS::ensureFolderPathExists(path); reloadLocalFiles(); d->watcher = new QFileSystemWatcher(this); connect(d->watcher, &QFileSystemWatcher::directoryChanged, this, &TranslationsModel::translationDirChanged); d->watcher->addPath(d->m_dir.canonicalPath()); } TranslationsModel::~TranslationsModel() {} void TranslationsModel::translationDirChanged(const QString& path) { qDebug() << "Dir changed:" << path; if (!d->no_language_set) { reloadLocalFiles(); } selectLanguage(selectedLanguage()); } void TranslationsModel::indexReceived() { qDebug() << "Got translations index!"; d->m_index_job.reset(); if (d->no_language_set) { reloadLocalFiles(); auto language = d->m_system_locale; if (!findLanguageAsOptional(language).has_value()) { language = d->m_system_language; } selectLanguage(language); if (selectedLanguage() != defaultLangCode) { updateLanguage(selectedLanguage()); } APPLICATION->settings()->set("Language", selectedLanguage()); d->no_language_set = false; } else if (d->m_selectedLanguage != defaultLangCode) { downloadTranslation(d->m_selectedLanguage); } } namespace { void readIndex(const QString& path, QMap<QString, Language>& languages) { QByteArray data; try { data = FS::read(path); } catch ([[maybe_unused]] const Exception& e) { qCritical() << "Translations Download Failed: index file not readable"; return; } try { auto toplevel_doc = Json::requireDocument(data); auto doc = Json::requireObject(toplevel_doc); auto file_type = Json::requireString(doc, "file_type"); if (file_type != "MMC-TRANSLATION-INDEX") { qCritical() << "Translations Download Failed: index file is of unknown file type" << file_type; return; } auto version = Json::requireInteger(doc, "version"); if (version > 2) { qCritical() << "Translations Download Failed: index file is of unknown format version" << file_type; return; } auto langObjs = Json::requireObject(doc, "languages"); for (auto iter = langObjs.begin(); iter != langObjs.end(); iter++) { Language lang(iter.key()); auto langObj = Json::requireObject(iter.value()); lang.setTranslationStats(Json::ensureInteger(langObj, "translated", 0), Json::ensureInteger(langObj, "untranslated", 0), Json::ensureInteger(langObj, "fuzzy", 0)); lang.file_name = Json::requireString(langObj, "file"); lang.file_sha1 = Json::requireString(langObj, "sha1"); lang.file_size = Json::requireInteger(langObj, "size"); languages.insert(lang.key, lang); } } catch ([[maybe_unused]] Json::JsonException& e) { qCritical() << "Translations Download Failed: index file could not be parsed as json"; } } } // namespace void TranslationsModel::reloadLocalFiles() { QMap<QString, Language> languages = { { defaultLangCode, Language(defaultLangCode) } }; readIndex(d->m_dir.absoluteFilePath("index_v2.json"), languages); auto entries = d->m_dir.entryInfoList({ "mmc_*.qm", "*.po" }, QDir::Files | QDir::NoDotAndDotDot); for (auto& entry : entries) { auto completeSuffix = entry.completeSuffix(); QString langCode; FileType fileType = FileType::NONE; if (completeSuffix == "qm") { langCode = entry.baseName().remove(0, 4); fileType = FileType::QM; } else if (completeSuffix == "po") { langCode = entry.baseName(); fileType = FileType::PO; } else { continue; } auto langIter = languages.find(langCode); if (langIter != languages.end()) { auto& language = *langIter; if (int(fileType) > int(language.localFileType)) { language.localFileType = fileType; } } else { if (fileType == FileType::PO) { Language localFound(langCode); localFound.localFileType = FileType::PO; languages.insert(langCode, localFound); } } } // changed and removed languages for (auto iter = d->m_languages.begin(); iter != d->m_languages.end();) { auto& language = *iter; auto row = iter - d->m_languages.begin(); auto updatedLanguageIter = languages.find(language.key); if (updatedLanguageIter != languages.end()) { if (language.isIdenticalTo(*updatedLanguageIter)) { languages.remove(language.key); } else { language.apply(*updatedLanguageIter); emit dataChanged(index(row), index(row)); languages.remove(language.key); } iter++; } else { beginRemoveRows(QModelIndex(), row, row); iter = d->m_languages.erase(iter); endRemoveRows(); } } // added languages if (languages.isEmpty()) { return; } beginInsertRows(QModelIndex(), 0, d->m_languages.size() + languages.size() - 1); for (auto& language : languages) { d->m_languages.append(language); } std::sort(d->m_languages.begin(), d->m_languages.end(), [this](const Language& a, const Language& b) { if (a.key != b.key) { if (a.key == d->m_system_locale || a.key == d->m_system_language) { return true; } if (b.key == d->m_system_locale || b.key == d->m_system_language) { return false; } } return a.languageName().toLower() < b.languageName().toLower(); }); endInsertRows(); } namespace { enum class Column { Language, Completeness }; } QVariant TranslationsModel::data(const QModelIndex& index, int role) const { if (!index.isValid()) return QVariant(); int row = index.row(); auto column = static_cast<Column>(index.column()); if (row < 0 || row >= d->m_languages.size()) return QVariant(); auto& lang = d->m_languages[row]; switch (role) { case Qt::DisplayRole: { switch (column) { case Column::Language: { return lang.languageName(); } case Column::Completeness: { return QString("%1%").arg(lang.percentTranslated(), 3, 'f', 1); } } qWarning("TranslationModel::data not implemented when role is DisplayRole"); } case Qt::ToolTipRole: { return tr("%1:\n%2 translated\n%3 fuzzy\n%4 total") .arg(lang.key, QString::number(lang.translated), QString::number(lang.fuzzy), QString::number(lang.total)); } case Qt::UserRole: return lang.key; default: return QVariant(); } } QVariant TranslationsModel::headerData(int section, Qt::Orientation orientation, int role) const { auto column = static_cast<Column>(section); if (role == Qt::DisplayRole) { switch (column) { case Column::Language: { return tr("Language"); } case Column::Completeness: { return tr("Completeness"); } } } else if (role == Qt::ToolTipRole) { switch (column) { case Column::Language: { return tr("The native language name."); } case Column::Completeness: { return tr("Completeness is the percentage of fully translated strings, not counting automatically guessed ones."); } } } return QAbstractListModel::headerData(section, orientation, role); } int TranslationsModel::rowCount([[maybe_unused]] const QModelIndex& parent) const { return d->m_languages.size(); } int TranslationsModel::columnCount([[maybe_unused]] const QModelIndex& parent) const { return 2; } QVector<Language>::Iterator TranslationsModel::findLanguage(const QString& key) { return std::find_if(d->m_languages.begin(), d->m_languages.end(), [key](Language& lang) { return lang.key == key; }); } std::optional<Language> TranslationsModel::findLanguageAsOptional(const QString& key) { auto found = findLanguage(key); if (found != d->m_languages.end()) return *found; return {}; } void TranslationsModel::setUseSystemLocale(bool useSystemLocale) { APPLICATION->settings()->set("UseSystemLocale", useSystemLocale); QLocale::setDefault(QLocale(useSystemLocale ? QString::fromStdString(std::locale().name()) : defaultLangCode)); } bool TranslationsModel::selectLanguage(QString key) { QString& langCode = key; auto langPtr = findLanguageAsOptional(key); if (langCode.isEmpty()) { d->no_language_set = true; } if (!langPtr.has_value()) { qWarning() << "Selected invalid language" << key << ", defaulting to" << defaultLangCode; langCode = defaultLangCode; } else { langCode = langPtr->key; } // uninstall existing translators if there are any if (d->m_app_translator) { QCoreApplication::removeTranslator(d->m_app_translator.get()); d->m_app_translator.reset(); } if (d->m_qt_translator) { QCoreApplication::removeTranslator(d->m_qt_translator.get()); d->m_qt_translator.reset(); } /* * FIXME: potential source of crashes: * In a multithreaded application, the default locale should be set at application startup, before any non-GUI threads are created. * This function is not reentrant. */ QLocale::setDefault( QLocale(APPLICATION->settings()->get("UseSystemLocale").toBool() ? QString::fromStdString(std::locale().name()) : langCode)); // if it's the default UI language, finish if (langCode == defaultLangCode) { d->m_selectedLanguage = langCode; return true; } // otherwise install new translations bool successful = false; // FIXME: this is likely never present. FIX IT. d->m_qt_translator.reset(new QTranslator()); if (d->m_qt_translator->load("qt_" + langCode, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) { qDebug() << "Loading Qt Language File for" << langCode.toLocal8Bit().constData() << "..."; if (!QCoreApplication::installTranslator(d->m_qt_translator.get())) { qCritical() << "Loading Qt Language File failed."; d->m_qt_translator.reset(); } else { successful = true; } } else { d->m_qt_translator.reset(); } if (langPtr->localFileType == FileType::PO) { qDebug() << "Loading Application Language File for" << langCode.toLocal8Bit().constData() << "..."; auto poTranslator = new POTranslator(FS::PathCombine(d->m_dir.path(), langCode + ".po")); if (!poTranslator->isEmpty()) { if (!QCoreApplication::installTranslator(poTranslator)) { delete poTranslator; qCritical() << "Installing Application Language File failed."; } else { d->m_app_translator.reset(poTranslator); successful = true; } } else { qCritical() << "Loading Application Language File failed."; d->m_app_translator.reset(); } } else if (langPtr->localFileType == FileType::QM) { d->m_app_translator.reset(new QTranslator()); if (d->m_app_translator->load("mmc_" + langCode, d->m_dir.path())) { qDebug() << "Loading Application Language File for" << langCode.toLocal8Bit().constData() << "..."; if (!QCoreApplication::installTranslator(d->m_app_translator.get())) { qCritical() << "Installing Application Language File failed."; d->m_app_translator.reset(); } else { successful = true; } } else { d->m_app_translator.reset(); } } else { d->m_app_translator.reset(); } d->m_selectedLanguage = langCode; return successful; } QModelIndex TranslationsModel::selectedIndex() { auto found = findLanguage(d->m_selectedLanguage); if (found != d->m_languages.end()) { return index(std::distance(d->m_languages.begin(), found), 0, QModelIndex()); } return QModelIndex(); } QString TranslationsModel::selectedLanguage() { return d->m_selectedLanguage; } void TranslationsModel::downloadIndex() { if (d->m_index_job || d->m_dl_job) { return; } qDebug() << "Downloading Translations Index..."; d->m_index_job.reset(new NetJob("Translations Index", APPLICATION->network())); MetaEntryPtr entry = APPLICATION->metacache()->resolveEntry("translations", "index_v2.json"); entry->setStale(true); auto task = Net::Download::makeCached(QUrl(BuildConfig.TRANSLATION_FILES_URL + "index_v2.json"), entry); d->m_index_task = task.get(); d->m_index_job->addNetAction(task); d->m_index_job->setAskRetry(false); connect(d->m_index_job.get(), &NetJob::failed, this, &TranslationsModel::indexFailed); connect(d->m_index_job.get(), &NetJob::succeeded, this, &TranslationsModel::indexReceived); d->m_index_job->start(); } void TranslationsModel::updateLanguage(QString key) { if (key == defaultLangCode) { qWarning() << "Cannot update builtin language" << key; return; } auto found = findLanguageAsOptional(key); if (!found.has_value()) { qWarning() << "Cannot update invalid language" << key; return; } if (!found->updated) { downloadTranslation(key); } } void TranslationsModel::downloadTranslation(QString key) { if (d->m_dl_job) { d->m_nextDownload = key; return; } auto lang = findLanguageAsOptional(key); if (!lang.has_value()) { qWarning() << "Will not download an unknown translation" << key; return; } d->m_downloadingTranslation = key; MetaEntryPtr entry = APPLICATION->metacache()->resolveEntry("translations", "mmc_" + key + ".qm"); entry->setStale(true); auto dl = Net::Download::makeCached(QUrl(BuildConfig.TRANSLATION_FILES_URL + lang->file_name), entry); dl->addValidator(new Net::ChecksumValidator(QCryptographicHash::Sha1, lang->file_sha1)); dl->setProgress(dl->getProgress(), lang->file_size); d->m_dl_job.reset(new NetJob("Translation for " + key, APPLICATION->network())); d->m_dl_job->addNetAction(dl); d->m_dl_job->setAskRetry(false); connect(d->m_dl_job.get(), &NetJob::succeeded, this, &TranslationsModel::dlGood); connect(d->m_dl_job.get(), &NetJob::failed, this, &TranslationsModel::dlFailed); d->m_dl_job->start(); } void TranslationsModel::downloadNext() { if (!d->m_nextDownload.isEmpty()) { downloadTranslation(d->m_nextDownload); d->m_nextDownload.clear(); } } void TranslationsModel::dlFailed(QString reason) { qCritical() << "Translations Download Failed:" << reason; d->m_dl_job.reset(); downloadNext(); } void TranslationsModel::dlGood() { qDebug() << "Got translation:" << d->m_downloadingTranslation; if (d->m_downloadingTranslation == d->m_selectedLanguage) { selectLanguage(d->m_selectedLanguage); } d->m_dl_job.reset(); downloadNext(); } void TranslationsModel::indexFailed(QString reason) { qCritical() << "Translations Index Download Failed:" << reason; d->m_index_job.reset(); }
21,342
C++
.cpp
561
31.048128
136
0.626812
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,131
TaskStepWrapper.cpp
PrismLauncher_PrismLauncher/launcher/launch/TaskStepWrapper.cpp
/* 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 "TaskStepWrapper.h" #include "tasks/Task.h" void TaskStepWrapper::executeTask() { if (m_state == Task::State::AbortedByUser) { emitFailed(tr("Task aborted.")); return; } connect(m_task.get(), &Task::finished, this, &TaskStepWrapper::updateFinished); connect(m_task.get(), &Task::progress, this, &TaskStepWrapper::setProgress); connect(m_task.get(), &Task::stepProgress, this, &TaskStepWrapper::propagateStepProgress); connect(m_task.get(), &Task::status, this, &TaskStepWrapper::setStatus); connect(m_task.get(), &Task::details, this, &TaskStepWrapper::setDetails); emit progressReportingRequest(); } void TaskStepWrapper::proceed() { m_task->start(); } void TaskStepWrapper::updateFinished() { if (m_task->wasSuccessful()) { m_task.reset(); emitSucceeded(); } else { QString reason = tr("Instance update failed because: %1\n\n").arg(m_task->failReason()); m_task.reset(); emit logLine(reason, MessageLevel::Fatal); emitFailed(reason); } } bool TaskStepWrapper::canAbort() const { if (m_task) { return m_task->canAbort(); } return true; } bool TaskStepWrapper::abort() { if (m_task && m_task->canAbort()) { auto status = m_task->abort(); emitFailed("Aborted."); return status; } return Task::abort(); }
1,992
C++
.cpp
61
28.590164
96
0.685714
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,132
LaunchTask.cpp
PrismLauncher_PrismLauncher/launcher/launch/LaunchTask.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Authors: Orochimarufan <orochimarufan.x3@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "launch/LaunchTask.h" #include <assert.h> #include <QCoreApplication> #include <QDebug> #include <QDir> #include <QEventLoop> #include <QRegularExpression> #include <QStandardPaths> #include "MessageLevel.h" #include "tasks/Task.h" void LaunchTask::init() { m_instance->setRunning(true); } shared_qobject_ptr<LaunchTask> LaunchTask::create(MinecraftInstancePtr inst) { shared_qobject_ptr<LaunchTask> proc(new LaunchTask(inst)); proc->init(); return proc; } LaunchTask::LaunchTask(MinecraftInstancePtr instance) : m_instance(instance) {} void LaunchTask::appendStep(shared_qobject_ptr<LaunchStep> step) { m_steps.append(step); } void LaunchTask::prependStep(shared_qobject_ptr<LaunchStep> step) { m_steps.prepend(step); } void LaunchTask::executeTask() { m_instance->setCrashed(false); if (!m_steps.size()) { state = LaunchTask::Finished; emitSucceeded(); } state = LaunchTask::Running; onStepFinished(); } void LaunchTask::onReadyForLaunch() { state = LaunchTask::Waiting; emit readyForLaunch(); } void LaunchTask::onStepFinished() { // initial -> just start the first step if (currentStep == -1) { currentStep++; m_steps[currentStep]->start(); return; } auto step = m_steps[currentStep]; if (step->wasSuccessful()) { // end? if (currentStep == m_steps.size() - 1) { finalizeSteps(true, QString()); } else { currentStep++; step = m_steps[currentStep]; step->start(); } } else { finalizeSteps(false, step->failReason()); } } void LaunchTask::finalizeSteps(bool successful, const QString& error) { for (auto step = currentStep; step >= 0; step--) { m_steps[step]->finalize(); } if (successful) { emitSucceeded(); } else { emitFailed(error); } } void LaunchTask::onProgressReportingRequested() { state = LaunchTask::Waiting; emit requestProgress(m_steps[currentStep].get()); } void LaunchTask::setCensorFilter(QMap<QString, QString> filter) { m_censorFilter = filter; } QString LaunchTask::censorPrivateInfo(QString in) { auto iter = m_censorFilter.begin(); while (iter != m_censorFilter.end()) { in.replace(iter.key(), iter.value()); iter++; } return in; } void LaunchTask::proceed() { if (state != LaunchTask::Waiting) { return; } m_steps[currentStep]->proceed(); } bool LaunchTask::canAbort() const { switch (state) { case LaunchTask::Aborted: case LaunchTask::Failed: case LaunchTask::Finished: return false; case LaunchTask::NotStarted: return true; case LaunchTask::Running: case LaunchTask::Waiting: { auto step = m_steps[currentStep]; return step->canAbort(); } } return false; } bool LaunchTask::abort() { switch (state) { case LaunchTask::Aborted: case LaunchTask::Failed: case LaunchTask::Finished: return true; case LaunchTask::NotStarted: { state = LaunchTask::Aborted; emitFailed("Aborted"); return true; } case LaunchTask::Running: case LaunchTask::Waiting: { auto step = m_steps[currentStep]; if (!step->canAbort()) { return false; } if (step->abort()) { state = LaunchTask::Aborted; return true; } } default: break; } return false; } shared_qobject_ptr<LogModel> LaunchTask::getLogModel() { if (!m_logModel) { m_logModel.reset(new LogModel()); m_logModel->setMaxLines(m_instance->getConsoleMaxLines()); m_logModel->setStopOnOverflow(m_instance->shouldStopOnConsoleOverflow()); // FIXME: should this really be here? m_logModel->setOverflowMessage(tr("Stopped watching the game log because the log length surpassed %1 lines.\n" "You may have to fix your mods because the game is still logging to files and" " likely wasting harddrive space at an alarming rate!") .arg(m_logModel->getMaxLines())); } return m_logModel; } void LaunchTask::onLogLines(const QStringList& lines, MessageLevel::Enum defaultLevel) { for (auto& line : lines) { onLogLine(line, defaultLevel); } } void LaunchTask::onLogLine(QString line, MessageLevel::Enum level) { // if the launcher part set a log level, use it auto innerLevel = MessageLevel::fromLine(line); if (innerLevel != MessageLevel::Unknown) { level = innerLevel; } // If the level is still undetermined, guess level if (level == MessageLevel::StdErr || level == MessageLevel::StdOut || level == MessageLevel::Unknown) { level = m_instance->guessLevel(line, level); } // censor private user info line = censorPrivateInfo(line); auto& model = *getLogModel(); model.append(level, line); } void LaunchTask::emitSucceeded() { m_instance->setRunning(false); Task::emitSucceeded(); } void LaunchTask::emitFailed(QString reason) { m_instance->setRunning(false); m_instance->setCrashed(true); Task::emitFailed(reason); } void LaunchTask::substituteVariables(QStringList& args) const { auto env = m_instance->createEnvironment(); for (auto key : env.keys()) { args.replaceInStrings("$" + key, env.value(key)); } } void LaunchTask::substituteVariables(QString& cmd) const { auto env = m_instance->createEnvironment(); for (auto key : env.keys()) { cmd.replace("$" + key, env.value(key)); } }
7,422
C++
.cpp
244
25.065574
120
0.652958
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,133
LogModel.cpp
PrismLauncher_PrismLauncher/launcher/launch/LogModel.cpp
#include "LogModel.h" LogModel::LogModel(QObject* parent) : QAbstractListModel(parent) { m_content.resize(m_maxLines); } int LogModel::rowCount(const QModelIndex& parent) const { if (parent.isValid()) return 0; return m_numLines; } QVariant LogModel::data(const QModelIndex& index, int role) const { if (index.row() < 0 || index.row() >= m_numLines) return QVariant(); auto row = index.row(); auto realRow = (row + m_firstLine) % m_maxLines; if (role == Qt::DisplayRole || role == Qt::EditRole) { return m_content[realRow].line; } if (role == LevelRole) { return m_content[realRow].level; } return QVariant(); } void LogModel::append(MessageLevel::Enum level, QString line) { if (m_suspended) { return; } int lineNum = (m_firstLine + m_numLines) % m_maxLines; // overflow if (m_numLines == m_maxLines) { if (m_stopOnOverflow) { // nothing more to do, the buffer is full return; } beginRemoveRows(QModelIndex(), 0, 0); m_firstLine = (m_firstLine + 1) % m_maxLines; m_numLines--; endRemoveRows(); } else if (m_numLines == m_maxLines - 1 && m_stopOnOverflow) { level = MessageLevel::Fatal; line = m_overflowMessage; } beginInsertRows(QModelIndex(), m_numLines, m_numLines); m_numLines++; m_content[lineNum].level = level; m_content[lineNum].line = line; endInsertRows(); } void LogModel::suspend(bool suspend) { m_suspended = suspend; } bool LogModel::suspended() { return m_suspended; } void LogModel::clear() { beginResetModel(); m_firstLine = 0; m_numLines = 0; endResetModel(); } QString LogModel::toPlainText() { QString out; out.reserve(m_numLines * 80); for (int i = 0; i < m_numLines; i++) { QString& line = m_content[(m_firstLine + i) % m_maxLines].line; out.append(line + '\n'); } out.squeeze(); return out; } void LogModel::setMaxLines(int maxLines) { // no-op if (maxLines == m_maxLines) { return; } // if it all still fits in the buffer, just resize it if (m_firstLine + m_numLines < m_maxLines) { m_maxLines = maxLines; m_content.resize(maxLines); return; } // otherwise, we need to reorganize the data because it crosses the wrap boundary QVector<entry> newContent; newContent.resize(maxLines); if (m_numLines <= maxLines) { // if it all fits in the new buffer, just copy it over for (int i = 0; i < m_numLines; i++) { newContent[i] = m_content[(m_firstLine + i) % m_maxLines]; } m_content.swap(newContent); } else { // if it doesn't fit, part of the data needs to be thrown away (the oldest log messages) int lead = m_numLines - maxLines; beginRemoveRows(QModelIndex(), 0, lead - 1); for (int i = 0; i < maxLines; i++) { newContent[i] = m_content[(m_firstLine + lead + i) % m_maxLines]; } m_numLines = m_maxLines; m_content.swap(newContent); endRemoveRows(); } m_firstLine = 0; m_maxLines = maxLines; } int LogModel::getMaxLines() { return m_maxLines; } void LogModel::setStopOnOverflow(bool stop) { m_stopOnOverflow = stop; } void LogModel::setOverflowMessage(const QString& overflowMessage) { m_overflowMessage = overflowMessage; } void LogModel::setLineWrap(bool state) { if (m_lineWrap != state) { m_lineWrap = state; } } bool LogModel::wrapLines() const { return m_lineWrap; }
3,636
C++
.cpp
134
22.097015
96
0.623529
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
29,134
LaunchStep.cpp
PrismLauncher_PrismLauncher/launcher/launch/LaunchStep.cpp
/* 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 "LaunchStep.h" #include "LaunchTask.h" LaunchStep::LaunchStep(LaunchTask* parent) : Task(), m_parent(parent) { connect(this, &LaunchStep::readyForLaunch, parent, &LaunchTask::onReadyForLaunch); connect(this, &LaunchStep::logLine, parent, &LaunchTask::onLogLine); connect(this, &LaunchStep::logLines, parent, &LaunchTask::onLogLines); connect(this, &LaunchStep::finished, parent, &LaunchTask::onStepFinished); connect(this, &LaunchStep::progressReportingRequest, parent, &LaunchTask::onProgressReportingRequested); }
1,153
C++
.cpp
24
45.583333
108
0.766637
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,136
LookupServerAddress.cpp
PrismLauncher_PrismLauncher/launcher/launch/steps/LookupServerAddress.cpp
/* 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 "LookupServerAddress.h" #include <launch/LaunchTask.h> LookupServerAddress::LookupServerAddress(LaunchTask* parent) : LaunchStep(parent), m_dnsLookup(new QDnsLookup(this)) { connect(m_dnsLookup, &QDnsLookup::finished, this, &LookupServerAddress::on_dnsLookupFinished); m_dnsLookup->setType(QDnsLookup::SRV); } void LookupServerAddress::setLookupAddress(const QString& lookupAddress) { m_lookupAddress = lookupAddress; m_dnsLookup->setName(QString("_minecraft._tcp.%1").arg(lookupAddress)); } void LookupServerAddress::setOutputAddressPtr(MinecraftTarget::Ptr output) { m_output = std::move(output); } bool LookupServerAddress::abort() { m_dnsLookup->abort(); emitFailed("Aborted"); return true; } void LookupServerAddress::executeTask() { m_dnsLookup->lookup(); } void LookupServerAddress::on_dnsLookupFinished() { if (isFinished()) { // Aborted return; } if (m_dnsLookup->error() != QDnsLookup::NoError) { emit logLine(QString("Failed to resolve server address (this is NOT an error!) %1: %2\n") .arg(m_dnsLookup->name(), m_dnsLookup->errorString()), MessageLevel::Launcher); resolve(m_lookupAddress, 25565); // Technically the task failed, however, we don't abort the launch // and leave it up to minecraft to fail (or maybe not) when connecting return; } const auto records = m_dnsLookup->serviceRecords(); if (records.empty()) { emit logLine(QString("Failed to resolve server address %1: the DNS lookup succeeded, but no records were returned.\n") .arg(m_dnsLookup->name()), MessageLevel::Warning); resolve(m_lookupAddress, 25565); // Technically the task failed, however, we don't abort the launch // and leave it up to minecraft to fail (or maybe not) when connecting return; } const auto& firstRecord = records.at(0); quint16 port = firstRecord.port(); emit logLine( QString("Resolved server address %1 to %2 with port %3\n").arg(m_dnsLookup->name(), firstRecord.target(), QString::number(port)), MessageLevel::Launcher); resolve(firstRecord.target(), port); } void LookupServerAddress::resolve(const QString& address, quint16 port) { m_output->address = address; m_output->port = port; emitSucceeded(); m_dnsLookup->deleteLater(); }
3,125
C++
.cpp
77
34.649351
137
0.683811
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,137
CheckJava.cpp
PrismLauncher_PrismLauncher/launcher/launch/steps/CheckJava.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 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 "CheckJava.h" #include <FileSystem.h> #include <launch/LaunchTask.h> #include <sys.h> #include <QCryptographicHash> #include <QFileInfo> #include <QStandardPaths> #include "java/JavaUtils.h" void CheckJava::executeTask() { auto instance = m_parent->instance(); auto settings = instance->settings(); QString javaPathSetting = settings->get("JavaPath").toString(); m_javaPath = FS::ResolveExecutable(javaPathSetting); bool perInstance = settings->get("OverrideJava").toBool() || settings->get("OverrideJavaLocation").toBool(); auto realJavaPath = QStandardPaths::findExecutable(m_javaPath); if (realJavaPath.isEmpty()) { if (perInstance) { emit logLine(QString("The Java binary \"%1\" couldn't be found. Please fix the Java path " "override in the instance's settings or disable it.") .arg(javaPathSetting), MessageLevel::Warning); } else { emit logLine(QString("The Java binary \"%1\" couldn't be found. Please set up Java in " "the settings.") .arg(javaPathSetting), MessageLevel::Warning); } emitFailed(QString("Java path is not valid.")); return; } else { emit logLine("Java path is:\n" + m_javaPath + "\n\n", MessageLevel::Launcher); } if (JavaUtils::getJavaCheckPath().isEmpty()) { const char* reason = QT_TR_NOOP("Java checker library could not be found. Please check your installation."); emit logLine(tr(reason), MessageLevel::Fatal); emitFailed(tr(reason)); return; } QFileInfo javaInfo(realJavaPath); qint64 javaUnixTime = javaInfo.lastModified().toMSecsSinceEpoch(); auto storedSignature = settings->get("JavaSignature").toString(); auto storedArchitecture = settings->get("JavaArchitecture").toString(); auto storedRealArchitecture = settings->get("JavaRealArchitecture").toString(); auto storedVersion = settings->get("JavaVersion").toString(); auto storedVendor = settings->get("JavaVendor").toString(); QCryptographicHash hash(QCryptographicHash::Sha1); hash.addData(QByteArray::number(javaUnixTime)); hash.addData(m_javaPath.toUtf8()); m_javaSignature = hash.result().toHex(); // if timestamps are not the same, or something is missing, check! if (m_javaSignature != storedSignature || storedVersion.size() == 0 || storedArchitecture.size() == 0 || storedRealArchitecture.size() == 0 || storedVendor.size() == 0) { m_JavaChecker.reset(new JavaChecker(realJavaPath, "", 0, 0, 0, 0)); emit logLine(QString("Checking Java version..."), MessageLevel::Launcher); connect(m_JavaChecker.get(), &JavaChecker::checkFinished, this, &CheckJava::checkJavaFinished); m_JavaChecker->start(); return; } else { auto verString = instance->settings()->get("JavaVersion").toString(); auto archString = instance->settings()->get("JavaArchitecture").toString(); auto realArchString = settings->get("JavaRealArchitecture").toString(); auto vendorString = instance->settings()->get("JavaVendor").toString(); printJavaInfo(verString, archString, realArchString, vendorString); } m_parent->instance()->updateRuntimeContext(); emitSucceeded(); } void CheckJava::checkJavaFinished(const JavaChecker::Result& result) { switch (result.validity) { case JavaChecker::Result::Validity::Errored: { // Error message displayed if java can't start emit logLine(QString("Could not start java:"), MessageLevel::Error); emit logLines(result.errorLog.split('\n'), MessageLevel::Error); emit logLine(QString("\nCheck your Java settings."), MessageLevel::Launcher); emitFailed(QString("Could not start java!")); return; } case JavaChecker::Result::Validity::ReturnedInvalidData: { emit logLine(QString("Java checker returned some invalid data we don't understand:"), MessageLevel::Error); emit logLines(result.outLog.split('\n'), MessageLevel::Warning); emit logLine("\nMinecraft might not start properly.", MessageLevel::Launcher); m_parent->instance()->updateRuntimeContext(); emitSucceeded(); return; } case JavaChecker::Result::Validity::Valid: { auto instance = m_parent->instance(); printJavaInfo(result.javaVersion.toString(), result.mojangPlatform, result.realPlatform, result.javaVendor); instance->settings()->set("JavaVersion", result.javaVersion.toString()); instance->settings()->set("JavaArchitecture", result.mojangPlatform); instance->settings()->set("JavaRealArchitecture", result.realPlatform); instance->settings()->set("JavaVendor", result.javaVendor); instance->settings()->set("JavaSignature", m_javaSignature); m_parent->instance()->updateRuntimeContext(); emitSucceeded(); return; } } } void CheckJava::printJavaInfo(const QString& version, const QString& architecture, const QString& realArchitecture, const QString& vendor) { emit logLine( QString("Java is version %1, using %2 (%3) architecture, from %4.\n\n").arg(version, architecture, realArchitecture, vendor), MessageLevel::Launcher); }
7,023
C++
.cpp
141
42.702128
138
0.673847
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,138
QuitAfterGameStop.cpp
PrismLauncher_PrismLauncher/launcher/launch/steps/QuitAfterGameStop.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 dada513 <dada513@protonmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "QuitAfterGameStop.h" #include <launch/LaunchTask.h> #include "Application.h" void QuitAfterGameStop::executeTask() { APPLICATION->quit(); }
895
C++
.cpp
24
35.416667
74
0.754891
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,139
TextPrint.cpp
PrismLauncher_PrismLauncher/launcher/launch/steps/TextPrint.cpp
#include "TextPrint.h" TextPrint::TextPrint(LaunchTask* parent, const QStringList& lines, MessageLevel::Enum level) : LaunchStep(parent) { m_lines = lines; m_level = level; } TextPrint::TextPrint(LaunchTask* parent, const QString& line, MessageLevel::Enum level) : LaunchStep(parent) { m_lines.append(line); m_level = level; } void TextPrint::executeTask() { emit logLines(m_lines, m_level); emitSucceeded(); } bool TextPrint::canAbort() const { return true; } bool TextPrint::abort() { emitFailed("Aborted."); return true; }
566
C++
.cpp
25
20.04
113
0.72067
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
29,140
PrintServers.cpp
PrismLauncher_PrismLauncher/launcher/launch/steps/PrintServers.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2024 Leia uwu <leia@tutamail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "PrintServers.h" #include "QHostInfo" PrintServers::PrintServers(LaunchTask* parent, const QStringList& servers) : LaunchStep(parent) { m_servers = servers; } void PrintServers::executeTask() { for (QString server : m_servers) { QHostInfo::lookupHost(server, this, &PrintServers::resolveServer); } } void PrintServers::resolveServer(const QHostInfo& host_info) { QString server = host_info.hostName(); QString addresses = server + " resolves to:\n ["; if (!host_info.addresses().isEmpty()) { for (QHostAddress address : host_info.addresses()) { addresses += address.toString(); if (!host_info.addresses().endsWith(address)) { addresses += ", "; } } } else { addresses += "N/A"; } addresses += "]\n\n"; m_server_to_address.insert(server, addresses); // print server info in order once all servers are resolved if (m_server_to_address.size() >= m_servers.size()) { for (QString serv : m_servers) { emit logLine(m_server_to_address.value(serv), MessageLevel::Launcher); } emitSucceeded(); } } bool PrintServers::canAbort() const { return true; }
1,974
C++
.cpp
57
30.140351
95
0.675746
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,142
FileLink.cpp
PrismLauncher_PrismLauncher/launcher/filelink/FileLink.cpp
// SPDX-FileCopyrightText: 2022 Rachel Powers <508861+Ryex@users.noreply.github.com> // // SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Rachel Powers <508861+Ryex@users.noreply.github.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #include "FileLink.h" #include "BuildConfig.h" #include "StringUtils.h" #include <iostream> #include <QAccessible> #include <QCommandLineParser> #include <QDebug> #include <DesktopServices.h> #include <sys.h> #if defined Q_OS_WIN32 #include "WindowsConsole.h" #endif // Snippet from https://github.com/gulrak/filesystem#using-it-as-single-file-header #ifdef __APPLE__ #include <Availability.h> // for deployment target to support pre-catalina targets without std::fs #endif // __APPLE__ #if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || (defined(__cplusplus) && __cplusplus >= 201703L)) && defined(__has_include) #if __has_include(<filesystem>) && (!defined(__MAC_OS_X_VERSION_MIN_REQUIRED) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 101500) #define GHC_USE_STD_FS #include <filesystem> namespace fs = std::filesystem; #endif // MacOS min version check #endif // Other OSes version check #ifndef GHC_USE_STD_FS #include <ghc/filesystem.hpp> namespace fs = ghc::filesystem; #endif FileLinkApp::FileLinkApp(int& argc, char** argv) : QCoreApplication(argc, argv), socket(new QLocalSocket(this)) { #if defined Q_OS_WIN32 // attach the parent console if (AttachWindowsConsole()) { consoleAttached = true; } #endif setOrganizationName(BuildConfig.LAUNCHER_NAME); setOrganizationDomain(BuildConfig.LAUNCHER_DOMAIN); setApplicationName(BuildConfig.LAUNCHER_NAME + "FileLink"); setApplicationVersion(BuildConfig.printableVersionString() + "\n" + BuildConfig.GIT_COMMIT); // Commandline parsing QCommandLineParser parser; parser.setApplicationDescription(QObject::tr("a batch MKLINK program for windows to be used with prismlauncher")); parser.addOptions({ { { "s", "server" }, "Join the specified server on launch", "pipe name" }, { { "H", "hard" }, "use hard links instead of symbolic", "true/false" } }); parser.addHelpOption(); parser.addVersionOption(); parser.process(arguments()); QString serverToJoin = parser.value("server"); m_useHardLinks = QVariant(parser.value("hard")).toBool(); qDebug() << "link program launched"; if (!serverToJoin.isEmpty()) { qDebug() << "joining server" << serverToJoin; joinServer(serverToJoin); } else { qDebug() << "no server to join"; m_status = Failed; exit(); } } void FileLinkApp::joinServer(QString server) { blockSize = 0; in.setDevice(&socket); connect(&socket, &QLocalSocket::connected, this, []() { qDebug() << "connected to server"; }); connect(&socket, &QLocalSocket::readyRead, this, &FileLinkApp::readPathPairs); connect(&socket, &QLocalSocket::errorOccurred, this, [this](QLocalSocket::LocalSocketError socketError) { m_status = Failed; switch (socketError) { case QLocalSocket::ServerNotFoundError: qDebug() << ("The host was not found. Please make sure " "that the server is running and that the " "server name is correct."); break; case QLocalSocket::ConnectionRefusedError: qDebug() << ("The connection was refused by the peer. " "Make sure the server is running, " "and check that the server name " "is correct."); break; case QLocalSocket::PeerClosedError: qDebug() << ("The connection was closed by the peer. "); break; default: qDebug() << "The following error occurred: " << socket.errorString(); } }); connect(&socket, &QLocalSocket::disconnected, this, [this]() { qDebug() << "disconnected from server, should exit"; m_status = Succeeded; exit(); }); socket.connectToServer(server); } void FileLinkApp::runLink() { std::error_code os_err; qDebug() << "creating links"; for (auto link : m_links_to_make) { QString src_path = link.src; QString dst_path = link.dst; FS::ensureFilePathExists(dst_path); if (m_useHardLinks) { qDebug() << "making hard link:" << src_path << "to" << dst_path; fs::create_hard_link(StringUtils::toStdString(src_path), StringUtils::toStdString(dst_path), os_err); } else if (fs::is_directory(StringUtils::toStdString(src_path))) { qDebug() << "making directory_symlink:" << src_path << "to" << dst_path; fs::create_directory_symlink(StringUtils::toStdString(src_path), StringUtils::toStdString(dst_path), os_err); } else { qDebug() << "making symlink:" << src_path << "to" << dst_path; fs::create_symlink(StringUtils::toStdString(src_path), StringUtils::toStdString(dst_path), os_err); } if (os_err) { qWarning() << "Failed to link files:" << QString::fromStdString(os_err.message()); qDebug() << "Source file:" << src_path; qDebug() << "Destination file:" << dst_path; qDebug() << "Error category:" << os_err.category().name(); qDebug() << "Error code:" << os_err.value(); FS::LinkResult result = { src_path, dst_path, QString::fromStdString(os_err.message()), os_err.value() }; m_path_results.append(result); } else { FS::LinkResult result = { src_path, dst_path, "", 0 }; m_path_results.append(result); } } sendResults(); qDebug() << "done, should exit soon"; } void FileLinkApp::sendResults() { // construct block of data to send QByteArray block; QDataStream out(&block, QIODevice::WriteOnly); qint32 blocksize = quint32(sizeof(quint32)); for (auto result : m_path_results) { blocksize += quint32(result.src.size()); blocksize += quint32(result.dst.size()); blocksize += quint32(result.err_msg.size()); blocksize += quint32(sizeof(quint32)); } qDebug() << "About to write block of size:" << blocksize; out << blocksize; out << quint32(m_path_results.length()); for (auto result : m_path_results) { out << result.src; out << result.dst; out << result.err_msg; out << quint32(result.err_value); } qint64 byteswritten = socket.write(block); bool bytesflushed = socket.flush(); qDebug() << "block flushed" << byteswritten << bytesflushed; } void FileLinkApp::readPathPairs() { m_links_to_make.clear(); qDebug() << "Reading path pairs from server"; qDebug() << "bytes available" << socket.bytesAvailable(); if (blockSize == 0) { // Relies on the fact that QDataStream serializes a quint32 into // sizeof(quint32) bytes if (socket.bytesAvailable() < (int)sizeof(quint32)) return; qDebug() << "reading block size"; in >> blockSize; } qDebug() << "blocksize is" << blockSize; qDebug() << "bytes available" << socket.bytesAvailable(); if (socket.bytesAvailable() < blockSize || in.atEnd()) return; quint32 numLinks; in >> numLinks; qDebug() << "numLinks" << numLinks; for (quint32 i = 0; i < numLinks; i++) { FS::LinkPair pair; in >> pair.src; in >> pair.dst; qDebug() << "link" << pair.src << "to" << pair.dst; m_links_to_make.append(pair); } runLink(); } FileLinkApp::~FileLinkApp() { qDebug() << "link program shutting down"; // Shut down logger by setting the logger function to nothing qInstallMessageHandler(nullptr); #if defined Q_OS_WIN32 // Detach from Windows console if (consoleAttached) { fclose(stdout); fclose(stdin); fclose(stderr); } #endif }
8,714
C++
.cpp
217
33.516129
130
0.631492
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,143
filelink_main.cpp
PrismLauncher_PrismLauncher/launcher/filelink/filelink_main.cpp
// SPDX-FileCopyrightText: 2022 Rachel Powers <508861+Ryex@users.noreply.github.com> // // SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Rachel Powers <508861+Ryex@users.noreply.github.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #include "FileLink.h" int main(int argc, char* argv[]) { FileLinkApp ldh(argc, argv); switch (ldh.status()) { case FileLinkApp::Starting: case FileLinkApp::Initialized: { return ldh.exec(); } case FileLinkApp::Failed: return 1; case FileLinkApp::Succeeded: return 0; default: return -1; } }
1,253
C++
.cpp
37
29.405405
84
0.688944
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,144
JavaMetadata.cpp
PrismLauncher_PrismLauncher/launcher/java/JavaMetadata.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2023-2024 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "java/JavaMetadata.h" #include <memory> #include "Json.h" #include "StringUtils.h" #include "java/JavaVersion.h" #include "minecraft/ParseUtils.h" namespace Java { DownloadType parseDownloadType(QString javaDownload) { if (javaDownload == "manifest") return DownloadType::Manifest; else if (javaDownload == "archive") return DownloadType::Archive; else return DownloadType::Unknown; } QString downloadTypeToString(DownloadType javaDownload) { switch (javaDownload) { case DownloadType::Manifest: return "manifest"; case DownloadType::Archive: return "archive"; case DownloadType::Unknown: break; } return "unknown"; } MetadataPtr parseJavaMeta(const QJsonObject& in) { auto meta = std::make_shared<Metadata>(); meta->m_name = Json::ensureString(in, "name", ""); meta->vendor = Json::ensureString(in, "vendor", ""); meta->url = Json::ensureString(in, "url", ""); meta->releaseTime = timeFromS3Time(Json::ensureString(in, "releaseTime", "")); meta->downloadType = parseDownloadType(Json::ensureString(in, "downloadType", "")); meta->packageType = Json::ensureString(in, "packageType", ""); meta->runtimeOS = Json::ensureString(in, "runtimeOS", "unknown"); if (in.contains("checksum")) { auto obj = Json::requireObject(in, "checksum"); meta->checksumHash = Json::ensureString(obj, "hash", ""); meta->checksumType = Json::ensureString(obj, "type", ""); } if (in.contains("version")) { auto obj = Json::requireObject(in, "version"); auto name = Json::ensureString(obj, "name", ""); auto major = Json::ensureInteger(obj, "major", 0); auto minor = Json::ensureInteger(obj, "minor", 0); auto security = Json::ensureInteger(obj, "security", 0); auto build = Json::ensureInteger(obj, "build", 0); meta->version = JavaVersion(major, minor, security, build, name); } return meta; } bool Metadata::operator<(const Metadata& rhs) { auto id = version; if (id < rhs.version) { return true; } if (id > rhs.version) { return false; } auto date = releaseTime; if (date < rhs.releaseTime) { return true; } if (date > rhs.releaseTime) { return false; } return StringUtils::naturalCompare(m_name, rhs.m_name, Qt::CaseInsensitive) < 0; } bool Metadata::operator==(const Metadata& rhs) { return version == rhs.version && m_name == rhs.m_name; } bool Metadata::operator>(const Metadata& rhs) { return (!operator<(rhs)) && (!operator==(rhs)); } bool Metadata::operator<(BaseVersion& a) { try { return operator<(dynamic_cast<Metadata&>(a)); } catch (const std::bad_cast& e) { return BaseVersion::operator<(a); } } bool Metadata::operator>(BaseVersion& a) { try { return operator>(dynamic_cast<Metadata&>(a)); } catch (const std::bad_cast& e) { return BaseVersion::operator>(a); } } } // namespace Java
3,829
C++
.cpp
114
29
87
0.663875
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,145
JavaVersion.cpp
PrismLauncher_PrismLauncher/launcher/java/JavaVersion.cpp
#include "JavaVersion.h" #include "StringUtils.h" #include <QRegularExpression> #include <QString> JavaVersion& JavaVersion::operator=(const QString& javaVersionString) { m_string = javaVersionString; auto getCapturedInteger = [](const QRegularExpressionMatch& match, const QString& what) -> int { auto str = match.captured(what); if (str.isEmpty()) { return 0; } return str.toInt(); }; QRegularExpression pattern; if (javaVersionString.startsWith("1.")) { pattern = QRegularExpression("1[.](?<major>[0-9]+)([.](?<minor>[0-9]+))?(_(?<security>[0-9]+)?)?(-(?<prerelease>[a-zA-Z0-9]+))?"); } else { pattern = QRegularExpression("(?<major>[0-9]+)([.](?<minor>[0-9]+))?([.](?<security>[0-9]+))?(-(?<prerelease>[a-zA-Z0-9]+))?"); } auto match = pattern.match(m_string); m_parseable = match.hasMatch(); m_major = getCapturedInteger(match, "major"); m_minor = getCapturedInteger(match, "minor"); m_security = getCapturedInteger(match, "security"); m_prerelease = match.captured("prerelease"); return *this; } JavaVersion::JavaVersion(const QString& rhs) { operator=(rhs); } QString JavaVersion::toString() const { return m_string; } bool JavaVersion::requiresPermGen() const { return !m_parseable || m_major < 8; } bool JavaVersion::defaultsToUtf8() const { // starting from Java 18, UTF-8 is the default charset: https://openjdk.org/jeps/400 return m_parseable && m_major >= 18; } bool JavaVersion::isModular() const { return m_parseable && m_major >= 9; } bool JavaVersion::operator<(const JavaVersion& rhs) { if (m_parseable && rhs.m_parseable) { auto major = m_major; auto rmajor = rhs.m_major; if (major < rmajor) return true; if (major > rmajor) return false; if (m_minor < rhs.m_minor) return true; if (m_minor > rhs.m_minor) return false; if (m_security < rhs.m_security) return true; if (m_security > rhs.m_security) return false; // everything else being equal, consider prerelease status bool thisPre = !m_prerelease.isEmpty(); bool rhsPre = !rhs.m_prerelease.isEmpty(); if (thisPre && !rhsPre) { // this is a prerelease and the other one isn't -> lesser return true; } else if (!thisPre && rhsPre) { // this isn't a prerelease and the other one is -> greater return false; } else if (thisPre && rhsPre) { // both are prereleases - use natural compare... return StringUtils::naturalCompare(m_prerelease, rhs.m_prerelease, Qt::CaseSensitive) < 0; } // neither is prerelease, so they are the same -> this cannot be less than rhs return false; } else return StringUtils::naturalCompare(m_string, rhs.m_string, Qt::CaseSensitive) < 0; } bool JavaVersion::operator==(const JavaVersion& rhs) { if (m_parseable && rhs.m_parseable) { return m_major == rhs.m_major && m_minor == rhs.m_minor && m_security == rhs.m_security && m_prerelease == rhs.m_prerelease; } return m_string == rhs.m_string; } bool JavaVersion::operator>(const JavaVersion& rhs) { return (!operator<(rhs)) && (!operator==(rhs)); } JavaVersion::JavaVersion(int major, int minor, int security, int build, QString name) : m_major(major), m_minor(minor), m_security(security), m_name(name), m_parseable(true) { QStringList versions; if (build != 0) { m_prerelease = QString::number(build); versions.push_front(m_prerelease); } if (m_security != 0) versions.push_front(QString::number(m_security)); else if (!versions.isEmpty()) versions.push_front("0"); if (m_minor != 0) versions.push_front(QString::number(m_minor)); else if (!versions.isEmpty()) versions.push_front("0"); versions.push_front(QString::number(m_major)); m_string = versions.join("."); }
4,082
C++
.cpp
114
29.842105
138
0.62557
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,146
JavaInstall.cpp
PrismLauncher_PrismLauncher/launcher/java/JavaInstall.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2023-2024 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "JavaInstall.h" #include "BaseVersion.h" #include "StringUtils.h" bool JavaInstall::operator<(const JavaInstall& rhs) { auto archCompare = StringUtils::naturalCompare(arch, rhs.arch, Qt::CaseInsensitive); if (archCompare != 0) return archCompare < 0; if (id < rhs.id) { return true; } if (id > rhs.id) { return false; } return StringUtils::naturalCompare(path, rhs.path, Qt::CaseInsensitive) < 0; } bool JavaInstall::operator==(const JavaInstall& rhs) { return arch == rhs.arch && id == rhs.id && path == rhs.path; } bool JavaInstall::operator>(const JavaInstall& rhs) { return (!operator<(rhs)) && (!operator==(rhs)); } bool JavaInstall::operator<(BaseVersion& a) { try { return operator<(dynamic_cast<JavaInstall&>(a)); } catch (const std::bad_cast& e) { return BaseVersion::operator<(a); } } bool JavaInstall::operator>(BaseVersion& a) { try { return operator>(dynamic_cast<JavaInstall&>(a)); } catch (const std::bad_cast& e) { return BaseVersion::operator>(a); } }
1,851
C++
.cpp
57
29.052632
88
0.693341
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,147
JavaInstallList.cpp
PrismLauncher_PrismLauncher/launcher/java/JavaInstallList.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * 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 * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <QtNetwork> #include <QtXml> #include <QDebug> #include <algorithm> #include "Application.h" #include "java/JavaChecker.h" #include "java/JavaInstallList.h" #include "java/JavaUtils.h" #include "tasks/ConcurrentTask.h" JavaInstallList::JavaInstallList(QObject* parent, bool onlyManagedVersions) : BaseVersionList(parent), m_only_managed_versions(onlyManagedVersions) {} Task::Ptr JavaInstallList::getLoadTask() { load(); return getCurrentTask(); } Task::Ptr JavaInstallList::getCurrentTask() { if (m_status == Status::InProgress) { return m_load_task; } return nullptr; } void JavaInstallList::load() { if (m_status != Status::InProgress) { m_status = Status::InProgress; m_load_task.reset(new JavaListLoadTask(this, m_only_managed_versions)); m_load_task->start(); } } const BaseVersion::Ptr JavaInstallList::at(int i) const { return m_vlist.at(i); } bool JavaInstallList::isLoaded() { return m_status == JavaInstallList::Status::Done; } int JavaInstallList::count() const { return m_vlist.count(); } QVariant JavaInstallList::data(const QModelIndex& index, int role) const { if (!index.isValid()) return QVariant(); if (index.row() > count()) return QVariant(); auto version = std::dynamic_pointer_cast<JavaInstall>(m_vlist[index.row()]); switch (role) { case SortRole: return -index.row(); case VersionPointerRole: return QVariant::fromValue(m_vlist[index.row()]); case VersionIdRole: return version->descriptor(); case VersionRole: return version->id.toString(); case RecommendedRole: return version->recommended; case PathRole: return version->path; case CPUArchitectureRole: return version->arch; default: return QVariant(); } } BaseVersionList::RoleList JavaInstallList::providesRoles() const { return { VersionPointerRole, VersionIdRole, VersionRole, RecommendedRole, PathRole, CPUArchitectureRole }; } void JavaInstallList::updateListData(QList<BaseVersion::Ptr> versions) { beginResetModel(); m_vlist = versions; sortVersions(); if (m_vlist.size()) { auto best = std::dynamic_pointer_cast<JavaInstall>(m_vlist[0]); best->recommended = true; } endResetModel(); m_status = Status::Done; m_load_task.reset(); } bool sortJavas(BaseVersion::Ptr left, BaseVersion::Ptr right) { auto rleft = std::dynamic_pointer_cast<JavaInstall>(right); auto rright = std::dynamic_pointer_cast<JavaInstall>(left); return (*rleft) > (*rright); } void JavaInstallList::sortVersions() { beginResetModel(); std::sort(m_vlist.begin(), m_vlist.end(), sortJavas); endResetModel(); } JavaListLoadTask::JavaListLoadTask(JavaInstallList* vlist, bool onlyManagedVersions) : Task(), m_only_managed_versions(onlyManagedVersions) { m_list = vlist; m_current_recommended = NULL; } void JavaListLoadTask::executeTask() { setStatus(tr("Detecting Java installations...")); JavaUtils ju; QList<QString> candidate_paths = m_only_managed_versions ? getPrismJavaBundle() : ju.FindJavaPaths(); ConcurrentTask::Ptr job(new ConcurrentTask("Java detection", APPLICATION->settings()->get("NumberOfConcurrentTasks").toInt())); m_job.reset(job); connect(m_job.get(), &Task::finished, this, &JavaListLoadTask::javaCheckerFinished); connect(m_job.get(), &Task::progress, this, &Task::setProgress); qDebug() << "Probing the following Java paths: "; int id = 0; for (QString candidate : candidate_paths) { auto checker = new JavaChecker(candidate, "", 0, 0, 0, id); connect(checker, &JavaChecker::checkFinished, [this](const JavaChecker::Result& result) { m_results << result; }); job->addTask(Task::Ptr(checker)); id++; } m_job->start(); } void JavaListLoadTask::javaCheckerFinished() { QList<JavaInstallPtr> candidates; std::sort(m_results.begin(), m_results.end(), [](const JavaChecker::Result& a, const JavaChecker::Result& b) { return a.id < b.id; }); qDebug() << "Found the following valid Java installations:"; for (auto result : m_results) { if (result.validity == JavaChecker::Result::Validity::Valid) { JavaInstallPtr javaVersion(new JavaInstall()); javaVersion->id = result.javaVersion; javaVersion->arch = result.realPlatform; javaVersion->path = result.path; javaVersion->is_64bit = result.is_64bit; candidates.append(javaVersion); qDebug() << " " << javaVersion->id.toString() << javaVersion->arch << javaVersion->path; } } QList<BaseVersion::Ptr> javas_bvp; for (auto java : candidates) { // qDebug() << java->id << java->arch << " at " << java->path; BaseVersion::Ptr bp_java = std::dynamic_pointer_cast<BaseVersion>(java); if (bp_java) { javas_bvp.append(java); } } m_list->updateListData(javas_bvp); emitSucceeded(); }
6,703
C++
.cpp
185
31.540541
139
0.685419
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,148
JavaUtils.cpp
PrismLauncher_PrismLauncher/launcher/java/JavaUtils.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 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 <QDir> #include <QFileInfo> #include <QString> #include <QStringList> #include <settings/Setting.h> #include <QDebug> #include "Application.h" #include "FileSystem.h" #include "java/JavaInstallList.h" #include "java/JavaUtils.h" #define IBUS "@im=ibus" JavaUtils::JavaUtils() {} QString stripVariableEntries(QString name, QString target, QString remove) { char delimiter = ':'; #ifdef Q_OS_WIN32 delimiter = ';'; #endif auto targetItems = target.split(delimiter); auto toRemove = remove.split(delimiter); for (QString item : toRemove) { bool removed = targetItems.removeOne(item); if (!removed) qWarning() << "Entry" << item << "could not be stripped from variable" << name; } return targetItems.join(delimiter); } QProcessEnvironment CleanEnviroment() { // prepare the process environment QProcessEnvironment rawenv = QProcessEnvironment::systemEnvironment(); QProcessEnvironment env; QStringList ignored = { "JAVA_ARGS", "CLASSPATH", "CONFIGPATH", "JAVA_HOME", "JRE_HOME", "_JAVA_OPTIONS", "JAVA_OPTIONS", "JAVA_TOOL_OPTIONS" }; QStringList stripped = { #if defined(Q_OS_LINUX) || defined(Q_OS_FREEBSD) || defined(Q_OS_OPENBSD) "LD_LIBRARY_PATH", "LD_PRELOAD", #endif "QT_PLUGIN_PATH", "QT_FONTPATH" }; for (auto key : rawenv.keys()) { auto value = rawenv.value(key); // filter out dangerous java crap if (ignored.contains(key)) { qDebug() << "Env: ignoring" << key << value; continue; } // These are used to strip the original variables // If there is "LD_LIBRARY_PATH" and "LAUNCHER_LD_LIBRARY_PATH", we want to // remove all values in "LAUNCHER_LD_LIBRARY_PATH" from "LD_LIBRARY_PATH" if (key.startsWith("LAUNCHER_")) { qDebug() << "Env: ignoring" << key << value; continue; } if (stripped.contains(key)) { QString newValue = stripVariableEntries(key, value, rawenv.value("LAUNCHER_" + key)); qDebug() << "Env: stripped" << key << value << "to" << newValue; value = newValue; } #if defined(Q_OS_LINUX) || defined(Q_OS_FREEBSD) || defined(Q_OS_OPENBSD) // Strip IBus // IBus is a Linux IME framework. For some reason, it breaks MC? if (key == "XMODIFIERS" && value.contains(IBUS)) { QString save = value; value.replace(IBUS, ""); qDebug() << "Env: stripped" << IBUS << "from" << save << ":" << value; } #endif // qDebug() << "Env: " << key << value; env.insert(key, value); } #ifdef Q_OS_LINUX // HACK: Workaround for QTBUG-42500 if (!env.contains("LD_LIBRARY_PATH")) { env.insert("LD_LIBRARY_PATH", ""); } #endif return env; } JavaInstallPtr JavaUtils::MakeJavaPtr(QString path, QString id, QString arch) { JavaInstallPtr javaVersion(new JavaInstall()); javaVersion->id = id; javaVersion->arch = arch; javaVersion->path = path; return javaVersion; } JavaInstallPtr JavaUtils::GetDefaultJava() { JavaInstallPtr javaVersion(new JavaInstall()); javaVersion->id = "java"; javaVersion->arch = "unknown"; #if defined(Q_OS_WIN32) javaVersion->path = "javaw"; #else javaVersion->path = "java"; #endif return javaVersion; } QStringList addJavasFromEnv(QList<QString> javas) { auto env = qEnvironmentVariable("PRISMLAUNCHER_JAVA_PATHS"); // FIXME: use launcher name from buildconfig #if defined(Q_OS_WIN32) QList<QString> javaPaths = env.replace("\\", "/").split(QLatin1String(";")); auto envPath = qEnvironmentVariable("PATH"); QList<QString> javaPathsfromPath = envPath.replace("\\", "/").split(QLatin1String(";")); for (QString string : javaPathsfromPath) { javaPaths.append(string + "/javaw.exe"); } #else QList<QString> javaPaths = env.split(QLatin1String(":")); #endif for (QString i : javaPaths) { javas.append(i); }; return javas; } #if defined(Q_OS_WIN32) QList<JavaInstallPtr> JavaUtils::FindJavaFromRegistryKey(DWORD keyType, QString keyName, QString keyJavaDir, QString subkeySuffix) { QList<JavaInstallPtr> javas; QString archType = "unknown"; if (keyType == KEY_WOW64_64KEY) archType = "64"; else if (keyType == KEY_WOW64_32KEY) archType = "32"; for (HKEY baseRegistry : { HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE }) { HKEY jreKey; if (RegOpenKeyExW(baseRegistry, keyName.toStdWString().c_str(), 0, KEY_READ | keyType | KEY_ENUMERATE_SUB_KEYS, &jreKey) == ERROR_SUCCESS) { // Read the current type version from the registry. // This will be used to find any key that contains the JavaHome value. WCHAR subKeyName[255]; DWORD subKeyNameSize, numSubKeys, retCode; // Get the number of subkeys RegQueryInfoKeyW(jreKey, NULL, NULL, NULL, &numSubKeys, NULL, NULL, NULL, NULL, NULL, NULL, NULL); // Iterate until RegEnumKeyEx fails if (numSubKeys > 0) { for (DWORD i = 0; i < numSubKeys; i++) { subKeyNameSize = 255; retCode = RegEnumKeyExW(jreKey, i, subKeyName, &subKeyNameSize, NULL, NULL, NULL, NULL); QString newSubkeyName = QString::fromWCharArray(subKeyName); if (retCode == ERROR_SUCCESS) { // Now open the registry key for the version that we just got. QString newKeyName = keyName + "\\" + newSubkeyName + subkeySuffix; HKEY newKey; if (RegOpenKeyExW(baseRegistry, newKeyName.toStdWString().c_str(), 0, KEY_READ | keyType, &newKey) == ERROR_SUCCESS) { // Read the JavaHome value to find where Java is installed. DWORD valueSz = 0; if (RegQueryValueExW(newKey, keyJavaDir.toStdWString().c_str(), NULL, NULL, NULL, &valueSz) == ERROR_SUCCESS) { WCHAR* value = new WCHAR[valueSz]; RegQueryValueExW(newKey, keyJavaDir.toStdWString().c_str(), NULL, NULL, (BYTE*)value, &valueSz); QString newValue = QString::fromWCharArray(value); delete[] value; // Now, we construct the version object and add it to the list. JavaInstallPtr javaVersion(new JavaInstall()); javaVersion->id = newSubkeyName; javaVersion->arch = archType; javaVersion->path = QDir(FS::PathCombine(newValue, "bin")).absoluteFilePath("javaw.exe"); javas.append(javaVersion); } RegCloseKey(newKey); } } } } RegCloseKey(jreKey); } } return javas; } QList<QString> JavaUtils::FindJavaPaths() { QList<JavaInstallPtr> java_candidates; // Oracle QList<JavaInstallPtr> JRE64s = this->FindJavaFromRegistryKey(KEY_WOW64_64KEY, "SOFTWARE\\JavaSoft\\Java Runtime Environment", "JavaHome"); QList<JavaInstallPtr> JDK64s = this->FindJavaFromRegistryKey(KEY_WOW64_64KEY, "SOFTWARE\\JavaSoft\\Java Development Kit", "JavaHome"); QList<JavaInstallPtr> JRE32s = this->FindJavaFromRegistryKey(KEY_WOW64_32KEY, "SOFTWARE\\JavaSoft\\Java Runtime Environment", "JavaHome"); QList<JavaInstallPtr> JDK32s = this->FindJavaFromRegistryKey(KEY_WOW64_32KEY, "SOFTWARE\\JavaSoft\\Java Development Kit", "JavaHome"); // Oracle for Java 9 and newer QList<JavaInstallPtr> NEWJRE64s = this->FindJavaFromRegistryKey(KEY_WOW64_64KEY, "SOFTWARE\\JavaSoft\\JRE", "JavaHome"); QList<JavaInstallPtr> NEWJDK64s = this->FindJavaFromRegistryKey(KEY_WOW64_64KEY, "SOFTWARE\\JavaSoft\\JDK", "JavaHome"); QList<JavaInstallPtr> NEWJRE32s = this->FindJavaFromRegistryKey(KEY_WOW64_32KEY, "SOFTWARE\\JavaSoft\\JRE", "JavaHome"); QList<JavaInstallPtr> NEWJDK32s = this->FindJavaFromRegistryKey(KEY_WOW64_32KEY, "SOFTWARE\\JavaSoft\\JDK", "JavaHome"); // AdoptOpenJDK QList<JavaInstallPtr> ADOPTOPENJRE32s = this->FindJavaFromRegistryKey(KEY_WOW64_32KEY, "SOFTWARE\\AdoptOpenJDK\\JRE", "Path", "\\hotspot\\MSI"); QList<JavaInstallPtr> ADOPTOPENJRE64s = this->FindJavaFromRegistryKey(KEY_WOW64_64KEY, "SOFTWARE\\AdoptOpenJDK\\JRE", "Path", "\\hotspot\\MSI"); QList<JavaInstallPtr> ADOPTOPENJDK32s = this->FindJavaFromRegistryKey(KEY_WOW64_32KEY, "SOFTWARE\\AdoptOpenJDK\\JDK", "Path", "\\hotspot\\MSI"); QList<JavaInstallPtr> ADOPTOPENJDK64s = this->FindJavaFromRegistryKey(KEY_WOW64_64KEY, "SOFTWARE\\AdoptOpenJDK\\JDK", "Path", "\\hotspot\\MSI"); // Eclipse Foundation QList<JavaInstallPtr> FOUNDATIONJDK32s = this->FindJavaFromRegistryKey(KEY_WOW64_32KEY, "SOFTWARE\\Eclipse Foundation\\JDK", "Path", "\\hotspot\\MSI"); QList<JavaInstallPtr> FOUNDATIONJDK64s = this->FindJavaFromRegistryKey(KEY_WOW64_64KEY, "SOFTWARE\\Eclipse Foundation\\JDK", "Path", "\\hotspot\\MSI"); // Eclipse Adoptium QList<JavaInstallPtr> ADOPTIUMJRE32s = this->FindJavaFromRegistryKey(KEY_WOW64_32KEY, "SOFTWARE\\Eclipse Adoptium\\JRE", "Path", "\\hotspot\\MSI"); QList<JavaInstallPtr> ADOPTIUMJRE64s = this->FindJavaFromRegistryKey(KEY_WOW64_64KEY, "SOFTWARE\\Eclipse Adoptium\\JRE", "Path", "\\hotspot\\MSI"); QList<JavaInstallPtr> ADOPTIUMJDK32s = this->FindJavaFromRegistryKey(KEY_WOW64_32KEY, "SOFTWARE\\Eclipse Adoptium\\JDK", "Path", "\\hotspot\\MSI"); QList<JavaInstallPtr> ADOPTIUMJDK64s = this->FindJavaFromRegistryKey(KEY_WOW64_64KEY, "SOFTWARE\\Eclipse Adoptium\\JDK", "Path", "\\hotspot\\MSI"); // IBM Semeru QList<JavaInstallPtr> SEMERUJRE32s = this->FindJavaFromRegistryKey(KEY_WOW64_32KEY, "SOFTWARE\\Semeru\\JRE", "Path", "\\openj9\\MSI"); QList<JavaInstallPtr> SEMERUJRE64s = this->FindJavaFromRegistryKey(KEY_WOW64_64KEY, "SOFTWARE\\Semeru\\JRE", "Path", "\\openj9\\MSI"); QList<JavaInstallPtr> SEMERUJDK32s = this->FindJavaFromRegistryKey(KEY_WOW64_32KEY, "SOFTWARE\\Semeru\\JDK", "Path", "\\openj9\\MSI"); QList<JavaInstallPtr> SEMERUJDK64s = this->FindJavaFromRegistryKey(KEY_WOW64_64KEY, "SOFTWARE\\Semeru\\JDK", "Path", "\\openj9\\MSI"); // Microsoft QList<JavaInstallPtr> MICROSOFTJDK64s = this->FindJavaFromRegistryKey(KEY_WOW64_64KEY, "SOFTWARE\\Microsoft\\JDK", "Path", "\\hotspot\\MSI"); // Azul Zulu QList<JavaInstallPtr> ZULU64s = this->FindJavaFromRegistryKey(KEY_WOW64_64KEY, "SOFTWARE\\Azul Systems\\Zulu", "InstallationPath"); QList<JavaInstallPtr> ZULU32s = this->FindJavaFromRegistryKey(KEY_WOW64_32KEY, "SOFTWARE\\Azul Systems\\Zulu", "InstallationPath"); // BellSoft Liberica QList<JavaInstallPtr> LIBERICA64s = this->FindJavaFromRegistryKey(KEY_WOW64_64KEY, "SOFTWARE\\BellSoft\\Liberica", "InstallationPath"); QList<JavaInstallPtr> LIBERICA32s = this->FindJavaFromRegistryKey(KEY_WOW64_32KEY, "SOFTWARE\\BellSoft\\Liberica", "InstallationPath"); // List x64 before x86 java_candidates.append(JRE64s); java_candidates.append(NEWJRE64s); java_candidates.append(ADOPTOPENJRE64s); java_candidates.append(ADOPTIUMJRE64s); java_candidates.append(SEMERUJRE64s); java_candidates.append(MakeJavaPtr("C:/Program Files/Java/jre8/bin/javaw.exe")); java_candidates.append(MakeJavaPtr("C:/Program Files/Java/jre7/bin/javaw.exe")); java_candidates.append(MakeJavaPtr("C:/Program Files/Java/jre6/bin/javaw.exe")); java_candidates.append(JDK64s); java_candidates.append(NEWJDK64s); java_candidates.append(ADOPTOPENJDK64s); java_candidates.append(FOUNDATIONJDK64s); java_candidates.append(ADOPTIUMJDK64s); java_candidates.append(SEMERUJDK64s); java_candidates.append(MICROSOFTJDK64s); java_candidates.append(ZULU64s); java_candidates.append(LIBERICA64s); java_candidates.append(JRE32s); java_candidates.append(NEWJRE32s); java_candidates.append(ADOPTOPENJRE32s); java_candidates.append(ADOPTIUMJRE32s); java_candidates.append(SEMERUJRE32s); java_candidates.append(MakeJavaPtr("C:/Program Files (x86)/Java/jre8/bin/javaw.exe")); java_candidates.append(MakeJavaPtr("C:/Program Files (x86)/Java/jre7/bin/javaw.exe")); java_candidates.append(MakeJavaPtr("C:/Program Files (x86)/Java/jre6/bin/javaw.exe")); java_candidates.append(JDK32s); java_candidates.append(NEWJDK32s); java_candidates.append(ADOPTOPENJDK32s); java_candidates.append(FOUNDATIONJDK32s); java_candidates.append(ADOPTIUMJDK32s); java_candidates.append(SEMERUJDK32s); java_candidates.append(ZULU32s); java_candidates.append(LIBERICA32s); java_candidates.append(MakeJavaPtr(this->GetDefaultJava()->path)); QList<QString> candidates; for (JavaInstallPtr java_candidate : java_candidates) { if (!candidates.contains(java_candidate->path)) { candidates.append(java_candidate->path); } } candidates.append(getMinecraftJavaBundle()); candidates.append(getPrismJavaBundle()); candidates = addJavasFromEnv(candidates); candidates.removeDuplicates(); return candidates; } #elif defined(Q_OS_MAC) QList<QString> JavaUtils::FindJavaPaths() { QList<QString> javas; javas.append(this->GetDefaultJava()->path); javas.append("/Applications/Xcode.app/Contents/Applications/Application Loader.app/Contents/MacOS/itms/java/bin/java"); javas.append("/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java"); javas.append("/System/Library/Frameworks/JavaVM.framework/Versions/Current/Commands/java"); QDir libraryJVMDir("/Library/Java/JavaVirtualMachines/"); QStringList libraryJVMJavas = libraryJVMDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot); foreach (const QString& java, libraryJVMJavas) { javas.append(libraryJVMDir.absolutePath() + "/" + java + "/Contents/Home/bin/java"); javas.append(libraryJVMDir.absolutePath() + "/" + java + "/Contents/Home/jre/bin/java"); } QDir systemLibraryJVMDir("/System/Library/Java/JavaVirtualMachines/"); QStringList systemLibraryJVMJavas = systemLibraryJVMDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot); foreach (const QString& java, systemLibraryJVMJavas) { javas.append(systemLibraryJVMDir.absolutePath() + "/" + java + "/Contents/Home/bin/java"); javas.append(systemLibraryJVMDir.absolutePath() + "/" + java + "/Contents/Commands/java"); } auto home = qEnvironmentVariable("HOME"); // javas downloaded by sdkman QDir sdkmanDir(FS::PathCombine(home, ".sdkman/candidates/java")); QStringList sdkmanJavas = sdkmanDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot); foreach (const QString& java, sdkmanJavas) { javas.append(sdkmanDir.absolutePath() + "/" + java + "/bin/java"); } // java in user library folder (like from intellij downloads) QDir userLibraryJVMDir(FS::PathCombine(home, "Library/Java/JavaVirtualMachines/")); QStringList userLibraryJVMJavas = userLibraryJVMDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot); foreach (const QString& java, userLibraryJVMJavas) { javas.append(userLibraryJVMDir.absolutePath() + "/" + java + "/Contents/Home/bin/java"); javas.append(userLibraryJVMDir.absolutePath() + "/" + java + "/Contents/Commands/java"); } javas.append(getMinecraftJavaBundle()); javas.append(getPrismJavaBundle()); javas = addJavasFromEnv(javas); javas.removeDuplicates(); return javas; } #elif defined(Q_OS_LINUX) || defined(Q_OS_OPENBSD) || defined(Q_OS_FREEBSD) QList<QString> JavaUtils::FindJavaPaths() { QList<QString> javas; javas.append(this->GetDefaultJava()->path); auto scanJavaDir = [&javas]( const QString& dirPath, const std::function<bool(const QFileInfo&)>& filter = [](const QFileInfo&) { return true; }) { QDir dir(dirPath); if (!dir.exists()) return; auto entries = dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot); for (auto& entry : entries) { if (!filter(entry)) continue; QString prefix; prefix = entry.canonicalFilePath(); javas.append(FS::PathCombine(prefix, "jre/bin/java")); javas.append(FS::PathCombine(prefix, "bin/java")); } }; // java installed in a snap is installed in the standard directory, but underneath $SNAP auto snap = qEnvironmentVariable("SNAP"); auto scanJavaDirs = [scanJavaDir, snap](const QString& dirPath) { scanJavaDir(dirPath); if (!snap.isNull()) { scanJavaDir(snap + dirPath); } }; #if defined(Q_OS_LINUX) // oracle RPMs scanJavaDirs("/usr/java"); // general locations used by distro packaging scanJavaDirs("/usr/lib/jvm"); scanJavaDirs("/usr/lib64/jvm"); scanJavaDirs("/usr/lib32/jvm"); // Gentoo's locations for openjdk and openjdk-bin respectively auto gentooFilter = [](const QFileInfo& info) { QString fileName = info.fileName(); return fileName.startsWith("openjdk-") || fileName.startsWith("openj9-"); }; scanJavaDir("/usr/lib64", gentooFilter); scanJavaDir("/usr/lib", gentooFilter); scanJavaDir("/opt", gentooFilter); // javas stored in Prism Launcher's folder scanJavaDirs("java"); // manually installed JDKs in /opt scanJavaDirs("/opt/jdk"); scanJavaDirs("/opt/jdks"); scanJavaDirs("/opt/ibm"); // IBM Semeru Certified Edition // flatpak scanJavaDirs("/app/jdk"); #elif defined(Q_OS_OPENBSD) || defined(Q_OS_FREEBSD) // ports install to /usr/local on OpenBSD & FreeBSD scanJavaDirs("/usr/local"); #endif auto home = qEnvironmentVariable("HOME"); // javas downloaded by IntelliJ scanJavaDirs(FS::PathCombine(home, ".jdks")); // javas downloaded by sdkman scanJavaDirs(FS::PathCombine(home, ".sdkman/candidates/java")); // javas downloaded by gradle (toolchains) scanJavaDirs(FS::PathCombine(home, ".gradle/jdks")); javas.append(getMinecraftJavaBundle()); javas.append(getPrismJavaBundle()); javas = addJavasFromEnv(javas); javas.removeDuplicates(); return javas; } #else QList<QString> JavaUtils::FindJavaPaths() { qDebug() << "Unknown operating system build - defaulting to \"java\""; QList<QString> javas; javas.append(this->GetDefaultJava()->path); javas.append(getMinecraftJavaBundle()); javas.append(getPrismJavaBundle()); javas.removeDuplicates(); return addJavasFromEnv(javas); } #endif QString JavaUtils::getJavaCheckPath() { return APPLICATION->getJarPath("JavaCheck.jar"); } QStringList getMinecraftJavaBundle() { QStringList processpaths; #if defined(Q_OS_OSX) processpaths << FS::PathCombine(QDir::homePath(), FS::PathCombine("Library", "Application Support", "minecraft", "runtime")); #elif defined(Q_OS_WIN32) auto appDataPath = QProcessEnvironment::systemEnvironment().value("APPDATA", ""); processpaths << FS::PathCombine(QFileInfo(appDataPath).absoluteFilePath(), ".minecraft", "runtime"); // add the microsoft store version of the launcher to the search. the current path is: // C:\Users\USERNAME\AppData\Local\Packages\Microsoft.4297127D64EC6_8wekyb3d8bbwe\LocalCache\Local\runtime auto localAppDataPath = QProcessEnvironment::systemEnvironment().value("LOCALAPPDATA", ""); auto minecraftMSStorePath = FS::PathCombine(QFileInfo(localAppDataPath).absoluteFilePath(), "Packages", "Microsoft.4297127D64EC6_8wekyb3d8bbwe"); processpaths << FS::PathCombine(minecraftMSStorePath, "LocalCache", "Local", "runtime"); #else processpaths << FS::PathCombine(QDir::homePath(), ".minecraft", "runtime"); #endif QStringList javas; while (!processpaths.isEmpty()) { auto dirPath = processpaths.takeFirst(); QDir dir(dirPath); if (!dir.exists()) continue; auto entries = dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot); auto binFound = false; for (auto& entry : entries) { if (entry.baseName() == "bin") { javas.append(FS::PathCombine(entry.canonicalFilePath(), JavaUtils::javaExecutable)); binFound = true; break; } } if (!binFound) { for (auto& entry : entries) { processpaths << entry.canonicalFilePath(); } } } return javas; } #if defined(Q_OS_WIN32) const QString JavaUtils::javaExecutable = "javaw.exe"; #else const QString JavaUtils::javaExecutable = "java"; #endif QStringList getPrismJavaBundle() { QList<QString> javas; auto scanDir = [&javas](QString prefix) { javas.append(FS::PathCombine(prefix, "jre", "bin", JavaUtils::javaExecutable)); javas.append(FS::PathCombine(prefix, "bin", JavaUtils::javaExecutable)); javas.append(FS::PathCombine(prefix, JavaUtils::javaExecutable)); }; auto scanJavaDir = [scanDir](const QString& dirPath) { QDir dir(dirPath); if (!dir.exists()) return; auto entries = dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot); for (auto& entry : entries) { scanDir(entry.canonicalFilePath()); } }; scanJavaDir(APPLICATION->javaPath()); return javas; }
23,369
C++
.cpp
495
40.169697
139
0.672134
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,149
JavaChecker.cpp
PrismLauncher_PrismLauncher/launcher/java/JavaChecker.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 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 "JavaChecker.h" #include <QDebug> #include <QFile> #include <QMap> #include <QProcess> #include "Commandline.h" #include "FileSystem.h" #include "java/JavaUtils.h" JavaChecker::JavaChecker(QString path, QString args, int minMem, int maxMem, int permGen, int id) : Task(), m_path(path), m_args(args), m_minMem(minMem), m_maxMem(maxMem), m_permGen(permGen), m_id(id) {} void JavaChecker::executeTask() { QString checkerJar = JavaUtils::getJavaCheckPath(); if (checkerJar.isEmpty()) { qDebug() << "Java checker library could not be found. Please check your installation."; return; } #ifdef Q_OS_WIN checkerJar = FS::getPathNameInLocal8bit(checkerJar); #endif QStringList args; process.reset(new QProcess()); if (m_args.size()) { auto extraArgs = Commandline::splitArgs(m_args); args.append(extraArgs); } if (m_minMem != 0) { args << QString("-Xms%1m").arg(m_minMem); } if (m_maxMem != 0) { args << QString("-Xmx%1m").arg(m_maxMem); } if (m_permGen != 64 && m_permGen != 0) { args << QString("-XX:PermSize=%1m").arg(m_permGen); } args.append({ "-jar", checkerJar }); process->setArguments(args); process->setProgram(m_path); process->setProcessChannelMode(QProcess::SeparateChannels); process->setProcessEnvironment(CleanEnviroment()); qDebug() << "Running java checker:" << m_path << args.join(" "); connect(process.get(), QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this, &JavaChecker::finished); connect(process.get(), &QProcess::errorOccurred, this, &JavaChecker::error); connect(process.get(), &QProcess::readyReadStandardOutput, this, &JavaChecker::stdoutReady); connect(process.get(), &QProcess::readyReadStandardError, this, &JavaChecker::stderrReady); connect(&killTimer, &QTimer::timeout, this, &JavaChecker::timeout); killTimer.setSingleShot(true); killTimer.start(15000); process->start(); } void JavaChecker::stdoutReady() { QByteArray data = process->readAllStandardOutput(); QString added = QString::fromLocal8Bit(data); added.remove('\r'); m_stdout += added; } void JavaChecker::stderrReady() { QByteArray data = process->readAllStandardError(); QString added = QString::fromLocal8Bit(data); added.remove('\r'); m_stderr += added; } void JavaChecker::finished(int exitcode, QProcess::ExitStatus status) { killTimer.stop(); QProcessPtr _process = process; process.reset(); Result result = { m_path, m_id, }; result.errorLog = m_stderr; result.outLog = m_stdout; qDebug() << "STDOUT" << m_stdout; qWarning() << "STDERR" << m_stderr; qDebug() << "Java checker finished with status" << status << "exit code" << exitcode; if (status == QProcess::CrashExit || exitcode == 1) { result.validity = Result::Validity::Errored; emit checkFinished(result); emitSucceeded(); return; } bool success = true; QMap<QString, QString> results; #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) QStringList lines = m_stdout.split("\n", Qt::SkipEmptyParts); #else QStringList lines = m_stdout.split("\n", QString::SkipEmptyParts); #endif for (QString line : lines) { line = line.trimmed(); // NOTE: workaround for GH-4125, where garbage is getting printed into stdout on bedrock linux if (line.contains("/bedrock/strata")) { continue; } #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) auto parts = line.split('=', Qt::SkipEmptyParts); #else auto parts = line.split('=', QString::SkipEmptyParts); #endif if (parts.size() != 2 || parts[0].isEmpty() || parts[1].isEmpty()) { continue; } else { results.insert(parts[0], parts[1]); } } if (!results.contains("os.arch") || !results.contains("java.version") || !results.contains("java.vendor") || !success) { result.validity = Result::Validity::ReturnedInvalidData; emit checkFinished(result); emitSucceeded(); return; } auto os_arch = results["os.arch"]; auto java_version = results["java.version"]; auto java_vendor = results["java.vendor"]; bool is_64 = os_arch == "x86_64" || os_arch == "amd64" || os_arch == "aarch64" || os_arch == "arm64"; result.validity = Result::Validity::Valid; result.is_64bit = is_64; result.mojangPlatform = is_64 ? "64" : "32"; result.realPlatform = os_arch; result.javaVersion = java_version; result.javaVendor = java_vendor; qDebug() << "Java checker succeeded."; emit checkFinished(result); emitSucceeded(); } void JavaChecker::error(QProcess::ProcessError err) { if (err == QProcess::FailedToStart) { qDebug() << "Java checker has failed to start."; qDebug() << "Process environment:"; qDebug() << process->environment(); qDebug() << "Native environment:"; qDebug() << QProcessEnvironment::systemEnvironment().toStringList(); killTimer.stop(); emit checkFinished({ m_path, m_id }); } emitSucceeded(); } void JavaChecker::timeout() { // NO MERCY. NO ABUSE. if (process) { qDebug() << "Java checker has been killed by timeout."; process->kill(); } }
6,873
C++
.cpp
184
32.679348
124
0.664816
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,150
SymlinkTask.cpp
PrismLauncher_PrismLauncher/launcher/java/download/SymlinkTask.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2023-2024 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "java/download/SymlinkTask.h" #include <QFileInfo> #include "FileSystem.h" namespace Java { SymlinkTask::SymlinkTask(QString final_path) : m_path(final_path) {} QString findBinPath(QString root, QString pattern) { auto path = FS::PathCombine(root, pattern); if (QFileInfo::exists(path)) { return path; } auto entries = QDir(root).entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot); for (auto& entry : entries) { path = FS::PathCombine(entry.absoluteFilePath(), pattern); if (QFileInfo::exists(path)) { return path; } } return {}; } void SymlinkTask::executeTask() { setStatus(tr("Checking for Java binary path")); const auto binPath = FS::PathCombine("bin", "java"); const auto wantedPath = FS::PathCombine(m_path, binPath); if (QFileInfo::exists(wantedPath)) { emitSucceeded(); return; } setStatus(tr("Searching for Java binary path")); const auto contentsPartialPath = FS::PathCombine("Contents", "Home", binPath); const auto relativePathToBin = findBinPath(m_path, contentsPartialPath); if (relativePathToBin.isEmpty()) { emitFailed(tr("Failed to find Java binary path")); return; } const auto folderToLink = relativePathToBin.chopped(binPath.length()); setStatus(tr("Collecting folders to symlink")); auto entries = QDir(folderToLink).entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries); QList<FS::LinkPair> files; setProgress(0, entries.length()); for (auto& entry : entries) { files.append({ entry.absoluteFilePath(), FS::PathCombine(m_path, entry.fileName()) }); } setStatus(tr("Symlinking Java binary path")); FS::create_link folderLink(files); connect(&folderLink, &FS::create_link::fileLinked, [this](QString src, QString dst) { setProgress(m_progress + 1, m_progressTotal); }); if (!folderLink()) { emitFailed(folderLink.getOSError().message().c_str()); } else { emitSucceeded(); } } } // namespace Java
2,805
C++
.cpp
71
35.070423
139
0.696514
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,151
ManifestDownloadTask.cpp
PrismLauncher_PrismLauncher/launcher/java/download/ManifestDownloadTask.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2023-2024 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "java/download/ManifestDownloadTask.h" #include "Application.h" #include "FileSystem.h" #include "Json.h" #include "net/ChecksumValidator.h" #include "net/NetJob.h" struct File { QString path; QString url; QByteArray hash; bool isExec; }; namespace Java { ManifestDownloadTask::ManifestDownloadTask(QUrl url, QString final_path, QString checksumType, QString checksumHash) : m_url(url), m_final_path(final_path), m_checksum_type(checksumType), m_checksum_hash(checksumHash) {} void ManifestDownloadTask::executeTask() { setStatus(tr("Downloading Java")); auto download = makeShared<NetJob>(QString("JRE::DownloadJava"), APPLICATION->network()); auto files = std::make_shared<QByteArray>(); auto action = Net::Download::makeByteArray(m_url, files); if (!m_checksum_hash.isEmpty() && !m_checksum_type.isEmpty()) { auto hashType = QCryptographicHash::Algorithm::Sha1; if (m_checksum_type == "sha256") { hashType = QCryptographicHash::Algorithm::Sha256; } action->addValidator(new Net::ChecksumValidator(hashType, QByteArray::fromHex(m_checksum_hash.toUtf8()))); } download->addNetAction(action); connect(download.get(), &Task::failed, this, &ManifestDownloadTask::emitFailed); connect(download.get(), &Task::progress, this, &ManifestDownloadTask::setProgress); connect(download.get(), &Task::stepProgress, this, &ManifestDownloadTask::propagateStepProgress); connect(download.get(), &Task::status, this, &ManifestDownloadTask::setStatus); connect(download.get(), &Task::details, this, &ManifestDownloadTask::setDetails); connect(download.get(), &Task::succeeded, [files, this] { QJsonParseError parse_error{}; QJsonDocument doc = QJsonDocument::fromJson(*files, &parse_error); if (parse_error.error != QJsonParseError::NoError) { qWarning() << "Error while parsing JSON response at " << parse_error.offset << ". Reason: " << parse_error.errorString(); qWarning() << *files; emitFailed(parse_error.errorString()); return; } downloadJava(doc); }); m_task = download; m_task->start(); } void ManifestDownloadTask::downloadJava(const QJsonDocument& doc) { // valid json doc, begin making jre spot FS::ensureFolderPathExists(m_final_path); std::vector<File> toDownload; auto list = Json::ensureObject(Json::ensureObject(doc.object()), "files"); for (const auto& paths : list.keys()) { auto file = FS::PathCombine(m_final_path, paths); const QJsonObject& meta = Json::ensureObject(list, paths); auto type = Json::ensureString(meta, "type"); if (type == "directory") { FS::ensureFolderPathExists(file); } else if (type == "link") { // this is linux only ! auto path = Json::ensureString(meta, "target"); if (!path.isEmpty()) { auto target = FS::PathCombine(file, "../" + path); QFile(target).link(file); } } else if (type == "file") { // TODO download compressed version if it exists ? auto raw = Json::ensureObject(Json::ensureObject(meta, "downloads"), "raw"); auto isExec = Json::ensureBoolean(meta, "executable", false); auto url = Json::ensureString(raw, "url"); if (!url.isEmpty() && QUrl(url).isValid()) { auto f = File{ file, url, QByteArray::fromHex(Json::ensureString(raw, "sha1").toLatin1()), isExec }; toDownload.push_back(f); } } } auto elementDownload = makeShared<NetJob>("JRE::FileDownload", APPLICATION->network()); for (const auto& file : toDownload) { auto dl = Net::Download::makeFile(file.url, file.path); if (!file.hash.isEmpty()) { dl->addValidator(new Net::ChecksumValidator(QCryptographicHash::Sha1, file.hash)); } if (file.isExec) { connect(dl.get(), &Net::Download::succeeded, [file] { QFile(file.path).setPermissions(QFile(file.path).permissions() | QFileDevice::Permissions(0x1111)); }); } elementDownload->addNetAction(dl); } connect(elementDownload.get(), &Task::failed, this, &ManifestDownloadTask::emitFailed); connect(elementDownload.get(), &Task::progress, this, &ManifestDownloadTask::setProgress); connect(elementDownload.get(), &Task::stepProgress, this, &ManifestDownloadTask::propagateStepProgress); connect(elementDownload.get(), &Task::status, this, &ManifestDownloadTask::setStatus); connect(elementDownload.get(), &Task::details, this, &ManifestDownloadTask::setDetails); connect(elementDownload.get(), &Task::succeeded, this, &ManifestDownloadTask::emitSucceeded); m_task = elementDownload; m_task->start(); } bool ManifestDownloadTask::abort() { auto aborted = canAbort(); if (m_task) aborted = m_task->abort(); emitAborted(); return aborted; }; } // namespace Java
5,825
C++
.cpp
126
39.849206
133
0.668601
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,152
ArchiveDownloadTask.cpp
PrismLauncher_PrismLauncher/launcher/java/download/ArchiveDownloadTask.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2023-2024 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "java/download/ArchiveDownloadTask.h" #include <quazip.h> #include <memory> #include "MMCZip.h" #include "Application.h" #include "Untar.h" #include "net/ChecksumValidator.h" #include "net/NetJob.h" #include "tasks/Task.h" namespace Java { ArchiveDownloadTask::ArchiveDownloadTask(QUrl url, QString final_path, QString checksumType, QString checksumHash) : m_url(url), m_final_path(final_path), m_checksum_type(checksumType), m_checksum_hash(checksumHash) {} void ArchiveDownloadTask::executeTask() { // JRE found ! download the zip setStatus(tr("Downloading Java")); MetaEntryPtr entry = APPLICATION->metacache()->resolveEntry("java", m_url.fileName()); auto download = makeShared<NetJob>(QString("JRE::DownloadJava"), APPLICATION->network()); auto action = Net::Download::makeCached(m_url, entry); if (!m_checksum_hash.isEmpty() && !m_checksum_type.isEmpty()) { auto hashType = QCryptographicHash::Algorithm::Sha1; if (m_checksum_type == "sha256") { hashType = QCryptographicHash::Algorithm::Sha256; } action->addValidator(new Net::ChecksumValidator(hashType, QByteArray::fromHex(m_checksum_hash.toUtf8()))); } download->addNetAction(action); auto fullPath = entry->getFullPath(); connect(download.get(), &Task::failed, this, &ArchiveDownloadTask::emitFailed); connect(download.get(), &Task::progress, this, &ArchiveDownloadTask::setProgress); connect(download.get(), &Task::stepProgress, this, &ArchiveDownloadTask::propagateStepProgress); connect(download.get(), &Task::status, this, &ArchiveDownloadTask::setStatus); connect(download.get(), &Task::details, this, &ArchiveDownloadTask::setDetails); connect(download.get(), &Task::succeeded, [this, fullPath] { // This should do all of the extracting and creating folders extractJava(fullPath); }); m_task = download; m_task->start(); } void ArchiveDownloadTask::extractJava(QString input) { setStatus(tr("Extracting Java")); if (input.endsWith("tar")) { setStatus(tr("Extracting Java (Progress is not reported for tar archives)")); QFile in(input); if (!in.open(QFile::ReadOnly)) { emitFailed(tr("Unable to open supplied tar file.")); return; } if (!Tar::extract(&in, QDir(m_final_path).absolutePath())) { emitFailed(tr("Unable to extract supplied tar file.")); return; } emitSucceeded(); return; } else if (input.endsWith("tar.gz") || input.endsWith("taz") || input.endsWith("tgz")) { setStatus(tr("Extracting Java (Progress is not reported for tar archives)")); if (!GZTar::extract(input, QDir(m_final_path).absolutePath())) { emitFailed(tr("Unable to extract supplied tar file.")); return; } emitSucceeded(); return; } else if (input.endsWith("zip")) { auto zip = std::make_shared<QuaZip>(input); if (!zip->open(QuaZip::mdUnzip)) { emitFailed(tr("Unable to open supplied zip file.")); return; } auto files = zip->getFileNameList(); if (files.isEmpty()) { emitFailed(tr("No files were found in the supplied zip file.")); return; } m_task = makeShared<MMCZip::ExtractZipTask>(zip, m_final_path, files[0]); auto progressStep = std::make_shared<TaskStepProgress>(); connect(m_task.get(), &Task::finished, this, [this, progressStep] { progressStep->state = TaskStepState::Succeeded; stepProgress(*progressStep); }); connect(m_task.get(), &Task::succeeded, this, &ArchiveDownloadTask::emitSucceeded); connect(m_task.get(), &Task::aborted, this, &ArchiveDownloadTask::emitAborted); connect(m_task.get(), &Task::failed, this, [this, progressStep](QString reason) { progressStep->state = TaskStepState::Failed; stepProgress(*progressStep); emitFailed(reason); }); connect(m_task.get(), &Task::stepProgress, this, &ArchiveDownloadTask::propagateStepProgress); connect(m_task.get(), &Task::progress, this, [this, progressStep](qint64 current, qint64 total) { progressStep->update(current, total); stepProgress(*progressStep); }); connect(m_task.get(), &Task::status, this, [this, progressStep](QString status) { progressStep->status = status; stepProgress(*progressStep); }); m_task->start(); return; } emitFailed(tr("Could not determine archive type!")); } bool ArchiveDownloadTask::abort() { auto aborted = canAbort(); if (m_task) aborted = m_task->abort(); emitAborted(); return aborted; }; } // namespace Java
5,615
C++
.cpp
129
37.023256
114
0.6621
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,153
Version.cpp
PrismLauncher_PrismLauncher/launcher/meta/Version.cpp
/* Copyright 2015-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 "Version.h" #include <QDateTime> #include "JsonFormat.h" Meta::Version::Version(const QString& uid, const QString& version) : BaseVersion(), m_uid(uid), m_version(version) {} QString Meta::Version::descriptor() { return m_version; } QString Meta::Version::name() { if (m_data) return m_data->name; return m_uid; } QString Meta::Version::typeString() const { return m_type; } QDateTime Meta::Version::time() const { return QDateTime::fromMSecsSinceEpoch(m_time * 1000, Qt::UTC); } void Meta::Version::parse(const QJsonObject& obj) { parseVersion(obj, this); } void Meta::Version::mergeFromList(const Meta::Version::Ptr& other) { if (other->m_providesRecommendations) { if (m_recommended != other->m_recommended) { setRecommended(other->m_recommended); } } if (m_type != other->m_type) { setType(other->m_type); } if (m_time != other->m_time) { setTime(other->m_time); } if (m_requires != other->m_requires) { m_requires = other->m_requires; } if (m_conflicts != other->m_conflicts) { m_conflicts = other->m_conflicts; } if (m_volatile != other->m_volatile) { setVolatile(other->m_volatile); } if (!other->m_sha256.isEmpty()) { m_sha256 = other->m_sha256; } } void Meta::Version::merge(const Version::Ptr& other) { mergeFromList(other); if (other->m_data) { setData(other->m_data); } } QString Meta::Version::localFilename() const { return m_uid + '/' + m_version + ".json"; } ::Version Meta::Version::toComparableVersion() const { return { const_cast<Meta::Version*>(this)->descriptor() }; } void Meta::Version::setType(const QString& type) { m_type = type; emit typeChanged(); } void Meta::Version::setTime(const qint64 time) { m_time = time; emit timeChanged(); } void Meta::Version::setRequires(const Meta::RequireSet& reqs, const Meta::RequireSet& conflicts) { m_requires = reqs; m_conflicts = conflicts; emit requiresChanged(); } void Meta::Version::setVolatile(bool volatile_) { m_volatile = volatile_; } void Meta::Version::setData(const VersionFilePtr& data) { m_data = data; } void Meta::Version::setProvidesRecommendations() { m_providesRecommendations = true; } void Meta::Version::setRecommended(bool recommended) { m_recommended = recommended; }
3,027
C++
.cpp
113
23.424779
117
0.686119
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,154
BaseEntity.cpp
PrismLauncher_PrismLauncher/launcher/meta/BaseEntity.cpp
/* Copyright 2015-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 "BaseEntity.h" #include "Exception.h" #include "FileSystem.h" #include "Json.h" #include "modplatform/helpers/HashUtils.h" #include "net/ApiDownload.h" #include "net/ChecksumValidator.h" #include "net/HttpMetaCache.h" #include "net/Mode.h" #include "net/NetJob.h" #include "Application.h" #include "BuildConfig.h" #include "tasks/Task.h" namespace Meta { class ParsingValidator : public Net::Validator { public: /* con/des */ ParsingValidator(BaseEntity* entity) : m_entity(entity) {}; virtual ~ParsingValidator() = default; public: /* methods */ bool init(QNetworkRequest&) override { m_data.clear(); return true; } bool write(QByteArray& data) override { this->m_data.append(data); return true; } bool abort() override { m_data.clear(); return true; } bool validate(QNetworkReply&) override { auto fname = m_entity->localFilename(); try { auto doc = Json::requireDocument(m_data, fname); auto obj = Json::requireObject(doc, fname); m_entity->parse(obj); return true; } catch (const Exception& e) { qWarning() << "Unable to parse response:" << e.cause(); return false; } } private: /* data */ QByteArray m_data; BaseEntity* m_entity; }; QUrl BaseEntity::url() const { auto s = APPLICATION->settings(); QString metaOverride = s->get("MetaURLOverride").toString(); if (metaOverride.isEmpty()) { return QUrl(BuildConfig.META_URL).resolved(localFilename()); } return QUrl(metaOverride).resolved(localFilename()); } Task::Ptr BaseEntity::loadTask(Net::Mode mode) { if (m_task && m_task->isRunning()) { return m_task; } m_task.reset(new BaseEntityLoadTask(this, mode)); return m_task; } bool BaseEntity::isLoaded() const { // consider it loaded only if the main hash is either empty and was remote loadded or the hashes match and was loaded return m_sha256.isEmpty() ? m_load_status == LoadStatus::Remote : m_load_status != LoadStatus::NotLoaded && m_sha256 == m_file_sha256; } void BaseEntity::setSha256(QString sha256) { m_sha256 = sha256; } BaseEntity::LoadStatus BaseEntity::status() const { return m_load_status; } BaseEntityLoadTask::BaseEntityLoadTask(BaseEntity* parent, Net::Mode mode) : m_entity(parent), m_mode(mode) {} void BaseEntityLoadTask::executeTask() { const QString fname = QDir("meta").absoluteFilePath(m_entity->localFilename()); auto hashMatches = false; // the file exists on disk try to load it if (QFile::exists(fname)) { try { QByteArray fileData; // read local file if nothing is loaded yet if (m_entity->m_load_status == BaseEntity::LoadStatus::NotLoaded || m_entity->m_file_sha256.isEmpty()) { setStatus(tr("Loading local file")); fileData = FS::read(fname); m_entity->m_file_sha256 = Hashing::hash(fileData, Hashing::Algorithm::Sha256); } // on online the hash needs to match hashMatches = m_entity->m_sha256 == m_entity->m_file_sha256; if (m_mode == Net::Mode::Online && !m_entity->m_sha256.isEmpty() && !hashMatches) { throw Exception("mismatched checksum"); } // load local file if (m_entity->m_load_status == BaseEntity::LoadStatus::NotLoaded) { auto doc = Json::requireDocument(fileData, fname); auto obj = Json::requireObject(doc, fname); m_entity->parse(obj); m_entity->m_load_status = BaseEntity::LoadStatus::Local; } } catch (const Exception& e) { qDebug() << QString("Unable to parse file %1: %2").arg(fname, e.cause()); // just make sure it's gone and we never consider it again. FS::deletePath(fname); m_entity->m_load_status = BaseEntity::LoadStatus::NotLoaded; } } // if we need remote update, run the update task auto wasLoadedOffline = m_entity->m_load_status != BaseEntity::LoadStatus::NotLoaded && m_mode == Net::Mode::Offline; // if has is not present allways fetch from remote(e.g. the main index file), else only fetch if hash doesn't match auto wasLoadedRemote = m_entity->m_sha256.isEmpty() ? m_entity->m_load_status == BaseEntity::LoadStatus::Remote : hashMatches; if (wasLoadedOffline || wasLoadedRemote) { emitSucceeded(); return; } m_task.reset(new NetJob(QObject::tr("Download of meta file %1").arg(m_entity->localFilename()), APPLICATION->network())); auto url = m_entity->url(); auto entry = APPLICATION->metacache()->resolveEntry("meta", m_entity->localFilename()); entry->setStale(true); auto dl = Net::ApiDownload::makeCached(url, entry); /* * The validator parses the file and loads it into the object. * If that fails, the file is not written to storage. */ if (!m_entity->m_sha256.isEmpty()) dl->addValidator(new Net::ChecksumValidator(QCryptographicHash::Algorithm::Sha256, m_entity->m_sha256)); dl->addValidator(new ParsingValidator(m_entity)); m_task->addNetAction(dl); m_task->setAskRetry(false); connect(m_task.get(), &Task::failed, this, &BaseEntityLoadTask::emitFailed); connect(m_task.get(), &Task::succeeded, this, &BaseEntityLoadTask::emitSucceeded); connect(m_task.get(), &Task::succeeded, this, [this]() { m_entity->m_load_status = BaseEntity::LoadStatus::Remote; m_entity->m_file_sha256 = m_entity->m_sha256; }); connect(m_task.get(), &Task::progress, this, &Task::setProgress); connect(m_task.get(), &Task::stepProgress, this, &BaseEntityLoadTask::propagateStepProgress); connect(m_task.get(), &Task::status, this, &Task::setStatus); connect(m_task.get(), &Task::details, this, &Task::setDetails); m_task->start(); } bool BaseEntityLoadTask::canAbort() const { return m_task ? m_task->canAbort() : false; } bool BaseEntityLoadTask::abort() { if (m_task) { Task::abort(); return m_task->abort(); } return Task::abort(); } } // namespace Meta
6,887
C++
.cpp
176
33.204545
138
0.654507
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,155
Index.cpp
PrismLauncher_PrismLauncher/launcher/meta/Index.cpp
/* Copyright 2015-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 "Index.h" #include "JsonFormat.h" #include "QObjectPtr.h" #include "VersionList.h" #include "meta/BaseEntity.h" #include "tasks/SequentialTask.h" namespace Meta { Index::Index(QObject* parent) : QAbstractListModel(parent) {} Index::Index(const QVector<VersionList::Ptr>& lists, QObject* parent) : QAbstractListModel(parent), m_lists(lists) { for (int i = 0; i < m_lists.size(); ++i) { m_uids.insert(m_lists.at(i)->uid(), m_lists.at(i)); connectVersionList(i, m_lists.at(i)); } } QVariant Index::data(const QModelIndex& index, int role) const { if (index.parent().isValid() || index.row() < 0 || index.row() >= m_lists.size()) { return QVariant(); } VersionList::Ptr list = m_lists.at(index.row()); switch (role) { case Qt::DisplayRole: if (index.column() == 0) { return list->humanReadable(); } else { break; } case UidRole: return list->uid(); case NameRole: return list->name(); case ListPtrRole: return QVariant::fromValue(list); } return QVariant(); } int Index::rowCount(const QModelIndex& parent) const { return parent.isValid() ? 0 : m_lists.size(); } int Index::columnCount(const QModelIndex& parent) const { return parent.isValid() ? 0 : 1; } QVariant Index::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Horizontal && role == Qt::DisplayRole && section == 0) { return tr("Name"); } else { return QVariant(); } } bool Index::hasUid(const QString& uid) const { return m_uids.contains(uid); } VersionList::Ptr Index::get(const QString& uid) { VersionList::Ptr out = m_uids.value(uid, nullptr); if (!out) { out = std::make_shared<VersionList>(uid); m_uids[uid] = out; m_lists.append(out); } return out; } Version::Ptr Index::get(const QString& uid, const QString& version) { auto list = get(uid); return list->getVersion(version); } void Index::parse(const QJsonObject& obj) { parseIndex(obj, this); } void Index::merge(const std::shared_ptr<Index>& other) { const QVector<VersionList::Ptr> lists = other->m_lists; // initial load, no need to merge if (m_lists.isEmpty()) { beginResetModel(); m_lists = lists; for (int i = 0; i < lists.size(); ++i) { m_uids.insert(lists.at(i)->uid(), lists.at(i)); connectVersionList(i, lists.at(i)); } endResetModel(); } else { for (const VersionList::Ptr& list : lists) { if (m_uids.contains(list->uid())) { m_uids[list->uid()]->mergeFromIndex(list); } else { beginInsertRows(QModelIndex(), m_lists.size(), m_lists.size()); connectVersionList(m_lists.size(), list); m_lists.append(list); m_uids.insert(list->uid(), list); endInsertRows(); } } } } void Index::connectVersionList(const int row, const VersionList::Ptr& list) { connect(list.get(), &VersionList::nameChanged, this, [this, row] { emit dataChanged(index(row), index(row), { Qt::DisplayRole }); }); } Task::Ptr Index::loadVersion(const QString& uid, const QString& version, Net::Mode mode, bool force) { if (mode == Net::Mode::Offline) { return get(uid, version)->loadTask(mode); } auto versionList = get(uid); auto loadTask = makeShared<SequentialTask>(tr("Load meta for %1:%2", "This is for the task name that loads the meta index.").arg(uid, version)); if (status() != BaseEntity::LoadStatus::Remote || force) { loadTask->addTask(this->loadTask(mode)); } loadTask->addTask(versionList->loadTask(mode)); loadTask->addTask(versionList->getVersion(version)->loadTask(mode)); return loadTask; } Version::Ptr Index::getLoadedVersion(const QString& uid, const QString& version) { QEventLoop ev; auto task = loadVersion(uid, version); QObject::connect(task.get(), &Task::finished, &ev, &QEventLoop::quit); task->start(); ev.exec(); return get(uid, version); } } // namespace Meta
4,863
C++
.cpp
145
28.165517
137
0.637524
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,156
JsonFormat.cpp
PrismLauncher_PrismLauncher/launcher/meta/JsonFormat.cpp
/* Copyright 2015-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 "JsonFormat.h" // FIXME: remove this from here... somehow #include "Json.h" #include "minecraft/OneSixVersionFormat.h" #include "Index.h" #include "Version.h" #include "VersionList.h" using namespace Json; namespace Meta { MetadataVersion currentFormatVersion() { return MetadataVersion::InitialRelease; } // Index static std::shared_ptr<Index> parseIndexInternal(const QJsonObject& obj) { const QVector<QJsonObject> objects = requireIsArrayOf<QJsonObject>(obj, "packages"); QVector<VersionList::Ptr> lists; lists.reserve(objects.size()); std::transform(objects.begin(), objects.end(), std::back_inserter(lists), [](const QJsonObject& obj) { VersionList::Ptr list = std::make_shared<VersionList>(requireString(obj, "uid")); list->setName(ensureString(obj, "name", QString())); list->setSha256(ensureString(obj, "sha256", QString())); return list; }); return std::make_shared<Index>(lists); } // Version static Version::Ptr parseCommonVersion(const QString& uid, const QJsonObject& obj) { Version::Ptr version = std::make_shared<Version>(uid, requireString(obj, "version")); version->setTime(QDateTime::fromString(requireString(obj, "releaseTime"), Qt::ISODate).toMSecsSinceEpoch() / 1000); version->setType(ensureString(obj, "type", QString())); version->setRecommended(ensureBoolean(obj, QString("recommended"), false)); version->setVolatile(ensureBoolean(obj, QString("volatile"), false)); RequireSet reqs, conflicts; parseRequires(obj, &reqs, "requires"); parseRequires(obj, &conflicts, "conflicts"); version->setRequires(reqs, conflicts); if (auto sha256 = ensureString(obj, "sha256", QString()); !sha256.isEmpty()) { version->setSha256(sha256); } return version; } static Version::Ptr parseVersionInternal(const QJsonObject& obj) { Version::Ptr version = parseCommonVersion(requireString(obj, "uid"), obj); version->setData(OneSixVersionFormat::versionFileFromJson( QJsonDocument(obj), QString("%1/%2.json").arg(version->uid(), version->version()), obj.contains("order"))); return version; } // Version list / package static VersionList::Ptr parseVersionListInternal(const QJsonObject& obj) { const QString uid = requireString(obj, "uid"); const QVector<QJsonObject> versionsRaw = requireIsArrayOf<QJsonObject>(obj, "versions"); QVector<Version::Ptr> versions; versions.reserve(versionsRaw.size()); std::transform(versionsRaw.begin(), versionsRaw.end(), std::back_inserter(versions), [uid](const QJsonObject& vObj) { auto version = parseCommonVersion(uid, vObj); version->setProvidesRecommendations(); return version; }); VersionList::Ptr list = std::make_shared<VersionList>(uid); list->setName(ensureString(obj, "name", QString())); list->setVersions(versions); return list; } MetadataVersion parseFormatVersion(const QJsonObject& obj, bool required) { if (!obj.contains("formatVersion")) { if (required) { return MetadataVersion::Invalid; } return MetadataVersion::InitialRelease; } if (!obj.value("formatVersion").isDouble()) { return MetadataVersion::Invalid; } switch (obj.value("formatVersion").toInt()) { case 0: case 1: return MetadataVersion::InitialRelease; default: return MetadataVersion::Invalid; } } void serializeFormatVersion(QJsonObject& obj, Meta::MetadataVersion version) { if (version == MetadataVersion::Invalid) { return; } obj.insert("formatVersion", int(version)); } void parseIndex(const QJsonObject& obj, Index* ptr) { const MetadataVersion version = parseFormatVersion(obj); switch (version) { case MetadataVersion::InitialRelease: ptr->merge(parseIndexInternal(obj)); break; case MetadataVersion::Invalid: throw ParseException(QObject::tr("Unknown format version!")); } } void parseVersionList(const QJsonObject& obj, VersionList* ptr) { const MetadataVersion version = parseFormatVersion(obj); switch (version) { case MetadataVersion::InitialRelease: ptr->merge(parseVersionListInternal(obj)); break; case MetadataVersion::Invalid: throw ParseException(QObject::tr("Unknown format version!")); } } void parseVersion(const QJsonObject& obj, Version* ptr) { const MetadataVersion version = parseFormatVersion(obj); switch (version) { case MetadataVersion::InitialRelease: ptr->merge(parseVersionInternal(obj)); break; case MetadataVersion::Invalid: throw ParseException(QObject::tr("Unknown format version!")); } } /* [ {"uid":"foo", "equals":"version"} ] */ void parseRequires(const QJsonObject& obj, RequireSet* ptr, const char* keyName) { if (obj.contains(keyName)) { auto reqArray = requireArray(obj, keyName); auto iter = reqArray.begin(); while (iter != reqArray.end()) { auto reqObject = requireObject(*iter); auto uid = requireString(reqObject, "uid"); auto equals = ensureString(reqObject, "equals", QString()); auto suggests = ensureString(reqObject, "suggests", QString()); ptr->insert({ uid, equals, suggests }); iter++; } } } void serializeRequires(QJsonObject& obj, RequireSet* ptr, const char* keyName) { if (!ptr || ptr->empty()) { return; } QJsonArray arrOut; for (auto& iter : *ptr) { QJsonObject reqOut; reqOut.insert("uid", iter.uid); if (!iter.equalsVersion.isEmpty()) { reqOut.insert("equals", iter.equalsVersion); } if (!iter.suggests.isEmpty()) { reqOut.insert("suggests", iter.suggests); } arrOut.append(reqOut); } obj.insert(keyName, arrOut); } } // namespace Meta
6,612
C++
.cpp
181
31.19337
121
0.68554
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,157
VersionList.cpp
PrismLauncher_PrismLauncher/launcher/meta/VersionList.cpp
/* Copyright 2015-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 "VersionList.h" #include <QDateTime> #include <algorithm> #include "Application.h" #include "Index.h" #include "JsonFormat.h" #include "Version.h" #include "meta/BaseEntity.h" #include "net/Mode.h" #include "tasks/SequentialTask.h" namespace Meta { VersionList::VersionList(const QString& uid, QObject* parent) : BaseVersionList(parent), m_uid(uid) { setObjectName("Version list: " + uid); } Task::Ptr VersionList::getLoadTask() { auto loadTask = makeShared<SequentialTask>(tr("Load meta for %1", "This is for the task name that loads the meta index.").arg(m_uid)); loadTask->addTask(APPLICATION->metadataIndex()->loadTask(Net::Mode::Online)); loadTask->addTask(this->loadTask(Net::Mode::Online)); return loadTask; } bool VersionList::isLoaded() { return BaseEntity::isLoaded(); } const BaseVersion::Ptr VersionList::at(int i) const { return m_versions.at(i); } int VersionList::count() const { return m_versions.size(); } void VersionList::sortVersions() { beginResetModel(); std::sort(m_versions.begin(), m_versions.end(), [](const Version::Ptr& a, const Version::Ptr& b) { return *a.get() < *b.get(); }); endResetModel(); } QVariant VersionList::data(const QModelIndex& index, int role) const { if (!index.isValid() || index.row() < 0 || index.row() >= m_versions.size() || index.parent().isValid()) { return QVariant(); } Version::Ptr version = m_versions.at(index.row()); switch (role) { case VersionPointerRole: return QVariant::fromValue(std::dynamic_pointer_cast<BaseVersion>(version)); case VersionRole: case VersionIdRole: return version->version(); case ParentVersionRole: { // FIXME: HACK: this should be generic and be replaced by something else. Anything that is a hard 'equals' dep is a 'parent // uid'. auto& reqs = version->requiredSet(); auto iter = std::find_if(reqs.begin(), reqs.end(), [](const Require& req) { return req.uid == "net.minecraft"; }); if (iter != reqs.end()) { return (*iter).equalsVersion; } return QVariant(); } case TypeRole: return version->type(); case UidRole: return version->uid(); case TimeRole: return version->time(); case RequiresRole: return QVariant::fromValue(version->requiredSet()); case SortRole: return version->rawTime(); case VersionPtrRole: return QVariant::fromValue(version); case RecommendedRole: return version->isRecommended() || m_externalRecommendsVersions.contains(version->version()); case JavaMajorRole: { auto major = version->version(); if (major.startsWith("java")) { major = "Java " + major.mid(4); } return major; } // FIXME: this should be determined in whatever view/proxy is used... // case LatestRole: return version == getLatestStable(); default: return QVariant(); } } BaseVersionList::RoleList VersionList::providesRoles() const { return m_provided_roles; } void VersionList::setProvidedRoles(RoleList roles) { m_provided_roles = roles; }; QHash<int, QByteArray> VersionList::roleNames() const { QHash<int, QByteArray> roles = BaseVersionList::roleNames(); roles.insert(UidRole, "uid"); roles.insert(TimeRole, "time"); roles.insert(SortRole, "sort"); roles.insert(RequiresRole, "requires"); return roles; } QString VersionList::localFilename() const { return m_uid + "/index.json"; } QString VersionList::humanReadable() const { return m_name.isEmpty() ? m_uid : m_name; } Version::Ptr VersionList::getVersion(const QString& version) { Version::Ptr out = m_lookup.value(version, nullptr); if (!out) { out = std::make_shared<Version>(m_uid, version); m_lookup[version] = out; setupAddedVersion(m_versions.size(), out); m_versions.append(out); } return out; } bool VersionList::hasVersion(QString version) const { auto ver = std::find_if(m_versions.constBegin(), m_versions.constEnd(), [version](Meta::Version::Ptr const& a) { return a->version() == version; }); return (ver != m_versions.constEnd()); } void VersionList::setName(const QString& name) { m_name = name; emit nameChanged(name); } void VersionList::setVersions(const QVector<Version::Ptr>& versions) { beginResetModel(); m_versions = versions; std::sort(m_versions.begin(), m_versions.end(), [](const Version::Ptr& a, const Version::Ptr& b) { return a->rawTime() > b->rawTime(); }); for (int i = 0; i < m_versions.size(); ++i) { m_lookup.insert(m_versions.at(i)->version(), m_versions.at(i)); setupAddedVersion(i, m_versions.at(i)); } // FIXME: this is dumb, we have 'recommended' as part of the metadata already... auto recommendedIt = std::find_if(m_versions.constBegin(), m_versions.constEnd(), [](const Version::Ptr& ptr) { return ptr->type() == "release"; }); m_recommended = recommendedIt == m_versions.constEnd() ? nullptr : *recommendedIt; endResetModel(); } void VersionList::parse(const QJsonObject& obj) { parseVersionList(obj, this); } void VersionList::addExternalRecommends(const QStringList& recommends) { m_externalRecommendsVersions.append(recommends); } void VersionList::clearExternalRecommends() { m_externalRecommendsVersions.clear(); } // FIXME: this is dumb, we have 'recommended' as part of the metadata already... static const Meta::Version::Ptr& getBetterVersion(const Meta::Version::Ptr& a, const Meta::Version::Ptr& b) { if (!a) return b; if (!b) return a; if (a->type() == b->type()) { // newer of same type wins return (a->rawTime() > b->rawTime() ? a : b); } // 'release' type wins return (a->type() == "release" ? a : b); } void VersionList::mergeFromIndex(const VersionList::Ptr& other) { if (m_name != other->m_name) { setName(other->m_name); } if (!other->m_sha256.isEmpty()) { m_sha256 = other->m_sha256; } } void VersionList::merge(const VersionList::Ptr& other) { if (m_name != other->m_name) { setName(other->m_name); } if (!other->m_sha256.isEmpty()) { m_sha256 = other->m_sha256; } // TODO: do not reset the whole model. maybe? beginResetModel(); if (other->m_versions.isEmpty()) { qWarning() << "Empty list loaded ..."; } for (auto version : other->m_versions) { // we already have the version. merge the contents if (m_lookup.contains(version->version())) { auto existing = m_lookup.value(version->version()); existing->mergeFromList(version); version = existing; } else { m_lookup.insert(version->version(), version); // connect it. setupAddedVersion(m_versions.size(), version); m_versions.append(version); } m_recommended = getBetterVersion(m_recommended, version); } endResetModel(); } void VersionList::setupAddedVersion(const int row, const Version::Ptr& version) { disconnect(version.get(), &Version::requiresChanged, this, nullptr); disconnect(version.get(), &Version::timeChanged, this, nullptr); disconnect(version.get(), &Version::typeChanged, this, nullptr); connect(version.get(), &Version::requiresChanged, this, [this, row]() { emit dataChanged(index(row), index(row), QVector<int>() << RequiresRole); }); connect(version.get(), &Version::timeChanged, this, [this, row]() { emit dataChanged(index(row), index(row), { TimeRole, SortRole }); }); connect(version.get(), &Version::typeChanged, this, [this, row]() { emit dataChanged(index(row), index(row), { TypeRole }); }); } BaseVersion::Ptr VersionList::getRecommended() const { return m_recommended; } void VersionList::waitToLoad() { if (isLoaded()) return; QEventLoop ev; auto task = getLoadTask(); QObject::connect(task.get(), &Task::finished, &ev, &QEventLoop::quit); task->start(); ev.exec(); } Version::Ptr VersionList::getRecommendedForParent(const QString& uid, const QString& version) { auto foundExplicit = std::find_if(m_versions.begin(), m_versions.end(), [uid, version](Version::Ptr ver) -> bool { auto& reqs = ver->requiredSet(); auto parentReq = std::find_if(reqs.begin(), reqs.end(), [uid, version](const Require& req) -> bool { return req.uid == uid && req.equalsVersion == version; }); return parentReq != reqs.end() && ver->isRecommended(); }); if (foundExplicit != m_versions.end()) { return *foundExplicit; } return nullptr; } Version::Ptr VersionList::getLatestForParent(const QString& uid, const QString& version) { Version::Ptr latestCompat = nullptr; for (auto ver : m_versions) { auto& reqs = ver->requiredSet(); auto parentReq = std::find_if(reqs.begin(), reqs.end(), [uid, version](const Require& req) -> bool { return req.uid == uid && req.equalsVersion == version; }); if (parentReq != reqs.end()) { latestCompat = getBetterVersion(latestCompat, ver); } } return latestCompat; } } // namespace Meta
10,157
C++
.cpp
284
30.274648
138
0.646234
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,158
VanillaInstanceCreationTask.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/VanillaInstanceCreationTask.cpp
#include "VanillaInstanceCreationTask.h" #include <utility> #include "FileSystem.h" #include "minecraft/MinecraftInstance.h" #include "minecraft/PackProfile.h" #include "settings/INISettingsObject.h" VanillaCreationTask::VanillaCreationTask(BaseVersion::Ptr version, QString loader, BaseVersion::Ptr loader_version) : InstanceCreationTask() , m_version(std::move(version)) , m_using_loader(true) , m_loader(std::move(loader)) , m_loader_version(std::move(loader_version)) {} bool VanillaCreationTask::createInstance() { setStatus(tr("Creating instance from version %1").arg(m_version->name())); auto instance_settings = std::make_shared<INISettingsObject>(FS::PathCombine(m_stagingPath, "instance.cfg")); instance_settings->suspendSave(); { MinecraftInstance inst(m_globalSettings, instance_settings, m_stagingPath); auto components = inst.getPackProfile(); components->buildingFromScratch(); components->setComponentVersion("net.minecraft", m_version->descriptor(), true); if (m_using_loader) components->setComponentVersion(m_loader, m_loader_version->descriptor()); inst.setName(name()); inst.setIconKey(m_instIcon); } instance_settings->resumeSave(); return true; }
1,293
C++
.cpp
31
36.741935
115
0.72749
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,159
LaunchProfile.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/LaunchProfile.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 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 "LaunchProfile.h" #include <Version.h> void LaunchProfile::clear() { m_minecraftVersion.clear(); m_minecraftVersionType.clear(); m_minecraftAssets.reset(); m_minecraftArguments.clear(); m_addnJvmArguments.clear(); m_tweakers.clear(); m_mainClass.clear(); m_appletClass.clear(); m_libraries.clear(); m_mavenFiles.clear(); m_agents.clear(); m_traits.clear(); m_jarMods.clear(); m_mainJar.reset(); m_problemSeverity = ProblemSeverity::None; } static void applyString(const QString& from, QString& to) { if (from.isEmpty()) return; to = from; } void LaunchProfile::applyMinecraftVersion(const QString& id) { applyString(id, this->m_minecraftVersion); } void LaunchProfile::applyAppletClass(const QString& appletClass) { applyString(appletClass, this->m_appletClass); } void LaunchProfile::applyMainClass(const QString& mainClass) { applyString(mainClass, this->m_mainClass); } void LaunchProfile::applyMinecraftArguments(const QString& minecraftArguments) { applyString(minecraftArguments, this->m_minecraftArguments); } void LaunchProfile::applyAddnJvmArguments(const QStringList& addnJvmArguments) { this->m_addnJvmArguments.append(addnJvmArguments); } void LaunchProfile::applyMinecraftVersionType(const QString& type) { applyString(type, this->m_minecraftVersionType); } void LaunchProfile::applyMinecraftAssets(MojangAssetIndexInfo::Ptr assets) { if (assets) { m_minecraftAssets = assets; } } void LaunchProfile::applyTraits(const QSet<QString>& traits) { this->m_traits.unite(traits); } void LaunchProfile::applyTweakers(const QStringList& tweakers) { // if the applied tweakers override an existing one, skip it. this effectively moves it later in the sequence QStringList newTweakers; for (auto& tweaker : m_tweakers) { if (tweakers.contains(tweaker)) { continue; } newTweakers.append(tweaker); } // then just append the new tweakers (or moved original ones) newTweakers += tweakers; m_tweakers = newTweakers; } void LaunchProfile::applyJarMods(const QList<LibraryPtr>& jarMods) { this->m_jarMods.append(jarMods); } static int findLibraryByName(QList<LibraryPtr>* haystack, const GradleSpecifier& needle) { int retval = -1; for (int i = 0; i < haystack->size(); ++i) { if (haystack->at(i)->rawName().matchName(needle)) { // only one is allowed. if (retval != -1) return -1; retval = i; } } return retval; } void LaunchProfile::applyMods(const QList<LibraryPtr>& mods) { QList<LibraryPtr>* list = &m_mods; for (auto& mod : mods) { auto modCopy = Library::limitedCopy(mod); // find the mod by name. const int index = findLibraryByName(list, mod->rawName()); // mod not found? just add it. if (index < 0) { list->append(modCopy); return; } auto existingLibrary = list->at(index); // if we are higher it means we should update if (Version(mod->version()) > Version(existingLibrary->version())) { list->replace(index, modCopy); } } } void LaunchProfile::applyCompatibleJavaMajors(QList<int>& javaMajor) { m_compatibleJavaMajors.append(javaMajor); } void LaunchProfile::applyCompatibleJavaName(QString javaName) { if (!javaName.isEmpty()) m_compatibleJavaName = javaName; } void LaunchProfile::applyLibrary(LibraryPtr library, const RuntimeContext& runtimeContext) { if (!library->isActive(runtimeContext)) { return; } QList<LibraryPtr>* list = &m_libraries; if (library->isNative()) { list = &m_nativeLibraries; } auto libraryCopy = Library::limitedCopy(library); // find the library by name. const int index = findLibraryByName(list, library->rawName()); // library not found? just add it. if (index < 0) { list->append(libraryCopy); return; } auto existingLibrary = list->at(index); // if we are higher it means we should update if (Version(library->version()) > Version(existingLibrary->version())) { list->replace(index, libraryCopy); } } void LaunchProfile::applyMavenFile(LibraryPtr mavenFile, const RuntimeContext& runtimeContext) { if (!mavenFile->isActive(runtimeContext)) { return; } if (mavenFile->isNative()) { return; } // unlike libraries, we do not keep only one version or try to dedupe them m_mavenFiles.append(Library::limitedCopy(mavenFile)); } void LaunchProfile::applyAgent(AgentPtr agent, const RuntimeContext& runtimeContext) { auto lib = agent->library(); if (!lib->isActive(runtimeContext)) { return; } if (lib->isNative()) { return; } m_agents.append(agent); } const LibraryPtr LaunchProfile::getMainJar() const { return m_mainJar; } void LaunchProfile::applyMainJar(LibraryPtr jar) { if (jar) { m_mainJar = jar; } } void LaunchProfile::applyProblemSeverity(ProblemSeverity severity) { if (m_problemSeverity < severity) { m_problemSeverity = severity; } } const QList<PatchProblem> LaunchProfile::getProblems() const { // FIXME: implement something that actually makes sense here return {}; } QString LaunchProfile::getMinecraftVersion() const { return m_minecraftVersion; } QString LaunchProfile::getAppletClass() const { return m_appletClass; } QString LaunchProfile::getMainClass() const { return m_mainClass; } const QSet<QString>& LaunchProfile::getTraits() const { return m_traits; } const QStringList& LaunchProfile::getTweakers() const { return m_tweakers; } bool LaunchProfile::hasTrait(const QString& trait) const { return m_traits.contains(trait); } ProblemSeverity LaunchProfile::getProblemSeverity() const { return m_problemSeverity; } QString LaunchProfile::getMinecraftVersionType() const { return m_minecraftVersionType; } std::shared_ptr<MojangAssetIndexInfo> LaunchProfile::getMinecraftAssets() const { if (!m_minecraftAssets) { return std::make_shared<MojangAssetIndexInfo>("legacy"); } return m_minecraftAssets; } QString LaunchProfile::getMinecraftArguments() const { return m_minecraftArguments; } const QStringList& LaunchProfile::getAddnJvmArguments() const { return m_addnJvmArguments; } const QList<LibraryPtr>& LaunchProfile::getJarMods() const { return m_jarMods; } const QList<LibraryPtr>& LaunchProfile::getLibraries() const { return m_libraries; } const QList<LibraryPtr>& LaunchProfile::getNativeLibraries() const { return m_nativeLibraries; } const QList<LibraryPtr>& LaunchProfile::getMavenFiles() const { return m_mavenFiles; } const QList<AgentPtr>& LaunchProfile::getAgents() const { return m_agents; } const QList<int>& LaunchProfile::getCompatibleJavaMajors() const { return m_compatibleJavaMajors; } const QString LaunchProfile::getCompatibleJavaName() const { return m_compatibleJavaName; } void LaunchProfile::getLibraryFiles(const RuntimeContext& runtimeContext, QStringList& jars, QStringList& nativeJars, const QString& overridePath, const QString& tempPath) const { QStringList native32, native64; jars.clear(); nativeJars.clear(); for (auto lib : getLibraries()) { lib->getApplicableFiles(runtimeContext, jars, nativeJars, native32, native64, overridePath); } // NOTE: order is important here, add main jar last to the lists if (m_mainJar) { // FIXME: HACK!! jar modding is weird and unsystematic! if (m_jarMods.size()) { QDir tempDir(tempPath); jars.append(tempDir.absoluteFilePath("minecraft.jar")); } else { m_mainJar->getApplicableFiles(runtimeContext, jars, nativeJars, native32, native64, overridePath); } } for (auto lib : getNativeLibraries()) { lib->getApplicableFiles(runtimeContext, jars, nativeJars, native32, native64, overridePath); } if (runtimeContext.javaArchitecture == "32") { nativeJars.append(native32); } else if (runtimeContext.javaArchitecture == "64") { nativeJars.append(native64); } }
9,963
C++
.cpp
325
26.243077
113
0.702034
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,160
MojangVersionFormat.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/MojangVersionFormat.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 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 "MojangVersionFormat.h" #include "MojangDownloadInfo.h" #include "OneSixVersionFormat.h" #include "Json.h" using namespace Json; #include <BuildConfig.h> #include "ParseUtils.h" static const int CURRENT_MINIMUM_LAUNCHER_VERSION = 18; static MojangAssetIndexInfo::Ptr assetIndexFromJson(const QJsonObject& obj); static MojangDownloadInfo::Ptr downloadInfoFromJson(const QJsonObject& obj); static MojangLibraryDownloadInfo::Ptr libDownloadInfoFromJson(const QJsonObject& libObj); static QJsonObject assetIndexToJson(MojangAssetIndexInfo::Ptr assetidxinfo); static QJsonObject libDownloadInfoToJson(MojangLibraryDownloadInfo::Ptr libinfo); static QJsonObject downloadInfoToJson(MojangDownloadInfo::Ptr info); namespace Bits { static void readString(const QJsonObject& root, const QString& key, QString& variable) { if (root.contains(key)) { variable = requireString(root.value(key)); } } static void readDownloadInfo(MojangDownloadInfo::Ptr out, const QJsonObject& obj) { // optional, not used readString(obj, "path", out->path); // required! out->sha1 = requireString(obj, "sha1"); out->url = requireString(obj, "url"); out->size = requireInteger(obj, "size"); } static void readAssetIndex(MojangAssetIndexInfo::Ptr out, const QJsonObject& obj) { out->totalSize = requireInteger(obj, "totalSize"); out->id = requireString(obj, "id"); // out->known = true; } } // namespace Bits MojangDownloadInfo::Ptr downloadInfoFromJson(const QJsonObject& obj) { auto out = std::make_shared<MojangDownloadInfo>(); Bits::readDownloadInfo(out, obj); return out; } MojangAssetIndexInfo::Ptr assetIndexFromJson(const QJsonObject& obj) { auto out = std::make_shared<MojangAssetIndexInfo>(); Bits::readDownloadInfo(out, obj); Bits::readAssetIndex(out, obj); return out; } QJsonObject downloadInfoToJson(MojangDownloadInfo::Ptr info) { QJsonObject out; if (!info->path.isNull()) { out.insert("path", info->path); } out.insert("sha1", info->sha1); out.insert("size", info->size); out.insert("url", info->url); return out; } MojangLibraryDownloadInfo::Ptr libDownloadInfoFromJson(const QJsonObject& libObj) { auto out = std::make_shared<MojangLibraryDownloadInfo>(); auto dlObj = requireObject(libObj.value("downloads")); if (dlObj.contains("artifact")) { out->artifact = downloadInfoFromJson(requireObject(dlObj, "artifact")); } if (dlObj.contains("classifiers")) { auto classifiersObj = requireObject(dlObj, "classifiers"); for (auto iter = classifiersObj.begin(); iter != classifiersObj.end(); iter++) { auto classifier = iter.key(); auto classifierObj = requireObject(iter.value()); out->classifiers[classifier] = downloadInfoFromJson(classifierObj); } } return out; } QJsonObject libDownloadInfoToJson(MojangLibraryDownloadInfo::Ptr libinfo) { QJsonObject out; if (libinfo->artifact) { out.insert("artifact", downloadInfoToJson(libinfo->artifact)); } if (!libinfo->classifiers.isEmpty()) { QJsonObject classifiersOut; for (auto iter = libinfo->classifiers.begin(); iter != libinfo->classifiers.end(); iter++) { classifiersOut.insert(iter.key(), downloadInfoToJson(iter.value())); } out.insert("classifiers", classifiersOut); } return out; } QJsonObject assetIndexToJson(MojangAssetIndexInfo::Ptr info) { QJsonObject out; if (!info->path.isNull()) { out.insert("path", info->path); } out.insert("sha1", info->sha1); out.insert("size", info->size); out.insert("url", info->url); out.insert("totalSize", info->totalSize); out.insert("id", info->id); return out; } void MojangVersionFormat::readVersionProperties(const QJsonObject& in, VersionFile* out) { Bits::readString(in, "id", out->minecraftVersion); Bits::readString(in, "mainClass", out->mainClass); Bits::readString(in, "minecraftArguments", out->minecraftArguments); Bits::readString(in, "type", out->type); Bits::readString(in, "assets", out->assets); if (in.contains("assetIndex")) { out->mojangAssetIndex = assetIndexFromJson(requireObject(in, "assetIndex")); } else if (!out->assets.isNull()) { out->mojangAssetIndex = std::make_shared<MojangAssetIndexInfo>(out->assets); } out->releaseTime = timeFromS3Time(in.value("releaseTime").toString("")); out->updateTime = timeFromS3Time(in.value("time").toString("")); if (in.contains("minimumLauncherVersion")) { out->minimumLauncherVersion = requireInteger(in.value("minimumLauncherVersion")); if (out->minimumLauncherVersion > CURRENT_MINIMUM_LAUNCHER_VERSION) { out->addProblem(ProblemSeverity::Warning, QObject::tr("The 'minimumLauncherVersion' value of this version (%1) is higher than " "supported by %3 (%2). It might not work properly!") .arg(out->minimumLauncherVersion) .arg(CURRENT_MINIMUM_LAUNCHER_VERSION) .arg(BuildConfig.LAUNCHER_DISPLAYNAME)); } } if (in.contains("compatibleJavaMajors")) { for (auto compatible : requireArray(in.value("compatibleJavaMajors"))) { out->compatibleJavaMajors.append(requireInteger(compatible)); } } if (in.contains("compatibleJavaName")) { out->compatibleJavaName = requireString(in.value("compatibleJavaName")); } if (in.contains("downloads")) { auto downloadsObj = requireObject(in, "downloads"); for (auto iter = downloadsObj.begin(); iter != downloadsObj.end(); iter++) { auto classifier = iter.key(); auto classifierObj = requireObject(iter.value()); out->mojangDownloads[classifier] = downloadInfoFromJson(classifierObj); } } } VersionFilePtr MojangVersionFormat::versionFileFromJson(const QJsonDocument& doc, const QString& filename) { VersionFilePtr out(new VersionFile()); if (doc.isEmpty() || doc.isNull()) { throw JSONValidationError(filename + " is empty or null"); } if (!doc.isObject()) { throw JSONValidationError(filename + " is not an object"); } QJsonObject root = doc.object(); readVersionProperties(root, out.get()); out->name = "Minecraft"; out->uid = "net.minecraft"; out->version = out->minecraftVersion; // out->filename = filename; if (root.contains("libraries")) { for (auto libVal : requireArray(root.value("libraries"))) { auto libObj = requireObject(libVal); auto lib = MojangVersionFormat::libraryFromJson(*out, libObj, filename); out->libraries.append(lib); } } return out; } void MojangVersionFormat::writeVersionProperties(const VersionFile* in, QJsonObject& out) { writeString(out, "id", in->minecraftVersion); writeString(out, "mainClass", in->mainClass); writeString(out, "minecraftArguments", in->minecraftArguments); writeString(out, "type", in->type); if (!in->releaseTime.isNull()) { writeString(out, "releaseTime", timeToS3Time(in->releaseTime)); } if (!in->updateTime.isNull()) { writeString(out, "time", timeToS3Time(in->updateTime)); } if (in->minimumLauncherVersion != -1) { out.insert("minimumLauncherVersion", in->minimumLauncherVersion); } writeString(out, "assets", in->assets); if (in->mojangAssetIndex && in->mojangAssetIndex->known) { out.insert("assetIndex", assetIndexToJson(in->mojangAssetIndex)); } if (!in->mojangDownloads.isEmpty()) { QJsonObject downloadsOut; for (auto iter = in->mojangDownloads.begin(); iter != in->mojangDownloads.end(); iter++) { downloadsOut.insert(iter.key(), downloadInfoToJson(iter.value())); } out.insert("downloads", downloadsOut); } if (!in->compatibleJavaMajors.isEmpty()) { QJsonArray compatibleJavaMajorsOut; for (auto compatibleJavaMajor : in->compatibleJavaMajors) { compatibleJavaMajorsOut.append(compatibleJavaMajor); } out.insert("compatibleJavaMajors", compatibleJavaMajorsOut); } if (!in->compatibleJavaName.isEmpty()) { writeString(out, "compatibleJavaName", in->compatibleJavaName); } } QJsonDocument MojangVersionFormat::versionFileToJson(const VersionFilePtr& patch) { QJsonObject root; writeVersionProperties(patch.get(), root); if (!patch->libraries.isEmpty()) { QJsonArray array; for (auto value : patch->libraries) { array.append(MojangVersionFormat::libraryToJson(value.get())); } root.insert("libraries", array); } // write the contents to a json document. { QJsonDocument out; out.setObject(root); return out; } } LibraryPtr MojangVersionFormat::libraryFromJson(ProblemContainer& problems, const QJsonObject& libObj, const QString& filename) { LibraryPtr out(new Library()); if (!libObj.contains("name")) { throw JSONValidationError(filename + "contains a library that doesn't have a 'name' field"); } auto rawName = libObj.value("name").toString(); out->m_name = rawName; if (!out->m_name.valid()) { problems.addProblem(ProblemSeverity::Error, QObject::tr("Library %1 name is broken and cannot be processed.").arg(rawName)); } Bits::readString(libObj, "url", out->m_repositoryURL); if (libObj.contains("extract")) { out->m_hasExcludes = true; auto extractObj = requireObject(libObj.value("extract")); for (auto excludeVal : requireArray(extractObj.value("exclude"))) { out->m_extractExcludes.append(requireString(excludeVal)); } } if (libObj.contains("natives")) { QJsonObject nativesObj = requireObject(libObj.value("natives")); for (auto it = nativesObj.begin(); it != nativesObj.end(); ++it) { if (!it.value().isString()) { qWarning() << filename << "contains an invalid native (skipping)"; } // FIXME: Skip unknown platforms out->m_nativeClassifiers[it.key()] = it.value().toString(); } } if (libObj.contains("rules")) { out->applyRules = true; out->m_rules = rulesFromJsonV4(libObj); } if (libObj.contains("downloads")) { out->m_mojangDownloads = libDownloadInfoFromJson(libObj); } return out; } QJsonObject MojangVersionFormat::libraryToJson(Library* library) { QJsonObject libRoot; libRoot.insert("name", library->m_name.serialize()); if (!library->m_repositoryURL.isEmpty()) { libRoot.insert("url", library->m_repositoryURL); } if (library->isNative()) { QJsonObject nativeList; auto iter = library->m_nativeClassifiers.begin(); while (iter != library->m_nativeClassifiers.end()) { nativeList.insert(iter.key(), iter.value()); iter++; } libRoot.insert("natives", nativeList); if (!library->m_extractExcludes.isEmpty()) { QJsonArray excludes; QJsonObject extract; for (auto exclude : library->m_extractExcludes) { excludes.append(exclude); } extract.insert("exclude", excludes); libRoot.insert("extract", extract); } } if (!library->m_rules.isEmpty()) { QJsonArray allRules; for (auto& rule : library->m_rules) { QJsonObject ruleObj = rule->toJson(); allRules.append(ruleObj); } libRoot.insert("rules", allRules); } if (library->m_mojangDownloads) { auto downloadsObj = libDownloadInfoToJson(library->m_mojangDownloads); libRoot.insert("downloads", downloadsObj); } return libRoot; }
13,613
C++
.cpp
337
34.020772
139
0.667724
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,161
Logging.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/Logging.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2023 Rachel Powers <508861+Ryex@users.noreply.github.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #include "minecraft/Logging.h" #include <qloggingcategory.h> Q_LOGGING_CATEGORY(instanceProfileC, "launcher.instance.profile") Q_LOGGING_CATEGORY(instanceProfileResolveC, "launcher.instance.profile.resolve")
998
C++
.cpp
22
42.363636
81
0.751546
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,162
WorldList.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/WorldList.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 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 "WorldList.h" #include <FileSystem.h> #include <QDebug> #include <QFileSystemWatcher> #include <QMimeData> #include <QString> #include <QUrl> #include <QUuid> #include <Qt> #include "Application.h" WorldList::WorldList(const QString& dir, BaseInstance* instance) : QAbstractListModel(), m_instance(instance), m_dir(dir) { FS::ensureFolderPathExists(m_dir.absolutePath()); m_dir.setFilter(QDir::Readable | QDir::NoDotAndDotDot | QDir::Files | QDir::Dirs); m_dir.setSorting(QDir::Name | QDir::IgnoreCase | QDir::LocaleAware); m_watcher = new QFileSystemWatcher(this); is_watching = false; connect(m_watcher, &QFileSystemWatcher::directoryChanged, this, &WorldList::directoryChanged); } void WorldList::startWatching() { if (is_watching) { return; } update(); is_watching = m_watcher->addPath(m_dir.absolutePath()); if (is_watching) { qDebug() << "Started watching " << m_dir.absolutePath(); } else { qDebug() << "Failed to start watching " << m_dir.absolutePath(); } } void WorldList::stopWatching() { if (!is_watching) { return; } is_watching = !m_watcher->removePath(m_dir.absolutePath()); if (!is_watching) { qDebug() << "Stopped watching " << m_dir.absolutePath(); } else { qDebug() << "Failed to stop watching " << m_dir.absolutePath(); } } bool WorldList::update() { if (!isValid()) return false; QList<World> newWorlds; m_dir.refresh(); auto folderContents = m_dir.entryInfoList(); // if there are any untracked files... for (QFileInfo entry : folderContents) { if (!entry.isDir()) continue; World w(entry); if (w.isValid()) { newWorlds.append(w); } } beginResetModel(); worlds.swap(newWorlds); endResetModel(); return true; } void WorldList::directoryChanged(QString path) { update(); } bool WorldList::isValid() { return m_dir.exists() && m_dir.isReadable(); } QString WorldList::instDirPath() const { return QFileInfo(m_instance->instanceRoot()).absoluteFilePath(); } bool WorldList::deleteWorld(int index) { if (index >= worlds.size() || index < 0) return false; World& m = worlds[index]; if (m.destroy()) { beginRemoveRows(QModelIndex(), index, index); worlds.removeAt(index); endRemoveRows(); emit changed(); return true; } return false; } bool WorldList::deleteWorlds(int first, int last) { for (int i = first; i <= last; i++) { World& m = worlds[i]; m.destroy(); } beginRemoveRows(QModelIndex(), first, last); worlds.erase(worlds.begin() + first, worlds.begin() + last + 1); endRemoveRows(); emit changed(); return true; } bool WorldList::resetIcon(int row) { if (row >= worlds.size() || row < 0) return false; World& m = worlds[row]; if (m.resetIcon()) { emit dataChanged(index(row), index(row), { WorldList::IconFileRole }); return true; } return false; } int WorldList::columnCount(const QModelIndex& parent) const { return parent.isValid() ? 0 : 5; } QVariant WorldList::data(const QModelIndex& index, int role) const { if (!index.isValid()) return QVariant(); int row = index.row(); int column = index.column(); if (row < 0 || row >= worlds.size()) return QVariant(); QLocale locale; auto& world = worlds[row]; switch (role) { case Qt::DisplayRole: switch (column) { case NameColumn: return world.name(); case GameModeColumn: return world.gameType().toTranslatedString(); case LastPlayedColumn: return world.lastPlayed(); case SizeColumn: return locale.formattedDataSize(world.bytes()); case InfoColumn: if (world.isSymLinkUnder(instDirPath())) { return tr("This world is symbolically linked from elsewhere."); } if (world.isMoreThanOneHardLink()) { return tr("\nThis world is hard linked elsewhere."); } return ""; default: return QVariant(); } case Qt::UserRole: switch (column) { case SizeColumn: return QVariant::fromValue<qlonglong>(world.bytes()); default: return data(index, Qt::DisplayRole); } case Qt::ToolTipRole: { if (column == InfoColumn) { if (world.isSymLinkUnder(instDirPath())) { return tr("Warning: This world is symbolically linked from elsewhere. Editing it will also change the original." "\nCanonical Path: %1") .arg(world.canonicalFilePath()); } if (world.isMoreThanOneHardLink()) { return tr("Warning: This world is hard linked elsewhere. Editing it will also change the original."); } } return world.folderName(); } case ObjectRole: { return QVariant::fromValue<void*>((void*)&world); } case FolderRole: { return QDir::toNativeSeparators(dir().absoluteFilePath(world.folderName())); } case SeedRole: { return QVariant::fromValue<qlonglong>(world.seed()); } case NameRole: { return world.name(); } case LastPlayedRole: { return world.lastPlayed(); } case SizeRole: { return QVariant::fromValue<qlonglong>(world.bytes()); } case IconFileRole: { return world.iconFile(); } default: return QVariant(); } } QVariant WorldList::headerData(int section, [[maybe_unused]] Qt::Orientation orientation, int role) const { switch (role) { case Qt::DisplayRole: switch (section) { case NameColumn: return tr("Name"); case GameModeColumn: return tr("Game Mode"); case LastPlayedColumn: return tr("Last Played"); case SizeColumn: //: World size on disk return tr("Size"); case InfoColumn: //: special warnings? return tr("Info"); default: return QVariant(); } case Qt::ToolTipRole: switch (section) { case NameColumn: return tr("The name of the world."); case GameModeColumn: return tr("Game mode of the world."); case LastPlayedColumn: return tr("Date and time the world was last played."); case SizeColumn: return tr("Size of the world on disk."); case InfoColumn: return tr("Information and warnings about the world."); default: return QVariant(); } default: return QVariant(); } } QStringList WorldList::mimeTypes() const { QStringList types; types << "text/uri-list"; return types; } class WorldMimeData : public QMimeData { Q_OBJECT public: WorldMimeData(QList<World> worlds) { m_worlds = worlds; } QStringList formats() const { return QMimeData::formats() << "text/uri-list"; } protected: #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) QVariant retrieveData(const QString& mimetype, QMetaType type) const #else QVariant retrieveData(const QString& mimetype, QVariant::Type type) const #endif { QList<QUrl> urls; for (auto& world : m_worlds) { if (!world.isValid() || !world.isOnFS()) continue; QString worldPath = world.container().absoluteFilePath(); qDebug() << worldPath; urls.append(QUrl::fromLocalFile(worldPath)); } const_cast<WorldMimeData*>(this)->setUrls(urls); return QMimeData::retrieveData(mimetype, type); } private: QList<World> m_worlds; }; QMimeData* WorldList::mimeData(const QModelIndexList& indexes) const { if (indexes.size() == 0) return new QMimeData(); 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]); } if (!worlds_.size()) { return new QMimeData(); } return new WorldMimeData(worlds_); } Qt::ItemFlags WorldList::flags(const QModelIndex& index) const { Qt::ItemFlags defaultFlags = QAbstractListModel::flags(index); if (index.isValid()) return Qt::ItemIsUserCheckable | Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | defaultFlags; else return Qt::ItemIsDropEnabled | defaultFlags; } Qt::DropActions WorldList::supportedDragActions() const { // move to other mod lists or VOID return Qt::MoveAction; } Qt::DropActions WorldList::supportedDropActions() const { // copy from outside, move from within and other mod lists return Qt::CopyAction | Qt::MoveAction; } void WorldList::installWorld(QFileInfo filename) { qDebug() << "installing: " << filename.absoluteFilePath(); World w(filename); if (!w.isValid()) { return; } w.install(m_dir.absolutePath()); } bool WorldList::dropMimeData(const QMimeData* data, Qt::DropAction action, [[maybe_unused]] int row, [[maybe_unused]] int column, [[maybe_unused]] const QModelIndex& parent) { if (action == Qt::IgnoreAction) return true; // check if the action is supported if (!data || !(action & supportedDropActions())) return false; // files dropped from outside? if (data->hasUrls()) { bool was_watching = is_watching; if (was_watching) stopWatching(); auto urls = data->urls(); for (auto url : urls) { // only local files may be dropped... if (!url.isLocalFile()) continue; QString filename = url.toLocalFile(); QFileInfo worldInfo(filename); if (!m_dir.entryInfoList().contains(worldInfo)) { installWorld(worldInfo); } } if (was_watching) startWatching(); return true; } return false; } #include "WorldList.moc"
12,496
C++
.cpp
379
24.923483
132
0.590822
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,163
PackProfile.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/PackProfile.cpp
// SPDX-FileCopyrightText: 2022-2023 Sefa Eyeoglu <contact@scrumplex.net> // // SPDX-License-Identifier: GPL-3.0-only AND Apache-2.0 /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022-2023 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2022 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 * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <Version.h> #include <qlogging.h> #include <QCryptographicHash> #include <QDebug> #include <QDir> #include <QFile> #include <QJsonArray> #include <QJsonDocument> #include <QSaveFile> #include <QTimer> #include <QUuid> #include <algorithm> #include <utility> #include "Application.h" #include "Exception.h" #include "FileSystem.h" #include "Json.h" #include "meta/Index.h" #include "meta/JsonFormat.h" #include "minecraft/Component.h" #include "minecraft/MinecraftInstance.h" #include "minecraft/OneSixVersionFormat.h" #include "minecraft/ProfileUtils.h" #include "ComponentUpdateTask.h" #include "PackProfile.h" #include "PackProfile_p.h" #include "modplatform/ModIndex.h" #include "minecraft/Logging.h" #include "ui/dialogs/CustomMessageBox.h" PackProfile::PackProfile(MinecraftInstance* instance) : QAbstractListModel() { d.reset(new PackProfileData); d->m_instance = instance; d->m_saveTimer.setSingleShot(true); d->m_saveTimer.setInterval(5000); d->interactionDisabled = instance->isRunning(); connect(d->m_instance, &BaseInstance::runningStatusChanged, this, &PackProfile::disableInteraction); connect(&d->m_saveTimer, &QTimer::timeout, this, &PackProfile::save_internal); } PackProfile::~PackProfile() { saveNow(); } // BEGIN: component file format static const int currentComponentsFileVersion = 1; static QJsonObject componentToJsonV1(ComponentPtr component) { QJsonObject obj; // critical obj.insert("uid", component->m_uid); if (!component->m_version.isEmpty()) { obj.insert("version", component->m_version); } if (component->m_dependencyOnly) { obj.insert("dependencyOnly", true); } if (component->m_important) { obj.insert("important", true); } if (component->m_disabled) { obj.insert("disabled", true); } // cached if (!component->m_cachedVersion.isEmpty()) { obj.insert("cachedVersion", component->m_cachedVersion); } if (!component->m_cachedName.isEmpty()) { obj.insert("cachedName", component->m_cachedName); } Meta::serializeRequires(obj, &component->m_cachedRequires, "cachedRequires"); Meta::serializeRequires(obj, &component->m_cachedConflicts, "cachedConflicts"); if (component->m_cachedVolatile) { obj.insert("cachedVolatile", true); } return obj; } static ComponentPtr componentFromJsonV1(PackProfile* parent, const QString& componentJsonPattern, const QJsonObject& obj) { // critical auto uid = Json::requireString(obj.value("uid")); auto filePath = componentJsonPattern.arg(uid); auto component = makeShared<Component>(parent, uid); component->m_version = Json::ensureString(obj.value("version")); component->m_dependencyOnly = Json::ensureBoolean(obj.value("dependencyOnly"), false); component->m_important = Json::ensureBoolean(obj.value("important"), false); // cached // TODO @RESILIENCE: ignore invalid values/structure here? component->m_cachedVersion = Json::ensureString(obj.value("cachedVersion")); component->m_cachedName = Json::ensureString(obj.value("cachedName")); Meta::parseRequires(obj, &component->m_cachedRequires, "cachedRequires"); Meta::parseRequires(obj, &component->m_cachedConflicts, "cachedConflicts"); component->m_cachedVolatile = Json::ensureBoolean(obj.value("volatile"), false); bool disabled = Json::ensureBoolean(obj.value("disabled"), false); component->setEnabled(!disabled); return component; } // Save the given component container data to a file static bool savePackProfile(const QString& filename, const ComponentContainer& container) { QJsonObject obj; obj.insert("formatVersion", currentComponentsFileVersion); QJsonArray orderArray; for (auto component : container) { orderArray.append(componentToJsonV1(component)); } obj.insert("components", orderArray); QSaveFile outFile(filename); if (!outFile.open(QFile::WriteOnly)) { qCCritical(instanceProfileC) << "Couldn't open" << outFile.fileName() << "for writing:" << outFile.errorString(); return false; } auto data = QJsonDocument(obj).toJson(QJsonDocument::Indented); if (outFile.write(data) != data.size()) { qCCritical(instanceProfileC) << "Couldn't write all the data into" << outFile.fileName() << "because:" << outFile.errorString(); return false; } if (!outFile.commit()) { qCCritical(instanceProfileC) << "Couldn't save" << outFile.fileName() << "because:" << outFile.errorString(); } return true; } // Read the given file into component containers static bool loadPackProfile(PackProfile* parent, const QString& filename, const QString& componentJsonPattern, ComponentContainer& container) { QFile componentsFile(filename); if (!componentsFile.exists()) { qCWarning(instanceProfileC) << "Components file" << filename << "doesn't exist. This should never happen."; return false; } if (!componentsFile.open(QFile::ReadOnly)) { qCCritical(instanceProfileC) << "Couldn't open" << componentsFile.fileName() << " for reading:" << componentsFile.errorString(); qCWarning(instanceProfileC) << "Ignoring overridden order"; return false; } // and it's valid JSON QJsonParseError error; QJsonDocument doc = QJsonDocument::fromJson(componentsFile.readAll(), &error); if (error.error != QJsonParseError::NoError) { qCCritical(instanceProfileC) << "Couldn't parse" << componentsFile.fileName() << ":" << error.errorString(); qCWarning(instanceProfileC) << "Ignoring overridden order"; return false; } // and then read it and process it if all above is true. try { auto obj = Json::requireObject(doc); // check order file version. auto version = Json::requireInteger(obj.value("formatVersion")); if (version != currentComponentsFileVersion) { throw JSONValidationError(QObject::tr("Invalid component file version, expected %1").arg(currentComponentsFileVersion)); } auto orderArray = Json::requireArray(obj.value("components")); for (auto item : orderArray) { auto comp_obj = Json::requireObject(item, "Component must be an object."); container.append(componentFromJsonV1(parent, componentJsonPattern, comp_obj)); } } catch ([[maybe_unused]] const JSONValidationError& err) { qCCritical(instanceProfileC) << "Couldn't parse" << componentsFile.fileName() << ": bad file format"; container.clear(); return false; } return true; } // END: component file format // BEGIN: save/load logic void PackProfile::saveNow() { if (saveIsScheduled()) { d->m_saveTimer.stop(); save_internal(); } } bool PackProfile::saveIsScheduled() const { return d->dirty; } void PackProfile::buildingFromScratch() { d->loaded = true; d->dirty = true; } void PackProfile::scheduleSave() { if (!d->loaded) { qDebug() << d->m_instance->name() << "|" << "Component list should never save if it didn't successfully load"; return; } if (!d->dirty) { d->dirty = true; qDebug() << d->m_instance->name() << "|" << "Component list save is scheduled"; } d->m_saveTimer.start(); } RuntimeContext PackProfile::runtimeContext() { return d->m_instance->runtimeContext(); } QString PackProfile::componentsFilePath() const { return FS::PathCombine(d->m_instance->instanceRoot(), "mmc-pack.json"); } QString PackProfile::patchesPattern() const { return FS::PathCombine(d->m_instance->instanceRoot(), "patches", "%1.json"); } QString PackProfile::patchFilePathForUid(const QString& uid) const { return patchesPattern().arg(uid); } void PackProfile::save_internal() { qDebug() << d->m_instance->name() << "|" << "Component list save performed now"; auto filename = componentsFilePath(); savePackProfile(filename, d->components); d->dirty = false; } bool PackProfile::load() { auto filename = componentsFilePath(); // load the new component list and swap it with the current one... ComponentContainer newComponents; if (!loadPackProfile(this, filename, patchesPattern(), newComponents)) { qCritical() << d->m_instance->name() << "|" << "Failed to load the component config"; return false; } else { // FIXME: actually use fine-grained updates, not this... beginResetModel(); // disconnect all the old components for (auto component : d->components) { disconnect(component.get(), &Component::dataChanged, this, &PackProfile::componentDataChanged); } d->components.clear(); d->componentIndex.clear(); for (auto component : newComponents) { if (d->componentIndex.contains(component->m_uid)) { qWarning() << d->m_instance->name() << "|" << "Ignoring duplicate component entry" << component->m_uid; continue; } connect(component.get(), &Component::dataChanged, this, &PackProfile::componentDataChanged); d->components.append(component); d->componentIndex[component->m_uid] = component; } endResetModel(); d->loaded = true; return true; } } void PackProfile::reload(Net::Mode netmode) { // Do not reload when the update/resolve task is running. It is in control. if (d->m_updateTask) { return; } // flush any scheduled saves to not lose state saveNow(); // FIXME: differentiate when a reapply is required by propagating state from components invalidateLaunchProfile(); if (load()) { resolve(netmode); } } Task::Ptr PackProfile::getCurrentTask() { return d->m_updateTask; } void PackProfile::resolve(Net::Mode netmode) { auto updateTask = new ComponentUpdateTask(ComponentUpdateTask::Mode::Resolution, netmode, this); d->m_updateTask.reset(updateTask); connect(updateTask, &ComponentUpdateTask::succeeded, this, &PackProfile::updateSucceeded); connect(updateTask, &ComponentUpdateTask::failed, this, &PackProfile::updateFailed); connect(updateTask, &ComponentUpdateTask::aborted, this, [this] { updateFailed(tr("Aborted")); }); d->m_updateTask->start(); } void PackProfile::updateSucceeded() { qCDebug(instanceProfileC) << d->m_instance->name() << "|" << "Component list update/resolve task succeeded"; d->m_updateTask.reset(); invalidateLaunchProfile(); } void PackProfile::updateFailed(const QString& error) { qCDebug(instanceProfileC) << d->m_instance->name() << "|" << "Component list update/resolve task failed " << "Reason:" << error; d->m_updateTask.reset(); invalidateLaunchProfile(); } // END: save/load void PackProfile::appendComponent(ComponentPtr component) { insertComponent(d->components.size(), component); } void PackProfile::insertComponent(size_t index, ComponentPtr component) { auto id = component->getID(); if (id.isEmpty()) { qCWarning(instanceProfileC) << d->m_instance->name() << "|" << "Attempt to add a component with empty ID!"; return; } if (d->componentIndex.contains(id)) { qCWarning(instanceProfileC) << d->m_instance->name() << "|" << "Attempt to add a component that is already present!"; return; } beginInsertRows(QModelIndex(), static_cast<int>(index), static_cast<int>(index)); d->components.insert(index, component); d->componentIndex[id] = component; endInsertRows(); connect(component.get(), &Component::dataChanged, this, &PackProfile::componentDataChanged); scheduleSave(); } void PackProfile::componentDataChanged() { auto objPtr = qobject_cast<Component*>(sender()); if (!objPtr) { qCWarning(instanceProfileC) << d->m_instance->name() << "|" << "PackProfile got dataChanged signal from a non-Component!"; return; } if (objPtr->getID() == "net.minecraft") { emit minecraftChanged(); } // figure out which one is it... in a seriously dumb way. int index = 0; for (auto component : d->components) { if (component.get() == objPtr) { emit dataChanged(createIndex(index, 0), createIndex(index, columnCount(QModelIndex()) - 1)); scheduleSave(); return; } index++; } qCWarning(instanceProfileC) << d->m_instance->name() << "|" << "PackProfile got dataChanged signal from a Component which does not belong to it!"; } bool PackProfile::remove(const int index) { auto patch = getComponent(index); if (!patch->isRemovable()) { qCWarning(instanceProfileC) << d->m_instance->name() << "|" << "Patch" << patch->getID() << "is non-removable"; return false; } if (!removeComponent_internal(patch)) { qCCritical(instanceProfileC) << d->m_instance->name() << "|" << "Patch" << patch->getID() << "could not be removed"; return false; } beginRemoveRows(QModelIndex(), index, index); d->components.removeAt(index); d->componentIndex.remove(patch->getID()); endRemoveRows(); invalidateLaunchProfile(); scheduleSave(); return true; } bool PackProfile::remove(const QString& id) { int i = 0; for (auto patch : d->components) { if (patch->getID() == id) { return remove(i); } i++; } return false; } bool PackProfile::customize(int index) { auto patch = getComponent(index); if (!patch->isCustomizable()) { qCDebug(instanceProfileC) << d->m_instance->name() << "|" << "Patch" << patch->getID() << "is not customizable"; return false; } if (!patch->customize()) { qCCritical(instanceProfileC) << d->m_instance->name() << "|" << "Patch" << patch->getID() << "could not be customized"; return false; } invalidateLaunchProfile(); scheduleSave(); return true; } bool PackProfile::revertToBase(int index) { auto patch = getComponent(index); if (!patch->isRevertible()) { qCDebug(instanceProfileC) << d->m_instance->name() << "|" << "Patch" << patch->getID() << "is not revertible"; return false; } if (!patch->revert()) { qCCritical(instanceProfileC) << d->m_instance->name() << "|" << "Patch" << patch->getID() << "could not be reverted"; return false; } invalidateLaunchProfile(); scheduleSave(); return true; } ComponentPtr PackProfile::getComponent(const QString& id) { auto iter = d->componentIndex.find(id); if (iter == d->componentIndex.end()) { return nullptr; } return (*iter); } ComponentPtr PackProfile::getComponent(size_t index) { if (index >= static_cast<size_t>(d->components.size())) { return nullptr; } return d->components[index]; } QVariant PackProfile::data(const QModelIndex& index, int role) const { if (!index.isValid()) return QVariant(); int row = index.row(); int column = index.column(); if (row < 0 || row >= d->components.size()) return QVariant(); auto patch = d->components.at(row); switch (role) { case Qt::CheckStateRole: { switch (column) { case NameColumn: { return patch->isEnabled() ? Qt::Checked : Qt::Unchecked; } default: return QVariant(); } } case Qt::DisplayRole: { switch (column) { case NameColumn: return patch->getName(); case VersionColumn: { if (patch->isCustom()) { return QString("%1 (Custom)").arg(patch->getVersion()); } else { return patch->getVersion(); } } default: return QVariant(); } } case Qt::DecorationRole: { if (column == NameColumn) { auto severity = patch->getProblemSeverity(); switch (severity) { case ProblemSeverity::Warning: return "warning"; case ProblemSeverity::Error: return "error"; default: return QVariant(); } } return QVariant(); } } return QVariant(); } 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; } if (role == Qt::CheckStateRole) { auto component = d->components[index.row()]; if (component->setEnabled(!component->isEnabled())) { return true; } } return false; } QVariant PackProfile::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Horizontal) { if (role == Qt::DisplayRole) { switch (section) { case NameColumn: return tr("Name"); case VersionColumn: return tr("Version"); default: return QVariant(); } } } return QVariant(); } // FIXME: zero precision mess Qt::ItemFlags PackProfile::flags(const QModelIndex& index) const { if (!index.isValid()) { return Qt::NoItemFlags; } Qt::ItemFlags outFlags = Qt::ItemIsSelectable | Qt::ItemIsEnabled; int row = index.row(); if (row < 0 || row >= d->components.size()) { return Qt::NoItemFlags; } auto patch = d->components.at(row); // TODO: this will need fine-tuning later... if (patch->canBeDisabled() && !d->interactionDisabled) { outFlags |= Qt::ItemIsUserCheckable; } return outFlags; } int PackProfile::rowCount(const QModelIndex& parent) const { return parent.isValid() ? 0 : d->components.size(); } int PackProfile::columnCount(const QModelIndex& parent) const { return parent.isValid() ? 0 : NUM_COLUMNS; } void PackProfile::move(const int index, const MoveDirection direction) { int theirIndex; if (direction == MoveUp) { theirIndex = index - 1; } else { theirIndex = index + 1; } if (index < 0 || index >= d->components.size()) return; if (theirIndex >= rowCount()) theirIndex = rowCount() - 1; if (theirIndex == -1) theirIndex = rowCount() - 1; if (index == theirIndex) return; int togap = theirIndex > index ? theirIndex + 1 : theirIndex; auto from = getComponent(index); auto to = getComponent(theirIndex); if (!from || !to || !to->isMoveable() || !from->isMoveable()) { return; } beginMoveRows(QModelIndex(), index, index, QModelIndex(), togap); #if QT_VERSION >= QT_VERSION_CHECK(5, 13, 0) d->components.swapItemsAt(index, theirIndex); #else d->components.swap(index, theirIndex); #endif endMoveRows(); invalidateLaunchProfile(); scheduleSave(); } void PackProfile::invalidateLaunchProfile() { d->m_profile.reset(); } void PackProfile::installJarMods(QStringList selectedFiles) { // FIXME: get rid of _internal installJarMods_internal(selectedFiles); } void PackProfile::installCustomJar(QString selectedFile) { // FIXME: get rid of _internal installCustomJar_internal(selectedFile); } bool PackProfile::installComponents(QStringList selectedFiles) { const QString patchDir = FS::PathCombine(d->m_instance->instanceRoot(), "patches"); if (!FS::ensureFolderPathExists(patchDir)) return false; bool result = true; for (const QString& source : selectedFiles) { const QFileInfo sourceInfo(source); auto versionFile = ProfileUtils::parseJsonFile(sourceInfo, false); const QString target = FS::PathCombine(patchDir, versionFile->uid + ".json"); if (!QFile::copy(source, target)) { qCWarning(instanceProfileC) << d->m_instance->name() << "|" << "Component" << source << "could not be copied to target" << target; result = false; continue; } appendComponent(makeShared<Component>(this, versionFile->uid, versionFile)); } scheduleSave(); invalidateLaunchProfile(); return result; } void PackProfile::installAgents(QStringList selectedFiles) { // FIXME: get rid of _internal installAgents_internal(selectedFiles); } bool PackProfile::installEmpty(const QString& uid, const QString& name) { QString patchDir = FS::PathCombine(d->m_instance->instanceRoot(), "patches"); if (!FS::ensureFolderPathExists(patchDir)) { return false; } auto f = std::make_shared<VersionFile>(); f->name = name; f->uid = uid; f->version = "1"; QString patchFileName = FS::PathCombine(patchDir, uid + ".json"); QFile file(patchFileName); if (!file.open(QFile::WriteOnly)) { qCCritical(instanceProfileC) << d->m_instance->name() << "|" << "Error opening" << file.fileName() << "for reading:" << file.errorString(); return false; } file.write(OneSixVersionFormat::versionFileToJson(f).toJson()); file.close(); appendComponent(makeShared<Component>(this, f->uid, f)); scheduleSave(); invalidateLaunchProfile(); return true; } bool PackProfile::removeComponent_internal(ComponentPtr patch) { bool ok = true; // first, remove the patch file. this ensures it's not used anymore auto fileName = patch->getFilename(); if (fileName.size()) { QFile patchFile(fileName); if (patchFile.exists() && !patchFile.remove()) { qCCritical(instanceProfileC) << d->m_instance->name() << "|" << "File" << fileName << "could not be removed because:" << patchFile.errorString(); return false; } } // FIXME: we need a generic way of removing local resources, not just jar mods... auto preRemoveJarMod = [this](LibraryPtr jarMod) -> bool { if (!jarMod->isLocal()) { return true; } QStringList jar, temp1, temp2, temp3; jarMod->getApplicableFiles(d->m_instance->runtimeContext(), jar, temp1, temp2, temp3, d->m_instance->jarmodsPath().absolutePath()); QFileInfo finfo(jar[0]); if (finfo.exists()) { QFile jarModFile(jar[0]); if (!jarModFile.remove()) { qCCritical(instanceProfileC) << d->m_instance->name() << "|" << "File" << jar[0] << "could not be removed because:" << jarModFile.errorString(); return false; } return true; } return true; }; auto vFile = patch->getVersionFile(); if (vFile) { auto& jarMods = vFile->jarMods; for (auto& jarmod : jarMods) { ok &= preRemoveJarMod(jarmod); } } return ok; } bool PackProfile::installJarMods_internal(QStringList filepaths) { QString patchDir = FS::PathCombine(d->m_instance->instanceRoot(), "patches"); if (!FS::ensureFolderPathExists(patchDir)) { return false; } if (!FS::ensureFolderPathExists(d->m_instance->jarModsDir())) { return false; } for (auto filepath : filepaths) { QFileInfo sourceInfo(filepath); QString id = QUuid::createUuid().toString(QUuid::WithoutBraces); QString target_filename = id + ".jar"; QString target_id = "custom.jarmod." + id; QString target_name = sourceInfo.completeBaseName() + " (jar mod)"; QString finalPath = FS::PathCombine(d->m_instance->jarModsDir(), target_filename); QFileInfo targetInfo(finalPath); Q_ASSERT(!targetInfo.exists()); if (!QFile::copy(sourceInfo.absoluteFilePath(), QFileInfo(finalPath).absoluteFilePath())) { return false; } auto f = std::make_shared<VersionFile>(); auto jarMod = std::make_shared<Library>(); jarMod->setRawName(GradleSpecifier("custom.jarmods:" + id + ":1")); jarMod->setFilename(target_filename); jarMod->setDisplayName(sourceInfo.completeBaseName()); jarMod->setHint("local"); f->jarMods.append(jarMod); f->name = target_name; f->uid = target_id; QString patchFileName = FS::PathCombine(patchDir, target_id + ".json"); QFile file(patchFileName); if (!file.open(QFile::WriteOnly)) { qCCritical(instanceProfileC) << d->m_instance->name() << "|" << "Error opening" << file.fileName() << "for reading:" << file.errorString(); return false; } file.write(OneSixVersionFormat::versionFileToJson(f).toJson()); file.close(); appendComponent(makeShared<Component>(this, f->uid, f)); } scheduleSave(); invalidateLaunchProfile(); return true; } bool PackProfile::installCustomJar_internal(QString filepath) { QString patchDir = FS::PathCombine(d->m_instance->instanceRoot(), "patches"); if (!FS::ensureFolderPathExists(patchDir)) { return false; } QString libDir = d->m_instance->getLocalLibraryPath(); if (!FS::ensureFolderPathExists(libDir)) { return false; } auto specifier = GradleSpecifier("custom:customjar:1"); QFileInfo sourceInfo(filepath); QString target_filename = specifier.getFileName(); QString target_id = specifier.artifactId(); QString target_name = sourceInfo.completeBaseName() + " (custom jar)"; QString finalPath = FS::PathCombine(libDir, target_filename); QFileInfo jarInfo(finalPath); if (jarInfo.exists()) { if (!FS::deletePath(finalPath)) { return false; } } if (!QFile::copy(filepath, finalPath)) { return false; } auto f = std::make_shared<VersionFile>(); auto jarMod = std::make_shared<Library>(); jarMod->setRawName(specifier); jarMod->setDisplayName(sourceInfo.completeBaseName()); jarMod->setHint("local"); f->mainJar = jarMod; f->name = target_name; f->uid = target_id; QString patchFileName = FS::PathCombine(patchDir, target_id + ".json"); QFile file(patchFileName); if (!file.open(QFile::WriteOnly)) { qCCritical(instanceProfileC) << d->m_instance->name() << "|" << "Error opening" << file.fileName() << "for reading:" << file.errorString(); return false; } file.write(OneSixVersionFormat::versionFileToJson(f).toJson()); file.close(); appendComponent(makeShared<Component>(this, f->uid, f)); scheduleSave(); invalidateLaunchProfile(); return true; } bool PackProfile::installAgents_internal(QStringList filepaths) { // FIXME code duplication const QString patchDir = FS::PathCombine(d->m_instance->instanceRoot(), "patches"); if (!FS::ensureFolderPathExists(patchDir)) return false; const QString libDir = d->m_instance->getLocalLibraryPath(); if (!FS::ensureFolderPathExists(libDir)) return false; for (const QString& source : filepaths) { const QFileInfo sourceInfo(source); const QString id = QUuid::createUuid().toString(QUuid::WithoutBraces); const QString targetBaseName = id + ".jar"; const QString targetId = "custom.agent." + id; const QString targetName = sourceInfo.completeBaseName() + " (agent)"; const QString target = FS::PathCombine(d->m_instance->getLocalLibraryPath(), targetBaseName); const QFileInfo targetInfo(target); Q_ASSERT(!targetInfo.exists()); if (!QFile::copy(source, target)) return false; auto versionFile = std::make_shared<VersionFile>(); auto agent = std::make_shared<Library>(); agent->setRawName("custom.agents:" + id + ":1"); agent->setFilename(targetBaseName); agent->setDisplayName(sourceInfo.completeBaseName()); agent->setHint("local"); versionFile->agents.append(std::make_shared<Agent>(agent, QString())); versionFile->name = targetName; versionFile->uid = targetId; QFile patchFile(FS::PathCombine(patchDir, targetId + ".json")); if (!patchFile.open(QFile::WriteOnly)) { qCCritical(instanceProfileC) << d->m_instance->name() << "|" << "Error opening" << patchFile.fileName() << "for reading:" << patchFile.errorString(); return false; } patchFile.write(OneSixVersionFormat::versionFileToJson(versionFile).toJson()); patchFile.close(); appendComponent(makeShared<Component>(this, versionFile->uid, versionFile)); } scheduleSave(); invalidateLaunchProfile(); return true; } std::shared_ptr<LaunchProfile> PackProfile::getProfile() const { if (!d->m_profile) { try { auto profile = std::make_shared<LaunchProfile>(); for (auto file : d->components) { qCDebug(instanceProfileC) << d->m_instance->name() << "|" << "Applying" << file->getID() << (file->getProblemSeverity() == ProblemSeverity::Error ? "ERROR" : "GOOD"); file->applyTo(profile.get()); } d->m_profile = profile; } catch (const Exception& error) { qCWarning(instanceProfileC) << d->m_instance->name() << "|" << "Couldn't apply profile patches because: " << error.cause(); } } return d->m_profile; } bool PackProfile::setComponentVersion(const QString& uid, const QString& version, bool important) { auto iter = d->componentIndex.find(uid); if (iter != d->componentIndex.end()) { ComponentPtr component = *iter; // set existing if (component->revert()) { // set new version auto oldVersion = component->getVersion(); component->setVersion(version); component->setImportant(important); if (important) { component->setUpdateAction(UpdateAction{ UpdateActionImportantChanged{ oldVersion } }); resolve(Net::Mode::Online); } return true; } return false; } else { // add new auto component = makeShared<Component>(this, uid); component->m_version = version; component->m_important = important; appendComponent(component); return true; } } QString PackProfile::getComponentVersion(const QString& uid) const { const auto iter = d->componentIndex.find(uid); if (iter != d->componentIndex.end()) { return (*iter)->getVersion(); } return QString(); } void PackProfile::disableInteraction(bool disable) { if (d->interactionDisabled != disable) { d->interactionDisabled = disable; auto size = d->components.size(); if (size) { emit dataChanged(index(0), index(size - 1)); } } } std::optional<ModPlatform::ModLoaderTypes> PackProfile::getModLoaders() { ModPlatform::ModLoaderTypes result; bool has_any_loader = false; QMapIterator<QString, ModloaderMapEntry> i(Component::KNOWN_MODLOADERS); while (i.hasNext()) { i.next(); if (auto c = getComponent(i.key()); c != nullptr && c->isEnabled()) { result |= i.value().type; has_any_loader = true; } } if (!has_any_loader) 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; } QList<ModPlatform::ModLoaderType> PackProfile::getModLoadersList() { QList<ModPlatform::ModLoaderType> result; for (auto c : d->components) { if (c->isEnabled() && Component::KNOWN_MODLOADERS.contains(c->getID())) { result.append(Component::KNOWN_MODLOADERS[c->getID()].type); } } // TODO: remove this or add version condition once Quilt drops official Fabric support if (result.contains(ModPlatform::Quilt) && !result.contains(ModPlatform::Fabric)) { result.append(ModPlatform::Fabric); } if (getComponentVersion("net.minecraft") == "1.20.1" && result.contains(ModPlatform::NeoForge) && !result.contains(ModPlatform::Forge)) { result.append(ModPlatform::Forge); } return result; }
35,019
C++
.cpp
934
30.88758
139
0.640042
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,164
ComponentUpdateTask.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/ComponentUpdateTask.cpp
#include "ComponentUpdateTask.h" #include <algorithm> #include "Component.h" #include "ComponentUpdateTask_p.h" #include "PackProfile.h" #include "PackProfile_p.h" #include "ProblemProvider.h" #include "Version.h" #include "cassert" #include "meta/Index.h" #include "meta/Version.h" #include "minecraft/MinecraftInstance.h" #include "minecraft/OneSixVersionFormat.h" #include "minecraft/ProfileUtils.h" #include "net/Mode.h" #include "Application.h" #include "tasks/Task.h" #include "minecraft/Logging.h" /* * This is responsible for loading the components of a component list AND resolving dependency issues between them */ /* * FIXME: the 'one shot async task' nature of this does not fit the intended usage * Really, it should be a reactor/state machine that receives input from the application * and dynamically adapts to changing requirements... * * The reactor should be the only entry into manipulating the PackProfile. * See: https://en.wikipedia.org/wiki/Reactor_pattern */ /* * Or make this operate on a snapshot of the PackProfile state, then merge results in as long as the snapshot and PackProfile didn't change? * If the component list changes, start over. */ ComponentUpdateTask::ComponentUpdateTask(Mode mode, Net::Mode netmode, PackProfile* list) : Task() { d.reset(new ComponentUpdateTaskData); d->m_profile = list; d->mode = mode; d->netmode = netmode; } ComponentUpdateTask::~ComponentUpdateTask() {} void ComponentUpdateTask::executeTask() { qCDebug(instanceProfileResolveC) << "Loading components"; loadComponents(); } namespace { enum class LoadResult { LoadedLocal, RequiresRemote, Failed }; LoadResult composeLoadResult(LoadResult a, LoadResult b) { if (a < b) { return b; } return a; } static LoadResult loadComponent(ComponentPtr component, Task::Ptr& loadTask, Net::Mode netmode) { if (component->m_loaded) { qCDebug(instanceProfileResolveC) << component->getName() << "is already loaded"; return LoadResult::LoadedLocal; } LoadResult result = LoadResult::Failed; auto customPatchFilename = component->getFilename(); if (QFile::exists(customPatchFilename)) { // if local file exists... // check for uid problems inside... bool fileChanged = false; auto file = ProfileUtils::parseJsonFile(QFileInfo(customPatchFilename), false); if (file->uid != component->m_uid) { file->uid = component->m_uid; fileChanged = true; } if (fileChanged) { // FIXME: @QUALITY do not ignore return value ProfileUtils::saveJsonFile(OneSixVersionFormat::versionFileToJson(file), customPatchFilename); } component->m_file = file; component->m_loaded = true; result = LoadResult::LoadedLocal; } else { auto metaVersion = APPLICATION->metadataIndex()->get(component->m_uid, component->m_version); component->m_metaVersion = metaVersion; if (metaVersion->isLoaded()) { component->m_loaded = true; result = LoadResult::LoadedLocal; } else { loadTask = APPLICATION->metadataIndex()->loadVersion(component->m_uid, component->m_version, netmode); loadTask->start(); if (netmode == Net::Mode::Online) result = LoadResult::RequiresRemote; else if (metaVersion->isLoaded()) result = LoadResult::LoadedLocal; else result = LoadResult::Failed; } } return result; } // FIXME: dead code. determine if this can still be useful? /* static LoadResult loadPackProfile(ComponentPtr component, Task::Ptr& loadTask, Net::Mode netmode) { if(component->m_loaded) { qDebug() << component->getName() << "is already loaded"; return LoadResult::LoadedLocal; } LoadResult result = LoadResult::Failed; auto metaList = APPLICATION->metadataIndex()->get(component->m_uid); if(metaList->isLoaded()) { component->m_loaded = true; result = LoadResult::LoadedLocal; } else { metaList->load(netmode); loadTask = metaList->getCurrentTask(); result = LoadResult::RequiresRemote; } return result; } */ } // namespace void ComponentUpdateTask::loadComponents() { LoadResult result = LoadResult::LoadedLocal; size_t taskIndex = 0; size_t componentIndex = 0; d->remoteLoadSuccessful = true; // load all the components OR their lists... for (auto component : d->m_profile->d->components) { Task::Ptr loadTask; LoadResult singleResult; RemoteLoadStatus::Type loadType; component->resetComponentProblems(); // FIXME: to do this right, we need to load the lists and decide on which versions to use during dependency resolution. For now, // ignore all that... #if 0 switch(d->mode) { case Mode::Launch: { singleResult = loadComponent(component, loadTask, d->netmode); loadType = RemoteLoadStatus::Type::Version; break; } case Mode::Resolution: { singleResult = loadPackProfile(component, loadTask, d->netmode); loadType = RemoteLoadStatus::Type::List; break; } } #else singleResult = loadComponent(component, loadTask, d->netmode); loadType = RemoteLoadStatus::Type::Version; #endif if (singleResult == LoadResult::LoadedLocal) { component->updateCachedData(); } result = composeLoadResult(result, singleResult); if (loadTask) { qCDebug(instanceProfileResolveC) << d->m_profile->d->m_instance->name() << "|" << "Remote loading is being run for" << component->getName(); connect(loadTask.get(), &Task::succeeded, this, [this, taskIndex]() { remoteLoadSucceeded(taskIndex); }); connect(loadTask.get(), &Task::failed, this, [this, taskIndex](const QString& error) { remoteLoadFailed(taskIndex, error); }); connect(loadTask.get(), &Task::aborted, this, [this, taskIndex]() { remoteLoadFailed(taskIndex, tr("Aborted")); }); RemoteLoadStatus status; status.type = loadType; status.PackProfileIndex = componentIndex; status.task = loadTask; d->remoteLoadStatusList.append(status); taskIndex++; } componentIndex++; } d->remoteTasksInProgress = taskIndex; switch (result) { case LoadResult::LoadedLocal: { // Everything got loaded. Advance to dependency resolution. performUpdateActions(); resolveDependencies(d->mode == Mode::Launch || d->netmode == Net::Mode::Offline); break; } case LoadResult::RequiresRemote: { // we wait for signals. break; } case LoadResult::Failed: { emitFailed(tr("Some component metadata load tasks failed.")); break; } } } namespace { struct RequireEx : public Meta::Require { size_t indexOfFirstDependee = 0; }; struct RequireCompositionResult { bool ok; RequireEx outcome; }; using RequireExSet = std::set<RequireEx>; } // namespace static RequireCompositionResult composeRequirement(const RequireEx& a, const RequireEx& b) { assert(a.uid == b.uid); RequireEx out; out.uid = a.uid; out.indexOfFirstDependee = std::min(a.indexOfFirstDependee, b.indexOfFirstDependee); if (a.equalsVersion.isEmpty()) { out.equalsVersion = b.equalsVersion; } else if (b.equalsVersion.isEmpty()) { out.equalsVersion = a.equalsVersion; } else if (a.equalsVersion == b.equalsVersion) { out.equalsVersion = a.equalsVersion; } else { // FIXME: mark error as explicit version conflict return { false, out }; } if (a.suggests.isEmpty()) { out.suggests = b.suggests; } else if (b.suggests.isEmpty()) { out.suggests = a.suggests; } else { Version aVer(a.suggests); Version bVer(b.suggests); out.suggests = (aVer < bVer ? b.suggests : a.suggests); } return { true, out }; } // gather the requirements from all components, finding any obvious conflicts static bool gatherRequirementsFromComponents(const ComponentContainer& input, RequireExSet& output) { bool succeeded = true; size_t componentNum = 0; for (auto component : input) { auto& componentRequires = component->m_cachedRequires; for (const auto& componentRequire : componentRequires) { auto found = std::find_if(output.cbegin(), output.cend(), [componentRequire](const Meta::Require& req) { return req.uid == componentRequire.uid; }); RequireEx componenRequireEx; componenRequireEx.uid = componentRequire.uid; componenRequireEx.suggests = componentRequire.suggests; componenRequireEx.equalsVersion = componentRequire.equalsVersion; componenRequireEx.indexOfFirstDependee = componentNum; if (found != output.cend()) { // found... process it further auto result = composeRequirement(componenRequireEx, *found); if (result.ok) { output.erase(componenRequireEx); output.insert(result.outcome); } else { qCCritical(instanceProfileResolveC) << "Conflicting requirements:" << componentRequire.uid << "versions:" << componentRequire.equalsVersion << ";" << (*found).equalsVersion; } succeeded &= result.ok; } else { // not found, accumulate output.insert(componenRequireEx); } } componentNum++; } return succeeded; } /// Get list of uids that can be trivially removed because nothing is depending on them anymore (and they are installed as deps) static void getTrivialRemovals(const ComponentContainer& components, const RequireExSet& reqs, QStringList& toRemove) { for (const auto& component : components) { if (!component->m_dependencyOnly) continue; if (!component->m_cachedVolatile) continue; RequireEx reqNeedle; reqNeedle.uid = component->m_uid; const auto iter = reqs.find(reqNeedle); if (iter == reqs.cend()) { toRemove.append(component->m_uid); } } } /** * handles: * - trivial addition (there is an unmet requirement and it can be trivially met by adding something) * - trivial version conflict of dependencies == explicit version required and installed is different * * toAdd - set of requirements than mean adding a new component * toChange - set of requirements that mean changing version of an existing component */ static bool getTrivialComponentChanges(const ComponentIndex& index, const RequireExSet& input, RequireExSet& toAdd, RequireExSet& toChange) { enum class Decision { Undetermined, Met, Missing, VersionNotSame, LockedVersionNotSame } decision = Decision::Undetermined; QString reqStr; bool succeeded = true; // list the composed requirements and say if they are met or unmet for (auto& req : input) { do { if (req.equalsVersion.isEmpty()) { reqStr = QString("Req: %1").arg(req.uid); if (index.contains(req.uid)) { decision = Decision::Met; } else { toAdd.insert(req); decision = Decision::Missing; } break; } else { reqStr = QString("Req: %1 == %2").arg(req.uid, req.equalsVersion); const auto& compIter = index.find(req.uid); if (compIter == index.cend()) { toAdd.insert(req); decision = Decision::Missing; break; } auto& comp = (*compIter); if (comp->getVersion() != req.equalsVersion) { if (comp->isCustom()) { decision = Decision::LockedVersionNotSame; } else { if (comp->m_dependencyOnly) { decision = Decision::VersionNotSame; } else { decision = Decision::LockedVersionNotSame; } } break; } decision = Decision::Met; } } while (false); switch (decision) { case Decision::Undetermined: qCCritical(instanceProfileResolveC) << "No decision for" << reqStr; succeeded = false; break; case Decision::Met: qCDebug(instanceProfileResolveC) << reqStr << "Is met."; break; case Decision::Missing: qCDebug(instanceProfileResolveC) << reqStr << "Is missing and should be added at" << req.indexOfFirstDependee; toAdd.insert(req); break; case Decision::VersionNotSame: qCDebug(instanceProfileResolveC) << reqStr << "already has different version that can be changed."; toChange.insert(req); break; case Decision::LockedVersionNotSame: qCDebug(instanceProfileResolveC) << reqStr << "already has different version that cannot be changed."; succeeded = false; break; } } return succeeded; } ComponentContainer ComponentUpdateTask::collectTreeLinked(const QString& uid) { ComponentContainer linked; auto& components = d->m_profile->d->components; auto& componentIndex = d->m_profile->d->componentIndex; auto& instance = d->m_profile->d->m_instance; for (auto comp : components) { qCDebug(instanceProfileResolveC) << instance->name() << "|" << "scanning" << comp->getID() << ":" << comp->getVersion() << "for tree link"; auto dep = std::find_if(comp->m_cachedRequires.cbegin(), comp->m_cachedRequires.cend(), [uid](const Meta::Require& req) -> bool { return req.uid == uid; }); if (dep != comp->m_cachedRequires.cend()) { qCDebug(instanceProfileResolveC) << instance->name() << "|" << comp->getID() << ":" << comp->getVersion() << "depends on" << uid; linked.append(comp); } } auto iter = componentIndex.find(uid); if (iter != componentIndex.end()) { ComponentPtr comp = *iter; comp->updateCachedData(); qCDebug(instanceProfileResolveC) << instance->name() << "|" << comp->getID() << ":" << comp->getVersion() << "has" << comp->m_cachedRequires.size() << "dependencies"; for (auto dep : comp->m_cachedRequires) { qCDebug(instanceProfileC) << instance->name() << "|" << uid << "depends on" << dep.uid; auto found = componentIndex.find(dep.uid); if (found != componentIndex.end()) { qCDebug(instanceProfileC) << instance->name() << "|" << (*found)->getID() << "is present"; linked.append(*found); } } } return linked; } // FIXME, TODO: decouple dependency resolution from loading // FIXME: This works directly with the PackProfile internals. It shouldn't! It needs richer data types than PackProfile uses. // FIXME: throw all this away and use a graph void ComponentUpdateTask::resolveDependencies(bool checkOnly) { qCDebug(instanceProfileResolveC) << "Resolving dependencies"; /* * this is a naive dependency resolving algorithm. all it does is check for following conditions and react in simple ways: * 1. There are conflicting dependencies on the same uid with different exact version numbers * -> hard error * 2. A dependency has non-matching exact version number * -> hard error * 3. A dependency is entirely missing and needs to be injected before the dependee(s) * -> requirements are injected * * NOTE: this is a placeholder and should eventually be replaced with something 'serious' */ auto& components = d->m_profile->d->components; auto& componentIndex = d->m_profile->d->componentIndex; RequireExSet allRequires; QStringList toRemove; do { allRequires.clear(); toRemove.clear(); if (!gatherRequirementsFromComponents(components, allRequires)) { finalizeComponents(); emitFailed(tr("Conflicting requirements detected during dependency checking!")); return; } getTrivialRemovals(components, allRequires, toRemove); if (!toRemove.isEmpty()) { qCDebug(instanceProfileResolveC) << "Removing obsolete components..."; for (auto& remove : toRemove) { qCDebug(instanceProfileResolveC) << "Removing" << remove; d->m_profile->remove(remove); } } } while (!toRemove.isEmpty()); RequireExSet toAdd; RequireExSet toChange; bool succeeded = getTrivialComponentChanges(componentIndex, allRequires, toAdd, toChange); if (!succeeded) { finalizeComponents(); emitFailed(tr("Instance has conflicting dependencies.")); return; } if (checkOnly) { finalizeComponents(); if (toAdd.size() || toChange.size()) { emitFailed(tr("Instance has unresolved dependencies while loading/checking for launch.")); } else { emitSucceeded(); } return; } bool recursionNeeded = false; if (toAdd.size()) { // add stuff... for (auto& add : toAdd) { auto component = makeShared<Component>(d->m_profile, add.uid); if (!add.equalsVersion.isEmpty()) { // exact version qCDebug(instanceProfileResolveC) << "Adding" << add.uid << "version" << add.equalsVersion << "at position" << add.indexOfFirstDependee; component->m_version = add.equalsVersion; } else { // version needs to be decided qCDebug(instanceProfileResolveC) << "Adding" << add.uid << "at position" << add.indexOfFirstDependee; // ############################################################################################################ // HACK HACK HACK HACK FIXME: this is a placeholder for deciding what version to use. For now, it is hardcoded. if (!add.suggests.isEmpty()) { component->m_version = add.suggests; } else { if (add.uid == "org.lwjgl") { component->m_version = "2.9.1"; } else if (add.uid == "org.lwjgl3") { component->m_version = "3.1.2"; } else if (add.uid == "net.fabricmc.intermediary" || add.uid == "org.quiltmc.hashed") { auto minecraft = std::find_if(components.begin(), components.end(), [](ComponentPtr& cmp) { return cmp->getID() == "net.minecraft"; }); if (minecraft != components.end()) { component->m_version = (*minecraft)->getVersion(); } } } // HACK HACK HACK HACK FIXME: this is a placeholder for deciding what version to use. For now, it is hardcoded. // ############################################################################################################ } component->m_dependencyOnly = true; // FIXME: this should not work directly with the component list d->m_profile->insertComponent(add.indexOfFirstDependee, component); componentIndex[add.uid] = component; } recursionNeeded = true; } if (toChange.size()) { // change a version of something that exists for (auto& change : toChange) { // FIXME: this should not work directly with the component list qCDebug(instanceProfileResolveC) << "Setting version of " << change.uid << "to" << change.equalsVersion; auto component = componentIndex[change.uid]; component->setVersion(change.equalsVersion); } recursionNeeded = true; } if (recursionNeeded) { loadComponents(); } else { finalizeComponents(); emitSucceeded(); } } // Variant visitation via lambda template <class... Ts> struct overload : Ts... { using Ts::operator()...; }; template <class... Ts> overload(Ts...) -> overload<Ts...>; void ComponentUpdateTask::performUpdateActions() { auto& instance = d->m_profile->d->m_instance; bool addedActions; QStringList toRemove; do { addedActions = false; toRemove.clear(); auto& components = d->m_profile->d->components; auto& componentIndex = d->m_profile->d->componentIndex; for (auto component : components) { if (!component) { continue; } auto action = component->getUpdateAction(); auto visitor = overload{ [](const UpdateActionNone&) { // noop }, [&component, &instance](const UpdateActionChangeVersion& cv) { qCDebug(instanceProfileResolveC) << instance->name() << "|" << "UpdateActionChangeVersion" << component->getID() << ":" << component->getVersion() << "change to" << cv.targetVersion; component->setVersion(cv.targetVersion); component->waitLoadMeta(); }, [&component, &instance](const UpdateActionLatestRecommendedCompatible lrc) { qCDebug(instanceProfileResolveC) << instance->name() << "|" << "UpdateActionLatestRecommendedCompatible" << component->getID() << ":" << component->getVersion() << "updating to latest recommend or compatible with" << lrc.parentUid << lrc.version; auto versionList = APPLICATION->metadataIndex()->get(component->getID()); if (versionList) { versionList->waitToLoad(); auto recommended = versionList->getRecommendedForParent(lrc.parentUid, lrc.version); if (!recommended) { recommended = versionList->getLatestForParent(lrc.parentUid, lrc.version); } if (recommended) { component->setVersion(recommended->version()); component->waitLoadMeta(); return; } else { component->addComponentProblem(ProblemSeverity::Error, QObject::tr("No compatible version of %1 found for %2 %3") .arg(component->getName(), lrc.parentName, lrc.version)); } } else { component->addComponentProblem( ProblemSeverity::Error, QObject::tr("No version list in metadata index for %1").arg(component->getID())); } }, [&component, &instance, &toRemove](const UpdateActionRemove&) { qCDebug(instanceProfileResolveC) << instance->name() << "|" << "UpdateActionRemove" << component->getID() << ":" << component->getVersion() << "removing"; toRemove.append(component->getID()); }, [this, &component, &instance, &addedActions, &componentIndex](const UpdateActionImportantChanged& ic) { qCDebug(instanceProfileResolveC) << instance->name() << "|" << "UpdateImportantChanged" << component->getID() << ":" << component->getVersion() << "was changed from" << ic.oldVersion << "updating linked components"; auto oldVersion = APPLICATION->metadataIndex()->getLoadedVersion(component->getID(), ic.oldVersion); for (auto oldReq : oldVersion->requiredSet()) { auto currentlyRequired = component->m_cachedRequires.find(oldReq); if (currentlyRequired == component->m_cachedRequires.cend()) { auto oldReqComp = componentIndex.find(oldReq.uid); if (oldReqComp != componentIndex.cend()) { (*oldReqComp)->setUpdateAction(UpdateAction{ UpdateActionRemove{} }); addedActions = true; } } } auto linked = collectTreeLinked(component->getID()); for (auto comp : linked) { if (comp->isCustom()) { continue; } auto compUid = comp->getID(); auto parentReq = std::find_if(component->m_cachedRequires.begin(), component->m_cachedRequires.end(), [compUid](const Meta::Require& req) { return req.uid == compUid; }); if (parentReq != component->m_cachedRequires.end()) { auto newVersion = parentReq->equalsVersion.isEmpty() ? parentReq->suggests : parentReq->equalsVersion; if (!newVersion.isEmpty()) { comp->setUpdateAction(UpdateAction{ UpdateActionChangeVersion{ newVersion } }); } else { comp->setUpdateAction(UpdateAction{ UpdateActionLatestRecommendedCompatible{ component->getID(), component->getName(), component->getVersion(), } }); } } else { comp->setUpdateAction(UpdateAction{ UpdateActionLatestRecommendedCompatible{ component->getID(), component->getName(), component->getVersion(), } }); } addedActions = true; } } }; std::visit(visitor, action); component->clearUpdateAction(); for (auto uid : toRemove) { d->m_profile->remove(uid); } } } while (addedActions); } void ComponentUpdateTask::finalizeComponents() { auto& components = d->m_profile->d->components; auto& componentIndex = d->m_profile->d->componentIndex; for (auto component : components) { for (auto req : component->m_cachedRequires) { auto found = componentIndex.find(req.uid); if (found == componentIndex.cend()) { component->addComponentProblem( ProblemSeverity::Error, QObject::tr("%1 is missing requirement %2 %3") .arg(component->getName(), req.uid, req.equalsVersion.isEmpty() ? req.suggests : req.equalsVersion)); } else { auto reqComp = *found; if (!reqComp->getProblems().isEmpty()) { component->addComponentProblem( reqComp->getProblemSeverity(), QObject::tr("%1, a dependency of this component, has reported issues").arg(reqComp->getName())); } if (!req.equalsVersion.isEmpty() && req.equalsVersion != reqComp->getVersion()) { component->addComponentProblem(ProblemSeverity::Error, QObject::tr("%1, a dependency of this component, is not the required version %2") .arg(reqComp->getName(), req.equalsVersion)); } else if (!req.suggests.isEmpty() && req.suggests != reqComp->getVersion()) { component->addComponentProblem(ProblemSeverity::Warning, QObject::tr("%1, a dependency of this component, is not the suggested version %2") .arg(reqComp->getName(), req.suggests)); } } } for (auto conflict : component->knownConflictingComponents()) { auto found = componentIndex.find(conflict); if (found != componentIndex.cend()) { auto foundComp = *found; if (foundComp->isCustom()) { continue; } component->addComponentProblem( ProblemSeverity::Warning, QObject::tr("%1 and %2 are known to not work together. It is recommended to remove one of them.") .arg(component->getName(), foundComp->getName())); } } } } void ComponentUpdateTask::remoteLoadSucceeded(size_t taskIndex) { if (static_cast<size_t>(d->remoteLoadStatusList.size()) < taskIndex) { qCWarning(instanceProfileResolveC) << "Got task index outside of results" << taskIndex; return; } auto& taskSlot = d->remoteLoadStatusList[taskIndex]; disconnect(taskSlot.task.get(), &Task::succeeded, this, nullptr); disconnect(taskSlot.task.get(), &Task::failed, this, nullptr); disconnect(taskSlot.task.get(), &Task::aborted, this, nullptr); if (taskSlot.finished) { qCWarning(instanceProfileResolveC) << "Got multiple results from remote load task" << taskIndex; return; } qCDebug(instanceProfileResolveC) << "Remote task" << taskIndex << "succeeded"; taskSlot.succeeded = false; taskSlot.finished = true; d->remoteTasksInProgress--; // update the cached data of the component from the downloaded version file. if (taskSlot.type == RemoteLoadStatus::Type::Version) { auto component = d->m_profile->getComponent(taskSlot.PackProfileIndex); component->m_loaded = true; component->updateCachedData(); } checkIfAllFinished(); } void ComponentUpdateTask::remoteLoadFailed(size_t taskIndex, const QString& msg) { if (static_cast<size_t>(d->remoteLoadStatusList.size()) < taskIndex) { qCWarning(instanceProfileResolveC) << "Got task index outside of results" << taskIndex; return; } auto& taskSlot = d->remoteLoadStatusList[taskIndex]; disconnect(taskSlot.task.get(), &Task::succeeded, this, nullptr); disconnect(taskSlot.task.get(), &Task::failed, this, nullptr); disconnect(taskSlot.task.get(), &Task::aborted, this, nullptr); if (taskSlot.finished) { qCWarning(instanceProfileResolveC) << "Got multiple results from remote load task" << taskIndex; return; } qCDebug(instanceProfileResolveC) << "Remote task" << taskIndex << "failed: " << msg; d->remoteLoadSuccessful = false; taskSlot.succeeded = false; taskSlot.finished = true; taskSlot.error = msg; d->remoteTasksInProgress--; checkIfAllFinished(); } void ComponentUpdateTask::checkIfAllFinished() { if (d->remoteTasksInProgress) { // not yet... return; } if (d->remoteLoadSuccessful) { // nothing bad happened... clear the temp load status and proceed with looking at dependencies d->remoteLoadStatusList.clear(); performUpdateActions(); resolveDependencies(d->mode == Mode::Launch); } else { // remote load failed... report error and bail QStringList allErrorsList; for (auto& item : d->remoteLoadStatusList) { if (!item.succeeded) { allErrorsList.append(item.error); } } auto allErrors = allErrorsList.join("\n"); emitFailed(tr("Component metadata update task failed while downloading from remote server:\n%1").arg(allErrors)); d->remoteLoadStatusList.clear(); } }
34,158
C++
.cpp
738
33.252033
140
0.556458
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,165
MinecraftLoadAndCheck.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/MinecraftLoadAndCheck.cpp
#include "MinecraftLoadAndCheck.h" #include "MinecraftInstance.h" #include "PackProfile.h" MinecraftLoadAndCheck::MinecraftLoadAndCheck(MinecraftInstance* inst, Net::Mode netmode) : m_inst(inst), m_netmode(netmode) {} void MinecraftLoadAndCheck::executeTask() { // add offline metadata load task auto components = m_inst->getPackProfile(); components->reload(m_netmode); m_task = components->getCurrentTask(); if (!m_task) { emitSucceeded(); return; } connect(m_task.get(), &Task::succeeded, this, &MinecraftLoadAndCheck::emitSucceeded); connect(m_task.get(), &Task::failed, this, &MinecraftLoadAndCheck::emitFailed); connect(m_task.get(), &Task::aborted, this, [this] { emitFailed(tr("Aborted")); }); connect(m_task.get(), &Task::progress, this, &MinecraftLoadAndCheck::setProgress); connect(m_task.get(), &Task::stepProgress, this, &MinecraftLoadAndCheck::propagateStepProgress); connect(m_task.get(), &Task::status, this, &MinecraftLoadAndCheck::setStatus); connect(m_task.get(), &Task::details, this, &MinecraftLoadAndCheck::setDetails); } bool MinecraftLoadAndCheck::canAbort() const { if (m_task) { return m_task->canAbort(); } return true; } bool MinecraftLoadAndCheck::abort() { if (m_task && m_task->canAbort()) { auto status = m_task->abort(); emitFailed("Aborted."); return status; } return Task::abort(); }
1,447
C++
.cpp
38
33.710526
126
0.69395
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,166
VersionFile.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/VersionFile.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2022 Jamie Mansfield <jmansfield@cadixdev.org> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <QJsonArray> #include <QJsonDocument> #include <QDebug> #include "ParseUtils.h" #include "minecraft/Library.h" #include "minecraft/PackProfile.h" #include "minecraft/VersionFile.h" #include <Version.h> static bool isMinecraftVersion(const QString& uid) { return uid == "net.minecraft"; } void VersionFile::applyTo(LaunchProfile* profile, const RuntimeContext& runtimeContext) { // Only real Minecraft can set those. Don't let anything override them. if (isMinecraftVersion(uid)) { profile->applyMinecraftVersion(version); profile->applyMinecraftVersionType(type); // 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/ profile->applyMinecraftAssets(mojangAssetIndex); } profile->applyMainJar(mainJar); profile->applyMainClass(mainClass); profile->applyAppletClass(appletClass); profile->applyMinecraftArguments(minecraftArguments); profile->applyAddnJvmArguments(addnJvmArguments); profile->applyTweakers(addTweakers); profile->applyJarMods(jarMods); profile->applyMods(mods); profile->applyTraits(traits); profile->applyCompatibleJavaMajors(compatibleJavaMajors); profile->applyCompatibleJavaName(compatibleJavaName); for (auto library : libraries) { profile->applyLibrary(library, runtimeContext); } for (auto mavenFile : mavenFiles) { profile->applyMavenFile(mavenFile, runtimeContext); } for (auto agent : agents) { profile->applyAgent(agent, runtimeContext); } profile->applyProblemSeverity(getProblemSeverity()); }
3,296
C++
.cpp
80
37.6875
87
0.740648
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,167
Library.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/Library.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 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 "Library.h" #include "MinecraftInstance.h" #include "net/NetRequest.h" #include <BuildConfig.h> #include <FileSystem.h> #include <net/ApiDownload.h> #include <net/ChecksumValidator.h> /** * @brief Collect applicable files for the library. * * Depending on whether the library is native or not, it adds paths to the * appropriate lists for jar files, native libraries for 32-bit, and native * libraries for 64-bit. * * @param runtimeContext The current runtime context. * @param jar List to store paths for jar files. * @param native List to store paths for native libraries. * @param native32 List to store paths for 32-bit native libraries. * @param native64 List to store paths for 64-bit native libraries. * @param overridePath Optional path to override the default storage path. */ void Library::getApplicableFiles(const RuntimeContext& runtimeContext, QStringList& jar, QStringList& native, QStringList& native32, QStringList& native64, const QString& overridePath) const { bool local = isLocal(); // Lambda function to get the absolute file path auto actualPath = [this, local, overridePath](QString relPath) { relPath = FS::RemoveInvalidPathChars(relPath); QFileInfo out(FS::PathCombine(storagePrefix(), relPath)); if (local && !overridePath.isEmpty()) { QString fileName = out.fileName(); return QFileInfo(FS::PathCombine(overridePath, fileName)).absoluteFilePath(); } return out.absoluteFilePath(); }; QString raw_storage = storageSuffix(runtimeContext); if (isNative()) { if (raw_storage.contains("${arch}")) { auto nat32Storage = raw_storage; nat32Storage.replace("${arch}", "32"); auto nat64Storage = raw_storage; nat64Storage.replace("${arch}", "64"); native32 += actualPath(nat32Storage); native64 += actualPath(nat64Storage); } else { native += actualPath(raw_storage); } } else { jar += actualPath(raw_storage); } } /** * @brief Get download requests for the library files. * * Depending on whether the library is native or not, and the current runtime context, * this function prepares download requests for the necessary files. It handles both local * and remote files, checks for stale cache entries, and adds checksummed downloads. * * @param runtimeContext The current runtime context. * @param cache Pointer to the HTTP meta cache. * @param failedLocalFiles List to store paths for failed local files. * @param overridePath Optional path to override the default storage path. * @return QList<Net::NetRequest::Ptr> List of download requests. */ QList<Net::NetRequest::Ptr> Library::getDownloads(const RuntimeContext& runtimeContext, class HttpMetaCache* cache, QStringList& failedLocalFiles, const QString& overridePath) const { QList<Net::NetRequest::Ptr> out; bool stale = isAlwaysStale(); bool local = isLocal(); // Lambda function to check if a local file exists auto check_local_file = [overridePath, &failedLocalFiles](QString storage) { QFileInfo fileinfo(storage); QString fileName = fileinfo.fileName(); auto fullPath = FS::PathCombine(overridePath, fileName); QFileInfo localFileInfo(fullPath); if (!localFileInfo.exists()) { failedLocalFiles.append(localFileInfo.filePath()); return false; } return true; }; // Lambda function to add a download request auto add_download = [this, local, check_local_file, cache, stale, &out](QString storage, QString url, QString sha1) { if (local) { return check_local_file(storage); } auto entry = cache->resolveEntry("libraries", storage); if (stale) { entry->setStale(true); } if (!entry->isStale()) return true; Net::Download::Options options; if (stale) { options |= Net::Download::Option::AcceptLocalFiles; } // Don't add a time limit for the libraries cache entry validity options |= Net::Download::Option::MakeEternal; if (sha1.size()) { auto dl = Net::ApiDownload::makeCached(url, entry, options); dl->addValidator(new Net::ChecksumValidator(QCryptographicHash::Sha1, sha1)); qDebug() << "Checksummed Download for:" << rawName().serialize() << "storage:" << storage << "url:" << url; out.append(dl); } else { out.append(Net::ApiDownload::makeCached(url, entry, options)); qDebug() << "Download for:" << rawName().serialize() << "storage:" << storage << "url:" << url; } return true; }; QString raw_storage = storageSuffix(runtimeContext); if (m_mojangDownloads) { if (isNative()) { auto nativeClassifier = getCompatibleNative(runtimeContext); if (!nativeClassifier.isNull()) { if (nativeClassifier.contains("${arch}")) { auto nat32Classifier = nativeClassifier; nat32Classifier.replace("${arch}", "32"); auto nat64Classifier = nativeClassifier; nat64Classifier.replace("${arch}", "64"); auto nat32info = m_mojangDownloads->getDownloadInfo(nat32Classifier); if (nat32info) { auto cooked_storage = raw_storage; cooked_storage.replace("${arch}", "32"); add_download(cooked_storage, nat32info->url, nat32info->sha1); } auto nat64info = m_mojangDownloads->getDownloadInfo(nat64Classifier); if (nat64info) { auto cooked_storage = raw_storage; cooked_storage.replace("${arch}", "64"); add_download(cooked_storage, nat64info->url, nat64info->sha1); } } else { auto info = m_mojangDownloads->getDownloadInfo(nativeClassifier); if (info) { add_download(raw_storage, info->url, info->sha1); } } } else { qDebug() << "Ignoring native library" << m_name.serialize() << "because it has no classifier for current OS"; } } else { if (m_mojangDownloads->artifact) { auto artifact = m_mojangDownloads->artifact; add_download(raw_storage, artifact->url, artifact->sha1); } else { qDebug() << "Ignoring java library" << m_name.serialize() << "because it has no artifact"; } } } else { auto raw_dl = [this, raw_storage]() { if (!m_absoluteURL.isEmpty()) { return m_absoluteURL; } if (m_repositoryURL.isEmpty()) { return BuildConfig.LIBRARY_BASE + raw_storage; } if (m_repositoryURL.endsWith('/')) { return m_repositoryURL + raw_storage; } else { return m_repositoryURL + QChar('/') + raw_storage; } }(); if (raw_storage.contains("${arch}")) { QString cooked_storage = raw_storage; QString cooked_dl = raw_dl; add_download(cooked_storage.replace("${arch}", "32"), cooked_dl.replace("${arch}", "32"), QString()); cooked_storage = raw_storage; cooked_dl = raw_dl; add_download(cooked_storage.replace("${arch}", "64"), cooked_dl.replace("${arch}", "64"), QString()); } else { add_download(raw_storage, raw_dl, QString()); } } return out; } /** * @brief Check if the library is active in the given runtime context. * * This function evaluates rules to determine if the library should be active, * considering both general rules and native compatibility. * * @param runtimeContext The current runtime context. * @return bool True if the library is active, false otherwise. */ bool Library::isActive(const RuntimeContext& runtimeContext) const { bool result = true; if (m_rules.empty()) { result = true; } else { RuleAction ruleResult = Disallow; for (auto rule : m_rules) { RuleAction temp = rule->apply(this, runtimeContext); if (temp != Defer) ruleResult = temp; } result = result && (ruleResult == Allow); } if (isNative()) { result = result && !getCompatibleNative(runtimeContext).isNull(); } return result; } /** * @brief Check if the library is considered local. * * @return bool True if the library is local, false otherwise. */ bool Library::isLocal() const { return m_hint == "local"; } /** * @brief Check if the library is always considered stale. * * @return bool True if the library is always stale, false otherwise. */ bool Library::isAlwaysStale() const { return m_hint == "always-stale"; } /** * @brief Get the compatible native classifier for the current runtime context. * * This function attempts to match the current runtime context with the appropriate * native classifier. * * @param runtimeContext The current runtime context. * @return QString The compatible native classifier, or an empty string if none is found. */ QString Library::getCompatibleNative(const RuntimeContext& runtimeContext) const { // try to match precise classifier "[os]-[arch]" auto entry = m_nativeClassifiers.constFind(runtimeContext.getClassifier()); // try to match imprecise classifier on legacy architectures "[os]" if (entry == m_nativeClassifiers.constEnd() && runtimeContext.isLegacyArch()) entry = m_nativeClassifiers.constFind(runtimeContext.system); if (entry == m_nativeClassifiers.constEnd()) return QString(); return entry.value(); } /** * @brief Set the storage prefix for the library. * * @param prefix The storage prefix to set. */ void Library::setStoragePrefix(QString prefix) { m_storagePrefix = prefix; } /** * @brief Get the default storage prefix for libraries. * * @return QString The default storage prefix. */ QString Library::defaultStoragePrefix() { return "libraries/"; } /** * @brief Get the current storage prefix for the library. * * @return QString The current storage prefix. */ QString Library::storagePrefix() const { if (m_storagePrefix.isEmpty()) { return defaultStoragePrefix(); } return m_storagePrefix; } /** * @brief Get the filename for the library in the current runtime context. * * This function determines the appropriate filename for the library, taking into * account native classifiers if applicable. * * @param runtimeContext The current runtime context. * @return QString The filename of the library. */ QString Library::filename(const RuntimeContext& runtimeContext) const { if (!m_filename.isEmpty()) { return m_filename; } // non-native? use only the gradle specifier if (!isNative()) { return m_name.getFileName(); } // otherwise native, override classifiers. Mojang HACK! GradleSpecifier nativeSpec = m_name; QString nativeClassifier = getCompatibleNative(runtimeContext); if (!nativeClassifier.isNull()) { nativeSpec.setClassifier(nativeClassifier); } else { nativeSpec.setClassifier("INVALID"); } return nativeSpec.getFileName(); } /** * @brief Get the display name for the library in the current runtime context. * * This function returns the display name for the library, defaulting to the filename * if no display name is set. * * @param runtimeContext The current runtime context. * @return QString The display name of the library. */ QString Library::displayName(const RuntimeContext& runtimeContext) const { if (!m_displayname.isEmpty()) return m_displayname; return filename(runtimeContext); } /** * @brief Get the storage suffix for the library in the current runtime context. * * This function determines the appropriate storage suffix for the library, taking into * account native classifiers if applicable. * * @param runtimeContext The current runtime context. * @return QString The storage suffix of the library. */ QString Library::storageSuffix(const RuntimeContext& runtimeContext) const { // non-native? use only the gradle specifier if (!isNative()) { return m_name.toPath(m_filename); } // otherwise native, override classifiers. Mojang HACK! GradleSpecifier nativeSpec = m_name; QString nativeClassifier = getCompatibleNative(runtimeContext); if (!nativeClassifier.isNull()) { nativeSpec.setClassifier(nativeClassifier); } else { nativeSpec.setClassifier("INVALID"); } return nativeSpec.toPath(m_filename); }
14,820
C++
.cpp
380
31.9
125
0.645206
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,168
World.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/World.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2022 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 * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "World.h" #include <QDebug> #include <QDir> #include <QDirIterator> #include <QString> #include <FileSystem.h> #include <MMCZip.h> #include <io/stream_reader.h> #include <quazip/quazip.h> #include <quazip/quazipdir.h> #include <quazip/quazipfile.h> #include <tag_primitive.h> #include <tag_string.h> #include <sstream> #include "GZip.h" #include <QCoreApplication> #include <optional> #include "FileSystem.h" #include "PSaveFile.h" using std::nullopt; using std::optional; GameType::GameType(std::optional<int> original) : original(original) { if (!original) { return; } switch (*original) { case 0: type = GameType::Survival; break; case 1: type = GameType::Creative; break; case 2: type = GameType::Adventure; break; case 3: type = GameType::Spectator; break; default: break; } } QString GameType::toTranslatedString() const { switch (type) { case GameType::Survival: return QCoreApplication::translate("GameType", "Survival"); case GameType::Creative: return QCoreApplication::translate("GameType", "Creative"); case GameType::Adventure: return QCoreApplication::translate("GameType", "Adventure"); case GameType::Spectator: return QCoreApplication::translate("GameType", "Spectator"); default: break; } if (original) { return QCoreApplication::translate("GameType", "Unknown (%1)").arg(*original); } return QCoreApplication::translate("GameType", "Undefined"); } QString GameType::toLogString() const { switch (type) { case GameType::Survival: return "Survival"; case GameType::Creative: return "Creative"; case GameType::Adventure: return "Adventure"; case GameType::Spectator: return "Spectator"; default: break; } if (original) { return QString("Unknown (%1)").arg(*original); } return "Undefined"; } std::unique_ptr<nbt::tag_compound> parseLevelDat(QByteArray data) { QByteArray output; if (!GZip::unzip(data, output)) { return nullptr; } std::istringstream foo(std::string(output.constData(), output.size())); try { auto pair = nbt::io::read_compound(foo); if (pair.first != "") return nullptr; if (pair.second == nullptr) return nullptr; return std::move(pair.second); } catch (const nbt::io::input_error& e) { qWarning() << "Unable to parse level.dat:" << e.what(); return nullptr; } } QByteArray serializeLevelDat(nbt::tag_compound* levelInfo) { std::ostringstream s; nbt::io::write_tag("", *levelInfo, s); QByteArray val(s.str().data(), (int)s.str().size()); return val; } QString getLevelDatFromFS(const QFileInfo& file) { QDir worldDir(file.filePath()); if (!file.isDir() || !worldDir.exists("level.dat")) { return QString(); } return worldDir.absoluteFilePath("level.dat"); } QByteArray getLevelDatDataFromFS(const QFileInfo& file) { auto fullFilePath = getLevelDatFromFS(file); if (fullFilePath.isNull()) { return QByteArray(); } QFile f(fullFilePath); if (!f.open(QIODevice::ReadOnly)) { return QByteArray(); } return f.readAll(); } bool putLevelDatDataToFS(const QFileInfo& file, QByteArray& data) { auto fullFilePath = getLevelDatFromFS(file); if (fullFilePath.isNull()) { return false; } PSaveFile f(fullFilePath); if (!f.open(QIODevice::WriteOnly)) { return false; } QByteArray compressed; if (!GZip::zip(data, compressed)) { return false; } if (f.write(compressed) != compressed.size()) { f.cancelWriting(); return false; } return f.commit(); } int64_t calculateWorldSize(const QFileInfo& file) { if (file.isFile() && file.suffix() == "zip") { return file.size(); } else if (file.isDir()) { QDirIterator it(file.absoluteFilePath(), QDir::Files, QDirIterator::Subdirectories); int64_t total = 0; while (it.hasNext()) { it.next(); total += it.fileInfo().size(); } return total; } return -1; } World::World(const QFileInfo& file) { repath(file); } void World::repath(const QFileInfo& file) { m_containerFile = file; m_folderName = file.fileName(); m_size = calculateWorldSize(file); if (file.isFile() && file.suffix() == "zip") { m_iconFile = QString(); readFromZip(file); } else if (file.isDir()) { QFileInfo assumedIconPath(file.absoluteFilePath() + "/icon.png"); if (assumedIconPath.exists()) { m_iconFile = assumedIconPath.absoluteFilePath(); } readFromFS(file); } } bool World::resetIcon() { if (m_iconFile.isNull()) { return false; } if (QFile(m_iconFile).remove()) { m_iconFile = QString(); return true; } return false; } void World::readFromFS(const QFileInfo& file) { auto bytes = getLevelDatDataFromFS(file); if (bytes.isEmpty()) { is_valid = false; return; } loadFromLevelDat(bytes); levelDatTime = file.lastModified(); } void World::readFromZip(const QFileInfo& file) { QuaZip zip(file.absoluteFilePath()); is_valid = zip.open(QuaZip::mdUnzip); if (!is_valid) { return; } auto location = MMCZip::findFolderOfFileInZip(&zip, "level.dat"); is_valid = !location.isEmpty(); if (!is_valid) { return; } m_containerOffsetPath = location; QuaZipFile zippedFile(&zip); // read the install profile is_valid = zip.setCurrentFile(location + "level.dat"); if (!is_valid) { return; } is_valid = zippedFile.open(QIODevice::ReadOnly); QuaZipFileInfo64 levelDatInfo; zippedFile.getFileInfo(&levelDatInfo); auto modTime = levelDatInfo.getNTFSmTime(); if (!modTime.isValid()) { modTime = levelDatInfo.dateTime; } levelDatTime = modTime; if (!is_valid) { return; } loadFromLevelDat(zippedFile.readAll()); zippedFile.close(); } bool World::install(const QString& to, const QString& name) { auto finalPath = FS::PathCombine(to, FS::DirNameFromString(m_actualName, to)); if (!FS::ensureFolderPathExists(finalPath)) { return false; } bool ok = false; if (m_containerFile.isFile()) { QuaZip zip(m_containerFile.absoluteFilePath()); if (!zip.open(QuaZip::mdUnzip)) { return false; } ok = !MMCZip::extractSubDir(&zip, m_containerOffsetPath, finalPath); } else if (m_containerFile.isDir()) { QString from = m_containerFile.filePath(); ok = FS::copy(from, finalPath)(); } if (ok && !name.isEmpty() && m_actualName != name) { QFileInfo finalPathInfo(finalPath); World newWorld(finalPathInfo); if (newWorld.isValid()) { newWorld.rename(name); } } return ok; } bool World::rename(const QString& newName) { if (m_containerFile.isFile()) { return false; } auto data = getLevelDatDataFromFS(m_containerFile); if (data.isEmpty()) { return false; } auto worldData = parseLevelDat(data); if (!worldData) { return false; } auto& val = worldData->at("Data"); if (val.get_type() != nbt::tag_type::Compound) { return false; } auto& dataCompound = val.as<nbt::tag_compound>(); dataCompound.put("LevelName", nbt::value_initializer(newName.toUtf8().data())); data = serializeLevelDat(worldData.get()); putLevelDatDataToFS(m_containerFile, data); m_actualName = newName; QDir parentDir(m_containerFile.absoluteFilePath()); parentDir.cdUp(); QFile container(m_containerFile.absoluteFilePath()); auto dirName = FS::DirNameFromString(m_actualName, parentDir.absolutePath()); container.rename(parentDir.absoluteFilePath(dirName)); return true; } namespace { optional<QString> read_string(nbt::value& parent, const char* name) { try { auto& namedValue = parent.at(name); if (namedValue.get_type() != nbt::tag_type::String) { return nullopt; } auto& tag_str = namedValue.as<nbt::tag_string>(); return QString::fromStdString(tag_str.get()); } 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 ([[maybe_unused]] const std::bad_cast& e) { // type mismatch qWarning() << "NBT tag" << name << "could not be converted to string."; return nullopt; } } optional<int64_t> read_long(nbt::value& parent, const char* name) { try { auto& namedValue = parent.at(name); if (namedValue.get_type() != nbt::tag_type::Long) { return nullopt; } auto& tag_str = namedValue.as<nbt::tag_long>(); return tag_str.get(); } 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 ([[maybe_unused]] const std::bad_cast& e) { // type mismatch qWarning() << "NBT tag" << name << "could not be converted to long."; return nullopt; } } optional<int> read_int(nbt::value& parent, const char* name) { try { auto& namedValue = parent.at(name); if (namedValue.get_type() != nbt::tag_type::Int) { return nullopt; } auto& tag_str = namedValue.as<nbt::tag_int>(); return tag_str.get(); } 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 ([[maybe_unused]] const std::bad_cast& e) { // type mismatch qWarning() << "NBT tag" << name << "could not be converted to int."; return nullopt; } } GameType read_gametype(nbt::value& parent, const char* name) { return GameType(read_int(parent, name)); } } // namespace void World::loadFromLevelDat(QByteArray data) { auto levelData = parseLevelDat(data); if (!levelData) { is_valid = false; return; } nbt::value* valPtr = nullptr; try { valPtr = &levelData->at("Data"); } catch (const std::out_of_range& e) { qWarning() << "Unable to read NBT tags from " << m_folderName << ":" << e.what(); is_valid = false; return; } nbt::value& val = *valPtr; is_valid = val.get_type() == nbt::tag_type::Compound; if (!is_valid) return; auto name = read_string(val, "LevelName"); m_actualName = name ? *name : m_folderName; auto timestamp = read_long(val, "LastPlayed"); m_lastPlayed = timestamp ? QDateTime::fromMSecsSinceEpoch(*timestamp) : levelDatTime; m_gameType = read_gametype(val, "GameType"); optional<int64_t> randomSeed; try { auto& WorldGen_val = val.at("WorldGenSettings"); randomSeed = read_long(WorldGen_val, "seed"); } catch (const std::out_of_range&) { } if (!randomSeed) { randomSeed = read_long(val, "RandomSeed"); } m_randomSeed = randomSeed ? *randomSeed : 0; qDebug() << "World Name:" << m_actualName; qDebug() << "Last Played:" << m_lastPlayed.toString(); if (randomSeed) { qDebug() << "Seed:" << *randomSeed; } qDebug() << "Size:" << m_size; qDebug() << "GameType:" << m_gameType.toLogString(); } bool World::replace(World& with) { if (!destroy()) return false; bool success = FS::copy(with.m_containerFile.filePath(), m_containerFile.path())(); if (success) { m_folderName = with.m_folderName; m_containerFile.refresh(); } return success; } bool World::destroy() { if (!is_valid) return false; if (FS::trash(m_containerFile.filePath())) return true; if (m_containerFile.isDir()) { QDir d(m_containerFile.filePath()); return d.removeRecursively(); } else if (m_containerFile.isFile()) { QFile file(m_containerFile.absoluteFilePath()); return file.remove(); } return true; } bool World::operator==(const World& other) const { return is_valid == other.is_valid && folderName() == other.folderName(); } bool World::isSymLinkUnder(const QString& instPath) const { if (isSymLink()) return true; auto instDir = QDir(instPath); auto relAbsPath = instDir.relativeFilePath(m_containerFile.absoluteFilePath()); auto relCanonPath = instDir.relativeFilePath(m_containerFile.canonicalFilePath()); return relAbsPath != relCanonPath; } bool World::isMoreThanOneHardLink() const { if (m_containerFile.isDir()) { return FS::hardLinkCount(QDir(m_containerFile.absoluteFilePath()).filePath("level.dat")) > 1; } return FS::hardLinkCount(m_containerFile.absoluteFilePath()) > 1; }
14,935
C++
.cpp
477
25.72956
101
0.633315
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,170
MinecraftInstance.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/MinecraftInstance.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2022 Jamie Mansfield <jmansfield@cadixdev.org> * 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 * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "MinecraftInstance.h" #include "Application.h" #include "BuildConfig.h" #include "QObjectPtr.h" #include "minecraft/launch/AutoInstallJava.h" #include "minecraft/launch/CreateGameFolders.h" #include "minecraft/launch/ExtractNatives.h" #include "minecraft/launch/PrintInstanceInfo.h" #include "minecraft/update/AssetUpdateTask.h" #include "minecraft/update/FMLLibrariesTask.h" #include "minecraft/update/LibrariesTask.h" #include "settings/Setting.h" #include "settings/SettingsObject.h" #include "FileSystem.h" #include "MMCTime.h" #include "java/JavaVersion.h" #include "pathmatcher/MultiMatcher.h" #include "pathmatcher/RegexpMatcher.h" #include "launch/LaunchTask.h" #include "launch/TaskStepWrapper.h" #include "launch/steps/CheckJava.h" #include "launch/steps/LookupServerAddress.h" #include "launch/steps/PostLaunchCommand.h" #include "launch/steps/PreLaunchCommand.h" #include "launch/steps/QuitAfterGameStop.h" #include "launch/steps/TextPrint.h" #include "minecraft/launch/ClaimAccount.h" #include "minecraft/launch/LauncherPartLaunch.h" #include "minecraft/launch/ModMinecraftJar.h" #include "minecraft/launch/ReconstructAssets.h" #include "minecraft/launch/ScanModFolders.h" #include "minecraft/launch/VerifyJavaInstall.h" #include "java/JavaUtils.h" #include "icons/IconList.h" #include "mod/ModFolderModel.h" #include "mod/ResourcePackFolderModel.h" #include "mod/ShaderPackFolderModel.h" #include "mod/TexturePackFolderModel.h" #include "WorldList.h" #include "AssetsUtils.h" #include "MinecraftLoadAndCheck.h" #include "PackProfile.h" #include "minecraft/gameoptions/GameOptions.h" #include "minecraft/update/FoldersTask.h" #include "tools/BaseProfiler.h" #include <QActionGroup> #include <QMainWindow> #include <QScreen> #include <QWindow> #ifdef Q_OS_LINUX #include "MangoHud.h" #endif #define IBUS "@im=ibus" // all of this because keeping things compatible with deprecated old settings // if either of the settings {a, b} is true, this also resolves to true class OrSetting : public Setting { Q_OBJECT public: OrSetting(QString id, std::shared_ptr<Setting> a, std::shared_ptr<Setting> b) : Setting({ id }, false), m_a(a), m_b(b) {} virtual QVariant get() const { bool a = m_a->get().toBool(); bool b = m_b->get().toBool(); return a || b; } virtual void reset() {} virtual void set(QVariant value) {} private: std::shared_ptr<Setting> m_a; std::shared_ptr<Setting> m_b; }; MinecraftInstance::MinecraftInstance(SettingsObjectPtr globalSettings, SettingsObjectPtr settings, const QString& rootDir) : BaseInstance(globalSettings, settings, rootDir) { m_components.reset(new PackProfile(this)); } void MinecraftInstance::saveNow() { m_components->saveNow(); } void MinecraftInstance::loadSpecificSettings() { if (isSpecificSettingsLoaded()) return; // Java Settings auto locationOverride = m_settings->registerSetting("OverrideJavaLocation", false); auto argsOverride = m_settings->registerSetting("OverrideJavaArgs", false); m_settings->registerSetting("AutomaticJava", false); if (auto global_settings = globalSettings()) { m_settings->registerOverride(global_settings->getSetting("JavaPath"), locationOverride); m_settings->registerOverride(global_settings->getSetting("JvmArgs"), argsOverride); m_settings->registerOverride(global_settings->getSetting("IgnoreJavaCompatibility"), locationOverride); // special! m_settings->registerPassthrough(global_settings->getSetting("JavaSignature"), locationOverride); m_settings->registerPassthrough(global_settings->getSetting("JavaArchitecture"), locationOverride); m_settings->registerPassthrough(global_settings->getSetting("JavaRealArchitecture"), locationOverride); m_settings->registerPassthrough(global_settings->getSetting("JavaVersion"), locationOverride); m_settings->registerPassthrough(global_settings->getSetting("JavaVendor"), locationOverride); // Window Size auto windowSetting = m_settings->registerSetting("OverrideWindow", false); m_settings->registerOverride(global_settings->getSetting("LaunchMaximized"), windowSetting); m_settings->registerOverride(global_settings->getSetting("MinecraftWinWidth"), windowSetting); m_settings->registerOverride(global_settings->getSetting("MinecraftWinHeight"), windowSetting); // Memory auto memorySetting = m_settings->registerSetting("OverrideMemory", false); m_settings->registerOverride(global_settings->getSetting("MinMemAlloc"), memorySetting); m_settings->registerOverride(global_settings->getSetting("MaxMemAlloc"), memorySetting); m_settings->registerOverride(global_settings->getSetting("PermGen"), memorySetting); // 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); // Performance related options auto performanceOverride = m_settings->registerSetting("OverridePerformance", false); m_settings->registerOverride(global_settings->getSetting("EnableFeralGamemode"), performanceOverride); m_settings->registerOverride(global_settings->getSetting("EnableMangoHud"), performanceOverride); m_settings->registerOverride(global_settings->getSetting("UseDiscreteGpu"), performanceOverride); m_settings->registerOverride(global_settings->getSetting("UseZink"), performanceOverride); // Miscellaneous auto miscellaneousOverride = m_settings->registerSetting("OverrideMiscellaneous", false); m_settings->registerOverride(global_settings->getSetting("CloseAfterLaunch"), miscellaneousOverride); m_settings->registerOverride(global_settings->getSetting("QuitAfterGameStop"), miscellaneousOverride); // Legacy-related options auto legacySettings = m_settings->registerSetting("OverrideLegacySettings", false); m_settings->registerOverride(global_settings->getSetting("OnlineFixes"), legacySettings); auto envSetting = m_settings->registerSetting("OverrideEnv", false); m_settings->registerOverride(global_settings->getSetting("Env"), envSetting); m_settings->set("InstanceType", "OneSix"); } // Join server on launch, this does not have a global override m_settings->registerSetting("JoinServerOnLaunch", false); m_settings->registerSetting("JoinServerOnLaunchAddress", ""); m_settings->registerSetting("JoinWorldOnLaunch", ""); // Use account for instance, this does not have a global override 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); updateRuntimeContext(); } void MinecraftInstance::updateRuntimeContext() { m_runtimeContext.updateFromInstanceSettings(m_settings); m_components->invalidateLaunchProfile(); } QString MinecraftInstance::typeName() const { return "Minecraft"; } std::shared_ptr<PackProfile> MinecraftInstance::getPackProfile() const { return m_components; } QSet<QString> MinecraftInstance::traits() const { auto components = getPackProfile(); if (!components) { return { "version-incomplete" }; } auto profile = components->getProfile(); if (!profile) { return { "version-incomplete" }; } 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")); QFileInfo dotMCDir(FS::PathCombine(instanceRoot(), ".minecraft")); if (dotMCDir.exists() && !mcDir.exists()) return dotMCDir.filePath(); else return mcDir.filePath(); } QString MinecraftInstance::binRoot() const { return FS::PathCombine(gameRoot(), "bin"); } QString MinecraftInstance::getNativePath() const { QDir natives_dir(FS::PathCombine(instanceRoot(), "natives/")); return natives_dir.absolutePath(); } QString MinecraftInstance::getLocalLibraryPath() const { QDir libraries_dir(FS::PathCombine(instanceRoot(), "libraries/")); return libraries_dir.absolutePath(); } bool MinecraftInstance::supportsDemo() const { Version instance_ver{ getPackProfile()->getComponentVersion("net.minecraft") }; // 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"); } QString MinecraftInstance::jarModsDir() const { QDir jarmods_dir(FS::PathCombine(instanceRoot(), "jarmods/")); return jarmods_dir.absolutePath(); } QString MinecraftInstance::modsRoot() const { return FS::PathCombine(gameRoot(), "mods"); } QString MinecraftInstance::modsCacheLocation() const { return FS::PathCombine(instanceRoot(), "mods.cache"); } QString MinecraftInstance::coreModsDir() const { return FS::PathCombine(gameRoot(), "coremods"); } QString MinecraftInstance::nilModsDir() const { return FS::PathCombine(gameRoot(), "nilmods"); } QString MinecraftInstance::resourcePacksDir() const { return FS::PathCombine(gameRoot(), "resourcepacks"); } QString MinecraftInstance::texturePacksDir() const { return FS::PathCombine(gameRoot(), "texturepacks"); } QString MinecraftInstance::shaderPacksDir() const { return FS::PathCombine(gameRoot(), "shaderpacks"); } QString MinecraftInstance::instanceConfigFolder() const { return FS::PathCombine(gameRoot(), "config"); } QString MinecraftInstance::libDir() const { return FS::PathCombine(gameRoot(), "lib"); } QString MinecraftInstance::worldDir() const { return FS::PathCombine(gameRoot(), "saves"); } QString MinecraftInstance::resourcesDir() const { return FS::PathCombine(gameRoot(), "resources"); } QDir MinecraftInstance::librariesPath() const { return QDir::current().absoluteFilePath("libraries"); } QDir MinecraftInstance::jarmodsPath() const { return QDir(jarModsDir()); } QDir MinecraftInstance::versionsPath() const { return QDir::current().absoluteFilePath("versions"); } QStringList MinecraftInstance::getClassPath() { QStringList jars, nativeJars; auto profile = m_components->getProfile(); profile->getLibraryFiles(runtimeContext(), jars, nativeJars, getLocalLibraryPath(), binRoot()); return jars; } QString MinecraftInstance::getMainClass() const { auto profile = m_components->getProfile(); return profile->getMainClass(); } QStringList MinecraftInstance::getNativeJars() { QStringList jars, nativeJars; auto profile = m_components->getProfile(); profile->getLibraryFiles(runtimeContext(), jars, nativeJars, getLocalLibraryPath(), binRoot()); return nativeJars; } QStringList MinecraftInstance::extraArguments() { auto list = BaseInstance::extraArguments(); auto version = getPackProfile(); if (!version) return list; auto jarMods = getJarMods(); if (!jarMods.isEmpty()) { list.append({ "-Dfml.ignoreInvalidMinecraftCertificates=true", "-Dfml.ignorePatchDiscrepancies=true" }); } auto addn = m_components->getProfile()->getAddnJvmArguments(); if (!addn.isEmpty()) { list.append(addn); } auto agents = m_components->getProfile()->getAgents(); for (auto agent : agents) { QStringList jar, temp1, temp2, temp3; agent->library()->getApplicableFiles(runtimeContext(), jar, temp1, temp2, temp3, getLocalLibraryPath()); list.append("-javaagent:" + jar[0] + (agent->argument().isEmpty() ? "" : "=" + agent->argument())); } { 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; } QStringList MinecraftInstance::javaArguments() { QStringList args; // custom args go first. we want to override them if we have our own here. args.append(extraArguments()); // OSX dock icon and name #ifdef Q_OS_MAC args << "-Xdock:icon=icon.png"; args << QString("-Xdock:name=\"%1\"").arg(windowTitle()); #endif auto traits_ = traits(); // HACK: fix issues on macOS with 1.13 snapshots // NOTE: Oracle Java option. if there are alternate jvm implementations, this would be the place to customize this for them #ifdef Q_OS_MAC if (traits_.contains("FirstThreadOnMacOS")) { args << QString("-XstartOnFirstThread"); } #endif // HACK: Stupid hack for Intel drivers. See: https://mojang.atlassian.net/browse/MCL-767 #ifdef Q_OS_WIN32 args << QString( "-XX:HeapDumpPath=MojangTricksIntelDriversForPerformance_javaw.exe_" "minecraft.exe.heapdump"); #endif int min = settings()->get("MinMemAlloc").toInt(); int max = settings()->get("MaxMemAlloc").toInt(); if (min < max) { args << QString("-Xms%1m").arg(min); args << QString("-Xmx%1m").arg(max); } else { args << QString("-Xms%1m").arg(max); args << QString("-Xmx%1m").arg(min); } // No PermGen in newer java. JavaVersion javaVersion = getJavaVersion(); if (javaVersion.requiresPermGen()) { auto permgen = settings()->get("PermGen").toInt(); if (permgen != 64) { args << QString("-XX:PermSize=%1m").arg(permgen); } } 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() { // use legacy launcher if the traits are set if (isLegacy()) return "legacy"; return "standard"; } bool MinecraftInstance::shouldApplyOnlineFixes() { return traits().contains("legacyServices") && settings()->get("OnlineFixes").toBool(); } QMap<QString, QString> MinecraftInstance::getVariables() { QMap<QString, QString> out; out.insert("INST_NAME", name()); out.insert("INST_ID", id()); out.insert("INST_DIR", QDir::toNativeSeparators(QDir(instanceRoot()).absolutePath())); out.insert("INST_MC_DIR", QDir::toNativeSeparators(QDir(gameRoot()).absolutePath())); out.insert("INST_JAVA", settings()->get("JavaPath").toString()); out.insert("INST_JAVA_ARGS", javaArguments().join(' ')); out.insert("NO_COLOR", "1"); return out; } QProcessEnvironment MinecraftInstance::createEnvironment() { // prepare the process environment QProcessEnvironment env = CleanEnviroment(); // export some infos auto variables = getVariables(); for (auto it = variables.begin(); it != variables.end(); ++it) { env.insert(it.key(), it.value()); } // custom env auto insertEnv = [&env](QMap<QString, QVariant> envMap) { if (envMap.isEmpty()) return; for (auto iter = envMap.begin(); iter != envMap.end(); iter++) env.insert(iter.key(), iter.value().toString()); }; bool overrideEnv = settings()->get("OverrideEnv").toBool(); if (!overrideEnv) insertEnv(APPLICATION->settings()->get("Env").toMap()); else insertEnv(settings()->get("Env").toMap()); return env; } QProcessEnvironment MinecraftInstance::createLaunchEnvironment() { // prepare the process environment QProcessEnvironment env = createEnvironment(); #ifdef Q_OS_LINUX if (settings()->get("EnableMangoHud").toBool() && APPLICATION->capabilities() & Application::SupportsMangoHud) { QStringList preloadList; if (auto value = env.value("LD_PRELOAD"); !value.isEmpty()) preloadList = value.split(QLatin1String(":")); auto mangoHudLibString = MangoHud::getLibraryString(); if (!mangoHudLibString.isEmpty()) { QFileInfo mangoHudLib(mangoHudLibString); QString libPath = mangoHudLib.absolutePath(); auto appendLib = [libPath, &preloadList](QString fileName) { if (QFileInfo(FS::PathCombine(libPath, fileName)).exists()) preloadList << FS::PathCombine(libPath, fileName); }; // dlsym variant is only needed for OpenGL and not included in the vulkan layer appendLib("libMangoHud_dlsym.so"); appendLib("libMangoHud_opengl.so"); preloadList << mangoHudLibString; } env.insert("LD_PRELOAD", preloadList.join(QLatin1String(":"))); env.insert("MANGOHUD", "1"); } if (settings()->get("UseDiscreteGpu").toBool()) { // Open Source Drivers env.insert("DRI_PRIME", "1"); // Proprietary Nvidia Drivers env.insert("__NV_PRIME_RENDER_OFFLOAD", "1"); env.insert("__VK_LAYER_NV_optimus", "NVIDIA_only"); env.insert("__GLX_VENDOR_LIBRARY_NAME", "nvidia"); } if (settings()->get("UseZink").toBool()) { // taken from https://wiki.archlinux.org/title/OpenGL#OpenGL_over_Vulkan_(Zink) env.insert("__GLX_VENDOR_LIBRARY_NAME", "mesa"); env.insert("MESA_LOADER_DRIVER_OVERRIDE", "zink"); env.insert("GALLIUM_DRIVER", "zink"); } #endif return env; } static QString replaceTokensIn(QString text, QMap<QString, QString> with) { // TODO: does this still work?? QString result; QRegularExpression token_regexp("\\$\\{(.+)\\}", QRegularExpression::InvertedGreedinessOption); QStringList list; QRegularExpressionMatchIterator i = token_regexp.globalMatch(text); int lastCapturedEnd = 0; while (i.hasNext()) { QRegularExpressionMatch match = i.next(); result.append(text.mid(lastCapturedEnd, match.capturedStart())); QString key = match.captured(1); auto iter = with.find(key); if (iter != with.end()) { result.append(*iter); } lastCapturedEnd = match.capturedEnd(); } result.append(text.mid(lastCapturedEnd)); return result; } QStringList MinecraftInstance::processMinecraftArgs(AuthSessionPtr session, MinecraftTarget::Ptr targetToJoin) const { auto profile = m_components->getProfile(); QString args_pattern = profile->getMinecraftArguments(); for (auto tweaker : profile->getTweakers()) { args_pattern += " --tweakClass " + tweaker; } if (targetToJoin) { if (!targetToJoin->address.isEmpty()) { if (profile->hasTrait("feature:is_quick_play_multiplayer")) { args_pattern += " --quickPlayMultiplayer " + targetToJoin->address + ':' + QString::number(targetToJoin->port); } else { args_pattern += " --server " + targetToJoin->address; args_pattern += " --port " + QString::number(targetToJoin->port); } } else if (!targetToJoin->world.isEmpty() && profile->hasTrait("feature:is_quick_play_singleplayer")) { args_pattern += " --quickPlaySingleplayer " + targetToJoin->world; } } QMap<QString, QString> token_mapping; // yggdrasil! if (session) { // token_mapping["auth_username"] = session->username; token_mapping["auth_session"] = session->session; token_mapping["auth_access_token"] = session->access_token; token_mapping["auth_player_name"] = session->player_name; token_mapping["auth_uuid"] = session->uuid; token_mapping["user_properties"] = session->serializeUserProperties(); token_mapping["user_type"] = session->user_type; if (session->demo) { args_pattern += " --demo"; } } token_mapping["profile_name"] = name(); token_mapping["version_name"] = profile->getMinecraftVersion(); token_mapping["version_type"] = profile->getMinecraftVersionType(); QString absRootDir = QDir(gameRoot()).absolutePath(); token_mapping["game_directory"] = absRootDir; QString absAssetsDir = QDir("assets/").absolutePath(); auto assets = profile->getMinecraftAssets(); token_mapping["game_assets"] = AssetsUtils::getAssetsDir(assets->id, resourcesDir()).absolutePath(); // 1.7.3+ assets tokens token_mapping["assets_root"] = absAssetsDir; token_mapping["assets_index_name"] = assets->id; #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) QStringList parts = args_pattern.split(' ', Qt::SkipEmptyParts); #else QStringList parts = args_pattern.split(' ', QString::SkipEmptyParts); #endif for (int i = 0; i < parts.length(); i++) { parts[i] = replaceTokensIn(parts[i], token_mapping); } return parts; } QString MinecraftInstance::createLaunchScript(AuthSessionPtr session, MinecraftTarget::Ptr targetToJoin) { QString launchScript; if (!m_components) return QString(); auto profile = m_components->getProfile(); if (!profile) return QString(); auto mainClass = getMainClass(); if (!mainClass.isEmpty()) { launchScript += "mainClass " + mainClass + "\n"; } auto appletClass = profile->getAppletClass(); if (!appletClass.isEmpty()) { launchScript += "appletClass " + appletClass + "\n"; } if (targetToJoin) { if (!targetToJoin->address.isEmpty()) { launchScript += "serverAddress " + targetToJoin->address + "\n"; launchScript += "serverPort " + QString::number(targetToJoin->port) + "\n"; } else if (!targetToJoin->world.isEmpty()) { launchScript += "worldName " + targetToJoin->world + "\n"; } } // generic minecraft params for (auto param : processMinecraftArgs(session, nullptr /* When using a launch script, the server parameters are handled by it*/ )) { launchScript += "param " + param + "\n"; } // window size, title and state, legacy { QString windowParams; if (settings()->get("LaunchMaximized").toBool()) { // FIXME doesn't support maximisation if (!isLegacy()) { auto screen = QGuiApplication::primaryScreen(); auto screenGeometry = screen->availableSize(); // small hack to get the widow decorations for (auto w : QApplication::topLevelWidgets()) { auto mainWindow = qobject_cast<QMainWindow*>(w); if (mainWindow) { auto m = mainWindow->windowHandle()->frameMargins(); #if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)) screenGeometry = screenGeometry.shrunkBy(m); #else screenGeometry = { screenGeometry.width() - m.left() - m.right(), screenGeometry.height() - m.top() - m.bottom() }; #endif break; } } windowParams = QString("%1x%2").arg(screenGeometry.width()).arg(screenGeometry.height()); } else { windowParams = "maximized"; } } else { windowParams = QString("%1x%2").arg(settings()->get("MinecraftWinWidth").toInt()).arg(settings()->get("MinecraftWinHeight").toInt()); } launchScript += "windowTitle " + windowTitle() + "\n"; launchScript += "windowParams " + windowParams + "\n"; } // launcher info { launchScript += "launcherBrand " + BuildConfig.LAUNCHER_NAME + "\n"; launchScript += "launcherVersion " + BuildConfig.printableVersionString() + "\n"; } // instance info { launchScript += "instanceName " + name() + "\n"; launchScript += "instanceIconKey " + name() + "\n"; launchScript += "instanceIconPath icon.png\n"; // we already save a copy here } // legacy auth if (session) { launchScript += "userName " + session->player_name + "\n"; launchScript += "sessionId " + session->session + "\n"; } for (auto trait : profile->getTraits()) { launchScript += "traits " + trait + "\n"; } if (shouldApplyOnlineFixes()) launchScript += "onlineFixes true\n"; launchScript += "launcher " + getLauncher() + "\n"; // qDebug() << "Generated launch script:" << launchScript; return launchScript; } QStringList MinecraftInstance::verboseDescription(AuthSessionPtr session, MinecraftTarget::Ptr targetToJoin) { QStringList out; out << "Main Class:" << " " + getMainClass() << ""; out << "Native path:" << " " + getNativePath() << ""; auto profile = m_components->getProfile(); // traits auto alltraits = traits(); if (alltraits.size()) { out << "Traits:"; for (auto trait : alltraits) { out << "traits " + trait; } out << ""; } // native libraries auto settings = this->settings(); bool nativeOpenAL = settings->get("UseNativeOpenAL").toBool(); bool nativeGLFW = settings->get("UseNativeGLFW").toBool(); if (nativeOpenAL || nativeGLFW) { if (nativeOpenAL) out << "Using system OpenAL."; if (nativeGLFW) out << "Using system GLFW."; out << ""; } // libraries and class path. { out << "Libraries:"; QStringList jars, nativeJars; profile->getLibraryFiles(runtimeContext(), jars, nativeJars, getLocalLibraryPath(), binRoot()); auto printLibFile = [&out](const QString& path) { QFileInfo info(path); if (info.exists()) { out << " " + path; } else { out << " " + path + " (missing)"; } }; for (auto file : jars) { printLibFile(file); } out << ""; out << "Native libraries:"; for (auto file : nativeJars) { printLibFile(file); } out << ""; } // mods and core mods auto printModList = [&out](const QString& label, ModFolderModel& model) { if (model.size()) { out << QString("%1:").arg(label); auto modList = model.allMods(); std::sort(modList.begin(), modList.end(), [](auto a, auto b) { auto aName = a->fileinfo().completeBaseName(); auto bName = b->fileinfo().completeBaseName(); return aName.localeAwareCompare(bName) < 0; }); for (auto mod : modList) { if (mod->type() == ResourceType::FOLDER) { out << u8" [🖿] " + mod->fileinfo().completeBaseName() + " (folder)"; continue; } if (mod->enabled()) { out << u8" [✔] " + mod->fileinfo().completeBaseName(); } else { out << u8" [✘] " + mod->fileinfo().completeBaseName() + " (disabled)"; } } out << ""; } }; printModList("Mods", *(loaderModList().get())); printModList("Core Mods", *(coreModList().get())); // jar mods auto& jarMods = profile->getJarMods(); if (jarMods.size()) { out << "Jar Mods:"; for (auto& jarmod : jarMods) { auto displayname = jarmod->displayName(runtimeContext()); auto realname = jarmod->filename(runtimeContext()); if (displayname != realname) { out << " " + displayname + " (" + realname + ")"; } else { out << " " + realname; } } out << ""; } // minecraft arguments auto params = processMinecraftArgs(nullptr, targetToJoin); out << "Params:"; out << " " + params.join(' '); out << ""; // window size QString windowParams; if (settings->get("LaunchMaximized").toBool()) { out << "Window size: max (if available)"; } else { auto width = settings->get("MinecraftWinWidth").toInt(); auto height = settings->get("MinecraftWinHeight").toInt(); out << "Window size: " + QString::number(width) + " x " + QString::number(height); } out << ""; out << "Launcher: " + getLauncher(); out << ""; return out; } QMap<QString, QString> MinecraftInstance::createCensorFilterFromSession(AuthSessionPtr session) { if (!session) { return QMap<QString, QString>(); } auto& sessionRef = *session.get(); QMap<QString, QString> filter; auto addToFilter = [&filter](QString key, QString value) { if (key.trimmed().size()) { filter[key] = value; } }; if (sessionRef.session != "-") { addToFilter(sessionRef.session, tr("<SESSION ID>")); } if (sessionRef.access_token != "0") { addToFilter(sessionRef.access_token, tr("<ACCESS TOKEN>")); } addToFilter(sessionRef.uuid, tr("<PROFILE ID>")); return filter; } MessageLevel::Enum MinecraftInstance::guessLevel(const QString& line, MessageLevel::Enum level) { QRegularExpression re("\\[(?<timestamp>[0-9:]+)\\] \\[[^/]+/(?<level>[^\\]]+)\\]"); auto match = re.match(line); if (match.hasMatch()) { // New style logs from log4j QString timestamp = match.captured("timestamp"); QString levelStr = match.captured("level"); if (levelStr == "INFO") level = MessageLevel::Message; if (levelStr == "WARN") level = MessageLevel::Warning; if (levelStr == "ERROR") level = MessageLevel::Error; if (levelStr == "FATAL") level = MessageLevel::Fatal; if (levelStr == "TRACE" || levelStr == "DEBUG") level = MessageLevel::Debug; } else { // Old style forge logs if (line.contains("[INFO]") || line.contains("[CONFIG]") || line.contains("[FINE]") || line.contains("[FINER]") || line.contains("[FINEST]")) level = MessageLevel::Message; if (line.contains("[SEVERE]") || line.contains("[STDERR]")) level = MessageLevel::Error; if (line.contains("[WARNING]")) level = MessageLevel::Warning; if (line.contains("[DEBUG]")) level = MessageLevel::Debug; } if (line.contains("overwriting existing")) return MessageLevel::Fatal; // NOTE: this diverges from the real regexp. no unicode, the first section is + instead of * static const QString javaSymbol = "([a-zA-Z_$][a-zA-Z\\d_$]*\\.)+[a-zA-Z_$][a-zA-Z\\d_$]*"; if (line.contains("Exception in thread") || line.contains(QRegularExpression("\\s+at " + javaSymbol)) || line.contains(QRegularExpression("Caused by: " + javaSymbol)) || line.contains(QRegularExpression("([a-zA-Z_$][a-zA-Z\\d_$]*\\.)+[a-zA-Z_$]?[a-zA-Z\\d_$]*(Exception|Error|Throwable)")) || line.contains(QRegularExpression("... \\d+ more$"))) return MessageLevel::Error; return level; } IPathMatcher::Ptr MinecraftInstance::getLogFileMatcher() { auto combined = std::make_shared<MultiMatcher>(); combined->add(std::make_shared<RegexpMatcher>(".*\\.log(\\.[0-9]*)?(\\.gz)?$")); combined->add(std::make_shared<RegexpMatcher>("crash-.*\\.txt")); combined->add(std::make_shared<RegexpMatcher>("IDMap dump.*\\.txt$")); combined->add(std::make_shared<RegexpMatcher>("ModLoader\\.txt(\\..*)?$")); return combined; } QString MinecraftInstance::getLogFileRoot() { return gameRoot(); } QString MinecraftInstance::getStatusbarDescription() { QStringList traits; if (hasVersionBroken()) { traits.append(tr("broken")); } QString mcVersion = m_components->getComponentVersion("net.minecraft"); if (mcVersion.isEmpty()) { // Load component info if needed m_components->reload(Net::Mode::Offline); mcVersion = m_components->getComponentVersion("net.minecraft"); } QString description; description.append(tr("Minecraft %1").arg(mcVersion)); if (m_settings->get("ShowGameTime").toBool()) { if (lastTimePlayed() > 0 && lastLaunch() > 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(), APPLICATION->settings()->get("ShowGameTimeWithoutDays").toBool()))); } if (totalTimePlayed() > 0) { description.append( tr(", total played for %1") .arg(Time::prettifyDuration(totalTimePlayed(), APPLICATION->settings()->get("ShowGameTimeWithoutDays").toBool()))); } } if (hasCrashed()) { description.append(tr(", has crashed.")); } return description; } QList<LaunchStep::Ptr> MinecraftInstance::createUpdateTask() { return { // create folders makeShared<FoldersTask>(this), // libraries download makeShared<LibrariesTask>(this), // FML libraries download and copy into the instance makeShared<FMLLibrariesTask>(this), // assets update makeShared<AssetUpdateTask>(this), }; } shared_qobject_ptr<LaunchTask> MinecraftInstance::createLaunchTask(AuthSessionPtr session, MinecraftTarget::Ptr targetToJoin) { updateRuntimeContext(); // FIXME: get rid of shared_from_this ... auto process = LaunchTask::create(std::dynamic_pointer_cast<MinecraftInstance>(shared_from_this())); auto pptr = process.get(); APPLICATION->icons()->saveIcon(iconKey(), FS::PathCombine(gameRoot(), "icon.png"), "PNG"); // print a header { process->appendStep(makeShared<TextPrint>(pptr, "Minecraft folder is:\n" + gameRoot() + "\n\n", MessageLevel::Launcher)); } // create the .minecraft folder and server-resource-packs (workaround for Minecraft bug MCL-3732) { process->appendStep(makeShared<CreateGameFolders>(pptr)); } if (!targetToJoin && settings()->get("JoinServerOnLaunch").toBool()) { QString fullAddress = settings()->get("JoinServerOnLaunchAddress").toString(); if (!fullAddress.isEmpty()) { targetToJoin.reset(new MinecraftTarget(MinecraftTarget::parse(fullAddress, false))); } else { QString world = settings()->get("JoinWorldOnLaunch").toString(); if (!world.isEmpty()) { targetToJoin.reset(new MinecraftTarget(MinecraftTarget::parse(world, true))); } } } if (targetToJoin && targetToJoin->port == 25565) { // Resolve server address to join on launch auto step = makeShared<LookupServerAddress>(pptr); step->setLookupAddress(targetToJoin->address); step->setOutputAddressPtr(targetToJoin); process->appendStep(step); } // run pre-launch command if that's needed if (getPreLaunchCommand().size()) { auto step = makeShared<PreLaunchCommand>(pptr); step->setWorkingDirectory(gameRoot()); process->appendStep(step); } // load meta { auto mode = session->status != AuthSession::PlayableOffline ? Net::Mode::Online : Net::Mode::Offline; process->appendStep(makeShared<TaskStepWrapper>(pptr, makeShared<MinecraftLoadAndCheck>(this, mode))); } // check java { process->appendStep(makeShared<AutoInstallJava>(pptr)); process->appendStep(makeShared<CheckJava>(pptr)); } // if we aren't in offline mode,. if (session->status != AuthSession::PlayableOffline) { if (!session->demo) { process->appendStep(makeShared<ClaimAccount>(pptr, session)); } for (auto t : createUpdateTask()) { process->appendStep(makeShared<TaskStepWrapper>(pptr, t)); } } // if there are any jar mods { process->appendStep(makeShared<ModMinecraftJar>(pptr)); } // Scan mods folders for mods { process->appendStep(makeShared<ScanModFolders>(pptr)); } // print some instance info here... { process->appendStep(makeShared<PrintInstanceInfo>(pptr, session, targetToJoin)); } // extract native jars if needed { process->appendStep(makeShared<ExtractNatives>(pptr)); } // reconstruct assets if needed { process->appendStep(makeShared<ReconstructAssets>(pptr)); } // verify that minimum Java requirements are met { process->appendStep(makeShared<VerifyJavaInstall>(pptr)); } { // actually launch the game auto step = makeShared<LauncherPartLaunch>(pptr); step->setWorkingDirectory(gameRoot()); step->setAuthSession(session); step->setTargetToJoin(targetToJoin); process->appendStep(step); } // run post-exit command if that's needed if (getPostExitCommand().size()) { auto step = makeShared<PostLaunchCommand>(pptr); step->setWorkingDirectory(gameRoot()); process->appendStep(step); } if (session) { process->setCensorFilter(createCensorFilterFromSession(session)); } if (m_settings->get("QuitAfterGameStop").toBool()) { process->appendStep(makeShared<QuitAfterGameStop>(pptr)); } m_launchProcess = process; emit launchTaskChanged(m_launchProcess); return m_launchProcess; } JavaVersion MinecraftInstance::getJavaVersion() { return JavaVersion(settings()->get("JavaVersion").toString()); } std::shared_ptr<ModFolderModel> MinecraftInstance::loaderModList() { if (!m_loader_mod_list) { bool is_indexed = !APPLICATION->settings()->get("ModMetadataDisabled").toBool(); m_loader_mod_list.reset(new ModFolderModel(modsRoot(), this, is_indexed, true)); } return m_loader_mod_list; } std::shared_ptr<ModFolderModel> MinecraftInstance::coreModList() { if (!m_core_mod_list) { bool is_indexed = !APPLICATION->settings()->get("ModMetadataDisabled").toBool(); m_core_mod_list.reset(new ModFolderModel(coreModsDir(), this, is_indexed, true)); } return m_core_mod_list; } std::shared_ptr<ModFolderModel> MinecraftInstance::nilModList() { if (!m_nil_mod_list) { bool is_indexed = !APPLICATION->settings()->get("ModMetadataDisabled").toBool(); m_nil_mod_list.reset(new ModFolderModel(nilModsDir(), this, is_indexed, false)); } return m_nil_mod_list; } std::shared_ptr<ResourcePackFolderModel> MinecraftInstance::resourcePackList() { if (!m_resource_pack_list) { bool is_indexed = !APPLICATION->settings()->get("ModMetadataDisabled").toBool(); m_resource_pack_list.reset(new ResourcePackFolderModel(resourcePacksDir(), this, is_indexed, true)); } return m_resource_pack_list; } std::shared_ptr<TexturePackFolderModel> MinecraftInstance::texturePackList() { if (!m_texture_pack_list) { bool is_indexed = !APPLICATION->settings()->get("ModMetadataDisabled").toBool(); m_texture_pack_list.reset(new TexturePackFolderModel(texturePacksDir(), this, is_indexed, true)); } return m_texture_pack_list; } std::shared_ptr<ShaderPackFolderModel> MinecraftInstance::shaderPackList() { if (!m_shader_pack_list) { bool is_indexed = !APPLICATION->settings()->get("ModMetadataDisabled").toBool(); m_shader_pack_list.reset(new ShaderPackFolderModel(shaderPacksDir(), this, is_indexed, true)); } return m_shader_pack_list; } QList<std::shared_ptr<ResourceFolderModel>> MinecraftInstance::resourceLists() { return { loaderModList(), coreModList(), nilModList(), resourcePackList(), texturePackList(), shaderPackList() }; } std::shared_ptr<WorldList> MinecraftInstance::worldList() { if (!m_world_list) { m_world_list.reset(new WorldList(worldDir(), this)); } return m_world_list; } std::shared_ptr<GameOptions> MinecraftInstance::gameOptionsModel() { if (!m_game_options) { m_game_options.reset(new GameOptions(FS::PathCombine(gameRoot(), "options.txt"))); } return m_game_options; } QList<Mod*> MinecraftInstance::getJarMods() const { auto profile = m_components->getProfile(); QList<Mod*> mods; for (auto jarmod : profile->getJarMods()) { QStringList jar, temp1, temp2, temp3; jarmod->getApplicableFiles(runtimeContext(), jar, temp1, temp2, temp3, jarmodsPath().absolutePath()); // QString filePath = jarmodsPath().absoluteFilePath(jarmod->filename(currentSystem)); mods.push_back(new Mod(QFileInfo(jar[0]))); } return mods; } #include "MinecraftInstance.moc"
45,917
C++
.cpp
1,113
34.986523
139
0.662939
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,171
AssetsUtils.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/AssetsUtils.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <QCryptographicHash> #include <QDebug> #include <QDir> #include <QDirIterator> #include <QFileInfo> #include <QJsonDocument> #include <QJsonObject> #include <QJsonParseError> #include <QVariant> #include "AssetsUtils.h" #include "BuildConfig.h" #include "FileSystem.h" #include "net/ApiDownload.h" #include "net/ChecksumValidator.h" #include "net/Download.h" #include "Application.h" #include "net/NetRequest.h" namespace { QSet<QString> collectPathsFromDir(QString dirPath) { QFileInfo dirInfo(dirPath); if (!dirInfo.exists()) { return {}; } QSet<QString> out; QDirIterator iter(dirPath, QDirIterator::Subdirectories); while (iter.hasNext()) { QString value = iter.next(); QFileInfo info(value); if (info.isFile()) { out.insert(value); qDebug() << value; } } return out; } } // namespace namespace AssetsUtils { /* * Returns true on success, with index populated * index is undefined otherwise */ bool loadAssetsIndexJson(const QString& assetsId, const QString& path, AssetsIndex& index) { /* { "objects": { "icons/icon_16x16.png": { "hash": "bdf48ef6b5d0d23bbb02e17d04865216179f510a", "size": 3665 }, ... } } } */ QFile file(path); // Try to open the file and fail if we can't. // TODO: We should probably report this error to the user. if (!file.open(QIODevice::ReadOnly)) { qCritical() << "Failed to read assets index file" << path; return false; } index.id = assetsId; // Read the file and close it. QByteArray jsonData = file.readAll(); file.close(); QJsonParseError parseError; QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonData, &parseError); // Fail if the JSON is invalid. if (parseError.error != QJsonParseError::NoError) { qCritical() << "Failed to parse assets index file:" << parseError.errorString() << "at offset " << QString::number(parseError.offset); return false; } // Make sure the root is an object. if (!jsonDoc.isObject()) { qCritical() << "Invalid assets index JSON: Root should be an array."; return false; } QJsonObject root = jsonDoc.object(); QJsonValue isVirtual = root.value("virtual"); if (!isVirtual.isUndefined()) { index.isVirtual = isVirtual.toBool(false); } QJsonValue mapToResources = root.value("map_to_resources"); if (!mapToResources.isUndefined()) { index.mapToResources = mapToResources.toBool(false); } QJsonValue objects = root.value("objects"); QVariantMap map = objects.toVariant().toMap(); for (QVariantMap::const_iterator iter = map.begin(); iter != map.end(); ++iter) { // qDebug() << iter.key(); QVariant variant = iter.value(); QVariantMap nested_objects = variant.toMap(); AssetObject object; for (QVariantMap::const_iterator nested_iter = nested_objects.begin(); nested_iter != nested_objects.end(); ++nested_iter) { // qDebug() << nested_iter.key() << nested_iter.value().toString(); QString key = nested_iter.key(); QVariant value = nested_iter.value(); if (key == "hash") { object.hash = value.toString(); } else if (key == "size") { object.size = value.toDouble(); } } index.objects.insert(iter.key(), object); } return true; } // FIXME: ugly code duplication QDir getAssetsDir(const QString& assetsId, const QString& resourcesFolder) { QDir assetsDir = QDir("assets/"); QDir indexDir = QDir(FS::PathCombine(assetsDir.path(), "indexes")); QDir objectDir = QDir(FS::PathCombine(assetsDir.path(), "objects")); QDir virtualDir = QDir(FS::PathCombine(assetsDir.path(), "virtual")); QString indexPath = FS::PathCombine(indexDir.path(), assetsId + ".json"); QFile indexFile(indexPath); QDir virtualRoot(FS::PathCombine(virtualDir.path(), assetsId)); if (!indexFile.exists()) { qCritical() << "No assets index file" << indexPath << "; can't determine assets path!"; return virtualRoot; } AssetsIndex index; if (!AssetsUtils::loadAssetsIndexJson(assetsId, indexPath, index)) { qCritical() << "Failed to load asset index file" << indexPath << "; can't determine assets path!"; return virtualRoot; } QString targetPath; if (index.isVirtual) { return virtualRoot; } else if (index.mapToResources) { return QDir(resourcesFolder); } return virtualRoot; } // FIXME: ugly code duplication bool reconstructAssets(QString assetsId, QString resourcesFolder) { QDir assetsDir = QDir("assets/"); QDir indexDir = QDir(FS::PathCombine(assetsDir.path(), "indexes")); QDir objectDir = QDir(FS::PathCombine(assetsDir.path(), "objects")); QDir virtualDir = QDir(FS::PathCombine(assetsDir.path(), "virtual")); QString indexPath = FS::PathCombine(indexDir.path(), assetsId + ".json"); QFile indexFile(indexPath); QDir virtualRoot(FS::PathCombine(virtualDir.path(), assetsId)); if (!indexFile.exists()) { qCritical() << "No assets index file" << indexPath << "; can't reconstruct assets!"; return false; } qDebug() << "reconstructAssets" << assetsDir.path() << indexDir.path() << objectDir.path() << virtualDir.path() << virtualRoot.path(); AssetsIndex index; if (!AssetsUtils::loadAssetsIndexJson(assetsId, indexPath, index)) { qCritical() << "Failed to load asset index file" << indexPath << "; can't reconstruct assets!"; return false; } QString targetPath; bool removeLeftovers = false; if (index.isVirtual) { targetPath = virtualRoot.path(); removeLeftovers = true; qDebug() << "Reconstructing virtual assets folder at" << targetPath; } else if (index.mapToResources) { targetPath = resourcesFolder; qDebug() << "Reconstructing resources folder at" << targetPath; } if (!targetPath.isNull()) { auto presentFiles = collectPathsFromDir(targetPath); for (QString map : index.objects.keys()) { AssetObject asset_object = index.objects.value(map); QString target_path = FS::PathCombine(targetPath, map); QFile target(target_path); QString tlk = asset_object.hash.left(2); QString original_path = FS::PathCombine(objectDir.path(), tlk, asset_object.hash); QFile original(original_path); if (!original.exists()) continue; presentFiles.remove(target_path); if (!target.exists()) { QFileInfo info(target_path); QDir target_dir = info.dir(); qDebug() << target_dir.path(); FS::ensureFolderPathExists(target_dir.path()); bool couldCopy = original.copy(target_path); qDebug() << " Copying" << original_path << "to" << target_path << QString::number(couldCopy); } } // TODO: Write last used time to virtualRoot/.lastused if (removeLeftovers) { for (auto& file : presentFiles) { qDebug() << "Would remove" << file; } } } return true; } } // namespace AssetsUtils Net::NetRequest::Ptr AssetObject::getDownloadAction() { QFileInfo objectFile(getLocalPath()); if ((!objectFile.isFile()) || (objectFile.size() != size)) { auto objectDL = Net::ApiDownload::makeFile(getUrl(), objectFile.filePath()); if (hash.size()) { objectDL->addValidator(new Net::ChecksumValidator(QCryptographicHash::Sha1, hash)); } objectDL->setProgress(objectDL->getProgress(), size); return objectDL; } return nullptr; } QString AssetObject::getLocalPath() { return "assets/objects/" + getRelPath(); } QUrl AssetObject::getUrl() { return BuildConfig.RESOURCE_BASE + getRelPath(); } QString AssetObject::getRelPath() { return hash.left(2) + "/" + hash; } NetJob::Ptr AssetsIndex::getDownloadJob() { auto job = makeShared<NetJob>(QObject::tr("Assets for %1").arg(id), APPLICATION->network()); for (auto& object : objects.values()) { auto dl = object.getDownloadAction(); if (dl) { job->addNetAction(dl); } } if (job->size()) return job; return nullptr; }
10,072
C++
.cpp
270
31.274074
138
0.648241
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,172
ParseUtils.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/ParseUtils.cpp
#include "ParseUtils.h" #include <QDateTime> #include <QDebug> #include <QString> #include <cstdlib> QDateTime timeFromS3Time(QString str) { return QDateTime::fromString(str, Qt::ISODate); } QString timeToS3Time(QDateTime time) { // this all because Qt can't format timestamps right. int offsetRaw = time.offsetFromUtc(); bool negative = offsetRaw < 0; int offsetAbs = std::abs(offsetRaw); int offsetSeconds = offsetAbs % 60; offsetAbs -= offsetSeconds; int offsetMinutes = offsetAbs % 3600; offsetAbs -= offsetMinutes; offsetMinutes /= 60; int offsetHours = offsetAbs / 3600; QString raw = time.toString("yyyy-MM-ddTHH:mm:ss"); raw += (negative ? QChar('-') : QChar('+')); raw += QString("%1").arg(offsetHours, 2, 10, QChar('0')); raw += ":"; raw += QString("%1").arg(offsetMinutes, 2, 10, QChar('0')); return raw; }
892
C++
.cpp
28
28.214286
63
0.67366
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,173
OneSixVersionFormat.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/OneSixVersionFormat.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 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 "OneSixVersionFormat.h" #include <Json.h> #include <minecraft/MojangVersionFormat.h> #include <QList> #include "java/JavaMetadata.h" #include "minecraft/Agent.h" #include "minecraft/ParseUtils.h" #include <QRegularExpression> using namespace Json; static void readString(const QJsonObject& root, const QString& key, QString& variable) { if (root.contains(key)) { variable = requireString(root.value(key)); } } LibraryPtr OneSixVersionFormat::libraryFromJson(ProblemContainer& problems, const QJsonObject& libObj, const QString& filename) { LibraryPtr out = MojangVersionFormat::libraryFromJson(problems, libObj, filename); readString(libObj, "MMC-hint", out->m_hint); readString(libObj, "MMC-absulute_url", out->m_absoluteURL); readString(libObj, "MMC-absoluteUrl", out->m_absoluteURL); readString(libObj, "MMC-filename", out->m_filename); readString(libObj, "MMC-displayname", out->m_displayname); return out; } QJsonObject OneSixVersionFormat::libraryToJson(Library* library) { QJsonObject libRoot = MojangVersionFormat::libraryToJson(library); if (!library->m_absoluteURL.isEmpty()) libRoot.insert("MMC-absoluteUrl", library->m_absoluteURL); if (!library->m_hint.isEmpty()) libRoot.insert("MMC-hint", library->m_hint); if (!library->m_filename.isEmpty()) libRoot.insert("MMC-filename", library->m_filename); if (!library->m_displayname.isEmpty()) libRoot.insert("MMC-displayname", library->m_displayname); return libRoot; } VersionFilePtr OneSixVersionFormat::versionFileFromJson(const QJsonDocument& doc, const QString& filename, const bool requireOrder) { VersionFilePtr out(new VersionFile()); if (doc.isEmpty() || doc.isNull()) { throw JSONValidationError(filename + " is empty or null"); } if (!doc.isObject()) { throw JSONValidationError(filename + " is not an object"); } QJsonObject root = doc.object(); Meta::MetadataVersion formatVersion = Meta::parseFormatVersion(root, false); switch (formatVersion) { case Meta::MetadataVersion::InitialRelease: break; case Meta::MetadataVersion::Invalid: throw JSONValidationError(filename + " does not contain a recognizable version of the metadata format."); } if (requireOrder) { if (root.contains("order")) { out->order = requireInteger(root.value("order")); } else { // FIXME: evaluate if we don't want to throw exceptions here instead qCritical() << filename << "doesn't contain an order field"; } } out->name = root.value("name").toString(); if (root.contains("uid")) { out->uid = root.value("uid").toString(); } else { out->uid = root.value("fileId").toString(); } const QRegularExpression valid_uid_regex{ QRegularExpression::anchoredPattern( QStringLiteral(R"([a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]+)*)")) }; if (!valid_uid_regex.match(out->uid).hasMatch()) { qCritical() << "The component's 'uid' contains illegal characters! UID:" << out->uid; out->addProblem(ProblemSeverity::Error, QObject::tr("The component's 'uid' contains illegal characters! This can cause security issues.")); } out->version = root.value("version").toString(); MojangVersionFormat::readVersionProperties(root, out.get()); // added for legacy Minecraft window embedding, TODO: remove readString(root, "appletClass", out->appletClass); if (root.contains("+tweakers")) { for (auto tweakerVal : requireArray(root.value("+tweakers"))) { out->addTweakers.append(requireString(tweakerVal)); } } if (root.contains("+traits")) { for (auto tweakerVal : requireArray(root.value("+traits"))) { out->traits.insert(requireString(tweakerVal)); } } if (root.contains("+jvmArgs")) { for (auto arg : requireArray(root.value("+jvmArgs"))) { out->addnJvmArguments.append(requireString(arg)); } } if (root.contains("jarMods")) { for (auto libVal : requireArray(root.value("jarMods"))) { QJsonObject libObj = requireObject(libVal); // parse the jarmod auto lib = OneSixVersionFormat::jarModFromJson(*out, libObj, filename); // and add to jar mods out->jarMods.append(lib); } } else if (root.contains("+jarMods")) // DEPRECATED: old style '+jarMods' are only here for backwards compatibility { for (auto libVal : requireArray(root.value("+jarMods"))) { QJsonObject libObj = requireObject(libVal); // parse the jarmod auto lib = OneSixVersionFormat::plusJarModFromJson(*out, libObj, filename, out->name); // and add to jar mods out->jarMods.append(lib); } } if (root.contains("mods")) { for (auto libVal : requireArray(root.value("mods"))) { QJsonObject libObj = requireObject(libVal); // parse the jarmod auto lib = OneSixVersionFormat::modFromJson(*out, libObj, filename); // and add to jar mods out->mods.append(lib); } } auto readLibs = [&root, &out, &filename](const char* which, QList<LibraryPtr>& outList) { for (auto libVal : requireArray(root.value(which))) { QJsonObject libObj = requireObject(libVal); // parse the library auto lib = libraryFromJson(*out, libObj, filename); outList.append(lib); } }; bool hasPlusLibs = root.contains("+libraries"); bool hasLibs = root.contains("libraries"); if (hasPlusLibs && hasLibs) { out->addProblem(ProblemSeverity::Warning, QObject::tr("Version file has both '+libraries' and 'libraries'. This is no longer supported.")); readLibs("libraries", out->libraries); readLibs("+libraries", out->libraries); } else if (hasLibs) { readLibs("libraries", out->libraries); } else if (hasPlusLibs) { readLibs("+libraries", out->libraries); } if (root.contains("mavenFiles")) { readLibs("mavenFiles", out->mavenFiles); } if (root.contains("+agents")) { for (auto agentVal : requireArray(root.value("+agents"))) { QJsonObject agentObj = requireObject(agentVal); auto lib = libraryFromJson(*out, agentObj, filename); QString arg = ""; readString(agentObj, "argument", arg); AgentPtr agent(new Agent(lib, arg)); out->agents.append(agent); } } // if we have mainJar, just use it if (root.contains("mainJar")) { QJsonObject libObj = requireObject(root, "mainJar"); out->mainJar = libraryFromJson(*out, libObj, filename); } // else reconstruct it from downloads and id ... if that's available else if (!out->minecraftVersion.isEmpty()) { auto lib = std::make_shared<Library>(); lib->setRawName(GradleSpecifier(QString("com.mojang:minecraft:%1:client").arg(out->minecraftVersion))); // we have a reliable client download, use it. if (out->mojangDownloads.contains("client")) { auto LibDLInfo = std::make_shared<MojangLibraryDownloadInfo>(); LibDLInfo->artifact = out->mojangDownloads["client"]; lib->setMojangDownloadInfo(LibDLInfo); } // we got nothing... else { out->addProblem( ProblemSeverity::Error, QObject::tr("URL for the main jar could not be determined - Mojang removed the server that we used as fallback.")); } out->mainJar = lib; } if (root.contains("requires")) { Meta::parseRequires(root, &out->m_requires); } QString dependsOnMinecraftVersion = root.value("mcVersion").toString(); if (!dependsOnMinecraftVersion.isEmpty()) { Meta::Require mcReq; mcReq.uid = "net.minecraft"; mcReq.equalsVersion = dependsOnMinecraftVersion; if (out->m_requires.count(mcReq) == 0) { out->m_requires.insert(mcReq); } } if (root.contains("conflicts")) { Meta::parseRequires(root, &out->conflicts); } if (root.contains("volatile")) { out->m_volatile = requireBoolean(root, "volatile"); } if (root.contains("runtimes")) { out->runtimes = {}; for (auto runtime : ensureArray(root, "runtimes")) { out->runtimes.append(Java::parseJavaMeta(ensureObject(runtime))); } } /* removed features that shouldn't be used */ if (root.contains("tweakers")) { out->addProblem(ProblemSeverity::Error, QObject::tr("Version file contains unsupported element 'tweakers'")); } if (root.contains("-libraries")) { out->addProblem(ProblemSeverity::Error, QObject::tr("Version file contains unsupported element '-libraries'")); } if (root.contains("-tweakers")) { out->addProblem(ProblemSeverity::Error, QObject::tr("Version file contains unsupported element '-tweakers'")); } if (root.contains("-minecraftArguments")) { out->addProblem(ProblemSeverity::Error, QObject::tr("Version file contains unsupported element '-minecraftArguments'")); } if (root.contains("+minecraftArguments")) { out->addProblem(ProblemSeverity::Error, QObject::tr("Version file contains unsupported element '+minecraftArguments'")); } return out; } QJsonDocument OneSixVersionFormat::versionFileToJson(const VersionFilePtr& patch) { QJsonObject root; writeString(root, "name", patch->name); writeString(root, "uid", patch->uid); writeString(root, "version", patch->version); Meta::serializeFormatVersion(root, Meta::MetadataVersion::InitialRelease); MojangVersionFormat::writeVersionProperties(patch.get(), root); if (patch->mainJar) { root.insert("mainJar", libraryToJson(patch->mainJar.get())); } writeString(root, "appletClass", patch->appletClass); writeStringList(root, "+tweakers", patch->addTweakers); writeStringList(root, "+traits", patch->traits.values()); writeStringList(root, "+jvmArgs", patch->addnJvmArguments); if (!patch->agents.isEmpty()) { QJsonArray array; for (auto value : patch->agents) { QJsonObject agentOut = OneSixVersionFormat::libraryToJson(value->library().get()); if (!value->argument().isEmpty()) agentOut.insert("argument", value->argument()); array.append(agentOut); } root.insert("+agents", array); } if (!patch->libraries.isEmpty()) { QJsonArray array; for (auto value : patch->libraries) { array.append(OneSixVersionFormat::libraryToJson(value.get())); } root.insert("libraries", array); } if (!patch->mavenFiles.isEmpty()) { QJsonArray array; for (auto value : patch->mavenFiles) { array.append(OneSixVersionFormat::libraryToJson(value.get())); } root.insert("mavenFiles", array); } if (!patch->jarMods.isEmpty()) { QJsonArray array; for (auto value : patch->jarMods) { array.append(OneSixVersionFormat::jarModtoJson(value.get())); } root.insert("jarMods", array); } if (!patch->mods.isEmpty()) { QJsonArray array; for (auto value : patch->jarMods) { array.append(OneSixVersionFormat::modtoJson(value.get())); } root.insert("mods", array); } if (!patch->m_requires.empty()) { Meta::serializeRequires(root, &patch->m_requires, "requires"); } if (!patch->conflicts.empty()) { Meta::serializeRequires(root, &patch->conflicts, "conflicts"); } if (patch->m_volatile) { root.insert("volatile", true); } // write the contents to a json document. { QJsonDocument out; out.setObject(root); return out; } } LibraryPtr OneSixVersionFormat::plusJarModFromJson([[maybe_unused]] ProblemContainer& problems, const QJsonObject& libObj, const QString& filename, const QString& originalName) { LibraryPtr out(new Library()); if (!libObj.contains("name")) { throw JSONValidationError(filename + "contains a jarmod that doesn't have a 'name' field"); } // just make up something unique on the spot for the library name. auto uuid = QUuid::createUuid(); QString id = uuid.toString().remove('{').remove('}'); out->setRawName(GradleSpecifier("org.multimc.jarmods:" + id + ":1")); // filename override is the old name out->setFilename(libObj.value("name").toString()); // it needs to be local, it is stored in the instance jarmods folder out->setHint("local"); // read the original name if present - some versions did not set it // it is the original jar mod filename before it got renamed at the point of addition auto displayName = libObj.value("originalName").toString(); if (displayName.isEmpty()) { auto fixed = originalName; fixed.remove(" (jar mod)"); out->setDisplayName(fixed); } else { out->setDisplayName(displayName); } return out; } LibraryPtr OneSixVersionFormat::jarModFromJson(ProblemContainer& problems, const QJsonObject& libObj, const QString& filename) { return libraryFromJson(problems, libObj, filename); } QJsonObject OneSixVersionFormat::jarModtoJson(Library* jarmod) { return libraryToJson(jarmod); } LibraryPtr OneSixVersionFormat::modFromJson(ProblemContainer& problems, const QJsonObject& libObj, const QString& filename) { return libraryFromJson(problems, libObj, filename); } QJsonObject OneSixVersionFormat::modtoJson(Library* jarmod) { return libraryToJson(jarmod); }
15,602
C++
.cpp
368
35.32337
131
0.651435
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,174
ProfileUtils.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/ProfileUtils.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 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 "ProfileUtils.h" #include <QDebug> #include "Json.h" #include "minecraft/OneSixVersionFormat.h" #include "minecraft/VersionFilterData.h" #include <QJsonArray> #include <QJsonDocument> #include <QRegularExpression> #include <QSaveFile> namespace ProfileUtils { static const int currentOrderFileVersion = 1; bool readOverrideOrders(QString path, PatchOrder& order) { QFile orderFile(path); if (!orderFile.exists()) { qWarning() << "Order file doesn't exist. Ignoring."; return false; } if (!orderFile.open(QFile::ReadOnly)) { qCritical() << "Couldn't open" << orderFile.fileName() << " for reading:" << orderFile.errorString(); qWarning() << "Ignoring overridden order"; return false; } // and it's valid JSON QJsonParseError error; QJsonDocument doc = QJsonDocument::fromJson(orderFile.readAll(), &error); if (error.error != QJsonParseError::NoError) { qCritical() << "Couldn't parse" << orderFile.fileName() << ":" << error.errorString(); qWarning() << "Ignoring overridden order"; return false; } // and then read it and process it if all above is true. try { auto obj = Json::requireObject(doc); // check order file version. auto version = Json::requireInteger(obj.value("version")); if (version != currentOrderFileVersion) { throw JSONValidationError(QObject::tr("Invalid order file version, expected %1").arg(currentOrderFileVersion)); } auto orderArray = Json::requireArray(obj.value("order")); for (auto item : orderArray) { order.append(Json::requireString(item)); } } catch ([[maybe_unused]] const JSONValidationError& err) { qCritical() << "Couldn't parse" << orderFile.fileName() << ": bad file format"; qWarning() << "Ignoring overridden order"; order.clear(); return false; } return true; } static VersionFilePtr createErrorVersionFile(QString fileId, QString filepath, QString error) { auto outError = std::make_shared<VersionFile>(); outError->uid = outError->name = fileId; // outError->filename = filepath; outError->addProblem(ProblemSeverity::Error, error); return outError; } static VersionFilePtr guardedParseJson(const QJsonDocument& doc, const QString& fileId, const QString& filepath, const bool& requireOrder) { try { return OneSixVersionFormat::versionFileFromJson(doc, filepath, requireOrder); } catch (const Exception& e) { return createErrorVersionFile(fileId, filepath, e.cause()); } } VersionFilePtr parseJsonFile(const QFileInfo& fileInfo, const bool requireOrder) { QFile file(fileInfo.absoluteFilePath()); if (!file.open(QFile::ReadOnly)) { auto errorStr = QObject::tr("Unable to open the version file %1: %2.").arg(fileInfo.fileName(), file.errorString()); return createErrorVersionFile(fileInfo.completeBaseName(), fileInfo.absoluteFilePath(), errorStr); } QJsonParseError error; auto data = file.readAll(); QJsonDocument doc = QJsonDocument::fromJson(data, &error); file.close(); if (error.error != QJsonParseError::NoError) { int line = 1; int column = 0; for (int i = 0; i < error.offset; i++) { if (data[i] == '\n') { line++; column = 0; continue; } column++; } auto errorStr = QObject::tr("Unable to process the version file %1: %2 at line %3 column %4.") .arg(fileInfo.fileName(), error.errorString()) .arg(line) .arg(column); return createErrorVersionFile(fileInfo.completeBaseName(), fileInfo.absoluteFilePath(), errorStr); } return guardedParseJson(doc, fileInfo.completeBaseName(), fileInfo.absoluteFilePath(), requireOrder); } bool saveJsonFile(const QJsonDocument& doc, const QString& filename) { auto data = doc.toJson(); QSaveFile jsonFile(filename); if (!jsonFile.open(QIODevice::WriteOnly)) { jsonFile.cancelWriting(); qWarning() << "Couldn't open" << filename << "for writing"; return false; } jsonFile.write(data); if (!jsonFile.commit()) { qWarning() << "Couldn't save" << filename; return false; } return true; } void removeLwjglFromPatch(VersionFilePtr patch) { auto filter = [](QList<LibraryPtr>& libs) { QList<LibraryPtr> filteredLibs; for (auto lib : libs) { if (!g_VersionFilterData.lwjglWhitelist.contains(lib->artifactPrefix())) { filteredLibs.append(lib); } } libs = filteredLibs; }; filter(patch->libraries); } } // namespace ProfileUtils
6,338
C++
.cpp
161
33.621118
138
0.667315
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,176
Component.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/Component.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 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 "Component.h" #include <meta/Index.h> #include <meta/VersionList.h> #include <QSaveFile> #include "Application.h" #include "FileSystem.h" #include "OneSixVersionFormat.h" #include "VersionFile.h" #include "meta/Version.h" #include "minecraft/Component.h" #include "minecraft/PackProfile.h" #include <assert.h> const QMap<QString, ModloaderMapEntry> Component::KNOWN_MODLOADERS = { { "net.neoforged", { ModPlatform::NeoForge, { "net.minecraftforge", "net.fabricmc.fabric-loader", "org.quiltmc.quilt-loader" } } }, { "net.minecraftforge", { ModPlatform::Forge, { "net.neoforged", "net.fabricmc.fabric-loader", "org.quiltmc.quilt-loader" } } }, { "net.fabricmc.fabric-loader", { ModPlatform::Fabric, { "net.minecraftforge", "net.neoforged", "org.quiltmc.quilt-loader" } } }, { "org.quiltmc.quilt-loader", { ModPlatform::Quilt, { "net.minecraftforge", "net.neoforged", "net.fabricmc.fabric-loader" } } }, { "com.mumfrey.liteloader", { ModPlatform::LiteLoader, {} } } }; Component::Component(PackProfile* parent, const QString& uid) { assert(parent); m_parent = parent; m_uid = uid; } Component::Component(PackProfile* parent, const QString& uid, std::shared_ptr<VersionFile> file) { assert(parent); m_parent = parent; m_file = file; m_uid = uid; m_cachedVersion = m_file->version; m_cachedName = m_file->name; m_loaded = true; } std::shared_ptr<Meta::Version> Component::getMeta() { return m_metaVersion; } void Component::applyTo(LaunchProfile* profile) { // do not apply disabled components if (!isEnabled()) { return; } auto vfile = getVersionFile(); if (vfile) { vfile->applyTo(profile, m_parent->runtimeContext()); } else { profile->applyProblemSeverity(getProblemSeverity()); } } std::shared_ptr<class VersionFile> Component::getVersionFile() const { if (m_metaVersion) { return m_metaVersion->data(); } else { return m_file; } } std::shared_ptr<class Meta::VersionList> Component::getVersionList() const { // FIXME: what if the metadata index isn't loaded yet? if (APPLICATION->metadataIndex()->hasUid(m_uid)) { return APPLICATION->metadataIndex()->get(m_uid); } return nullptr; } int Component::getOrder() { if (m_orderOverride) return m_order; auto vfile = getVersionFile(); if (vfile) { return vfile->order; } return 0; } void Component::setOrder(int order) { m_orderOverride = true; m_order = order; } QString Component::getID() { return m_uid; } QString Component::getName() { if (!m_cachedName.isEmpty()) return m_cachedName; return m_uid; } QString Component::getVersion() { return m_cachedVersion; } QString Component::getFilename() { return m_parent->patchFilePathForUid(m_uid); } QDateTime Component::getReleaseDateTime() { if (m_metaVersion) { return m_metaVersion->time(); } auto vfile = getVersionFile(); if (vfile) { return vfile->releaseTime; } // FIXME: fake return QDateTime::currentDateTime(); } bool Component::isEnabled() { return !canBeDisabled() || !m_disabled; } bool Component::canBeDisabled() { return isRemovable() && !m_dependencyOnly; } bool Component::setEnabled(bool state) { bool intendedDisabled = !state; if (!canBeDisabled()) { intendedDisabled = false; } if (intendedDisabled != m_disabled) { m_disabled = intendedDisabled; emit dataChanged(); return true; } return false; } bool Component::isCustom() { return m_file != nullptr; } bool Component::isCustomizable() { return m_metaVersion && getVersionFile(); } bool Component::isRemovable() { return !m_important; } bool Component::isRevertible() { if (isCustom()) { if (APPLICATION->metadataIndex()->hasUid(m_uid)) { return true; } } return false; } bool Component::isMoveable() { // HACK, FIXME: this was too dumb and wouldn't follow dependency constraints anyway. For now hardcoded to 'true'. return true; } bool Component::isVersionChangeable(bool wait) { auto list = getVersionList(); if (list) { if (wait) list->waitToLoad(); return list->count() != 0; } return false; } bool Component::isKnownModloader() { auto iter = KNOWN_MODLOADERS.find(m_uid); return iter != KNOWN_MODLOADERS.cend(); } QStringList Component::knownConflictingComponents() { auto iter = KNOWN_MODLOADERS.find(m_uid); if (iter != KNOWN_MODLOADERS.cend()) { return (*iter).knownConflictingComponents; } else { return {}; } } void Component::setImportant(bool state) { if (m_important != state) { m_important = state; emit dataChanged(); } } ProblemSeverity Component::getProblemSeverity() const { auto file = getVersionFile(); if (file) { auto severity = file->getProblemSeverity(); return m_componentProblemSeverity > severity ? m_componentProblemSeverity : severity; } return ProblemSeverity::Error; } const QList<PatchProblem> Component::getProblems() const { auto file = getVersionFile(); if (file) { auto problems = file->getProblems(); problems.append(m_componentProblems); return problems; } return { { ProblemSeverity::Error, QObject::tr("Patch is not loaded yet.") } }; } void Component::addComponentProblem(ProblemSeverity severity, const QString& description) { if (severity > m_componentProblemSeverity) { m_componentProblemSeverity = severity; } m_componentProblems.append({ severity, description }); emit dataChanged(); } void Component::resetComponentProblems() { m_componentProblems.clear(); m_componentProblemSeverity = ProblemSeverity::None; emit dataChanged(); } void Component::setVersion(const QString& version) { if (version == m_version) { return; } m_version = version; if (m_loaded) { // we are loaded and potentially have state to invalidate if (m_file) { // we have a file... explicit version has been changed and there is nothing else to do. } else { // we don't have a file, therefore we are loaded with metadata m_cachedVersion = version; // see if the meta version is loaded auto metaVersion = APPLICATION->metadataIndex()->get(m_uid, version); if (metaVersion->isLoaded()) { // if yes, we can continue with that. m_metaVersion = metaVersion; } else { // if not, we need loading m_metaVersion.reset(); m_loaded = false; } updateCachedData(); } } else { // not loaded... assume it will be sorted out later by the update task } emit dataChanged(); } bool Component::customize() { if (isCustom()) { return false; } auto filename = getFilename(); if (!FS::ensureFilePathExists(filename)) { return false; } // FIXME: get rid of this try-catch. try { QSaveFile jsonFile(filename); if (!jsonFile.open(QIODevice::WriteOnly)) { return false; } auto vfile = getVersionFile(); if (!vfile) { return false; } auto document = OneSixVersionFormat::versionFileToJson(vfile); jsonFile.write(document.toJson()); if (!jsonFile.commit()) { return false; } m_file = vfile; m_metaVersion.reset(); emit dataChanged(); } catch (const Exception& error) { qWarning() << "Version could not be loaded:" << error.cause(); } return true; } bool Component::revert() { if (!isCustom()) { // already not custom return true; } auto filename = getFilename(); bool result = true; // just kill the file and reload if (QFile::exists(filename)) { result = FS::deletePath(filename); } if (result) { // file gone... m_file.reset(); // check local cache for metadata... auto version = APPLICATION->metadataIndex()->get(m_uid, m_version); if (version->isLoaded()) { m_metaVersion = version; } else { m_metaVersion.reset(); m_loaded = false; } emit dataChanged(); } return result; } /** * deep inspecting compare for requirement sets * By default, only uids are compared for set operations. * This compares all fields of the Require structs in the sets. */ static bool deepCompare(const std::set<Meta::Require>& a, const std::set<Meta::Require>& b) { // NOTE: this needs to be rewritten if the type of Meta::RequireSet changes if (a.size() != b.size()) { return false; } for (const auto& reqA : a) { const auto& iter2 = b.find(reqA); if (iter2 == b.cend()) { return false; } const auto& reqB = *iter2; if (!reqA.deepEquals(reqB)) { return false; } } return true; } void Component::updateCachedData() { auto file = getVersionFile(); if (file) { bool changed = false; if (m_cachedName != file->name) { m_cachedName = file->name; changed = true; } if (m_cachedVersion != file->version) { m_cachedVersion = file->version; changed = true; } if (m_cachedVolatile != file->m_volatile) { m_cachedVolatile = file->m_volatile; changed = true; } if (!deepCompare(m_cachedRequires, file->m_requires)) { m_cachedRequires = file->m_requires; changed = true; } if (!deepCompare(m_cachedConflicts, file->conflicts)) { m_cachedConflicts = file->conflicts; changed = true; } if (changed) { emit dataChanged(); } } else { // in case we removed all the metadata m_cachedRequires.clear(); m_cachedConflicts.clear(); emit dataChanged(); } } void Component::waitLoadMeta() { if (!m_loaded) { if (!m_metaVersion || !m_metaVersion->isLoaded()) { // wait for the loaded version from meta m_metaVersion = APPLICATION->metadataIndex()->getLoadedVersion(m_uid, m_version); } m_loaded = true; updateCachedData(); } } void Component::setUpdateAction(UpdateAction action) { m_updateAction = action; } UpdateAction Component::getUpdateAction() { return m_updateAction; } void Component::clearUpdateAction() { m_updateAction = UpdateAction{ UpdateActionNone{} }; } QDebug operator<<(QDebug d, const Component& comp) { d << "Component(" << comp.m_uid << " : " << comp.m_cachedVersion << ")"; return d; }
12,504
C++
.cpp
433
23.685912
135
0.641348
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,177
SkinDelete.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/skins/SkinDelete.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "SkinDelete.h" #include "net/ByteArraySink.h" #include "net/RawHeaderProxy.h" SkinDelete::SkinDelete() : NetRequest() { logCat = taskMCSkinsLogC; } QNetworkReply* SkinDelete::getReply(QNetworkRequest& request) { setStatus(tr("Deleting skin")); return m_network->deleteResource(request); } SkinDelete::Ptr SkinDelete::make(QString token) { auto up = makeShared<SkinDelete>(); up->m_url = QUrl("https://api.minecraftservices.com/minecraft/profile/skins/active"); up->m_sink.reset(new Net::ByteArraySink(std::make_shared<QByteArray>())); up->addHeaderProxy(new Net::RawHeaderProxy(QList<Net::HeaderPair>{ { "Authorization", QString("Bearer %1").arg(token).toLocal8Bit() }, })); return up; }
2,301
C++
.cpp
57
37.929825
89
0.730683
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,178
SkinList.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/skins/SkinList.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "SkinList.h" #include <QFileInfo> #include <QMimeData> #include "FileSystem.h" #include "Json.h" #include "minecraft/skins/SkinModel.h" SkinList::SkinList(QObject* parent, QString path, MinecraftAccountPtr acct) : QAbstractListModel(parent), m_acct(acct) { FS::ensureFolderPathExists(m_dir.absolutePath()); m_dir.setFilter(QDir::Readable | QDir::NoDotAndDotDot | QDir::Files | QDir::Dirs); m_dir.setSorting(QDir::Name | QDir::IgnoreCase | QDir::LocaleAware); m_watcher.reset(new QFileSystemWatcher(this)); is_watching = false; connect(m_watcher.get(), &QFileSystemWatcher::directoryChanged, this, &SkinList::directoryChanged); connect(m_watcher.get(), &QFileSystemWatcher::fileChanged, this, &SkinList::fileChanged); directoryChanged(path); } void SkinList::startWatching() { if (is_watching) { return; } update(); is_watching = m_watcher->addPath(m_dir.absolutePath()); if (is_watching) { qDebug() << "Started watching " << m_dir.absolutePath(); } else { qDebug() << "Failed to start watching " << m_dir.absolutePath(); } } void SkinList::stopWatching() { save(); if (!is_watching) { return; } is_watching = !m_watcher->removePath(m_dir.absolutePath()); if (!is_watching) { qDebug() << "Stopped watching " << m_dir.absolutePath(); } else { qDebug() << "Failed to stop watching " << m_dir.absolutePath(); } } bool SkinList::update() { QVector<SkinModel> newSkins; m_dir.refresh(); auto manifestInfo = QFileInfo(m_dir.absoluteFilePath("index.json")); if (manifestInfo.exists()) { try { auto doc = Json::requireDocument(manifestInfo.absoluteFilePath(), "SkinList JSON file"); const auto root = doc.object(); auto skins = Json::ensureArray(root, "skins"); for (auto jSkin : skins) { SkinModel s(m_dir, Json::ensureObject(jSkin)); if (s.isValid()) { newSkins << s; } } } catch (const Exception& e) { qCritical() << "Couldn't load skins json:" << e.cause(); } } bool needsSave = false; const auto& skin = m_acct->accountData()->minecraftProfile.skin; if (!skin.url.isEmpty() && !skin.data.isEmpty()) { QPixmap skinTexture; SkinModel* nskin = nullptr; for (auto i = 0; i < newSkins.size(); i++) { if (newSkins[i].getURL() == skin.url) { nskin = &newSkins[i]; break; } } if (!nskin) { auto name = m_acct->profileName() + ".png"; if (QFileInfo(m_dir.absoluteFilePath(name)).exists()) { name = QUrl(skin.url).fileName() + ".png"; } auto path = m_dir.absoluteFilePath(name); if (skinTexture.loadFromData(skin.data, "PNG") && skinTexture.save(path)) { SkinModel s(path); s.setModel(skin.variant.toUpper() == "SLIM" ? SkinModel::SLIM : SkinModel::CLASSIC); s.setCapeId(m_acct->accountData()->minecraftProfile.currentCape); s.setURL(skin.url); newSkins << s; needsSave = true; } } else { nskin->setCapeId(m_acct->accountData()->minecraftProfile.currentCape); nskin->setModel(skin.variant.toUpper() == "SLIM" ? SkinModel::SLIM : SkinModel::CLASSIC); } } auto folderContents = m_dir.entryInfoList(); // if there are any untracked files... for (QFileInfo entry : folderContents) { if (!entry.isFile() && entry.suffix() != "png") continue; SkinModel w(entry.absoluteFilePath()); if (w.isValid()) { auto add = true; for (auto s : newSkins) { if (s.name() == w.name()) { add = false; break; } } if (add) { newSkins.append(w); needsSave = true; } } } std::sort(newSkins.begin(), newSkins.end(), [](const SkinModel& a, const SkinModel& b) { return a.getPath().localeAwareCompare(b.getPath()) < 0; }); beginResetModel(); m_skin_list.swap(newSkins); endResetModel(); if (needsSave) save(); return true; } void SkinList::directoryChanged(const QString& path) { QDir new_dir(path); if (!new_dir.exists()) if (!FS::ensureFolderPathExists(new_dir.absolutePath())) return; if (m_dir.absolutePath() != new_dir.absolutePath()) { m_dir.setPath(path); m_dir.refresh(); if (is_watching) stopWatching(); startWatching(); } update(); } void SkinList::fileChanged(const QString& path) { qDebug() << "Checking " << path; QFileInfo checkfile(path); if (!checkfile.exists()) return; for (int i = 0; i < m_skin_list.count(); i++) { if (m_skin_list[i].getPath() == checkfile.absoluteFilePath()) { m_skin_list[i].refresh(); dataChanged(index(i), index(i)); break; } } } QStringList SkinList::mimeTypes() const { return { "text/uri-list" }; } Qt::DropActions SkinList::supportedDropActions() const { return Qt::CopyAction; } bool SkinList::dropMimeData(const QMimeData* data, Qt::DropAction action, [[maybe_unused]] int row, [[maybe_unused]] int column, [[maybe_unused]] const QModelIndex& parent) { if (action == Qt::IgnoreAction) return true; // check if the action is supported if (!data || !(action & supportedDropActions())) return false; // files dropped from outside? if (data->hasUrls()) { auto urls = data->urls(); QStringList skinFiles; for (auto url : urls) { // only local files may be dropped... if (!url.isLocalFile()) continue; skinFiles << url.toLocalFile(); } installSkins(skinFiles); return true; } return false; } Qt::ItemFlags SkinList::flags(const QModelIndex& index) const { Qt::ItemFlags f = Qt::ItemIsDropEnabled | QAbstractListModel::flags(index); if (index.isValid()) { f |= (Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable); } return f; } QVariant SkinList::data(const QModelIndex& index, int role) const { if (!index.isValid()) return QVariant(); int row = index.row(); if (row < 0 || row >= m_skin_list.size()) return QVariant(); auto skin = m_skin_list[row]; switch (role) { case Qt::DecorationRole: return skin.getTexture(); case Qt::DisplayRole: return skin.name(); case Qt::UserRole: return skin.name(); case Qt::EditRole: return skin.name(); default: return QVariant(); } } int SkinList::rowCount(const QModelIndex& parent) const { return parent.isValid() ? 0 : m_skin_list.size(); } void SkinList::installSkins(const QStringList& iconFiles) { for (QString file : iconFiles) installSkin(file); } QString SkinList::installSkin(const QString& file, const QString& name) { if (file.isEmpty()) return tr("Path is empty."); QFileInfo fileinfo(file); if (!fileinfo.exists()) return tr("File doesn't exist."); if (!fileinfo.isFile()) return tr("Not a file."); if (!fileinfo.isReadable()) return tr("File is not readable."); if (fileinfo.suffix() != "png" && !SkinModel(fileinfo.absoluteFilePath()).isValid()) return tr("Skin images must be 64x64 or 64x32 pixel PNG files."); QString target = FS::PathCombine(m_dir.absolutePath(), name.isEmpty() ? fileinfo.fileName() : name); return QFile::copy(file, target) ? "" : tr("Unable to copy file"); } int SkinList::getSkinIndex(const QString& key) const { for (int i = 0; i < m_skin_list.count(); i++) { if (m_skin_list[i].name() == key) { return i; } } return -1; } const SkinModel* SkinList::skin(const QString& key) const { int idx = getSkinIndex(key); if (idx == -1) return nullptr; return &m_skin_list[idx]; } SkinModel* SkinList::skin(const QString& key) { int idx = getSkinIndex(key); if (idx == -1) return nullptr; return &m_skin_list[idx]; } bool SkinList::deleteSkin(const QString& key, const bool trash) { int idx = getSkinIndex(key); if (idx != -1) { auto s = m_skin_list[idx]; if (trash) { if (FS::trash(s.getPath(), nullptr)) { m_skin_list.remove(idx); save(); return true; } } else if (QFile::remove(s.getPath())) { m_skin_list.remove(idx); save(); return true; } } return false; } void SkinList::save() { QJsonObject doc; QJsonArray arr; for (auto s : m_skin_list) { arr << s.toJSON(); } doc["skins"] = arr; try { Json::write(doc, m_dir.absoluteFilePath("index.json")); } catch (const FS::FileSystemException& e) { qCritical() << "Failed to write skin index file :" << e.cause(); } } int SkinList::getSelectedAccountSkin() { const auto& skin = m_acct->accountData()->minecraftProfile.skin; for (int i = 0; i < m_skin_list.count(); i++) { if (m_skin_list[i].getURL() == skin.url) { return i; } } return -1; } bool SkinList::setData(const QModelIndex& idx, const QVariant& value, int role) { if (!idx.isValid() || role != Qt::EditRole) { return false; } int row = idx.row(); if (row < 0 || row >= m_skin_list.size()) return false; auto& skin = m_skin_list[row]; auto newName = value.toString(); if (skin.name() != newName) { skin.rename(newName); save(); } return true; } void SkinList::updateSkin(SkinModel* s) { auto done = false; for (auto i = 0; i < m_skin_list.size(); i++) { if (m_skin_list[i].getPath() == s->getPath()) { m_skin_list[i].setCapeId(s->getCapeId()); m_skin_list[i].setModel(s->getModel()); m_skin_list[i].setURL(s->getURL()); done = true; break; } } if (!done) { beginInsertRows(QModelIndex(), m_skin_list.count(), m_skin_list.count() + 1); m_skin_list.append(*s); endInsertRows(); } save(); }
11,495
C++
.cpp
357
25.078431
118
0.582508
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,179
SkinUpload.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/skins/SkinUpload.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "SkinUpload.h" #include <QHttpMultiPart> #include "FileSystem.h" #include "net/ByteArraySink.h" #include "net/RawHeaderProxy.h" SkinUpload::SkinUpload(QString path, QString variant) : NetRequest(), m_path(path), m_variant(variant) { logCat = taskMCSkinsLogC; } QNetworkReply* SkinUpload::getReply(QNetworkRequest& request) { QHttpMultiPart* multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType, this); QHttpPart skin; skin.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/png")); skin.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"file\"; filename=\"skin.png\"")); skin.setBody(FS::read(m_path)); QHttpPart model; model.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"variant\"")); model.setBody(m_variant.toUtf8()); multiPart->append(skin); multiPart->append(model); setStatus(tr("Uploading skin")); return m_network->post(request, multiPart); } SkinUpload::Ptr SkinUpload::make(QString token, QString path, QString variant) { auto up = makeShared<SkinUpload>(path, variant); up->m_url = QUrl("https://api.minecraftservices.com/minecraft/profile/skins"); up->setObjectName(QString("BYTES:") + up->m_url.toString()); up->m_sink.reset(new Net::ByteArraySink(std::make_shared<QByteArray>())); up->addHeaderProxy(new Net::RawHeaderProxy(QList<Net::HeaderPair>{ { "Authorization", QString("Bearer %1").arg(token).toLocal8Bit() }, })); return up; }
3,094
C++
.cpp
70
41.328571
123
0.733577
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,180
CapeChange.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/skins/CapeChange.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "CapeChange.h" #include <memory> #include "net/ByteArraySink.h" #include "net/RawHeaderProxy.h" CapeChange::CapeChange(QString cape) : NetRequest(), m_capeId(cape) { logCat = taskMCSkinsLogC; } QNetworkReply* CapeChange::getReply(QNetworkRequest& request) { if (m_capeId.isEmpty()) { setStatus(tr("Removing cape")); return m_network->deleteResource(request); } else { setStatus(tr("Equipping cape")); return m_network->put(request, QString("{\"capeId\":\"%1\"}").arg(m_capeId).toUtf8()); } } CapeChange::Ptr CapeChange::make(QString token, QString capeId) { auto up = makeShared<CapeChange>(capeId); up->m_url = QUrl("https://api.minecraftservices.com/minecraft/profile/capes/active"); up->setObjectName(QString("BYTES:") + up->m_url.toString()); up->m_sink.reset(new Net::ByteArraySink(std::make_shared<QByteArray>())); up->addHeaderProxy(new Net::RawHeaderProxy(QList<Net::HeaderPair>{ { "Authorization", QString("Bearer %1").arg(token).toLocal8Bit() }, })); return up; }
2,628
C++
.cpp
64
38.140625
94
0.715012
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,181
SkinModel.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/skins/SkinModel.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "SkinModel.h" #include <QFileInfo> #include <QImage> #include <QPainter> #include <QTransform> #include "FileSystem.h" #include "Json.h" SkinModel::SkinModel(QString path) : m_path(path), m_texture(path), m_model(Model::CLASSIC) {} SkinModel::SkinModel(QDir skinDir, QJsonObject obj) : m_cape_id(Json::ensureString(obj, "capeId")), m_model(Model::CLASSIC), m_url(Json::ensureString(obj, "url")) { auto name = Json::ensureString(obj, "name"); if (auto model = Json::ensureString(obj, "model"); model == "SLIM") { m_model = Model::SLIM; } m_path = skinDir.absoluteFilePath(name) + ".png"; m_texture = QPixmap(m_path); } QString SkinModel::name() const { return QFileInfo(m_path).completeBaseName(); } bool SkinModel::rename(QString newName) { auto info = QFileInfo(m_path); m_path = FS::PathCombine(info.absolutePath(), newName + ".png"); return FS::move(info.absoluteFilePath(), m_path); } QJsonObject SkinModel::toJSON() const { QJsonObject obj; obj["name"] = name(); obj["capeId"] = m_cape_id; obj["url"] = m_url; obj["model"] = getModelString(); return obj; } QString SkinModel::getModelString() const { switch (m_model) { case CLASSIC: return "CLASSIC"; case SLIM: return "SLIM"; } return {}; } bool SkinModel::isValid() const { return !m_texture.isNull() && (m_texture.size().height() == 32 || m_texture.size().height() == 64) && m_texture.size().width() == 64; }
2,260
C++
.cpp
68
29.985294
137
0.685151
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,182
TexturePack.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/mod/TexturePack.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "TexturePack.h" #include <QDebug> #include <QMap> #include <QRegularExpression> #include "MTPixmapCache.h" #include "minecraft/mod/tasks/LocalTexturePackParseTask.h" void TexturePack::setDescription(QString new_description) { QMutexLocker locker(&m_data_lock); m_description = new_description; } void TexturePack::setImage(QImage new_image) const { QMutexLocker locker(&m_data_lock); Q_ASSERT(!new_image.isNull()); if (m_pack_image_cache_key.key.isValid()) 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, Qt::SmoothTransformation)); m_pack_image_cache_key.key = PixmapCache::insert(pixmap); m_pack_image_cache_key.was_ever_used = true; } QPixmap TexturePack::image(QSize size, Qt::AspectRatioMode mode) const { QPixmap cached_image; if (PixmapCache::find(m_pack_image_cache_key.key, &cached_image)) { if (size.isNull()) return cached_image; return cached_image.scaled(size, mode, Qt::SmoothTransformation); } // No valid image we can get if (!m_pack_image_cache_key.was_ever_used) { return {}; } else { qDebug() << "Texture Pack" << name() << "Had it's image evicted from the cache. reloading..."; PixmapCache::markCacheMissByEviciton(); } // Imaged got evicted from the cache. Re-process it and retry. TexturePackUtils::processPackPNG(*this); return image(size); } bool TexturePack::valid() const { return m_description != nullptr; }
2,468
C++
.cpp
64
34.765625
132
0.719129
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,183
ResourceFolderModel.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/mod/ResourceFolderModel.cpp
#include "ResourceFolderModel.h" #include <QMessageBox> #include <QCoreApplication> #include <QDebug> #include <QFileInfo> #include <QHeaderView> #include <QIcon> #include <QMenu> #include <QMimeData> #include <QStyle> #include <QThreadPool> #include <QUrl> #include <utility> #include "Application.h" #include "FileSystem.h" #include "minecraft/mod/tasks/ResourceFolderLoadTask.h" #include "Json.h" #include "minecraft/mod/tasks/LocalResourceUpdateTask.h" #include "modplatform/flame/FlameAPI.h" #include "modplatform/flame/FlameModIndex.h" #include "settings/Setting.h" #include "tasks/Task.h" #include "ui/dialogs/CustomMessageBox.h" ResourceFolderModel::ResourceFolderModel(const QDir& dir, BaseInstance* instance, bool is_indexed, bool create_dir, QObject* parent) : QAbstractListModel(parent), m_dir(dir), m_instance(instance), m_watcher(this), m_is_indexed(is_indexed) { if (create_dir) { FS::ensureFolderPathExists(m_dir.absolutePath()); } m_dir.setFilter(QDir::Readable | QDir::NoDotAndDotDot | QDir::Files | QDir::Dirs); m_dir.setSorting(QDir::Name | QDir::IgnoreCase | QDir::LocaleAware); connect(&m_watcher, &QFileSystemWatcher::directoryChanged, this, &ResourceFolderModel::directoryChanged); connect(&m_helper_thread_task, &ConcurrentTask::finished, this, [this] { m_helper_thread_task.clear(); }); if (APPLICATION_DYN) { // in tests the application macro doesn't work m_helper_thread_task.setMaxConcurrent(APPLICATION->settings()->get("NumberOfConcurrentTasks").toInt()); } } ResourceFolderModel::~ResourceFolderModel() { while (!QThreadPool::globalInstance()->waitForDone(100)) QCoreApplication::processEvents(); } bool ResourceFolderModel::startWatching(const QStringList& paths) { // Remove orphaned metadata next time m_first_folder_load = true; if (m_is_watching) return false; auto couldnt_be_watched = m_watcher.addPaths(paths); for (auto path : paths) { if (couldnt_be_watched.contains(path)) qDebug() << "Failed to start watching " << path; else qDebug() << "Started watching " << path; } update(); m_is_watching = !m_is_watching; return m_is_watching; } bool ResourceFolderModel::stopWatching(const QStringList& paths) { if (!m_is_watching) return false; auto couldnt_be_stopped = m_watcher.removePaths(paths); for (auto path : paths) { if (couldnt_be_stopped.contains(path)) qDebug() << "Failed to stop watching " << path; else qDebug() << "Stopped watching " << path; } m_is_watching = !m_is_watching; return !m_is_watching; } bool ResourceFolderModel::installResource(QString original_path) { // NOTE: fix for GH-1178: remove trailing slash to avoid issues with using the empty result of QFileInfo::fileName original_path = FS::NormalizePath(original_path); QFileInfo file_info(original_path); if (!file_info.exists() || !file_info.isReadable()) { qWarning() << "Caught attempt to install non-existing file or file-like object:" << original_path; return false; } qDebug() << "Installing: " << file_info.absoluteFilePath(); Resource resource(file_info); if (!resource.valid()) { qWarning() << original_path << "is not a valid resource. Ignoring it."; return false; } auto new_path = FS::NormalizePath(m_dir.filePath(file_info.fileName())); if (original_path == new_path) { qWarning() << "Overwriting the mod (" << original_path << ") with itself makes no sense..."; return false; } switch (resource.type()) { case ResourceType::SINGLEFILE: case ResourceType::ZIPFILE: case ResourceType::LITEMOD: { if (QFile::exists(new_path) || QFile::exists(new_path + QString(".disabled"))) { if (!FS::deletePath(new_path)) { qCritical() << "Cleaning up new location (" << new_path << ") was unsuccessful!"; return false; } qDebug() << new_path << "has been deleted."; } if (!QFile::copy(original_path, new_path)) { qCritical() << "Copy from" << original_path << "to" << new_path << "has failed."; return false; } FS::updateTimestamp(new_path); QFileInfo new_path_file_info(new_path); resource.setFile(new_path_file_info); if (!m_is_watching) return update(); return true; } case ResourceType::FOLDER: { if (QFile::exists(new_path)) { qDebug() << "Ignoring folder '" << original_path << "', it would merge with" << new_path; return false; } if (!FS::copy(original_path, new_path)()) { qWarning() << "Copy of folder from" << original_path << "to" << new_path << "has (potentially partially) failed."; return false; } QFileInfo newpathInfo(new_path); resource.setFile(newpathInfo); if (!m_is_watching) return update(); return true; } default: break; } return false; } bool ResourceFolderModel::installResourceWithFlameMetadata(QString 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(); } LocalResourceUpdateTask update_metadata(indexDir(), pack, vers); QObject::connect(&update_metadata, &Task::finished, &loop, &QEventLoop::quit); update_metadata.start(); }); job->start(); loop.exec(); } return installResource(std::move(path)); } bool ResourceFolderModel::uninstallResource(QString file_name, bool preserve_metadata) { for (auto& resource : m_resources) { if (resource->fileinfo().fileName() == file_name) { auto res = resource->destroy(indexDir(), preserve_metadata, false); update(); return res; } } return false; } bool ResourceFolderModel::deleteResources(const QModelIndexList& indexes) { if (indexes.isEmpty()) return true; for (auto i : indexes) { if (i.column() != 0) continue; auto& resource = m_resources.at(i.row()); resource->destroy(indexDir()); } update(); return true; } void ResourceFolderModel::deleteMetadata(const QModelIndexList& indexes) { if (indexes.isEmpty()) return; for (auto i : indexes) { if (i.column() != 0) continue; auto& resource = m_resources.at(i.row()); resource->destroyMetadata(indexDir()); } update(); } bool ResourceFolderModel::setResourceEnabled(const QModelIndexList& indexes, EnableAction action) { if (indexes.isEmpty()) return true; bool succeeded = true; for (auto const& idx : indexes) { if (!validateIndex(idx) || idx.column() != 0) continue; int row = idx.row(); auto& resource = m_resources[row]; // Preserve the row, but change its ID auto old_id = resource->internal_id(); if (!resource->enable(action)) { succeeded = false; continue; } auto new_id = resource->internal_id(); m_resources_index.remove(old_id); m_resources_index[new_id] = row; emit dataChanged(index(row, 0), index(row, columnCount(QModelIndex()) - 1)); } return succeeded; } static QMutex s_update_task_mutex; bool ResourceFolderModel::update() { // We hold a lock here to prevent race conditions on the m_current_update_task reset. QMutexLocker lock(&s_update_task_mutex); // Already updating, so we schedule a future update and return. if (m_current_update_task) { m_scheduled_update = true; return false; } m_current_update_task.reset(createUpdateTask()); if (!m_current_update_task) return false; connect(m_current_update_task.get(), &Task::succeeded, this, &ResourceFolderModel::onUpdateSucceeded, Qt::ConnectionType::QueuedConnection); connect(m_current_update_task.get(), &Task::failed, this, &ResourceFolderModel::onUpdateFailed, Qt::ConnectionType::QueuedConnection); connect( m_current_update_task.get(), &Task::finished, this, [this] { m_current_update_task.reset(); if (m_scheduled_update) { m_scheduled_update = false; update(); } else { emit updateFinished(); } }, Qt::ConnectionType::QueuedConnection); QThreadPool::globalInstance()->start(m_current_update_task.get()); return true; } void ResourceFolderModel::resolveResource(Resource::Ptr res) { if (!res->shouldResolve()) { return; } Task::Ptr task{ createParseTask(*res) }; if (!task) return; int ticket = m_next_resolution_ticket.fetch_add(1); res->setResolving(true, ticket); m_active_parse_tasks.insert(ticket, task); connect( task.get(), &Task::succeeded, this, [this, ticket, res] { onParseSucceeded(ticket, res->internal_id()); }, Qt::ConnectionType::QueuedConnection); connect( task.get(), &Task::failed, this, [this, ticket, res] { onParseFailed(ticket, res->internal_id()); }, Qt::ConnectionType::QueuedConnection); connect( task.get(), &Task::finished, this, [this, ticket] { m_active_parse_tasks.remove(ticket); emit parseFinished(); }, Qt::ConnectionType::QueuedConnection); m_helper_thread_task.addTask(task); if (!m_helper_thread_task.isRunning()) { QThreadPool::globalInstance()->start(&m_helper_thread_task); } } void ResourceFolderModel::onUpdateSucceeded() { auto update_results = static_cast<ResourceFolderLoadTask*>(m_current_update_task.get())->result(); auto& new_resources = update_results->resources; #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) auto current_list = m_resources_index.keys(); QSet<QString> current_set(current_list.begin(), current_list.end()); auto new_list = new_resources.keys(); QSet<QString> new_set(new_list.begin(), new_list.end()); #else QSet<QString> current_set(m_resources_index.keys().toSet()); QSet<QString> new_set(new_resources.keys().toSet()); #endif applyUpdates(current_set, new_set, new_resources); } void ResourceFolderModel::onParseSucceeded(int ticket, QString resource_id) { auto iter = m_active_parse_tasks.constFind(ticket); if (iter == m_active_parse_tasks.constEnd() || !m_resources_index.contains(resource_id)) return; int row = m_resources_index[resource_id]; emit dataChanged(index(row), index(row, columnCount(QModelIndex()) - 1)); } Task* ResourceFolderModel::createUpdateTask() { auto index_dir = indexDir(); auto task = new ResourceFolderLoadTask(dir(), index_dir, m_is_indexed, m_first_folder_load, [this](const QFileInfo& file) { return createResource(file); }); m_first_folder_load = false; return task; } bool ResourceFolderModel::hasPendingParseTasks() const { return !m_active_parse_tasks.isEmpty(); } void ResourceFolderModel::directoryChanged(QString path) { update(); } Qt::DropActions ResourceFolderModel::supportedDropActions() const { // copy from outside, move from within and other resource lists return Qt::CopyAction | Qt::MoveAction; } Qt::ItemFlags ResourceFolderModel::flags(const QModelIndex& index) const { Qt::ItemFlags defaultFlags = QAbstractListModel::flags(index); auto flags = defaultFlags | Qt::ItemIsDropEnabled; if (index.isValid()) flags |= Qt::ItemIsUserCheckable; return flags; } QStringList ResourceFolderModel::mimeTypes() const { QStringList types; types << "text/uri-list"; return types; } bool ResourceFolderModel::dropMimeData(const QMimeData* data, Qt::DropAction action, int, int, const QModelIndex&) { if (action == Qt::IgnoreAction) { return true; } // check if the action is supported if (!data || !(action & supportedDropActions())) { return false; } // files dropped from outside? if (data->hasUrls()) { auto urls = data->urls(); for (auto url : urls) { // only local files may be dropped... if (!url.isLocalFile()) { continue; } // TODO: implement not only copy, but also move // FIXME: handle errors here installResource(url.toLocalFile()); } return true; } return false; } bool ResourceFolderModel::validateIndex(const QModelIndex& index) const { if (!index.isValid()) return false; int row = index.row(); if (row < 0 || row >= m_resources.size()) return false; return true; } QVariant ResourceFolderModel::data(const QModelIndex& index, int role) const { if (!validateIndex(index)) return {}; int row = index.row(); int column = index.column(); switch (role) { case Qt::DisplayRole: switch (column) { case NameColumn: return m_resources[row]->name(); case DateColumn: return m_resources[row]->dateTimeChanged(); case ProviderColumn: return m_resources[row]->provider(); case SizeColumn: return m_resources[row]->sizeStr(); default: return {}; } case Qt::ToolTipRole: if (column == NameColumn) { if (at(row).isSymLinkUnder(instDirPath())) { return m_resources[row]->internal_id() + tr("\nWarning: This resource is symbolically linked from elsewhere. Editing it will also change the original." "\nCanonical Path: %1") .arg(at(row).fileinfo().canonicalFilePath()); ; } if (at(row).isMoreThanOneHardLink()) { return m_resources[row]->internal_id() + tr("\nWarning: This resource is hard linked elsewhere. Editing it will also change the original."); } } return m_resources[row]->internal_id(); case Qt::DecorationRole: { if (column == NameColumn && (at(row).isSymLinkUnder(instDirPath()) || at(row).isMoreThanOneHardLink())) return APPLICATION->getThemedIcon("status-yellow"); return {}; } case Qt::CheckStateRole: switch (column) { case ActiveColumn: return m_resources[row]->enabled() ? Qt::Checked : Qt::Unchecked; default: return {}; } default: return {}; } } 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()) return false; if (role == Qt::CheckStateRole) { if (m_instance != nullptr && m_instance->isRunning()) { auto response = CustomMessageBox::selectable(nullptr, tr("Confirm toggle"), tr("If you enable/disable this resource while the game is running it may crash your game.\n" "Are you sure you want to do this?"), QMessageBox::Warning, QMessageBox::Yes | QMessageBox::No, QMessageBox::No) ->exec(); if (response != QMessageBox::Yes) return false; } return setResourceEnabled({ index }, EnableAction::TOGGLE); } return false; } QVariant ResourceFolderModel::headerData(int section, [[maybe_unused]] Qt::Orientation orientation, int role) const { switch (role) { case Qt::DisplayRole: switch (section) { case ActiveColumn: case NameColumn: case DateColumn: case ProviderColumn: case SizeColumn: return columnNames().at(section); default: return {}; } case Qt::ToolTipRole: { //: Here, resource is a generic term for external resources, like Mods, Resource Packs, Shader Packs, etc. switch (section) { case ActiveColumn: return tr("Is the resource enabled?"); case NameColumn: return tr("The name of the resource."); case DateColumn: return tr("The date and time this resource was last changed (or added)."); case ProviderColumn: return tr("The source provider of the resource."); case SizeColumn: return tr("The size of the resource."); default: return {}; } } default: break; } return {}; } void ResourceFolderModel::setupHeaderAction(QAction* act, int column) { Q_ASSERT(act); act->setText(columnNames().at(column)); } void ResourceFolderModel::saveColumns(QTreeView* tree) { auto const setting_name = QString("UI/%1_Page/Columns").arg(id()); auto setting = (m_instance->settings()->contains(setting_name)) ? m_instance->settings()->getSetting(setting_name) : m_instance->settings()->registerSetting(setting_name); setting->set(tree->header()->saveState()); } void ResourceFolderModel::loadColumns(QTreeView* tree) { for (auto i = 0; i < m_columnsHiddenByDefault.size(); ++i) { tree->setColumnHidden(i, m_columnsHiddenByDefault[i]); } auto const setting_name = QString("UI/%1_Page/Columns").arg(id()); auto setting = (m_instance->settings()->contains(setting_name)) ? m_instance->settings()->getSetting(setting_name) : m_instance->settings()->registerSetting(setting_name); tree->header()->restoreState(setting->get().toByteArray()); } QMenu* ResourceFolderModel::createHeaderContextMenu(QTreeView* tree) { auto menu = new QMenu(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); act->setCheckable(true); act->setChecked(!tree->isColumnHidden(col)); connect(act, &QAction::toggled, tree, [this, col, tree](bool toggled) { tree->setColumnHidden(col, !toggled); for (int c = 0; c < columnCount(); ++c) { if (m_column_resize_modes.at(c) == QHeaderView::ResizeToContents) tree->resizeColumnToContents(c); } saveColumns(tree); }); menu->addAction(act); } return menu; } QSortFilterProxyModel* ResourceFolderModel::createFilterProxyModel(QObject* parent) { return new ProxyModel(parent); } SortType ResourceFolderModel::columnToSortKey(size_t column) const { Q_ASSERT(m_column_sort_keys.size() == columnCount()); return m_column_sort_keys.at(column); } /* Standard Proxy Model for createFilterProxyModel */ [[nodiscard]] bool ResourceFolderModel::ProxyModel::filterAcceptsRow(int source_row, [[maybe_unused]] const QModelIndex& source_parent) const { auto* model = qobject_cast<ResourceFolderModel*>(sourceModel()); if (!model) return true; const auto& resource = model->at(source_row); return resource.applyFilter(filterRegularExpression()); } [[nodiscard]] bool ResourceFolderModel::ProxyModel::lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const { auto* model = qobject_cast<ResourceFolderModel*>(sourceModel()); if (!model || !source_left.isValid() || !source_right.isValid() || source_left.column() != source_right.column()) { return QSortFilterProxyModel::lessThan(source_left, source_right); } // we are now guaranteed to have two valid indexes in the same column... we love the provided invariants unconditionally and // proceed. auto column_sort_key = model->columnToSortKey(source_left.column()); auto const& resource_left = model->at(source_left.row()); auto const& resource_right = model->at(source_right.row()); auto compare_result = resource_left.compare(resource_right, column_sort_key); if (compare_result == 0) return QSortFilterProxyModel::lessThan(source_left, source_right); return compare_result < 0; } QString ResourceFolderModel::instDirPath() const { return QFileInfo(m_instance->instanceRoot()).absoluteFilePath(); } void ResourceFolderModel::onParseFailed(int ticket, QString resource_id) { auto iter = m_active_parse_tasks.constFind(ticket); if (iter == m_active_parse_tasks.constEnd() || !m_resources_index.contains(resource_id)) return; auto removed_index = m_resources_index[resource_id]; auto removed_it = m_resources.begin() + removed_index; Q_ASSERT(removed_it != m_resources.end()); beginRemoveRows(QModelIndex(), removed_index, removed_index); m_resources.erase(removed_it); // update index m_resources_index.clear(); int idx = 0; for (auto const& mod : qAsConst(m_resources)) { m_resources_index[mod->internal_id()] = idx; idx++; } endRemoveRows(); } void ResourceFolderModel::applyUpdates(QSet<QString>& current_set, QSet<QString>& new_set, QMap<QString, Resource::Ptr>& new_resources) { // see if the kept resources changed in some way { QSet<QString> kept_set = current_set; kept_set.intersect(new_set); for (auto const& kept : kept_set) { auto row_it = m_resources_index.constFind(kept); Q_ASSERT(row_it != m_resources_index.constEnd()); auto row = row_it.value(); auto& new_resource = new_resources[kept]; auto const& current_resource = m_resources.at(row); if (new_resource->dateTimeChanged() == current_resource->dateTimeChanged()) { // no significant change, ignore... continue; } // If the resource is resolving, but something about it changed, we don't want to // continue the resolving. if (current_resource->isResolving()) { auto ticket = current_resource->resolutionTicket(); if (m_active_parse_tasks.contains(ticket)) { auto task = (*m_active_parse_tasks.find(ticket)).get(); task->abort(); } } m_resources[row].reset(new_resource); resolveResource(m_resources.at(row)); emit dataChanged(index(row, 0), index(row, columnCount(QModelIndex()) - 1)); } } // remove resources no longer present { QSet<QString> removed_set = current_set; removed_set.subtract(new_set); QList<int> removed_rows; for (auto& removed : removed_set) removed_rows.append(m_resources_index[removed]); std::sort(removed_rows.begin(), removed_rows.end(), std::greater<int>()); for (auto& removed_index : removed_rows) { auto removed_it = m_resources.begin() + removed_index; Q_ASSERT(removed_it != m_resources.end()); if ((*removed_it)->isResolving()) { auto ticket = (*removed_it)->resolutionTicket(); if (m_active_parse_tasks.contains(ticket)) { auto task = (*m_active_parse_tasks.find(ticket)).get(); task->abort(); } } beginRemoveRows(QModelIndex(), removed_index, removed_index); m_resources.erase(removed_it); endRemoveRows(); } } // add new resources to the end { QSet<QString> added_set = new_set; added_set.subtract(current_set); // When you have a Qt build with assertions turned on, proceeding here will abort the application if (added_set.size() > 0) { 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]; m_resources.append(res); resolveResource(m_resources.last()); } endInsertRows(); } } // update index { m_resources_index.clear(); int idx = 0; for (auto const& mod : qAsConst(m_resources)) { m_resources_index[mod->internal_id()] = idx; idx++; } } } Resource::Ptr ResourceFolderModel::find(QString id) { auto iter = std::find_if(m_resources.constBegin(), m_resources.constEnd(), [&](Resource::Ptr const& r) { return r->internal_id() == id; }); if (iter == m_resources.constEnd()) return nullptr; return *iter; } QList<Resource*> ResourceFolderModel::allResources() { QList<Resource*> result; result.reserve(m_resources.size()); for (const Resource ::Ptr& resource : m_resources) result.append((resource.get())); return result; } QList<Resource*> ResourceFolderModel::selectedResources(const QModelIndexList& indexes) { QList<Resource*> result; for (const QModelIndex& index : indexes) { if (index.column() != 0) continue; result.append(&at(index.row())); } return result; }
27,724
C++
.cpp
699
30.914163
138
0.607657
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,184
Resource.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/mod/Resource.cpp
#include "Resource.h" #include <QDirIterator> #include <QFileInfo> #include <QRegularExpression> #include <tuple> #include "FileSystem.h" #include "StringUtils.h" Resource::Resource(QObject* parent) : QObject(parent) {} Resource::Resource(QFileInfo file_info) : QObject() { setFile(file_info); } void Resource::setFile(QFileInfo file_info) { m_file_info = file_info; parseFile(); } static std::tuple<QString, qint64> calculateFileSize(const QFileInfo& file) { if (file.isDir()) { auto dir = QDir(file.absoluteFilePath()); dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot); auto count = dir.count(); auto str = QObject::tr("item"); if (count != 1) str = QObject::tr("items"); return { QString("%1 %2").arg(QString::number(count), str), count }; } return { StringUtils::humanReadableFileSize(file.size(), true), file.size() }; } void Resource::parseFile() { QString file_name{ m_file_info.fileName() }; m_type = ResourceType::UNKNOWN; m_internal_id = file_name; std::tie(m_size_str, m_size_info) = calculateFileSize(m_file_info); if (m_file_info.isDir()) { m_type = ResourceType::FOLDER; m_name = file_name; } else if (m_file_info.isFile()) { if (file_name.endsWith(".disabled")) { file_name.chop(9); m_enabled = false; } if (file_name.endsWith(".zip") || file_name.endsWith(".jar")) { m_type = ResourceType::ZIPFILE; file_name.chop(4); } else if (file_name.endsWith(".nilmod")) { m_type = ResourceType::ZIPFILE; file_name.chop(7); } else if (file_name.endsWith(".litemod")) { m_type = ResourceType::LITEMOD; file_name.chop(8); } else { m_type = ResourceType::SINGLEFILE; } m_name = file_name; } m_changed_date_time = m_file_info.lastModified(); } auto Resource::name() const -> QString { if (metadata()) return metadata()->name; return m_name; } static void removeThePrefix(QString& string) { QRegularExpression regex(QStringLiteral("^(?:the|teh) +"), QRegularExpression::CaseInsensitiveOption); string.remove(regex); string = string.trimmed(); } auto Resource::provider() const -> QString { if (metadata()) return ModPlatform::ProviderCapabilities::readableName(metadata()->provider); return tr("Unknown"); } auto Resource::homepage() const -> QString { if (metadata()) return ModPlatform::getMetaURL(metadata()->provider, metadata()->project_id); return {}; } void Resource::setMetadata(std::shared_ptr<Metadata::ModStruct>&& metadata) { if (status() == ResourceStatus::NO_METADATA) setStatus(ResourceStatus::INSTALLED); m_metadata = metadata; } int Resource::compare(const Resource& other, SortType type) const { switch (type) { default: case SortType::ENABLED: if (enabled() && !other.enabled()) return 1; if (!enabled() && other.enabled()) return -1; break; case SortType::NAME: { QString this_name{ name() }; QString other_name{ other.name() }; // TODO do we need this? it could result in 0 being returned removeThePrefix(this_name); removeThePrefix(other_name); return QString::compare(this_name, other_name, Qt::CaseInsensitive); } case SortType::DATE: if (dateTimeChanged() > other.dateTimeChanged()) return 1; if (dateTimeChanged() < other.dateTimeChanged()) return -1; break; case SortType::SIZE: { if (this->type() != other.type()) { if (this->type() == ResourceType::FOLDER) return -1; if (other.type() == ResourceType::FOLDER) return 1; } if (sizeInfo() > other.sizeInfo()) return 1; if (sizeInfo() < other.sizeInfo()) return -1; break; } case SortType::PROVIDER: { auto compare_result = QString::compare(provider(), other.provider(), Qt::CaseInsensitive); if (compare_result != 0) return compare_result; break; } } return 0; } bool Resource::applyFilter(QRegularExpression filter) const { return filter.match(name()).hasMatch(); } bool Resource::enable(EnableAction action) { if (m_type == ResourceType::UNKNOWN || m_type == ResourceType::FOLDER) return false; QString path = m_file_info.absoluteFilePath(); QFile file(path); bool enable = true; switch (action) { case EnableAction::ENABLE: enable = true; break; case EnableAction::DISABLE: enable = false; break; case EnableAction::TOGGLE: default: enable = !enabled(); break; } if (m_enabled == enable) return false; if (enable) { // m_enabled is false, but there's no '.disabled' suffix. // TODO: Report error? if (!path.endsWith(".disabled")) return false; path.chop(9); } else { path += ".disabled"; if (QFile::exists(path)) { path = FS::getUniqueResourceName(path); } } if (!file.rename(path)) return false; setFile(QFileInfo(path)); m_enabled = enable; return true; } auto Resource::destroy(const QDir& index_dir, bool preserve_metadata, bool attempt_trash) -> bool { m_type = ResourceType::UNKNOWN; if (!preserve_metadata) { qDebug() << QString("Destroying metadata for '%1' on purpose").arg(name()); destroyMetadata(index_dir); } return (attempt_trash && FS::trash(m_file_info.filePath())) || FS::deletePath(m_file_info.filePath()); } auto Resource::destroyMetadata(const QDir& index_dir) -> void { if (metadata()) { Metadata::remove(index_dir, metadata()->slug); } else { auto n = name(); Metadata::remove(index_dir, n); } m_metadata = nullptr; } bool Resource::isSymLinkUnder(const QString& instPath) const { if (isSymLink()) return true; auto instDir = QDir(instPath); auto relAbsPath = instDir.relativeFilePath(m_file_info.absoluteFilePath()); auto relCanonPath = instDir.relativeFilePath(m_file_info.canonicalFilePath()); return relAbsPath != relCanonPath; } bool Resource::isMoreThanOneHardLink() const { return FS::hardLinkCount(m_file_info.absoluteFilePath()) > 1; } auto Resource::getOriginalFileName() const -> QString { auto fileName = m_file_info.fileName(); if (!m_enabled) fileName.chop(9); return fileName; }
6,926
C++
.cpp
218
24.697248
106
0.602341
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,185
ResourcePack.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/mod/ResourcePack.cpp
#include "ResourcePack.h" #include <QCoreApplication> #include <QDebug> #include <QMap> #include <QRegularExpression> #include "MTPixmapCache.h" #include "Version.h" #include "minecraft/mod/tasks/LocalResourcePackParseTask.h" // Values taken from: // https://minecraft.wiki/w/Pack_format#List_of_resource_pack_formats 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") } }, { 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") } }, { 8, { Version("1.18"), Version("1.18.2") } }, { 9, { Version("1.19"), Version("1.19.2") } }, { 11, { Version("22w42a"), Version("22w44a") } }, { 12, { Version("1.19.3"), Version("1.19.3") } }, { 13, { Version("1.19.4"), Version("1.19.4") } }, { 14, { Version("23w14a"), Version("23w16a") } }, { 15, { Version("1.20"), Version("1.20.1") } }, { 16, { Version("23w31a"), Version("23w31a") } }, { 17, { Version("23w32a"), Version("23w35a") } }, { 18, { Version("1.20.2"), Version("23w16a") } }, { 19, { Version("23w42a"), Version("23w42a") } }, { 20, { Version("23w43a"), Version("23w44a") } }, { 21, { Version("23w45a"), Version("23w46a") } }, { 22, { Version("1.20.3-pre1"), Version("23w51b") } }, { 24, { Version("24w03a"), Version("24w04a") } }, { 25, { Version("24w05a"), Version("24w05b") } }, { 26, { Version("24w06a"), Version("24w07a") } }, { 28, { Version("24w09a"), Version("24w10a") } }, { 29, { Version("24w11a"), Version("24w11a") } }, { 30, { Version("24w12a"), Version("23w12a") } }, { 31, { Version("24w13a"), Version("1.20.5-pre3") } }, { 32, { Version("1.20.5-pre4"), Version("1.20.6") } }, { 33, { Version("24w18a"), Version("24w20a") } }, { 34, { Version("24w21a"), Version("1.21") } } }; void ResourcePack::setPackFormat(int new_format_id) { QMutexLocker locker(&m_data_lock); if (!s_pack_format_versions.contains(new_format_id)) { qWarning() << "Pack format '" << new_format_id << "' is not a recognized resource pack id!"; } m_pack_format = new_format_id; } void ResourcePack::setDescription(QString new_description) { QMutexLocker locker(&m_data_lock); m_description = new_description; } void ResourcePack::setImage(QImage new_image) const { QMutexLocker locker(&m_data_lock); Q_ASSERT(!new_image.isNull()); if (m_pack_image_cache_key.key.isValid()) 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, Qt::SmoothTransformation)); m_pack_image_cache_key.key = PixmapCache::instance().insert(pixmap); m_pack_image_cache_key.was_ever_used = true; // This can happen if the pixmap is too big to fit in the cache :c if (!m_pack_image_cache_key.key.isValid()) { qWarning() << "Could not insert a image cache entry! Ignoring it."; m_pack_image_cache_key.was_ever_used = false; } } QPixmap ResourcePack::image(QSize size, Qt::AspectRatioMode mode) const { QPixmap cached_image; if (PixmapCache::instance().find(m_pack_image_cache_key.key, &cached_image)) { if (size.isNull()) return cached_image; return cached_image.scaled(size, mode, Qt::SmoothTransformation); } // No valid image we can get if (!m_pack_image_cache_key.was_ever_used) { return {}; } else { qDebug() << "Resource Pack" << name() << "Had it's image evicted from the cache. reloading..."; PixmapCache::markCacheMissByEviciton(); } // Imaged got evicted from the cache. Re-process it and retry. ResourcePackUtils::processPackPNG(*this); return image(size); } std::pair<Version, Version> ResourcePack::compatibleVersions() const { if (!s_pack_format_versions.contains(m_pack_format)) { return { {}, {} }; } return s_pack_format_versions.constFind(m_pack_format).value(); } int ResourcePack::compare(const Resource& other, SortType type) const { auto const& cast_other = static_cast<ResourcePack const&>(other); switch (type) { default: return Resource::compare(other, type); case SortType::PACK_FORMAT: { auto this_ver = packFormat(); auto other_ver = cast_other.packFormat(); if (this_ver > other_ver) return 1; if (this_ver < other_ver) return -1; break; } } return 0; } bool ResourcePack::applyFilter(QRegularExpression filter) const { if (filter.match(description()).hasMatch()) return true; if (filter.match(QString::number(packFormat())).hasMatch()) return true; if (filter.match(compatibleVersions().first.toString()).hasMatch()) return true; if (filter.match(compatibleVersions().second.toString()).hasMatch()) return true; return Resource::applyFilter(filter); } bool ResourcePack::valid() const { return m_pack_format != 0; }
5,400
C++
.cpp
118
40.466102
132
0.613511
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,186
WorldSave.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/mod/WorldSave.cpp
// SPDX-FileCopyrightText: 2022 Rachel Powers <508861+Ryex@users.noreply.github.com> // // SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Rachel Powers <508861+Ryex@users.noreply.github.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "WorldSave.h" #include "minecraft/mod/tasks/LocalWorldSaveParseTask.h" void WorldSave::setSaveFormat(WorldSaveFormat new_save_format) { QMutexLocker locker(&m_data_lock); m_save_format = new_save_format; } void WorldSave::setSaveDirName(QString dir_name) { QMutexLocker locker(&m_data_lock); m_save_dir_name = dir_name; } bool WorldSave::valid() const { return m_save_format != WorldSaveFormat::INVALID; }
1,290
C++
.cpp
35
34.628571
84
0.757017
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,187
DataPack.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/mod/DataPack.cpp
// SPDX-FileCopyrightText: 2022 Rachel Powers <508861+Ryex@users.noreply.github.com> // // SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Rachel Powers <508861+Ryex@users.noreply.github.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "DataPack.h" #include <QDebug> #include <QMap> #include <QRegularExpression> #include "Version.h" // Values taken from: // https://minecraft.wiki/w/Pack_format#List_of_data_pack_formats 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") } }, { 8, { Version("1.18"), Version("1.18.1") } }, { 9, { Version("1.18.2"), Version("1.18.2") } }, { 10, { Version("1.19"), Version("1.19.3") } }, { 11, { Version("23w03a"), Version("23w05a") } }, { 12, { Version("1.19.4"), Version("1.19.4") } }, { 13, { Version("23w12a"), Version("23w14a") } }, { 14, { Version("23w16a"), Version("23w17a") } }, { 15, { Version("1.20"), Version("1.20.1") } }, { 16, { Version("23w31a"), Version("23w31a") } }, { 17, { Version("23w32a"), Version("23w35a") } }, { 18, { Version("1.20.2"), Version("1.20.2") } }, { 19, { Version("23w40a"), Version("23w40a") } }, { 20, { Version("23w41a"), Version("23w41a") } }, { 21, { Version("23w42a"), Version("23w42a") } }, { 22, { Version("23w43a"), Version("23w43b") } }, { 23, { Version("23w44a"), Version("23w44a") } }, { 24, { Version("23w45a"), Version("23w45a") } }, { 25, { Version("23w46a"), Version("23w46a") } }, { 26, { Version("1.20.3"), Version("1.20.4") } }, { 27, { Version("23w51a"), Version("23w51b") } }, { 28, { Version("24w05a"), Version("24w05b") } }, { 29, { Version("24w04a"), Version("24w04a") } }, { 30, { Version("24w05a"), Version("24w05b") } }, { 31, { Version("24w06a"), Version("24w06a") } }, { 32, { Version("24w07a"), Version("24w07a") } }, { 33, { Version("24w09a"), Version("24w09a") } }, { 34, { Version("24w10a"), Version("24w10a") } }, { 35, { Version("24w11a"), Version("24w11a") } }, { 36, { Version("24w12a"), Version("24w12a") } }, { 37, { Version("24w13a"), Version("24w13a") } }, { 38, { Version("24w14a"), Version("24w14a") } }, { 39, { Version("1.20.5-pre1"), Version("1.20.5-pre1") } }, { 40, { Version("1.20.5-pre2"), Version("1.20.5-pre2") } }, { 41, { Version("1.20.5"), Version("1.20.6") } }, { 42, { Version("24w18a"), Version("24w18a") } }, { 43, { Version("24w19a"), Version("24w19b") } }, { 44, { Version("24w20a"), Version("24w20a") } }, { 45, { Version("21w21a"), Version("21w21b") } }, { 46, { Version("1.21-pre1"), Version("1.21-pre1") } }, { 47, { Version("1.21-pre2"), Version("1.21-pre2") } }, { 48, { Version("1.21"), Version("1.21") } } }; void DataPack::setPackFormat(int new_format_id) { QMutexLocker locker(&m_data_lock); if (!s_pack_format_versions.contains(new_format_id)) { qWarning() << "Pack format '" << new_format_id << "' is not a recognized data pack id!"; } m_pack_format = new_format_id; } void DataPack::setDescription(QString new_description) { QMutexLocker locker(&m_data_lock); m_description = new_description; } std::pair<Version, Version> DataPack::compatibleVersions() const { if (!s_pack_format_versions.contains(m_pack_format)) { return { {}, {} }; } return s_pack_format_versions.constFind(m_pack_format).value(); } int DataPack::compare(const Resource& other, SortType type) const { auto const& cast_other = static_cast<DataPack const&>(other); switch (type) { default: return Resource::compare(other, type); case SortType::PACK_FORMAT: { auto this_ver = packFormat(); auto other_ver = cast_other.packFormat(); if (this_ver > other_ver) return 1; if (this_ver < other_ver) return -1; break; } } return 0; } bool DataPack::applyFilter(QRegularExpression filter) const { if (filter.match(description()).hasMatch()) return true; if (filter.match(QString::number(packFormat())).hasMatch()) return true; if (filter.match(compatibleVersions().first.toString()).hasMatch()) return true; if (filter.match(compatibleVersions().second.toString()).hasMatch()) return true; return Resource::applyFilter(filter); } bool DataPack::valid() const { return m_pack_format != 0; }
8,577
C++
.cpp
125
37.52
138
0.366299
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,188
Mod.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/mod/Mod.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "Mod.h" #include <qpixmap.h> #include <QDir> #include <QRegularExpression> #include <QString> #include "MTPixmapCache.h" #include "MetadataHandler.h" #include "Resource.h" #include "Version.h" #include "minecraft/mod/ModDetails.h" #include "minecraft/mod/tasks/LocalModParseTask.h" Mod::Mod(const QFileInfo& file) : Resource(file), m_local_details() { m_enabled = (file.suffix() != "disabled"); } void Mod::setDetails(const ModDetails& details) { m_local_details = details; } int Mod::compare(const Resource& other, SortType type) const { auto cast_other = dynamic_cast<Mod const*>(&other); if (!cast_other) return Resource::compare(other, type); switch (type) { default: case SortType::ENABLED: case SortType::NAME: case SortType::DATE: case SortType::SIZE: return Resource::compare(other, type); case SortType::VERSION: { auto this_ver = Version(version()); auto other_ver = Version(cast_other->version()); if (this_ver > other_ver) return 1; if (this_ver < other_ver) return -1; break; } case SortType::SIDE: { auto compare_result = QString::compare(side(), cast_other->side(), Qt::CaseInsensitive); if (compare_result != 0) return compare_result; break; } case SortType::MC_VERSIONS: { auto compare_result = QString::compare(mcVersions(), cast_other->mcVersions(), Qt::CaseInsensitive); if (compare_result != 0) return compare_result; break; } case SortType::LOADERS: { auto compare_result = QString::compare(loaders(), cast_other->loaders(), Qt::CaseInsensitive); if (compare_result != 0) return compare_result; break; } case SortType::RELEASE_TYPE: { auto compare_result = QString::compare(releaseType(), cast_other->releaseType(), Qt::CaseInsensitive); if (compare_result != 0) return compare_result; break; } } return 0; } bool Mod::applyFilter(QRegularExpression filter) const { if (filter.match(description()).hasMatch()) return true; for (auto& author : authors()) { if (filter.match(author).hasMatch()) { return true; } } return Resource::applyFilter(filter); } auto Mod::details() const -> const ModDetails& { return m_local_details; } auto Mod::name() const -> QString { auto d_name = details().name; if (!d_name.isEmpty()) return d_name; return Resource::name(); } auto Mod::version() const -> QString { return details().version; } auto Mod::homepage() const -> QString { QString metaUrl = Resource::homepage(); if (metaUrl.isEmpty()) return details().homeurl; else return metaUrl; } auto Mod::loaders() const -> QString { if (metadata()) { QStringList loaders; auto modLoaders = metadata()->loaders; for (auto loader : { ModPlatform::NeoForge, ModPlatform::Forge, ModPlatform::Cauldron, ModPlatform::LiteLoader, ModPlatform::Fabric, ModPlatform::Quilt }) { if (modLoaders & loader) { loaders << getModLoaderAsString(loader); } } return loaders.join(", "); } return {}; } auto Mod::side() const -> QString { if (metadata()) return Metadata::modSideToString(metadata()->side); return Metadata::modSideToString(Metadata::ModSide::UniversalSide); } auto Mod::mcVersions() const -> QString { if (metadata()) return metadata()->mcVersions.join(", "); return {}; } auto Mod::releaseType() const -> QString { if (metadata()) return metadata()->releaseType.toString(); return ModPlatform::IndexedVersionType().toString(); } auto Mod::description() const -> QString { return details().description; } auto Mod::authors() const -> QStringList { return details().authors; } void Mod::finishResolvingWithDetails(ModDetails&& details) { m_is_resolving = false; m_is_resolved = true; m_local_details = std::move(details); if (!iconPath().isEmpty()) { m_packImageCacheKey.wasReadAttempt = false; } } auto Mod::licenses() const -> const QList<ModLicense>& { return details().licenses; } auto Mod::issueTracker() const -> QString { return details().issue_tracker; } QPixmap Mod::setIcon(QImage new_image) const { QMutexLocker locker(&m_data_lock); Q_ASSERT(!new_image.isNull()); if (m_packImageCacheKey.key.isValid()) PixmapCache::remove(m_packImageCacheKey.key); // scale the image to avoid flooding the pixmapcache auto pixmap = QPixmap::fromImage(new_image.scaled({ 64, 64 }, Qt::AspectRatioMode::KeepAspectRatioByExpanding, Qt::SmoothTransformation)); m_packImageCacheKey.key = PixmapCache::insert(pixmap); m_packImageCacheKey.wasEverUsed = true; m_packImageCacheKey.wasReadAttempt = true; return pixmap; } QPixmap Mod::icon(QSize size, Qt::AspectRatioMode mode) const { auto pixmap_transform = [&size, &mode](QPixmap pixmap) { if (size.isNull()) return pixmap; return pixmap.scaled(size, mode, Qt::SmoothTransformation); }; QPixmap cached_image; if (PixmapCache::find(m_packImageCacheKey.key, &cached_image)) { return pixmap_transform(cached_image); } // No valid image we can get if ((!m_packImageCacheKey.wasEverUsed && m_packImageCacheKey.wasReadAttempt) || iconPath().isEmpty()) return {}; if (m_packImageCacheKey.wasEverUsed) { qDebug() << "Mod" << name() << "Had it's icon evicted from the cache. reloading..."; PixmapCache::markCacheMissByEviciton(); } // Image got evicted from the cache or an attempt to load it has not been made. load it and retry. m_packImageCacheKey.wasReadAttempt = true; if (ModUtils::loadIconFile(*this, &cached_image)) { return pixmap_transform(cached_image); } // Image failed to load return {}; } bool Mod::valid() const { return !m_local_details.mod_id.isEmpty(); }
7,934
C++
.cpp
239
27.8159
140
0.657479
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,189
ModFolderModel.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/mod/ModFolderModel.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ModFolderModel.h" #include <FileSystem.h> #include <QDebug> #include <QFileSystemWatcher> #include <QHeaderView> #include <QIcon> #include <QMimeData> #include <QString> #include <QStyle> #include <QThreadPool> #include <QUrl> #include <QUuid> #include "Application.h" #include "minecraft/mod/tasks/LocalModParseTask.h" ModFolderModel::ModFolderModel(const QDir& dir, BaseInstance* instance, bool is_indexed, bool create_dir, QObject* parent) : ResourceFolderModel(QDir(dir), instance, is_indexed, create_dir, parent) { m_column_names = QStringList({ "Enable", "Image", "Name", "Version", "Last Modified", "Provider", "Size", "Side", "Loaders", "Minecraft Versions", "Release Type" }); m_column_names_translated = QStringList({ tr("Enable"), tr("Image"), tr("Name"), tr("Version"), tr("Last Modified"), tr("Provider"), tr("Size"), tr("Side"), tr("Loaders"), tr("Minecraft Versions"), tr("Release Type") }); m_column_sort_keys = { SortType::ENABLED, SortType::NAME, SortType::NAME, SortType::VERSION, SortType::DATE, SortType::PROVIDER, SortType::SIZE, SortType::SIDE, SortType::LOADERS, SortType::MC_VERSIONS, SortType::RELEASE_TYPE }; m_column_resize_modes = { QHeaderView::Interactive, QHeaderView::Interactive, QHeaderView::Stretch, QHeaderView::Interactive, QHeaderView::Interactive, QHeaderView::Interactive, QHeaderView::Interactive, QHeaderView::Interactive, QHeaderView::Interactive, QHeaderView::Interactive, QHeaderView::Interactive }; m_columnsHideable = { false, true, false, true, true, true, true, true, true, true, true }; m_columnsHiddenByDefault = { false, false, false, false, false, false, false, true, true, true, true }; } QVariant ModFolderModel::data(const QModelIndex& index, int role) const { if (!validateIndex(index)) return {}; int row = index.row(); int column = index.column(); switch (role) { case Qt::DisplayRole: switch (column) { case NameColumn: return m_resources[row]->name(); case VersionColumn: { switch (at(row).type()) { case ResourceType::FOLDER: return tr("Folder"); case ResourceType::SINGLEFILE: return tr("File"); default: break; } return at(row).version(); } case DateColumn: return at(row).dateTimeChanged(); case ProviderColumn: { return at(row).provider(); } case SideColumn: { return at(row).side(); } case LoadersColumn: { return at(row).loaders(); } case McVersionsColumn: { return at(row).mcVersions(); } case ReleaseTypeColumn: { return at(row).releaseType(); } case SizeColumn: return at(row).sizeStr(); default: return QVariant(); } case Qt::ToolTipRole: if (column == NameColumn) { if (at(row).isSymLinkUnder(instDirPath())) { return m_resources[row]->internal_id() + tr("\nWarning: This resource is symbolically linked from elsewhere. Editing it will also change the original." "\nCanonical Path: %1") .arg(at(row).fileinfo().canonicalFilePath()); } if (at(row).isMoreThanOneHardLink()) { return m_resources[row]->internal_id() + tr("\nWarning: This resource is hard linked elsewhere. Editing it will also change the original."); } } return m_resources[row]->internal_id(); case Qt::DecorationRole: { if (column == NameColumn && (at(row).isSymLinkUnder(instDirPath()) || at(row).isMoreThanOneHardLink())) return APPLICATION->getThemedIcon("status-yellow"); if (column == ImageColumn) { return at(row).icon({ 32, 32 }, Qt::AspectRatioMode::KeepAspectRatioByExpanding); } return {}; } case Qt::SizeHintRole: if (column == ImageColumn) { return QSize(32, 32); } return {}; case Qt::CheckStateRole: switch (column) { case ActiveColumn: return at(row).enabled() ? Qt::Checked : Qt::Unchecked; default: return QVariant(); } default: return QVariant(); } } QVariant ModFolderModel::headerData(int section, [[maybe_unused]] Qt::Orientation orientation, int role) const { switch (role) { case Qt::DisplayRole: switch (section) { case ActiveColumn: case NameColumn: case VersionColumn: case DateColumn: case ProviderColumn: case ImageColumn: case SideColumn: case LoadersColumn: case McVersionsColumn: case ReleaseTypeColumn: case SizeColumn: return columnNames().at(section); default: return QVariant(); } case Qt::ToolTipRole: switch (section) { case ActiveColumn: return tr("Is the mod enabled?"); case NameColumn: return tr("The name of the mod."); case VersionColumn: return tr("The version of the mod."); case DateColumn: return tr("The date and time this mod was last changed (or added)."); case ProviderColumn: return tr("The source provider of the mod."); case SideColumn: return tr("On what environment the mod is running."); case LoadersColumn: return tr("The mod loader."); case McVersionsColumn: return tr("The supported minecraft versions."); case ReleaseTypeColumn: return tr("The release type."); case SizeColumn: return tr("The size of the mod."); default: return QVariant(); } default: return QVariant(); } return QVariant(); } int ModFolderModel::columnCount(const QModelIndex& parent) const { return parent.isValid() ? 0 : NUM_COLUMNS; } Task* ModFolderModel::createParseTask(Resource& resource) { return new LocalModParseTask(m_next_resolution_ticket, resource.type(), resource.fileinfo()); } bool ModFolderModel::isValid() { return m_dir.exists() && m_dir.isReadable(); } void ModFolderModel::onParseSucceeded(int ticket, QString mod_id) { auto iter = m_active_parse_tasks.constFind(ticket); if (iter == m_active_parse_tasks.constEnd()) return; int row = m_resources_index[mod_id]; auto parse_task = *iter; auto cast_task = static_cast<LocalModParseTask*>(parse_task.get()); Q_ASSERT(cast_task->token() == ticket); auto resource = find(mod_id); auto result = cast_task->result(); if (result && resource) static_cast<Mod*>(resource.get())->finishResolvingWithDetails(std::move(result->details)); emit dataChanged(index(row), index(row, columnCount(QModelIndex()) - 1)); }
9,682
C++
.cpp
225
31.697778
137
0.571747
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,190
TexturePackFolderModel.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/mod/TexturePackFolderModel.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 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 <QCoreApplication> #include "Application.h" #include "TexturePackFolderModel.h" #include "minecraft/mod/tasks/LocalTexturePackParseTask.h" #include "minecraft/mod/tasks/ResourceFolderLoadTask.h" TexturePackFolderModel::TexturePackFolderModel(const QDir& dir, BaseInstance* instance, bool is_indexed, bool create_dir, QObject* parent) : ResourceFolderModel(QDir(dir), instance, is_indexed, create_dir, parent) { m_column_names = QStringList({ "Enable", "Image", "Name", "Last Modified", "Provider", "Size" }); m_column_names_translated = QStringList({ tr("Enable"), tr("Image"), tr("Name"), tr("Last Modified"), tr("Provider"), tr("Size") }); m_column_sort_keys = { SortType::ENABLED, SortType::NAME, SortType::NAME, SortType::DATE, SortType::PROVIDER, SortType::SIZE }; m_column_resize_modes = { QHeaderView::Interactive, QHeaderView::Interactive, QHeaderView::Stretch, QHeaderView::Interactive, QHeaderView::Interactive, QHeaderView::Interactive }; m_columnsHideable = { false, true, false, true, true, true }; m_columnsHiddenByDefault = { false, false, false, false, false, true }; } Task* TexturePackFolderModel::createParseTask(Resource& resource) { return new LocalTexturePackParseTask(m_next_resolution_ticket, static_cast<TexturePack&>(resource)); } QVariant TexturePackFolderModel::data(const QModelIndex& index, int role) const { if (!validateIndex(index)) return {}; int row = index.row(); int column = index.column(); switch (role) { case Qt::DisplayRole: switch (column) { case NameColumn: return m_resources[row]->name(); case DateColumn: return m_resources[row]->dateTimeChanged(); case ProviderColumn: return m_resources[row]->provider(); case SizeColumn: return m_resources[row]->sizeStr(); default: return {}; } case Qt::ToolTipRole: if (column == NameColumn) { if (at(row).isSymLinkUnder(instDirPath())) { return m_resources[row]->internal_id() + tr("\nWarning: This resource is symbolically linked from elsewhere. Editing it will also change the original." "\nCanonical Path: %1") .arg(at(row).fileinfo().canonicalFilePath()); ; } if (at(row).isMoreThanOneHardLink()) { return m_resources[row]->internal_id() + tr("\nWarning: This resource is hard linked elsewhere. Editing it will also change the original."); } } return m_resources[row]->internal_id(); case Qt::DecorationRole: { if (column == NameColumn && (at(row).isSymLinkUnder(instDirPath()) || at(row).isMoreThanOneHardLink())) return APPLICATION->getThemedIcon("status-yellow"); if (column == ImageColumn) { return at(row).image({ 32, 32 }, Qt::AspectRatioMode::KeepAspectRatioByExpanding); } return {}; } case Qt::SizeHintRole: if (column == ImageColumn) { return QSize(32, 32); } return {}; case Qt::CheckStateRole: if (column == ActiveColumn) { return m_resources[row]->enabled() ? Qt::Checked : Qt::Unchecked; } return {}; default: return {}; } } QVariant TexturePackFolderModel::headerData(int section, [[maybe_unused]] Qt::Orientation orientation, int role) const { switch (role) { case Qt::DisplayRole: switch (section) { case ActiveColumn: case NameColumn: case DateColumn: case ImageColumn: case ProviderColumn: case SizeColumn: return columnNames().at(section); default: return {}; } case Qt::ToolTipRole: { switch (section) { case ActiveColumn: return tr("Is the texture pack enabled?"); case NameColumn: return tr("The name of the texture pack."); case DateColumn: return tr("The date and time this texture pack was last changed (or added)."); case ProviderColumn: return tr("The source provider of the texture pack."); case SizeColumn: return tr("The size of the texture pack."); default: return {}; } } default: break; } return {}; } int TexturePackFolderModel::columnCount(const QModelIndex& parent) const { return parent.isValid() ? 0 : NUM_COLUMNS; }
6,580
C++
.cpp
151
33.887417
183
0.606358
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,191
ResourcePackFolderModel.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/mod/ResourcePackFolderModel.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 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 "ResourcePackFolderModel.h" #include <qnamespace.h> #include <qsize.h> #include <QIcon> #include <QStyle> #include "Application.h" #include "Version.h" #include "minecraft/mod/tasks/LocalResourcePackParseTask.h" ResourcePackFolderModel::ResourcePackFolderModel(const QDir& dir, BaseInstance* instance, bool is_indexed, bool create_dir, QObject* parent) : ResourceFolderModel(dir, instance, is_indexed, create_dir, parent) { m_column_names = QStringList({ "Enable", "Image", "Name", "Pack Format", "Last Modified", "Provider", "Size" }); m_column_names_translated = QStringList({ tr("Enable"), tr("Image"), tr("Name"), tr("Pack Format"), tr("Last Modified"), tr("Provider"), tr("Size") }); m_column_sort_keys = { SortType::ENABLED, SortType::NAME, SortType::NAME, SortType::PACK_FORMAT, SortType::DATE, SortType::PROVIDER, SortType::SIZE }; m_column_resize_modes = { QHeaderView::Interactive, QHeaderView::Interactive, QHeaderView::Stretch, QHeaderView::Interactive, QHeaderView::Interactive, QHeaderView::Interactive, QHeaderView::Interactive }; m_columnsHideable = { false, true, false, true, true, true, true }; } QVariant ResourcePackFolderModel::data(const QModelIndex& index, int role) const { if (!validateIndex(index)) return {}; int row = index.row(); int column = index.column(); switch (role) { case Qt::DisplayRole: switch (column) { case NameColumn: return m_resources[row]->name(); case PackFormatColumn: { auto& resource = at(row); auto pack_format = resource.packFormat(); if (pack_format == 0) return tr("Unrecognized"); auto version_bounds = resource.compatibleVersions(); if (version_bounds.first.toString().isEmpty()) return QString::number(pack_format); return QString("%1 (%2 - %3)") .arg(QString::number(pack_format), version_bounds.first.toString(), version_bounds.second.toString()); } case DateColumn: return m_resources[row]->dateTimeChanged(); case ProviderColumn: return m_resources[row]->provider(); case SizeColumn: return m_resources[row]->sizeStr(); default: return {}; } case Qt::DecorationRole: { if (column == NameColumn && (at(row).isSymLinkUnder(instDirPath()) || at(row).isMoreThanOneHardLink())) return APPLICATION->getThemedIcon("status-yellow"); if (column == ImageColumn) { return at(row).image({ 32, 32 }, Qt::AspectRatioMode::KeepAspectRatioByExpanding); } return {}; } case Qt::ToolTipRole: { if (column == PackFormatColumn) { //: The string being explained by this is in the format: ID (Lower version - Upper version) return tr("The resource pack format ID, as well as the Minecraft versions it was designed for."); } if (column == NameColumn) { if (at(row).isSymLinkUnder(instDirPath())) { return m_resources[row]->internal_id() + tr("\nWarning: This resource is symbolically linked from elsewhere. Editing it will also change the original." "\nCanonical Path: %1") .arg(at(row).fileinfo().canonicalFilePath()); ; } if (at(row).isMoreThanOneHardLink()) { return m_resources[row]->internal_id() + tr("\nWarning: This resource is hard linked elsewhere. Editing it will also change the original."); } } return m_resources[row]->internal_id(); } case Qt::SizeHintRole: if (column == ImageColumn) { return QSize(32, 32); } return {}; case Qt::CheckStateRole: switch (column) { case ActiveColumn: return at(row).enabled() ? Qt::Checked : Qt::Unchecked; default: return {}; } default: return {}; } } QVariant ResourcePackFolderModel::headerData(int section, [[maybe_unused]] Qt::Orientation orientation, int role) const { switch (role) { case Qt::DisplayRole: switch (section) { case ActiveColumn: case NameColumn: case PackFormatColumn: case DateColumn: case ImageColumn: case ProviderColumn: case SizeColumn: return columnNames().at(section); default: return {}; } case Qt::ToolTipRole: switch (section) { case ActiveColumn: return tr("Is the resource pack enabled?"); case NameColumn: return tr("The name of the resource pack."); case PackFormatColumn: //: The string being explained by this is in the format: ID (Lower version - Upper version) return tr("The resource pack format ID, as well as the Minecraft versions it was designed for."); case DateColumn: return tr("The date and time this resource pack was last changed (or added)."); case ProviderColumn: return tr("The source provider of the resource pack."); case SizeColumn: return tr("The size of the resource pack."); default: return {}; } case Qt::SizeHintRole: if (section == ImageColumn) { return QSize(64, 0); } return {}; default: return {}; } } int ResourcePackFolderModel::columnCount(const QModelIndex& parent) const { return parent.isValid() ? 0 : NUM_COLUMNS; } Task* ResourcePackFolderModel::createParseTask(Resource& resource) { return new LocalResourcePackParseTask(m_next_resolution_ticket, static_cast<ResourcePack&>(resource)); }
8,109
C++
.cpp
181
33.707182
140
0.585166
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,192
ShaderPack.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/mod/ShaderPack.cpp
// SPDX-FileCopyrightText: 2022 Rachel Powers <508861+Ryex@users.noreply.github.com> // // SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Rachel Powers <508861+Ryex@users.noreply.github.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "ShaderPack.h" #include <QRegularExpression> void ShaderPack::setPackFormat(ShaderPackFormat new_format) { QMutexLocker locker(&m_data_lock); m_pack_format = new_format; } bool ShaderPack::valid() const { return m_pack_format != ShaderPackFormat::INVALID; }
1,133
C++
.cpp
30
35.633333
84
0.758212
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,193
GetModDependenciesTask.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/mod/tasks/GetModDependenciesTask.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "GetModDependenciesTask.h" #include <QDebug> #include <algorithm> #include <memory> #include "Json.h" #include "QObjectPtr.h" #include "minecraft/PackProfile.h" #include "minecraft/mod/MetadataHandler.h" #include "modplatform/ModIndex.h" #include "modplatform/ResourceAPI.h" #include "modplatform/flame/FlameAPI.h" #include "modplatform/modrinth/ModrinthAPI.h" #include "tasks/SequentialTask.h" #include "ui/pages/modplatform/ModModel.h" #include "ui/pages/modplatform/flame/FlameResourceModels.h" #include "ui/pages/modplatform/modrinth/ModrinthResourceModels.h" static Version mcVersion(BaseInstance* inst) { return static_cast<MinecraftInstance*>(inst)->getPackProfile()->getComponent("net.minecraft")->getVersion(); } static ModPlatform::ModLoaderTypes mcLoaders(BaseInstance* inst) { return static_cast<MinecraftInstance*>(inst)->getPackProfile()->getSupportedModLoaders().value(); } static bool checkDependencies(std::shared_ptr<GetModDependenciesTask::PackDependency> sel, Version mcVersion, ModPlatform::ModLoaderTypes loaders) { return (sel->pack->versions.isEmpty() || sel->version.mcVersion.contains(mcVersion.toString())) && (!loaders || !sel->version.loaders || sel->version.loaders & loaders); } GetModDependenciesTask::GetModDependenciesTask(BaseInstance* instance, ModFolderModel* folder, QList<std::shared_ptr<PackDependency>> selected) : SequentialTask(tr("Get dependencies")) , m_selected(selected) , m_flame_provider{ ModPlatform::ResourceProvider::FLAME, std::make_shared<ResourceDownload::FlameModModel>(*instance), std::make_shared<FlameAPI>() } , m_modrinth_provider{ ModPlatform::ResourceProvider::MODRINTH, std::make_shared<ResourceDownload::ModrinthModModel>(*instance), std::make_shared<ModrinthAPI>() } , m_version(mcVersion(instance)) , m_loaderType(mcLoaders(instance)) { for (auto mod : folder->allMods()) { m_mods_file_names << mod->fileinfo().fileName(); if (auto meta = mod->metadata(); meta) m_mods.append(meta); } prepare(); } void GetModDependenciesTask::prepare() { for (auto sel : m_selected) { if (checkDependencies(sel, m_version, m_loaderType)) for (auto dep : getDependenciesForVersion(sel->version, sel->pack->provider)) { addTask(prepareDependencyTask(dep, sel->pack->provider, 20)); } } } ModPlatform::Dependency GetModDependenciesTask::getOverride(const ModPlatform::Dependency& dep, const ModPlatform::ResourceProvider providerName) { 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); }); if (over != overide.cend()) { return { isQuilt ? over->quilt : over->fabric, dep.type }; } } return dep; } QList<ModPlatform::Dependency> GetModDependenciesTask::getDependenciesForVersion(const ModPlatform::IndexedVersion& version, const ModPlatform::ResourceProvider providerName) { QList<ModPlatform::Dependency> c_dependencies; 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) { return isOnlyVersion ? i.version == ver_dep.version : i.addonId == ver_dep.addonId; }); dep != c_dependencies.end()) continue; // check the current dependency list if (auto dep = std::find_if(m_selected.begin(), m_selected.end(), [&ver_dep, providerName, isOnlyVersion](std::shared_ptr<PackDependency> i) { return i->pack->provider == providerName && (isOnlyVersion ? i->version.version == ver_dep.version : i->pack->addonId == ver_dep.addonId); }); dep != m_selected.end()) continue; // check the selected versions if (auto dep = std::find_if(m_mods.begin(), m_mods.end(), [&ver_dep, providerName, isOnlyVersion](std::shared_ptr<Metadata::ModStruct> i) { return i->provider == providerName && (isOnlyVersion ? i->file_id == ver_dep.version : i->project_id == ver_dep.addonId); }); dep != m_mods.end()) continue; // check the existing mods if (auto dep = std::find_if(m_pack_dependencies.begin(), m_pack_dependencies.end(), [&ver_dep, providerName, isOnlyVersion](std::shared_ptr<PackDependency> i) { return i->pack->provider == providerName && (isOnlyVersion ? i->version.version == ver_dep.addonId : i->pack->addonId == ver_dep.addonId); }); dep != m_pack_dependencies.end()) // check loaded dependencies continue; c_dependencies.append(ver_dep); } return c_dependencies; } Task::Ptr GetModDependenciesTask::getProjectInfoTask(std::shared_ptr<PackDependency> pDep) { auto provider = pDep->pack->provider == m_flame_provider.name ? m_flame_provider : m_modrinth_provider; auto responseInfo = std::make_shared<QByteArray>(); auto info = provider.api->getProject(pDep->pack->addonId.toString(), responseInfo); QObject::connect(info.get(), &NetJob::succeeded, [this, responseInfo, provider, pDep] { QJsonParseError parse_error{}; QJsonDocument doc = QJsonDocument::fromJson(*responseInfo, &parse_error); if (parse_error.error != QJsonParseError::NoError) { removePack(pDep->pack->addonId); qWarning() << "Error while parsing JSON response for mod info at " << parse_error.offset << " reason: " << parse_error.errorString(); qDebug() << *responseInfo; return; } try { auto obj = provider.name == ModPlatform::ResourceProvider::FLAME ? Json::requireObject(Json::requireObject(doc), "data") : Json::requireObject(doc); provider.mod->loadIndexedPack(*pDep->pack, obj); } catch (const JSONValidationError& e) { removePack(pDep->pack->addonId); qDebug() << doc; qWarning() << "Error while reading mod info: " << e.cause(); } }); return info; } Task::Ptr GetModDependenciesTask::prepareDependencyTask(const ModPlatform::Dependency& dep, const ModPlatform::ResourceProvider providerName, int level) { auto pDep = std::make_shared<PackDependency>(); pDep->dependency = dep; pDep->pack = std::make_shared<ModPlatform::IndexedPack>(); pDep->pack->addonId = dep.addonId; pDep->pack->provider = providerName; m_pack_dependencies.append(pDep); auto provider = providerName == m_flame_provider.name ? m_flame_provider : m_modrinth_provider; auto tasks = makeShared<SequentialTask>( QString("DependencyInfo: %1").arg(dep.addonId.toString().isEmpty() ? dep.version : dep.addonId.toString())); if (!dep.addonId.toString().isEmpty()) { tasks->addTask(getProjectInfoTask(pDep)); } ResourceAPI::DependencySearchArgs args = { dep, m_version, m_loaderType }; ResourceAPI::DependencySearchCallbacks callbacks; callbacks.on_fail = [](QString reason, int) { qCritical() << tr("A network error occurred. Could not load project dependencies:%1").arg(reason); }; callbacks.on_succeed = [dep, provider, pDep, level, this](auto& doc, [[maybe_unused]] auto& pack) { try { QJsonArray arr; if (dep.version.length() != 0 && doc.isObject()) { arr.append(doc.object()); } else { arr = doc.isObject() ? Json::ensureArray(doc.object(), "data") : doc.array(); } pDep->version = provider.mod->loadDependencyVersions(dep, arr); if (!pDep->version.addonId.isValid()) { 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; }); if (over != overide.cend()) { removePack(dep.addonId); addTask(prepareDependencyTask({ over->fabric, dep.type }, provider.name, level)); return; } } removePack(dep.addonId); qWarning() << "Error while reading mod version empty "; qDebug() << doc; return; } pDep->version.is_currently_selected = true; pDep->pack->versions = { pDep->version }; pDep->pack->versionsLoaded = true; } catch (const JSONValidationError& e) { removePack(dep.addonId); qDebug() << doc; qWarning() << "Error while reading mod version: " << e.cause(); return; } if (level == 0) { removePack(dep.addonId); 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) { removePack(pDep->version.addonId); addTask(prepareDependencyTask(dep_, provider.name, level)); } else { addTask(getProjectInfoTask(pDep)); } } if (isLocalyInstalled(pDep)) { removePack(pDep->version.addonId); return; } 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) { auto pred = [addonId](const std::shared_ptr<PackDependency>& v) { return v->pack->addonId == addonId; }; #if QT_VERSION >= QT_VERSION_CHECK(6, 1, 0) m_pack_dependencies.removeIf(pred); #else for (auto it = m_pack_dependencies.begin(); it != m_pack_dependencies.end();) if (pred(*it)) it = m_pack_dependencies.erase(it); else ++it; #endif } auto GetModDependenciesTask::getExtraInfo() -> QHash<QString, PackDependencyExtraInfo> { QHash<QString, PackDependencyExtraInfo> 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()] = { maybeInstalled(mod), req }; } return rby; } // super lax compare (but not fuzzy) // convert to lowercase // convert all speratores to whitespace // simplify sequence of internal whitespace to a single space // efectivly compare two strings ignoring all separators and case auto laxCompare = [](QString fsfilename, QString metadataFilename, bool excludeDigits = false) { // allowed character seperators QList<QChar> allowedSeperators = { '-', '+', '.', '_' }; if (excludeDigits) allowedSeperators.append({ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }); // copy in lowercase auto fsName = fsfilename.toLower(); auto metaName = metadataFilename.toLower(); // replace all potential allowed seperatores with whitespace for (auto sep : allowedSeperators) { fsName = fsName.replace(sep, ' '); metaName = metaName.replace(sep, ' '); } // remove extraneous whitespace fsName = fsName.simplified(); metaName = metaName.simplified(); return fsName.compare(metaName) == 0; }; bool GetModDependenciesTask::isLocalyInstalled(std::shared_ptr<PackDependency> pDep) { return pDep->version.fileName.isEmpty() || std::find_if(m_selected.begin(), m_selected.end(), [pDep](std::shared_ptr<PackDependency> i) { return !i->version.fileName.isEmpty() && laxCompare(i->version.fileName, pDep->version.fileName); }) != m_selected.end() || // check the selected versions std::find_if(m_mods_file_names.begin(), m_mods_file_names.end(), [pDep](QString i) { return !i.isEmpty() && laxCompare(i, pDep->version.fileName); }) != m_mods_file_names.end() || // check the existing mods std::find_if(m_pack_dependencies.begin(), m_pack_dependencies.end(), [pDep](std::shared_ptr<PackDependency> i) { return pDep->pack->addonId != i->pack->addonId && !i->version.fileName.isEmpty() && laxCompare(pDep->version.fileName, i->version.fileName); }) != m_pack_dependencies.end(); // check loaded dependencies } bool GetModDependenciesTask::maybeInstalled(std::shared_ptr<PackDependency> pDep) { return std::find_if(m_mods_file_names.begin(), m_mods_file_names.end(), [pDep](QString i) { return !i.isEmpty() && laxCompare(i, pDep->version.fileName, true); }) != m_mods_file_names.end(); // check the existing mods }
16,711
C++
.cpp
324
39.552469
138
0.588174
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,194
LocalModParseTask.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/mod/tasks/LocalModParseTask.cpp
#include "LocalModParseTask.h" #include <qdcss.h> #include <quazip/quazip.h> #include <quazip/quazipfile.h> #include <toml++/toml.h> #include <QJsonArray> #include <QJsonDocument> #include <QJsonObject> #include <QJsonValue> #include <QString> #include "FileSystem.h" #include "Json.h" #include "minecraft/mod/ModDetails.h" #include "settings/INIFile.h" namespace ModUtils { // NEW format // https://github.com/MinecraftForge/FML/wiki/FML-mod-information-file/c8d8f1929aff9979e322af79a59ce81f3e02db6a // OLD format: // https://github.com/MinecraftForge/FML/wiki/FML-mod-information-file/5bf6a2d05145ec79387acc0d45c958642fb049fc ModDetails ReadMCModInfo(QByteArray contents) { auto getInfoFromArray = [](QJsonArray arr) -> ModDetails { if (!arr.at(0).isObject()) { return {}; } ModDetails details; auto firstObj = arr.at(0).toObject(); details.mod_id = firstObj.value("modid").toString(); auto name = firstObj.value("name").toString(); // NOTE: ignore stupid example mods copies where the author didn't even bother to change the name if (name != "Example Mod") { details.name = name; } details.version = firstObj.value("version").toString(); auto homeurl = firstObj.value("url").toString().trimmed(); if (!homeurl.isEmpty()) { // fix up url. if (!homeurl.startsWith("http://") && !homeurl.startsWith("https://") && !homeurl.startsWith("ftp://")) { homeurl.prepend("http://"); } } details.homeurl = homeurl; details.description = firstObj.value("description").toString(); QJsonArray authors = firstObj.value("authorList").toArray(); if (authors.size() == 0) { // FIXME: what is the format of this? is there any? authors = firstObj.value("authors").toArray(); } if (firstObj.contains("logoFile")) { details.icon_file = firstObj.value("logoFile").toString(); } for (auto author : authors) { details.authors.append(author.toString()); } return details; }; QJsonParseError jsonError; QJsonDocument jsonDoc = QJsonDocument::fromJson(contents, &jsonError); // this is the very old format that had just the array if (jsonDoc.isArray()) { return getInfoFromArray(jsonDoc.array()); } else if (jsonDoc.isObject()) { auto val = jsonDoc.object().value("modinfoversion"); if (val.isUndefined()) { val = jsonDoc.object().value("modListVersion"); } int version = Json::ensureInteger(val, -1); // Some mods set the number with "", so it's a String instead if (version < 0) version = Json::ensureString(val, "").toInt(); if (version != 2) { qWarning() << QString(R"(The value of 'modListVersion' is "%1" (expected "2")! The file may be corrupted.)").arg(version); qWarning() << "The contents of 'mcmod.info' are as follows:"; qWarning() << contents; } auto arrVal = jsonDoc.object().value("modlist"); if (arrVal.isUndefined()) { arrVal = jsonDoc.object().value("modList"); } if (arrVal.isArray()) { return getInfoFromArray(arrVal.toArray()); } } return {}; } // https://github.com/MinecraftForge/Documentation/blob/5ab4ba6cf9abc0ac4c0abd96ad187461aefd72af/docs/gettingstarted/structuring.md ModDetails ReadMCModTOML(QByteArray contents) { ModDetails details; toml::table tomlData; #if TOML_EXCEPTIONS try { tomlData = toml::parse(contents.toStdString()); } catch ([[maybe_unused]] const toml::parse_error& err) { return {}; } #else toml::parse_result result = toml::parse(contents.toStdString()); if (!result) { return {}; } tomlData = result.table(); #endif // array defined by [[mods]] auto tomlModsArr = tomlData["mods"].as_array(); if (!tomlModsArr) { qWarning() << "Corrupted mods.toml? Couldn't find [[mods]] array!"; return {}; } // we only really care about the first element, since multiple mods in one file is not supported by us at the moment auto tomlModsTable0 = tomlModsArr->get(0); if (!tomlModsTable0) { qWarning() << "Corrupted mods.toml? [[mods]] didn't have an element at index 0!"; return {}; } auto modsTable = tomlModsTable0->as_table(); if (!modsTable) { qWarning() << "Corrupted mods.toml? [[mods]] was not a table!"; return {}; } // mandatory properties - always in [[mods]] if (auto modIdDatum = (*modsTable)["modId"].as_string()) { details.mod_id = QString::fromStdString(modIdDatum->get()); } if (auto versionDatum = (*modsTable)["version"].as_string()) { details.version = QString::fromStdString(versionDatum->get()); } if (auto displayNameDatum = (*modsTable)["displayName"].as_string()) { details.name = QString::fromStdString(displayNameDatum->get()); } if (auto descriptionDatum = (*modsTable)["description"].as_string()) { details.description = QString::fromStdString(descriptionDatum->get()); } // optional properties - can be in the root table or [[mods]] QString authors = ""; if (auto authorsDatum = tomlData["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); } QString homeurl = ""; if (auto homeurlDatum = tomlData["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://")) { homeurl.prepend("http://"); } details.homeurl = homeurl; QString issueTrackerURL = ""; if (auto issueTrackerURLDatum = tomlData["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 licenseDatumMods = (*modsTable)["license"].as_string()) { license = QString::fromStdString(licenseDatumMods->get()); } if (!license.isEmpty()) details.licenses.append(ModLicense(license)); QString logoFile = ""; if (auto logoFileDatum = tomlData["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; return details; } // https://fabricmc.net/wiki/documentation:fabric_mod_json ModDetails ReadFabricModInfo(QByteArray contents) { QJsonParseError jsonError; QJsonDocument jsonDoc = QJsonDocument::fromJson(contents, &jsonError); auto object = jsonDoc.object(); auto schemaVersion = object.contains("schemaVersion") ? object.value("schemaVersion").toInt(0) : 0; ModDetails details; details.mod_id = object.value("id").toString(); details.version = object.value("version").toString(); details.name = object.contains("name") ? object.value("name").toString() : details.mod_id; details.description = object.value("description").toString(); if (schemaVersion >= 1) { QJsonArray authors = object.value("authors").toArray(); for (auto author : authors) { if (author.isObject()) { details.authors.append(author.toObject().value("name").toString()); } else { details.authors.append(author.toString()); } } if (object.contains("contact")) { QJsonObject contact = object.value("contact").toObject(); if (contact.contains("homepage")) { details.homeurl = contact.value("homepage").toString(); } if (contact.contains("issues")) { details.issue_tracker = contact.value("issues").toString(); } } if (object.contains("license")) { auto license = object.value("license"); if (license.isArray()) { for (auto l : license.toArray()) { if (l.isString()) { details.licenses.append(ModLicense(l.toString())); } else if (l.isObject()) { auto obj = l.toObject(); details.licenses.append(ModLicense(obj.value("name").toString(), obj.value("id").toString(), obj.value("url").toString(), obj.value("description").toString())); } } } else if (license.isString()) { details.licenses.append(ModLicense(license.toString())); } else if (license.isObject()) { auto obj = license.toObject(); details.licenses.append(ModLicense(obj.value("name").toString(), obj.value("id").toString(), obj.value("url").toString(), obj.value("description").toString())); } } if (object.contains("icon")) { auto icon = object.value("icon"); if (icon.isObject()) { auto obj = icon.toObject(); // take the largest icon int largest = 0; for (auto key : obj.keys()) { auto size = key.split('x').first().toInt(); if (size > largest) { largest = size; } } if (largest > 0) { auto key = QString::number(largest) + "x" + QString::number(largest); details.icon_file = obj.value(key).toString(); } else { // parsing the sizes failed // take the first for (auto i : obj) { details.icon_file = i.toString(); break; } } } else if (icon.isString()) { details.icon_file = icon.toString(); } } } return details; } // https://github.com/QuiltMC/rfcs/blob/master/specification/0002-quilt.mod.json.md ModDetails ReadQuiltModInfo(QByteArray contents) { QJsonParseError jsonError; QJsonDocument jsonDoc = QJsonDocument::fromJson(contents, &jsonError); auto object = Json::requireObject(jsonDoc, "quilt.mod.json"); auto schemaVersion = Json::ensureInteger(object.value("schema_version"), 0, "Quilt schema_version"); ModDetails details; // https://github.com/QuiltMC/rfcs/blob/be6ba280d785395fefa90a43db48e5bfc1d15eb4/specification/0002-quilt.mod.json.md if (schemaVersion == 1) { auto modInfo = Json::requireObject(object.value("quilt_loader"), "Quilt mod info"); details.mod_id = Json::requireString(modInfo.value("id"), "Mod ID"); details.version = Json::requireString(modInfo.value("version"), "Mod version"); auto modMetadata = Json::ensureObject(modInfo.value("metadata")); details.name = Json::ensureString(modMetadata.value("name"), details.mod_id); details.description = Json::ensureString(modMetadata.value("description")); auto modContributors = Json::ensureObject(modMetadata.value("contributors")); // We don't really care about the role of a contributor here details.authors += modContributors.keys(); auto modContact = Json::ensureObject(modMetadata.value("contact")); if (modContact.contains("homepage")) { details.homeurl = Json::requireString(modContact.value("homepage")); } if (modContact.contains("issues")) { details.issue_tracker = Json::requireString(modContact.value("issues")); } if (modMetadata.contains("license")) { auto license = modMetadata.value("license"); if (license.isArray()) { for (auto l : license.toArray()) { if (l.isString()) { details.licenses.append(ModLicense(l.toString())); } else if (l.isObject()) { auto obj = l.toObject(); details.licenses.append(ModLicense(obj.value("name").toString(), obj.value("id").toString(), obj.value("url").toString(), obj.value("description").toString())); } } } else if (license.isString()) { details.licenses.append(ModLicense(license.toString())); } else if (license.isObject()) { auto obj = license.toObject(); details.licenses.append(ModLicense(obj.value("name").toString(), obj.value("id").toString(), obj.value("url").toString(), obj.value("description").toString())); } } if (modMetadata.contains("icon")) { auto icon = modMetadata.value("icon"); if (icon.isObject()) { auto obj = icon.toObject(); // take the largest icon int largest = 0; for (auto key : obj.keys()) { auto size = key.split('x').first().toInt(); if (size > largest) { largest = size; } } if (largest > 0) { auto key = QString::number(largest) + "x" + QString::number(largest); details.icon_file = obj.value(key).toString(); } else { // parsing the sizes failed // take the first for (auto i : obj) { details.icon_file = i.toString(); break; } } } else if (icon.isString()) { details.icon_file = icon.toString(); } } } return details; } ModDetails ReadForgeInfo(QByteArray contents) { ModDetails details; // Read the data details.name = "Minecraft Forge"; details.mod_id = "Forge"; details.homeurl = "http://www.minecraftforge.net/forum/"; INIFile ini; if (!ini.loadFile(contents)) return details; QString major = ini.get("forge.major.number", "0").toString(); QString minor = ini.get("forge.minor.number", "0").toString(); QString revision = ini.get("forge.revision.number", "0").toString(); QString build = ini.get("forge.build.number", "0").toString(); details.version = major + "." + minor + "." + revision + "." + build; return details; } ModDetails ReadLiteModInfo(QByteArray contents) { ModDetails details; QJsonParseError jsonError; QJsonDocument jsonDoc = QJsonDocument::fromJson(contents, &jsonError); auto object = jsonDoc.object(); if (object.contains("name")) { details.mod_id = details.name = object.value("name").toString(); } if (object.contains("version")) { details.version = object.value("version").toString(""); } else { details.version = object.value("revision").toString(""); } details.mcversion = object.value("mcversion").toString(); auto author = object.value("author").toString(); if (!author.isEmpty()) { details.authors.append(author); } details.description = object.value("description").toString(); details.homeurl = object.value("url").toString(); return details; } // https://git.sleeping.town/unascribed/NilLoader/src/commit/d7fc87b255fc31019ff90f80d45894927fac6efc/src/main/java/nilloader/api/NilMetadata.java#L64 ModDetails ReadNilModInfo(QByteArray contents, QString fname) { ModDetails details; QDCSS cssData = QDCSS(contents); auto name = cssData.get("@nilmod.name"); auto desc = cssData.get("@nilmod.description"); auto authors = cssData.get("@nilmod.authors"); if (name->has_value()) { details.name = name->value(); } if (desc->has_value()) { details.description = desc->value(); } if (authors->has_value()) { details.authors.append(authors->value()); } details.version = cssData.get("@nilmod.version")->value_or("?"); details.mod_id = fname.remove(".nilmod.css"); return details; } bool process(Mod& mod, ProcessingLevel level) { switch (mod.type()) { case ResourceType::FOLDER: return processFolder(mod, level); case ResourceType::ZIPFILE: return processZIP(mod, level); case ResourceType::LITEMOD: return processLitemod(mod); default: qWarning() << "Invalid type for mod parse task!"; return false; } } bool processZIP(Mod& mod, [[maybe_unused]] ProcessingLevel level) { ModDetails details; QuaZip zip(mod.fileinfo().filePath()); if (!zip.open(QuaZip::mdUnzip)) return false; QuaZipFile file(&zip); if (zip.setCurrentFile("META-INF/mods.toml") || zip.setCurrentFile("META-INF/neoforge.mods.toml")) { if (!file.open(QIODevice::ReadOnly)) { zip.close(); return false; } details = ReadMCModTOML(file.readAll()); file.close(); // to replace ${file.jarVersion} with the actual version, as needed if (details.version == "${file.jarVersion}") { if (zip.setCurrentFile("META-INF/MANIFEST.MF")) { if (!file.open(QIODevice::ReadOnly)) { zip.close(); return false; } // quick and dirty line-by-line parser auto manifestLines = file.readAll().split('\n'); QString manifestVersion = ""; for (auto& line : manifestLines) { if (QString(line).startsWith("Implementation-Version: ")) { manifestVersion = QString(line).remove("Implementation-Version: "); break; } } // some mods use ${projectversion} in their build.gradle, causing this mess to show up in MANIFEST.MF // also keep with forge's behavior of setting the version to "NONE" if none is found if (manifestVersion.contains("task ':jar' property 'archiveVersion'") || manifestVersion == "") { manifestVersion = "NONE"; } details.version = manifestVersion; file.close(); } } zip.close(); mod.setDetails(details); return true; } else if (zip.setCurrentFile("mcmod.info")) { if (!file.open(QIODevice::ReadOnly)) { zip.close(); return false; } details = ReadMCModInfo(file.readAll()); file.close(); zip.close(); mod.setDetails(details); return true; } else if (zip.setCurrentFile("quilt.mod.json")) { if (!file.open(QIODevice::ReadOnly)) { zip.close(); return false; } details = ReadQuiltModInfo(file.readAll()); file.close(); zip.close(); mod.setDetails(details); return true; } else if (zip.setCurrentFile("fabric.mod.json")) { if (!file.open(QIODevice::ReadOnly)) { zip.close(); return false; } details = ReadFabricModInfo(file.readAll()); file.close(); zip.close(); mod.setDetails(details); return true; } else if (zip.setCurrentFile("forgeversion.properties")) { if (!file.open(QIODevice::ReadOnly)) { zip.close(); return false; } details = ReadForgeInfo(file.readAll()); file.close(); zip.close(); mod.setDetails(details); return true; } else if (zip.setCurrentFile("META-INF/nil/mappings.json")) { // nilloader uses the filename of the metadata file for the modid, so we can't know the exact filename // thankfully, there is a good file to use as a canary so we don't look for nil meta all the time QString foundNilMeta; for (auto& fname : zip.getFileNameList()) { // nilmods can shade nilloader to be able to run as a standalone agent - which includes nilloader's own meta file if (fname.endsWith(".nilmod.css") && fname != "nilloader.nilmod.css") { foundNilMeta = fname; break; } } if (zip.setCurrentFile(foundNilMeta)) { if (!file.open(QIODevice::ReadOnly)) { zip.close(); return false; } details = ReadNilModInfo(file.readAll(), foundNilMeta); file.close(); zip.close(); mod.setDetails(details); return true; } } zip.close(); return false; // no valid mod found in archive } bool processFolder(Mod& mod, [[maybe_unused]] ProcessingLevel level) { ModDetails details; QFileInfo mcmod_info(FS::PathCombine(mod.fileinfo().filePath(), "mcmod.info")); if (mcmod_info.exists() && mcmod_info.isFile()) { QFile mcmod(mcmod_info.filePath()); if (!mcmod.open(QIODevice::ReadOnly)) return false; auto data = mcmod.readAll(); if (data.isEmpty() || data.isNull()) return false; details = ReadMCModInfo(data); mod.setDetails(details); return true; } return false; // no valid mcmod.info file found } bool processLitemod(Mod& mod, [[maybe_unused]] ProcessingLevel level) { ModDetails details; QuaZip zip(mod.fileinfo().filePath()); if (!zip.open(QuaZip::mdUnzip)) return false; QuaZipFile file(&zip); if (zip.setCurrentFile("litemod.json")) { if (!file.open(QIODevice::ReadOnly)) { zip.close(); return false; } details = ReadLiteModInfo(file.readAll()); file.close(); mod.setDetails(details); return true; } zip.close(); return false; // no valid litemod.json found in archive } /** Checks whether a file is valid as a mod or not. */ bool validate(QFileInfo file) { Mod mod{ file }; return ModUtils::process(mod, ProcessingLevel::BasicInfoOnly) && mod.valid(); } bool processIconPNG(const Mod& mod, QByteArray&& raw_data, QPixmap* pixmap) { auto img = QImage::fromData(raw_data); if (!img.isNull()) { *pixmap = mod.setIcon(img); } else { qWarning() << "Failed to parse mod logo:" << mod.iconPath() << "from" << mod.name(); return false; } return true; } bool loadIconFile(const Mod& mod, QPixmap* pixmap) { if (mod.iconPath().isEmpty()) { qWarning() << "No Iconfile set, be sure to parse the mod first"; return false; } auto png_invalid = [&mod](const QString& reason) { qWarning() << "Mod at" << mod.fileinfo().filePath() << "does not have a valid icon:" << reason; return false; }; switch (mod.type()) { case ResourceType::FOLDER: { QFileInfo icon_info(FS::PathCombine(mod.fileinfo().filePath(), mod.iconPath())); if (icon_info.exists() && icon_info.isFile()) { QFile icon(icon_info.filePath()); if (!icon.open(QIODevice::ReadOnly)) { return png_invalid("failed to open file " + icon_info.filePath()); } auto data = icon.readAll(); bool icon_result = ModUtils::processIconPNG(mod, std::move(data), pixmap); icon.close(); if (!icon_result) { return png_invalid("invalid png image"); // icon invalid } return true; } return png_invalid("file '" + icon_info.filePath() + "' does not exists or is not a file"); } case ResourceType::ZIPFILE: { QuaZip zip(mod.fileinfo().filePath()); if (!zip.open(QuaZip::mdUnzip)) return png_invalid("failed to open '" + mod.fileinfo().filePath() + "' as a zip archive"); QuaZipFile file(&zip); if (zip.setCurrentFile(mod.iconPath())) { if (!file.open(QIODevice::ReadOnly)) { qCritical() << "Failed to open file in zip."; zip.close(); return png_invalid("Failed to open '" + mod.iconPath() + "' in zip archive"); } auto data = file.readAll(); bool icon_result = ModUtils::processIconPNG(mod, std::move(data), pixmap); file.close(); if (!icon_result) { return png_invalid("invalid png image"); // icon png invalid } return true; } return png_invalid("Failed to set '" + mod.iconPath() + "' as current file in zip archive"); // could not set icon as current file. } case ResourceType::LITEMOD: { return png_invalid("litemods do not have icons"); // can lightmods even have icons? } default: return png_invalid("Invalid type for mod, can not load icon."); } } } // namespace ModUtils LocalModParseTask::LocalModParseTask(int token, ResourceType type, const QFileInfo& modFile) : Task(false), m_token(token), m_type(type), m_modFile(modFile), m_result(new Result()) {} bool LocalModParseTask::abort() { m_aborted.store(true); return true; } void LocalModParseTask::executeTask() { Mod mod{ m_modFile }; ModUtils::process(mod, ModUtils::ProcessingLevel::Full); m_result->details = mod.details(); if (m_aborted) emitAborted(); else emitSucceeded(); }
26,889
C++
.cpp
645
31.945736
150
0.582951
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,195
ResourceFolderLoadTask.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/mod/tasks/ResourceFolderLoadTask.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 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 "ResourceFolderLoadTask.h" #include "Application.h" #include "FileSystem.h" #include "minecraft/mod/MetadataHandler.h" #include <QThread> ResourceFolderLoadTask::ResourceFolderLoadTask(const QDir& resource_dir, const QDir& index_dir, bool is_indexed, bool clean_orphan, std::function<Resource*(const QFileInfo&)> create_function) : Task(false) , m_resource_dir(resource_dir) , m_index_dir(index_dir) , m_is_indexed(is_indexed) , m_clean_orphan(clean_orphan) , m_create_func(create_function) , m_result(new Result()) , m_thread_to_spawn_into(thread()) {} void ResourceFolderLoadTask::executeTask() { if (thread() != m_thread_to_spawn_into) connect(this, &Task::finished, this->thread(), &QThread::quit); if (m_is_indexed) { // Read metadata first getFromMetadata(); } // Read JAR files that don't have metadata m_resource_dir.refresh(); for (auto entry : m_resource_dir.entryInfoList()) { auto filePath = entry.absoluteFilePath(); if (auto app = APPLICATION_DYN; app && app->checkQSavePath(filePath)) { continue; } auto newFilePath = FS::getUniqueResourceName(filePath); if (newFilePath != filePath) { FS::move(filePath, newFilePath); entry = QFileInfo(newFilePath); } Resource* resource = m_create_func(entry); if (resource->enabled()) { if (m_result->resources.contains(resource->internal_id())) { m_result->resources[resource->internal_id()]->setStatus(ResourceStatus::INSTALLED); // Delete the object we just created, since a valid one is already in the mods list. delete resource; } else { m_result->resources[resource->internal_id()].reset(resource); m_result->resources[resource->internal_id()]->setStatus(ResourceStatus::NO_METADATA); } } else { QString chopped_id = resource->internal_id().chopped(9); if (m_result->resources.contains(chopped_id)) { m_result->resources[resource->internal_id()].reset(resource); auto metadata = m_result->resources[chopped_id]->metadata(); if (metadata) { resource->setMetadata(*metadata); m_result->resources[resource->internal_id()]->setStatus(ResourceStatus::INSTALLED); m_result->resources.remove(chopped_id); } } else { m_result->resources[resource->internal_id()].reset(resource); m_result->resources[resource->internal_id()]->setStatus(ResourceStatus::NO_METADATA); } } } // Remove orphan metadata to prevent issues // See https://github.com/PolyMC/PolyMC/issues/996 if (m_clean_orphan) { QMutableMapIterator iter(m_result->resources); while (iter.hasNext()) { auto resource = iter.next().value(); if (resource->status() == ResourceStatus::NOT_INSTALLED) { resource->destroy(m_index_dir, false, false); iter.remove(); } } } for (auto mod : m_result->resources) mod->moveToThread(m_thread_to_spawn_into); if (m_aborted) emit finished(); else emitSucceeded(); } void ResourceFolderLoadTask::getFromMetadata() { m_index_dir.refresh(); for (auto entry : m_index_dir.entryList(QDir::Files)) { auto metadata = Metadata::get(m_index_dir, entry); if (!metadata.isValid()) continue; auto* resource = m_create_func(QFileInfo(m_resource_dir.filePath(metadata.filename))); resource->setMetadata(metadata); resource->setStatus(ResourceStatus::NOT_INSTALLED); m_result->resources[resource->internal_id()].reset(resource); } }
5,656
C++
.cpp
132
34.469697
106
0.627747
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,196
LocalResourceUpdateTask.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/mod/tasks/LocalResourceUpdateTask.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "LocalResourceUpdateTask.h" #include "FileSystem.h" #include "minecraft/mod/MetadataHandler.h" #ifdef Q_OS_WIN32 #include <windows.h> #endif LocalResourceUpdateTask::LocalResourceUpdateTask(QDir index_dir, ModPlatform::IndexedPack& project, ModPlatform::IndexedVersion& version) : m_index_dir(index_dir), m_project(project), m_version(version) { // Ensure a '.index' folder exists in the mods folder, and create it if it does not if (!FS::ensureFolderPathExists(index_dir.path())) { emitFailed(QString("Unable to create index directory at %1!").arg(index_dir.absolutePath())); } #ifdef Q_OS_WIN32 SetFileAttributesW(index_dir.path().toStdWString().c_str(), FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_NOT_CONTENT_INDEXED); #endif } void LocalResourceUpdateTask::executeTask() { setStatus(tr("Updating index for resource:\n%1").arg(m_project.name)); auto old_metadata = Metadata::get(m_index_dir, m_project.addonId); if (old_metadata.isValid()) { emit hasOldResource(old_metadata.name, old_metadata.filename); if (m_project.slug.isEmpty()) m_project.slug = old_metadata.slug; } auto pw_mod = Metadata::create(m_index_dir, m_project, m_version); if (pw_mod.isValid()) { Metadata::update(m_index_dir, pw_mod); emitSucceeded(); } else { qCritical() << "Tried to update an invalid resource!"; emitFailed(tr("Invalid metadata")); } } auto LocalResourceUpdateTask::abort() -> bool { emitAborted(); return true; }
2,343
C++
.cpp
58
36.758621
137
0.719684
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,197
LocalShaderPackParseTask.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/mod/tasks/LocalShaderPackParseTask.cpp
// SPDX-FileCopyrightText: 2022 Rachel Powers <508861+Ryex@users.noreply.github.com> // // SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Rachel Powers <508861+Ryex@users.noreply.github.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "LocalShaderPackParseTask.h" #include "FileSystem.h" #include <quazip/quazip.h> #include <quazip/quazipdir.h> #include <quazip/quazipfile.h> namespace ShaderPackUtils { bool process(ShaderPack& pack, ProcessingLevel level) { switch (pack.type()) { case ResourceType::FOLDER: return ShaderPackUtils::processFolder(pack, level); case ResourceType::ZIPFILE: return ShaderPackUtils::processZIP(pack, level); default: qWarning() << "Invalid type for shader pack parse task!"; return false; } } bool processFolder(ShaderPack& pack, ProcessingLevel level) { Q_ASSERT(pack.type() == ResourceType::FOLDER); QFileInfo shaders_dir_info(FS::PathCombine(pack.fileinfo().filePath(), "shaders")); if (!shaders_dir_info.exists() || !shaders_dir_info.isDir()) { return false; // assets dir does not exists or isn't valid } pack.setPackFormat(ShaderPackFormat::VALID); if (level == ProcessingLevel::BasicInfoOnly) { return true; // only need basic info already checked } return true; // all tests passed } bool processZIP(ShaderPack& pack, ProcessingLevel level) { Q_ASSERT(pack.type() == ResourceType::ZIPFILE); QuaZip zip(pack.fileinfo().filePath()); if (!zip.open(QuaZip::mdUnzip)) return false; // can't open zip file QuaZipFile file(&zip); QuaZipDir zipDir(&zip); if (!zipDir.exists("/shaders")) { return false; // assets dir does not exists at zip root } pack.setPackFormat(ShaderPackFormat::VALID); if (level == ProcessingLevel::BasicInfoOnly) { zip.close(); return true; // only need basic info already checked } zip.close(); return true; } bool validate(QFileInfo file) { ShaderPack sp{ file }; return ShaderPackUtils::process(sp, ProcessingLevel::BasicInfoOnly) && sp.valid(); } } // namespace ShaderPackUtils LocalShaderPackParseTask::LocalShaderPackParseTask(int token, ShaderPack& sp) : Task(false), m_token(token), m_shader_pack(sp) {} bool LocalShaderPackParseTask::abort() { m_aborted = true; return true; } void LocalShaderPackParseTask::executeTask() { if (!ShaderPackUtils::process(m_shader_pack)) { emitFailed("this is not a shader pack"); return; } if (m_aborted) emitAborted(); else emitSucceeded(); }
3,264
C++
.cpp
92
31.108696
129
0.702763
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,198
LocalTexturePackParseTask.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/mod/tasks/LocalTexturePackParseTask.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "LocalTexturePackParseTask.h" #include "FileSystem.h" #include <quazip/quazip.h> #include <quazip/quazipfile.h> #include <QCryptographicHash> namespace TexturePackUtils { bool process(TexturePack& pack, ProcessingLevel level) { switch (pack.type()) { case ResourceType::FOLDER: return TexturePackUtils::processFolder(pack, level); case ResourceType::ZIPFILE: return TexturePackUtils::processZIP(pack, level); default: qWarning() << "Invalid type for resource pack parse task!"; return false; } } bool processFolder(TexturePack& pack, ProcessingLevel level) { Q_ASSERT(pack.type() == ResourceType::FOLDER); QFileInfo mcmeta_file_info(FS::PathCombine(pack.fileinfo().filePath(), "pack.txt")); if (mcmeta_file_info.isFile()) { QFile mcmeta_file(mcmeta_file_info.filePath()); if (!mcmeta_file.open(QIODevice::ReadOnly)) return false; auto data = mcmeta_file.readAll(); bool packTXT_result = TexturePackUtils::processPackTXT(pack, std::move(data)); mcmeta_file.close(); if (!packTXT_result) { return false; } } else { return false; } if (level == ProcessingLevel::BasicInfoOnly) return true; QFileInfo image_file_info(FS::PathCombine(pack.fileinfo().filePath(), "pack.png")); if (image_file_info.isFile()) { QFile mcmeta_file(image_file_info.filePath()); if (!mcmeta_file.open(QIODevice::ReadOnly)) return false; auto data = mcmeta_file.readAll(); bool packPNG_result = TexturePackUtils::processPackPNG(pack, std::move(data)); mcmeta_file.close(); if (!packPNG_result) { return false; } } else { return false; } return true; } bool processZIP(TexturePack& pack, ProcessingLevel level) { Q_ASSERT(pack.type() == ResourceType::ZIPFILE); QuaZip zip(pack.fileinfo().filePath()); if (!zip.open(QuaZip::mdUnzip)) return false; QuaZipFile file(&zip); if (zip.setCurrentFile("pack.txt")) { if (!file.open(QIODevice::ReadOnly)) { qCritical() << "Failed to open file in zip."; zip.close(); return false; } auto data = file.readAll(); bool packTXT_result = TexturePackUtils::processPackTXT(pack, std::move(data)); file.close(); if (!packTXT_result) { return false; } } if (level == ProcessingLevel::BasicInfoOnly) { zip.close(); return true; } if (zip.setCurrentFile("pack.png")) { if (!file.open(QIODevice::ReadOnly)) { qCritical() << "Failed to open file in zip."; zip.close(); return false; } auto data = file.readAll(); bool packPNG_result = TexturePackUtils::processPackPNG(pack, std::move(data)); file.close(); zip.close(); if (!packPNG_result) { return false; } } zip.close(); return true; } bool processPackTXT(TexturePack& pack, QByteArray&& raw_data) { pack.setDescription(QString(raw_data)); return true; } bool processPackPNG(const TexturePack& pack, QByteArray&& raw_data) { auto img = QImage::fromData(raw_data); if (!img.isNull()) { pack.setImage(img); } else { qWarning() << "Failed to parse pack.png."; return false; } return true; } bool processPackPNG(const TexturePack& pack) { auto png_invalid = [&pack]() { qWarning() << "Texture pack at" << pack.fileinfo().filePath() << "does not have a valid pack.png"; return false; }; switch (pack.type()) { case ResourceType::FOLDER: { QFileInfo image_file_info(FS::PathCombine(pack.fileinfo().filePath(), "pack.png")); if (image_file_info.exists() && image_file_info.isFile()) { QFile pack_png_file(image_file_info.filePath()); if (!pack_png_file.open(QIODevice::ReadOnly)) return png_invalid(); // can't open pack.png file auto data = pack_png_file.readAll(); bool pack_png_result = TexturePackUtils::processPackPNG(pack, std::move(data)); pack_png_file.close(); if (!pack_png_result) { return png_invalid(); // pack.png invalid } } else { return png_invalid(); // pack.png does not exists or is not a valid file. } return false; } case ResourceType::ZIPFILE: { QuaZip zip(pack.fileinfo().filePath()); if (!zip.open(QuaZip::mdUnzip)) return false; // can't open zip file QuaZipFile file(&zip); if (zip.setCurrentFile("pack.png")) { if (!file.open(QIODevice::ReadOnly)) { qCritical() << "Failed to open file in zip."; zip.close(); return png_invalid(); } auto data = file.readAll(); bool pack_png_result = TexturePackUtils::processPackPNG(pack, std::move(data)); file.close(); if (!pack_png_result) { zip.close(); return png_invalid(); // pack.png invalid } } else { zip.close(); return png_invalid(); // could not set pack.mcmeta as current file. } return false; } default: qWarning() << "Invalid type for resource pack parse task!"; return false; } } bool validate(QFileInfo file) { TexturePack rp{ file }; return TexturePackUtils::process(rp, ProcessingLevel::BasicInfoOnly) && rp.valid(); } } // namespace TexturePackUtils LocalTexturePackParseTask::LocalTexturePackParseTask(int token, TexturePack& rp) : Task(false), m_token(token), m_texture_pack(rp) {} bool LocalTexturePackParseTask::abort() { m_aborted = true; return true; } void LocalTexturePackParseTask::executeTask() { if (!TexturePackUtils::process(m_texture_pack)) { emitFailed("this is not a texture pack"); return; } if (m_aborted) emitAborted(); else emitSucceeded(); }
7,226
C++
.cpp
204
27.343137
133
0.60281
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,199
LocalWorldSaveParseTask.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/mod/tasks/LocalWorldSaveParseTask.cpp
// SPDX-FileCopyrightText: 2022 Rachel Powers <508861+Ryex@users.noreply.github.com> // // SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Rachel Powers <508861+Ryex@users.noreply.github.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "LocalWorldSaveParseTask.h" #include "FileSystem.h" #include <quazip/quazip.h> #include <quazip/quazipdir.h> #include <quazip/quazipfile.h> #include <QDir> #include <QFileInfo> namespace WorldSaveUtils { bool process(WorldSave& pack, ProcessingLevel level) { switch (pack.type()) { case ResourceType::FOLDER: return WorldSaveUtils::processFolder(pack, level); case ResourceType::ZIPFILE: return WorldSaveUtils::processZIP(pack, level); default: qWarning() << "Invalid type for world save parse task!"; return false; } } /// @brief checks a folder structure to see if it contains a level.dat /// @param dir the path to check /// @param saves used in recursive call if a "saves" dir was found /// @return std::tuple of ( /// bool <found level.dat>, /// QString <name of folder containing level.dat>, /// bool <saves folder found> /// ) static std::tuple<bool, QString, bool> contains_level_dat(QDir dir, bool saves = false) { for (auto const& entry : dir.entryInfoList()) { if (!entry.isDir()) { continue; } if (!saves && entry.fileName() == "saves") { return contains_level_dat(QDir(entry.filePath()), true); } QFileInfo level_dat(FS::PathCombine(entry.filePath(), "level.dat")); if (level_dat.exists() && level_dat.isFile()) { return std::make_tuple(true, entry.fileName(), saves); } } return std::make_tuple(false, "", saves); } bool processFolder(WorldSave& save, ProcessingLevel level) { Q_ASSERT(save.type() == ResourceType::FOLDER); auto [found, save_dir_name, found_saves_dir] = contains_level_dat(QDir(save.fileinfo().filePath())); if (!found) { return false; } save.setSaveDirName(save_dir_name); if (found_saves_dir) { save.setSaveFormat(WorldSaveFormat::MULTI); } else { save.setSaveFormat(WorldSaveFormat::SINGLE); } if (level == ProcessingLevel::BasicInfoOnly) { return true; // only need basic info already checked } // reserved for more intensive processing return true; // all tests passed } /// @brief checks a folder structure to see if it contains a level.dat /// @param zip the zip file to check /// @return std::tuple of ( /// bool <found level.dat>, /// QString <name of folder containing level.dat>, /// bool <saves folder found> /// ) static std::tuple<bool, QString, bool> contains_level_dat(QuaZip& zip) { bool saves = false; QuaZipDir zipDir(&zip); if (zipDir.exists("/saves")) { saves = true; zipDir.cd("/saves"); } for (auto const& entry : zipDir.entryList()) { zipDir.cd(entry); if (zipDir.exists("level.dat")) { return std::make_tuple(true, entry, saves); } zipDir.cd(".."); } return std::make_tuple(false, "", saves); } bool processZIP(WorldSave& save, ProcessingLevel level) { Q_ASSERT(save.type() == ResourceType::ZIPFILE); QuaZip zip(save.fileinfo().filePath()); if (!zip.open(QuaZip::mdUnzip)) return false; // can't open zip file auto [found, save_dir_name, found_saves_dir] = contains_level_dat(zip); if (save_dir_name.endsWith("/")) { save_dir_name.chop(1); } if (!found) { return false; } save.setSaveDirName(save_dir_name); if (found_saves_dir) { save.setSaveFormat(WorldSaveFormat::MULTI); } else { save.setSaveFormat(WorldSaveFormat::SINGLE); } if (level == ProcessingLevel::BasicInfoOnly) { zip.close(); return true; // only need basic info already checked } // reserved for more intensive processing zip.close(); return true; } bool validate(QFileInfo file) { WorldSave sp{ file }; return WorldSaveUtils::process(sp, ProcessingLevel::BasicInfoOnly) && sp.valid(); } } // namespace WorldSaveUtils LocalWorldSaveParseTask::LocalWorldSaveParseTask(int token, WorldSave& save) : Task(false), m_token(token), m_save(save) {} bool LocalWorldSaveParseTask::abort() { m_aborted = true; return true; } void LocalWorldSaveParseTask::executeTask() { if (!WorldSaveUtils::process(m_save)) return; if (m_aborted) emitAborted(); else emitSucceeded(); }
5,296
C++
.cpp
154
29.62987
123
0.656874
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,200
LocalDataPackParseTask.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/mod/tasks/LocalDataPackParseTask.cpp
// SPDX-FileCopyrightText: 2022 Rachel Powers <508861+Ryex@users.noreply.github.com> // // SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Rachel Powers <508861+Ryex@users.noreply.github.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "LocalDataPackParseTask.h" #include "FileSystem.h" #include "Json.h" #include <quazip/quazip.h> #include <quazip/quazipdir.h> #include <quazip/quazipfile.h> #include <QCryptographicHash> namespace DataPackUtils { bool process(DataPack& pack, ProcessingLevel level) { switch (pack.type()) { case ResourceType::FOLDER: return DataPackUtils::processFolder(pack, level); case ResourceType::ZIPFILE: return DataPackUtils::processZIP(pack, level); default: qWarning() << "Invalid type for data pack parse task!"; return false; } } bool processFolder(DataPack& pack, ProcessingLevel level) { Q_ASSERT(pack.type() == ResourceType::FOLDER); auto mcmeta_invalid = [&pack]() { qWarning() << "Data pack at" << pack.fileinfo().filePath() << "does not have a valid pack.mcmeta"; return false; // the mcmeta is not optional }; QFileInfo mcmeta_file_info(FS::PathCombine(pack.fileinfo().filePath(), "pack.mcmeta")); if (mcmeta_file_info.exists() && mcmeta_file_info.isFile()) { QFile mcmeta_file(mcmeta_file_info.filePath()); if (!mcmeta_file.open(QIODevice::ReadOnly)) return mcmeta_invalid(); // can't open mcmeta file auto data = mcmeta_file.readAll(); bool mcmeta_result = DataPackUtils::processMCMeta(pack, std::move(data)); mcmeta_file.close(); if (!mcmeta_result) { return mcmeta_invalid(); // mcmeta invalid } } else { return mcmeta_invalid(); // mcmeta file isn't a valid file } QFileInfo data_dir_info(FS::PathCombine(pack.fileinfo().filePath(), "data")); if (!data_dir_info.exists() || !data_dir_info.isDir()) { return false; // data dir does not exists or isn't valid } if (level == ProcessingLevel::BasicInfoOnly) { return true; // only need basic info already checked } return true; // all tests passed } bool processZIP(DataPack& pack, ProcessingLevel level) { Q_ASSERT(pack.type() == ResourceType::ZIPFILE); QuaZip zip(pack.fileinfo().filePath()); if (!zip.open(QuaZip::mdUnzip)) return false; // can't open zip file QuaZipFile file(&zip); auto mcmeta_invalid = [&pack]() { qWarning() << "Data pack at" << pack.fileinfo().filePath() << "does not have a valid pack.mcmeta"; return false; // the mcmeta is not optional }; if (zip.setCurrentFile("pack.mcmeta")) { if (!file.open(QIODevice::ReadOnly)) { qCritical() << "Failed to open file in zip."; zip.close(); return mcmeta_invalid(); } auto data = file.readAll(); bool mcmeta_result = DataPackUtils::processMCMeta(pack, std::move(data)); file.close(); if (!mcmeta_result) { return mcmeta_invalid(); // mcmeta invalid } } else { return mcmeta_invalid(); // could not set pack.mcmeta as current file. } QuaZipDir zipDir(&zip); if (!zipDir.exists("/data")) { return false; // data dir does not exists at zip root } if (level == ProcessingLevel::BasicInfoOnly) { zip.close(); return true; // only need basic info already checked } zip.close(); return true; } // https://minecraft.wiki/w/Data_pack#pack.mcmeta bool processMCMeta(DataPack& pack, QByteArray&& raw_data) { try { auto json_doc = QJsonDocument::fromJson(raw_data); auto pack_obj = Json::requireObject(json_doc.object(), "pack", {}); pack.setPackFormat(Json::ensureInteger(pack_obj, "pack_format", 0)); pack.setDescription(Json::ensureString(pack_obj, "description", "")); } catch (Json::JsonException& e) { qWarning() << "JsonException: " << e.what() << e.cause(); return false; } return true; } bool validate(QFileInfo file) { DataPack dp{ file }; return DataPackUtils::process(dp, ProcessingLevel::BasicInfoOnly) && dp.valid(); } } // namespace DataPackUtils LocalDataPackParseTask::LocalDataPackParseTask(int token, DataPack& dp) : Task(false), m_token(token), m_data_pack(dp) {} bool LocalDataPackParseTask::abort() { m_aborted = true; return true; } void LocalDataPackParseTask::executeTask() { if (!DataPackUtils::process(m_data_pack)) return; if (m_aborted) emitAborted(); else emitSucceeded(); }
5,309
C++
.cpp
141
32.092199
121
0.658807
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,201
LocalResourceParse.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/mod/tasks/LocalResourceParse.cpp
// SPDX-FileCopyrightText: 2022 Rachel Powers <508861+Ryex@users.noreply.github.com> // // SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Rachel Powers <508861+Ryex@users.noreply.github.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <QObject> #include "LocalResourceParse.h" #include "LocalDataPackParseTask.h" #include "LocalModParseTask.h" #include "LocalResourcePackParseTask.h" #include "LocalShaderPackParseTask.h" #include "LocalTexturePackParseTask.h" #include "LocalWorldSaveParseTask.h" static const QMap<PackedResourceType, QString> s_packed_type_names = { { PackedResourceType::ResourcePack, QObject::tr("resource pack") }, { PackedResourceType::TexturePack, QObject::tr("texture pack") }, { PackedResourceType::DataPack, QObject::tr("data pack") }, { PackedResourceType::ShaderPack, QObject::tr("shader pack") }, { PackedResourceType::WorldSave, QObject::tr("world save") }, { PackedResourceType::Mod, QObject::tr("mod") }, { PackedResourceType::UNKNOWN, QObject::tr("unknown") } }; namespace ResourceUtils { PackedResourceType identify(QFileInfo file) { if (file.exists() && file.isFile()) { if (ModUtils::validate(file)) { // mods can contain resource and data packs so they must be tested first qDebug() << file.fileName() << "is a mod"; return PackedResourceType::Mod; } else if (ResourcePackUtils::validate(file)) { qDebug() << file.fileName() << "is a resource pack"; return PackedResourceType::ResourcePack; } else if (TexturePackUtils::validate(file)) { qDebug() << file.fileName() << "is a pre 1.6 texture pack"; return PackedResourceType::TexturePack; } else if (DataPackUtils::validate(file)) { qDebug() << file.fileName() << "is a data pack"; return PackedResourceType::DataPack; } else if (WorldSaveUtils::validate(file)) { qDebug() << file.fileName() << "is a world save"; return PackedResourceType::WorldSave; } else if (ShaderPackUtils::validate(file)) { qDebug() << file.fileName() << "is a shader pack"; return PackedResourceType::ShaderPack; } else { qDebug() << "Can't Identify" << file.fileName(); } } else { qDebug() << "Can't find" << file.absolutePath(); } return PackedResourceType::UNKNOWN; } QString getPackedTypeName(PackedResourceType type) { return s_packed_type_names.constFind(type).value(); } } // namespace ResourceUtils
3,585
C++
.cpp
70
40.085714
138
0.607357
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,202
LocalResourcePackParseTask.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/mod/tasks/LocalResourcePackParseTask.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "LocalResourcePackParseTask.h" #include "FileSystem.h" #include "Json.h" #include <quazip/quazip.h> #include <quazip/quazipdir.h> #include <quazip/quazipfile.h> #include <QCryptographicHash> namespace ResourcePackUtils { bool process(ResourcePack& pack, ProcessingLevel level) { switch (pack.type()) { case ResourceType::FOLDER: return ResourcePackUtils::processFolder(pack, level); case ResourceType::ZIPFILE: return ResourcePackUtils::processZIP(pack, level); default: qWarning() << "Invalid type for resource pack parse task!"; return false; } } bool processFolder(ResourcePack& pack, ProcessingLevel level) { Q_ASSERT(pack.type() == ResourceType::FOLDER); auto mcmeta_invalid = [&pack]() { qWarning() << "Resource pack at" << pack.fileinfo().filePath() << "does not have a valid pack.mcmeta"; return false; // the mcmeta is not optional }; QFileInfo mcmeta_file_info(FS::PathCombine(pack.fileinfo().filePath(), "pack.mcmeta")); if (mcmeta_file_info.exists() && mcmeta_file_info.isFile()) { QFile mcmeta_file(mcmeta_file_info.filePath()); if (!mcmeta_file.open(QIODevice::ReadOnly)) return mcmeta_invalid(); // can't open mcmeta file auto data = mcmeta_file.readAll(); bool mcmeta_result = ResourcePackUtils::processMCMeta(pack, std::move(data)); mcmeta_file.close(); if (!mcmeta_result) { return mcmeta_invalid(); // mcmeta invalid } } else { return mcmeta_invalid(); // mcmeta file isn't a valid file } QFileInfo assets_dir_info(FS::PathCombine(pack.fileinfo().filePath(), "assets")); if (!assets_dir_info.exists() || !assets_dir_info.isDir()) { return false; // assets dir does not exists or isn't valid } if (level == ProcessingLevel::BasicInfoOnly) { return true; // only need basic info already checked } auto png_invalid = [&pack]() { qWarning() << "Resource pack at" << pack.fileinfo().filePath() << "does not have a valid pack.png"; return true; // the png is optional }; QFileInfo image_file_info(FS::PathCombine(pack.fileinfo().filePath(), "pack.png")); if (image_file_info.exists() && image_file_info.isFile()) { QFile pack_png_file(image_file_info.filePath()); if (!pack_png_file.open(QIODevice::ReadOnly)) return png_invalid(); // can't open pack.png file auto data = pack_png_file.readAll(); bool pack_png_result = ResourcePackUtils::processPackPNG(pack, std::move(data)); pack_png_file.close(); if (!pack_png_result) { return png_invalid(); // pack.png invalid } } else { return png_invalid(); // pack.png does not exists or is not a valid file. } return true; // all tests passed } bool processZIP(ResourcePack& pack, ProcessingLevel level) { Q_ASSERT(pack.type() == ResourceType::ZIPFILE); QuaZip zip(pack.fileinfo().filePath()); if (!zip.open(QuaZip::mdUnzip)) return false; // can't open zip file QuaZipFile file(&zip); auto mcmeta_invalid = [&pack]() { qWarning() << "Resource pack at" << pack.fileinfo().filePath() << "does not have a valid pack.mcmeta"; return false; // the mcmeta is not optional }; if (zip.setCurrentFile("pack.mcmeta")) { if (!file.open(QIODevice::ReadOnly)) { qCritical() << "Failed to open file in zip."; zip.close(); return mcmeta_invalid(); } auto data = file.readAll(); bool mcmeta_result = ResourcePackUtils::processMCMeta(pack, std::move(data)); file.close(); if (!mcmeta_result) { return mcmeta_invalid(); // mcmeta invalid } } else { return mcmeta_invalid(); // could not set pack.mcmeta as current file. } QuaZipDir zipDir(&zip); if (!zipDir.exists("/assets")) { return false; // assets dir does not exists at zip root } if (level == ProcessingLevel::BasicInfoOnly) { zip.close(); return true; // only need basic info already checked } auto png_invalid = [&pack]() { qWarning() << "Resource pack at" << pack.fileinfo().filePath() << "does not have a valid pack.png"; return true; // the png is optional }; if (zip.setCurrentFile("pack.png")) { if (!file.open(QIODevice::ReadOnly)) { qCritical() << "Failed to open file in zip."; zip.close(); return png_invalid(); } auto data = file.readAll(); bool pack_png_result = ResourcePackUtils::processPackPNG(pack, std::move(data)); file.close(); zip.close(); if (!pack_png_result) { return png_invalid(); // pack.png invalid } } else { zip.close(); return png_invalid(); // could not set pack.mcmeta as current file. } zip.close(); return true; } QString buildStyle(const QJsonObject& obj) { QStringList styles; if (auto color = Json::ensureString(obj, "color"); !color.isEmpty()) { styles << QString("color: %1;").arg(color); } if (obj.contains("bold")) { QString weight = "normal"; if (Json::ensureBoolean(obj, "bold", false)) { weight = "bold"; } styles << QString("font-weight: %1;").arg(weight); } if (obj.contains("italic")) { QString style = "normal"; if (Json::ensureBoolean(obj, "italic", false)) { style = "italic"; } styles << QString("font-style: %1;").arg(style); } return styles.isEmpty() ? "" : QString("style=\"%1\"").arg(styles.join(" ")); } QString processComponent(const QJsonArray& value, bool strikethrough, bool underline) { QString result; for (auto current : value) result += processComponent(current, strikethrough, underline); return result; } QString processComponent(const QJsonObject& obj, bool strikethrough, bool underline) { underline = Json::ensureBoolean(obj, "underlined", underline); strikethrough = Json::ensureBoolean(obj, "strikethrough", strikethrough); QString result = Json::ensureString(obj, "text"); if (underline) { result = QString("<u>%1</u>").arg(result); } if (strikethrough) { result = QString("<s>%1</s>").arg(result); } // the extra needs to be a array result += processComponent(Json::ensureArray(obj, "extra"), strikethrough, underline); if (auto style = buildStyle(obj); !style.isEmpty()) { result = QString("<span %1>%2</span>").arg(style, result); } if (obj.contains("clickEvent")) { auto click_event = Json::ensureObject(obj, "clickEvent"); auto action = Json::ensureString(click_event, "action"); auto value = Json::ensureString(click_event, "value"); if (action == "open_url" && !value.isEmpty()) { result = QString("<a href=\"%1\">%2</a>").arg(value, result); } } return result; } QString processComponent(const QJsonValue& value, bool strikethrough, bool underline) { if (value.isString()) { return value.toString(); } if (value.isBool()) { return value.toBool() ? "true" : "false"; } if (value.isDouble()) { return QString::number(value.toDouble()); } if (value.isArray()) { return processComponent(value.toArray(), strikethrough, underline); } if (value.isObject()) { return processComponent(value.toObject(), strikethrough, underline); } qWarning() << "Invalid component type!"; return {}; } // https://minecraft.wiki/w/Raw_JSON_text_format // https://minecraft.wiki/w/Tutorials/Creating_a_resource_pack#Formatting_pack.mcmeta bool processMCMeta(ResourcePack& pack, QByteArray&& raw_data) { try { auto json_doc = QJsonDocument::fromJson(raw_data); auto pack_obj = Json::requireObject(json_doc.object(), "pack", {}); pack.setPackFormat(Json::ensureInteger(pack_obj, "pack_format", 0)); pack.setDescription(processComponent(pack_obj.value("description"))); } catch (Json::JsonException& e) { qWarning() << "JsonException: " << e.what() << e.cause(); return false; } return true; } bool processPackPNG(const ResourcePack& pack, QByteArray&& raw_data) { auto img = QImage::fromData(raw_data); if (!img.isNull()) { pack.setImage(img); } else { qWarning() << "Failed to parse pack.png."; return false; } return true; } bool processPackPNG(const ResourcePack& pack) { auto png_invalid = [&pack]() { qWarning() << "Resource pack at" << pack.fileinfo().filePath() << "does not have a valid pack.png"; return false; }; switch (pack.type()) { case ResourceType::FOLDER: { QFileInfo image_file_info(FS::PathCombine(pack.fileinfo().filePath(), "pack.png")); if (image_file_info.exists() && image_file_info.isFile()) { QFile pack_png_file(image_file_info.filePath()); if (!pack_png_file.open(QIODevice::ReadOnly)) return png_invalid(); // can't open pack.png file auto data = pack_png_file.readAll(); bool pack_png_result = ResourcePackUtils::processPackPNG(pack, std::move(data)); pack_png_file.close(); if (!pack_png_result) { return png_invalid(); // pack.png invalid } } else { return png_invalid(); // pack.png does not exists or is not a valid file. } return false; // not processed correctly; https://github.com/PrismLauncher/PrismLauncher/issues/1740 } case ResourceType::ZIPFILE: { QuaZip zip(pack.fileinfo().filePath()); if (!zip.open(QuaZip::mdUnzip)) return false; // can't open zip file QuaZipFile file(&zip); if (zip.setCurrentFile("pack.png")) { if (!file.open(QIODevice::ReadOnly)) { qCritical() << "Failed to open file in zip."; zip.close(); return png_invalid(); } auto data = file.readAll(); bool pack_png_result = ResourcePackUtils::processPackPNG(pack, std::move(data)); file.close(); if (!pack_png_result) { return png_invalid(); // pack.png invalid } } else { return png_invalid(); // could not set pack.mcmeta as current file. } return false; // not processed correctly; https://github.com/PrismLauncher/PrismLauncher/issues/1740 } default: qWarning() << "Invalid type for resource pack parse task!"; return false; } } bool validate(QFileInfo file) { ResourcePack rp{ file }; return ResourcePackUtils::process(rp, ProcessingLevel::BasicInfoOnly) && rp.valid(); } } // namespace ResourcePackUtils LocalResourcePackParseTask::LocalResourcePackParseTask(int token, ResourcePack& rp) : Task(false), m_token(token), m_resource_pack(rp) {} bool LocalResourcePackParseTask::abort() { m_aborted = true; return true; } void LocalResourcePackParseTask::executeTask() { if (!ResourcePackUtils::process(m_resource_pack)) { emitFailed("this is not a resource pack"); return; } if (m_aborted) emitAborted(); else emitSucceeded(); }
12,468
C++
.cpp
318
31.86478
137
0.616396
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,203
GameOptions.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/gameoptions/GameOptions.cpp
#include "GameOptions.h" #include <QDebug> #include <QSaveFile> #include "FileSystem.h" namespace { bool load(const QString& path, std::vector<GameOptionItem>& contents, int& version) { contents.clear(); QFile file(path); if (!file.open(QFile::ReadOnly)) { qWarning() << "Failed to read options file."; return false; } version = 0; while (!file.atEnd()) { auto line = file.readLine(); if (line.endsWith('\n')) { line.chop(1); } auto separatorIndex = line.indexOf(':'); if (separatorIndex == -1) { continue; } auto key = QString::fromUtf8(line.data(), separatorIndex); auto value = QString::fromUtf8(line.data() + separatorIndex + 1, line.size() - 1 - separatorIndex); qDebug() << "!!" << key << "!!"; if (key == "version") { version = value.toInt(); continue; } contents.emplace_back(GameOptionItem{ key, value }); } qDebug() << "Loaded" << path << "with version:" << version; return true; } bool save(const QString& path, std::vector<GameOptionItem>& mapping, int version) { QSaveFile out(path); if (!out.open(QIODevice::WriteOnly)) { return false; } if (version != 0) { QString versionLine = QString("version:%1\n").arg(version); out.write(versionLine.toUtf8()); } auto iter = mapping.begin(); while (iter != mapping.end()) { out.write(iter->key.toUtf8()); out.write(":"); out.write(iter->value.toUtf8()); out.write("\n"); iter++; } return out.commit(); } } // namespace GameOptions::GameOptions(const QString& path) : path(path) { reload(); } QVariant GameOptions::headerData(int section, Qt::Orientation orientation, int role) const { if (role != Qt::DisplayRole) { return QAbstractListModel::headerData(section, orientation, role); } switch (section) { case 0: return tr("Key"); case 1: return tr("Value"); default: return QVariant(); } } QVariant GameOptions::data(const QModelIndex& index, int role) const { if (!index.isValid()) return QVariant(); int row = index.row(); int column = index.column(); if (row < 0 || row >= int(contents.size())) return QVariant(); switch (role) { case Qt::DisplayRole: if (column == 0) { return contents[row].key; } else { return contents[row].value; } default: return QVariant(); } } int GameOptions::rowCount(const QModelIndex&) const { return static_cast<int>(contents.size()); } int GameOptions::columnCount(const QModelIndex&) const { return 2; } bool GameOptions::isLoaded() const { return loaded; } bool GameOptions::reload() { beginResetModel(); loaded = load(path, contents, version); endResetModel(); return loaded; } bool GameOptions::save() { return ::save(path, contents, version); }
3,102
C++
.cpp
116
20.87931
107
0.590114
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,204
AuthFlow.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/auth/AuthFlow.cpp
#include <QDebug> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QNetworkRequest> #include "minecraft/auth/AccountData.h" #include "minecraft/auth/steps/EntitlementsStep.h" #include "minecraft/auth/steps/GetSkinStep.h" #include "minecraft/auth/steps/LauncherLoginStep.h" #include "minecraft/auth/steps/MSADeviceCodeStep.h" #include "minecraft/auth/steps/MSAStep.h" #include "minecraft/auth/steps/MinecraftProfileStep.h" #include "minecraft/auth/steps/XboxAuthorizationStep.h" #include "minecraft/auth/steps/XboxProfileStep.h" #include "minecraft/auth/steps/XboxUserStep.h" #include "tasks/Task.h" #include "AuthFlow.h" #include <Application.h> AuthFlow::AuthFlow(AccountData* data, Action action) : Task(), m_data(data) { if (data->type == AccountType::MSA) { if (action == Action::DeviceCode) { auto oauthStep = makeShared<MSADeviceCodeStep>(m_data); connect(oauthStep.get(), &MSADeviceCodeStep::authorizeWithBrowser, this, &AuthFlow::authorizeWithBrowserWithExtra); connect(this, &Task::aborted, oauthStep.get(), &MSADeviceCodeStep::abort); m_steps.append(oauthStep); } else { auto oauthStep = makeShared<MSAStep>(m_data, action == Action::Refresh); connect(oauthStep.get(), &MSAStep::authorizeWithBrowser, this, &AuthFlow::authorizeWithBrowser); m_steps.append(oauthStep); } m_steps.append(makeShared<XboxUserStep>(m_data)); m_steps.append(makeShared<XboxAuthorizationStep>(m_data, &m_data->xboxApiToken, "http://xboxlive.com", "Xbox")); m_steps.append( makeShared<XboxAuthorizationStep>(m_data, &m_data->mojangservicesToken, "rp://api.minecraftservices.com/", "Mojang")); m_steps.append(makeShared<LauncherLoginStep>(m_data)); m_steps.append(makeShared<XboxProfileStep>(m_data)); m_steps.append(makeShared<EntitlementsStep>(m_data)); m_steps.append(makeShared<MinecraftProfileStep>(m_data)); m_steps.append(makeShared<GetSkinStep>(m_data)); } changeState(AccountTaskState::STATE_CREATED); } void AuthFlow::succeed() { m_data->validity_ = Validity::Certain; changeState(AccountTaskState::STATE_SUCCEEDED, tr("Finished all authentication steps")); } void AuthFlow::executeTask() { changeState(AccountTaskState::STATE_WORKING, tr("Initializing")); nextStep(); } void AuthFlow::nextStep() { if (!Task::isRunning()) { return; } if (m_steps.size() == 0) { // we got to the end without an incident... assume this is all. m_currentStep.reset(); succeed(); return; } m_currentStep = m_steps.front(); qDebug() << "AuthFlow:" << m_currentStep->describe(); m_steps.pop_front(); connect(m_currentStep.get(), &AuthStep::finished, this, &AuthFlow::stepFinished); m_currentStep->perform(); } void AuthFlow::stepFinished(AccountTaskState resultingState, QString message) { if (changeState(resultingState, message)) nextStep(); } bool AuthFlow::changeState(AccountTaskState newState, QString reason) { m_taskState = newState; setDetails(reason); switch (newState) { case AccountTaskState::STATE_CREATED: { setStatus(tr("Waiting...")); m_data->errorString.clear(); return true; } case AccountTaskState::STATE_WORKING: { setStatus(m_currentStep ? m_currentStep->describe() : tr("Working...")); m_data->accountState = AccountState::Working; return true; } case AccountTaskState::STATE_SUCCEEDED: { setStatus(tr("Authentication task succeeded.")); m_data->accountState = AccountState::Online; emitSucceeded(); return false; } case AccountTaskState::STATE_OFFLINE: { setStatus(tr("Failed to contact the authentication server.")); m_data->errorString = reason; m_data->accountState = AccountState::Offline; emitFailed(reason); return false; } case AccountTaskState::STATE_DISABLED: { setStatus(tr("Client ID has changed. New session needs to be created.")); m_data->errorString = reason; m_data->accountState = AccountState::Disabled; emitFailed(reason); return false; } case AccountTaskState::STATE_FAILED_SOFT: { setStatus(tr("Encountered an error during authentication.")); m_data->errorString = reason; m_data->accountState = AccountState::Errored; emitFailed(reason); return false; } case AccountTaskState::STATE_FAILED_HARD: { setStatus(tr("Failed to authenticate. The session has expired.")); m_data->errorString = reason; m_data->accountState = AccountState::Expired; emitFailed(reason); return false; } case AccountTaskState::STATE_FAILED_GONE: { setStatus(tr("Failed to authenticate. The account no longer exists.")); m_data->errorString = reason; m_data->accountState = AccountState::Gone; emitFailed(reason); return false; } default: { setStatus(tr("...")); QString error = tr("Unknown account task state: %1").arg(int(newState)); m_data->accountState = AccountState::Errored; emitFailed(error); return false; } } } bool AuthFlow::abort() { emitAborted(); if (m_currentStep) m_currentStep->abort(); return true; }
5,696
C++
.cpp
146
31.376712
130
0.648258
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,205
Parsers.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/auth/Parsers.cpp
#include "Parsers.h" #include "Json.h" #include "Logging.h" #include <QDebug> #include <QJsonArray> #include <QJsonDocument> namespace Parsers { bool getDateTime(QJsonValue value, QDateTime& out) { if (!value.isString()) { return false; } out = QDateTime::fromString(value.toString(), Qt::ISODate); return out.isValid(); } bool getString(QJsonValue value, QString& out) { if (!value.isString()) { return false; } out = value.toString(); return true; } bool getNumber(QJsonValue value, double& out) { if (!value.isDouble()) { return false; } out = value.toDouble(); return true; } bool getNumber(QJsonValue value, int64_t& out) { if (!value.isDouble()) { return false; } out = (int64_t)value.toDouble(); return true; } bool getBool(QJsonValue value, bool& out) { if (!value.isBool()) { return false; } out = value.toBool(); return true; } /* { "IssueInstant":"2020-12-07T19:52:08.4463796Z", "NotAfter":"2020-12-21T19:52:08.4463796Z", "Token":"token", "DisplayClaims":{ "xui":[ { "uhs":"userhash" } ] } } */ // TODO: handle error responses ... /* { "Identity":"0", "XErr":2148916238, "Message":"", "Redirect":"https://start.ui.xboxlive.com/AddChildToFamily" } // 2148916233 = missing XBox account // 2148916238 = child account not linked to a family */ bool parseXTokenResponse(QByteArray& data, Token& output, QString name) { qDebug() << "Parsing" << name << ":"; qCDebug(authCredentials()) << data; QJsonParseError jsonError; QJsonDocument doc = QJsonDocument::fromJson(data, &jsonError); if (jsonError.error) { qWarning() << "Failed to parse response from user.auth.xboxlive.com as JSON: " << jsonError.errorString(); return false; } auto obj = doc.object(); if (!getDateTime(obj.value("IssueInstant"), output.issueInstant)) { qWarning() << "User IssueInstant is not a timestamp"; return false; } if (!getDateTime(obj.value("NotAfter"), output.notAfter)) { qWarning() << "User NotAfter is not a timestamp"; return false; } if (!getString(obj.value("Token"), output.token)) { qWarning() << "User Token is not a string"; return false; } auto arrayVal = obj.value("DisplayClaims").toObject().value("xui"); if (!arrayVal.isArray()) { qWarning() << "Missing xui claims array"; return false; } bool foundUHS = false; for (auto item : arrayVal.toArray()) { if (!item.isObject()) { continue; } 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++) { QString claim; if (!getString(obj_.value(iter.key()), claim)) { qWarning() << "display claim " << iter.key() << " is not a string..."; return false; } output.extra[iter.key()] = claim; } break; } if (!foundUHS) { qWarning() << "Missing uhs"; return false; } output.validity = Validity::Certain; qDebug() << name << "is valid."; return true; } bool parseMinecraftProfile(QByteArray& data, MinecraftProfile& output) { qDebug() << "Parsing Minecraft profile..."; qCDebug(authCredentials()) << data; QJsonParseError jsonError; QJsonDocument doc = QJsonDocument::fromJson(data, &jsonError); if (jsonError.error) { qWarning() << "Failed to parse response from user.auth.xboxlive.com as JSON: " << jsonError.errorString(); return false; } auto obj = doc.object(); if (!getString(obj.value("id"), output.id)) { qWarning() << "Minecraft profile id is not a string"; return false; } if (!getString(obj.value("name"), output.name)) { qWarning() << "Minecraft profile name is not a string"; return false; } auto skinsArray = obj.value("skins").toArray(); for (auto skin : skinsArray) { auto skinObj = skin.toObject(); Skin skinOut; if (!getString(skinObj.value("id"), skinOut.id)) { continue; } QString state; if (!getString(skinObj.value("state"), state)) { continue; } if (state != "ACTIVE") { continue; } if (!getString(skinObj.value("url"), skinOut.url)) { continue; } skinOut.url.replace("http://textures.minecraft.net", "https://textures.minecraft.net"); if (!getString(skinObj.value("variant"), skinOut.variant)) { continue; } // we deal with only the active skin output.skin = skinOut; break; } auto capesArray = obj.value("capes").toArray(); QString currentCape; for (auto cape : capesArray) { auto capeObj = cape.toObject(); Cape capeOut; if (!getString(capeObj.value("id"), capeOut.id)) { continue; } QString state; if (!getString(capeObj.value("state"), state)) { continue; } if (state == "ACTIVE") { currentCape = capeOut.id; } if (!getString(capeObj.value("url"), capeOut.url)) { continue; } if (!getString(capeObj.value("alias"), capeOut.alias)) { continue; } output.capes[capeOut.id] = capeOut; } output.currentCape = currentCape; output.validity = Validity::Certain; return true; } namespace { // these skin URLs are for the MHF_Steve and MHF_Alex accounts (made by a Mojang employee) // they are needed because the session server doesn't return skin urls for default skins static const QString SKIN_URL_STEVE = "https://textures.minecraft.net/texture/1a4af718455d4aab528e7a61f86fa25e6a369d1768dcb13f7df319a713eb810b"; static const QString SKIN_URL_ALEX = "https://textures.minecraft.net/texture/83cee5ca6afcdb171285aa00e8049c297b2dbeba0efb8ff970a5677a1b644032"; bool isDefaultModelSteve(QString uuid) { // need to calculate *Java* hashCode of UUID // if number is even, skin/model is steve, otherwise it is alex // just in case dashes are in the id uuid.remove('-'); if (uuid.size() != 32) { return true; } // qulonglong is guaranteed to be 64 bits // we need to use unsigned numbers to guarantee truncation below qulonglong most = uuid.left(16).toULongLong(nullptr, 16); qulonglong least = uuid.right(16).toULongLong(nullptr, 16); qulonglong xored = most ^ least; return ((static_cast<quint32>(xored >> 32)) ^ static_cast<quint32>(xored)) % 2 == 0; } } // namespace /** Uses session server for skin/cape lookup instead of profile, because locked Mojang accounts cannot access profile endpoint (https://api.minecraftservices.com/minecraft/profile/) ref: https://wiki.vg/Mojang_API#UUID_to_Profile_and_Skin.2FCape { "id": "<profile identifier>", "name": "<player name>", "properties": [ { "name": "textures", "value": "<base64 string>" } ] } decoded base64 "value": { "timestamp": <java time in ms>, "profileId": "<profile uuid>", "profileName": "<player name>", "textures": { "SKIN": { "url": "<player skin URL>" }, "CAPE": { "url": "<player cape URL>" } } } */ bool parseMinecraftProfileMojang(QByteArray& data, MinecraftProfile& output) { qDebug() << "Parsing Minecraft profile..."; qCDebug(authCredentials()) << data; QJsonParseError jsonError; QJsonDocument doc = QJsonDocument::fromJson(data, &jsonError); if (jsonError.error) { qWarning() << "Failed to parse response as JSON: " << jsonError.errorString(); return false; } auto obj = Json::requireObject(doc, "mojang minecraft profile"); if (!getString(obj.value("id"), output.id)) { qWarning() << "Minecraft profile id is not a string"; return false; } if (!getString(obj.value("name"), output.name)) { qWarning() << "Minecraft profile name is not a string"; return false; } auto propsArray = obj.value("properties").toArray(); QByteArray texturePayload; for (auto p : propsArray) { auto pObj = p.toObject(); auto name = pObj.value("name"); if (!name.isString() || name.toString() != "textures") { continue; } auto value = pObj.value("value"); if (value.isString()) { #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) texturePayload = QByteArray::fromBase64(value.toString().toUtf8(), QByteArray::AbortOnBase64DecodingErrors); #else texturePayload = QByteArray::fromBase64(value.toString().toUtf8()); #endif } if (!texturePayload.isEmpty()) { break; } } if (texturePayload.isNull()) { qWarning() << "No texture payload data"; return false; } doc = QJsonDocument::fromJson(texturePayload, &jsonError); if (jsonError.error) { qWarning() << "Failed to parse response as JSON: " << jsonError.errorString(); return false; } obj = Json::requireObject(doc, "session texture payload"); auto textures = obj.value("textures"); if (!textures.isObject()) { qWarning() << "No textures array in response"; return false; } Skin skinOut; // fill in default skin info ourselves, as this endpoint doesn't provide it bool steve = isDefaultModelSteve(output.id); skinOut.variant = steve ? "CLASSIC" : "SLIM"; skinOut.url = steve ? SKIN_URL_STEVE : SKIN_URL_ALEX; // sadly we can't figure this out, but I don't think it really matters... skinOut.id = "00000000-0000-0000-0000-000000000000"; Cape capeOut; auto tObj = textures.toObject(); for (auto idx = tObj.constBegin(); idx != tObj.constEnd(); ++idx) { if (idx->isObject()) { if (idx.key() == "SKIN") { auto skin = idx->toObject(); if (!getString(skin.value("url"), skinOut.url)) { qWarning() << "Skin url is not a string"; return false; } auto maybeMeta = skin.find("metadata"); if (maybeMeta != skin.end() && maybeMeta->isObject()) { auto meta = maybeMeta->toObject(); // might not be present getString(meta.value("model"), skinOut.variant); } } else if (idx.key() == "CAPE") { auto cape = idx->toObject(); if (!getString(cape.value("url"), capeOut.url)) { qWarning() << "Cape url is not a string"; return false; } // we don't know the cape ID as it is not returned from the session server // so just fake it - changing capes is probably locked anyway :( capeOut.alias = "cape"; } } } output.skin = skinOut; if (capeOut.alias == "cape") { output.capes = QMap<QString, Cape>({ { capeOut.alias, capeOut } }); output.currentCape = capeOut.alias; } output.validity = Validity::Certain; return true; } bool parseMinecraftEntitlements(QByteArray& data, MinecraftEntitlement& output) { qDebug() << "Parsing Minecraft entitlements..."; qCDebug(authCredentials()) << data; QJsonParseError jsonError; QJsonDocument doc = QJsonDocument::fromJson(data, &jsonError); if (jsonError.error) { qWarning() << "Failed to parse response from user.auth.xboxlive.com as JSON: " << jsonError.errorString(); return false; } auto obj = doc.object(); output.canPlayMinecraft = false; output.ownsMinecraft = false; auto itemsArray = obj.value("items").toArray(); for (auto item : itemsArray) { auto itemObj = item.toObject(); QString name; if (!getString(itemObj.value("name"), name)) { continue; } if (name == "game_minecraft") { output.canPlayMinecraft = true; } if (name == "product_minecraft") { output.ownsMinecraft = true; } } output.validity = Validity::Certain; return true; } bool parseRolloutResponse(QByteArray& data, bool& result) { qDebug() << "Parsing Rollout response..."; qCDebug(authCredentials()) << data; QJsonParseError jsonError; QJsonDocument doc = QJsonDocument::fromJson(data, &jsonError); if (jsonError.error) { qWarning() << "Failed to parse response from https://api.minecraftservices.com/rollout/v1/msamigration as JSON: " << jsonError.errorString(); return false; } auto obj = doc.object(); QString feature; if (!getString(obj.value("feature"), feature)) { qWarning() << "Rollout feature is not a string"; return false; } if (feature != "msamigration") { qWarning() << "Rollout feature is not what we expected (msamigration), but is instead \"" << feature << "\""; return false; } if (!getBool(obj.value("rollout"), result)) { qWarning() << "Rollout feature is not a string"; return false; } return true; } bool parseMojangResponse(QByteArray& data, Token& output) { QJsonParseError jsonError; qDebug() << "Parsing Mojang response..."; qCDebug(authCredentials()) << data; QJsonDocument doc = QJsonDocument::fromJson(data, &jsonError); if (jsonError.error) { qWarning() << "Failed to parse response from api.minecraftservices.com/launcher/login as JSON: " << jsonError.errorString(); return false; } auto obj = doc.object(); double expires_in = 0; if (!getNumber(obj.value("expires_in"), expires_in)) { qWarning() << "expires_in is not a valid number"; return false; } auto currentTime = QDateTime::currentDateTimeUtc(); output.issueInstant = currentTime; output.notAfter = currentTime.addSecs(expires_in); QString username; if (!getString(obj.value("username"), username)) { qWarning() << "username is not valid"; return false; } // TODO: it's a JWT... validate it? if (!getString(obj.value("access_token"), output.token)) { qWarning() << "access_token is not valid"; return false; } output.validity = Validity::Certain; qDebug() << "Mojang response is valid."; return true; } } // namespace Parsers
14,870
C++
.cpp
443
26.75395
132
0.606345
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,206
AuthSession.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/auth/AuthSession.cpp
#include "AuthSession.h" #include <QJsonArray> #include <QJsonDocument> #include <QJsonObject> #include <QStringList> QString AuthSession::serializeUserProperties() { QJsonObject userAttrs; /* for (auto key : u.properties.keys()) { auto array = QJsonArray::fromStringList(u.properties.values(key)); userAttrs.insert(key, array); } */ QJsonDocument value(userAttrs); return value.toJson(QJsonDocument::Compact); } bool AuthSession::MakeOffline(QString offline_playername) { if (status != PlayableOffline && status != PlayableOnline) { return false; } session = "-"; access_token = "0"; player_name = offline_playername; status = PlayableOffline; return true; } void AuthSession::MakeDemo(QString name, QString u) { wants_online = false; demo = true; uuid = u; session = "-"; access_token = "0"; player_name = name; status = PlayableOnline; // needs online to download the assets };
996
C++
.cpp
39
21.615385
74
0.68377
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,207
MinecraftAccount.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/auth/MinecraftAccount.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Authors: Orochimarufan <orochimarufan.x3@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "MinecraftAccount.h" #include <QColor> #include <QCryptographicHash> #include <QJsonArray> #include <QJsonDocument> #include <QJsonObject> #include <QRegularExpression> #include <QStringList> #include <QUuid> #include <QDebug> #include <QPainter> #include "minecraft/auth/AccountData.h" #include "minecraft/auth/AuthFlow.h" MinecraftAccount::MinecraftAccount(QObject* parent) : QObject(parent) { data.internalId = QUuid::createUuid().toString().remove(QRegularExpression("[{}-]")); } MinecraftAccountPtr MinecraftAccount::loadFromJsonV3(const QJsonObject& json) { MinecraftAccountPtr account(new MinecraftAccount()); if (account->data.resumeStateFromV3(json)) { return account; } return nullptr; } MinecraftAccountPtr MinecraftAccount::createBlankMSA() { MinecraftAccountPtr account(new MinecraftAccount()); account->data.type = AccountType::MSA; return account; } MinecraftAccountPtr MinecraftAccount::createOffline(const QString& username) { auto account = makeShared<MinecraftAccount>(); account->data.type = AccountType::Offline; account->data.yggdrasilToken.token = "0"; account->data.yggdrasilToken.validity = Validity::Certain; account->data.yggdrasilToken.issueInstant = QDateTime::currentDateTimeUtc(); account->data.yggdrasilToken.extra["userName"] = username; account->data.yggdrasilToken.extra["clientToken"] = QUuid::createUuid().toString().remove(QRegularExpression("[{}-]")); account->data.minecraftProfile.id = uuidFromUsername(username).toString().remove(QRegularExpression("[{}-]")); account->data.minecraftProfile.name = username; account->data.minecraftProfile.validity = Validity::Certain; return account; } QJsonObject MinecraftAccount::saveToJson() const { return data.saveState(); } AccountState MinecraftAccount::accountState() const { return data.accountState; } QPixmap MinecraftAccount::getFace() const { QPixmap skinTexture; if (!skinTexture.loadFromData(data.minecraftProfile.skin.data, "PNG")) { 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<AuthFlow> MinecraftAccount::login(bool useDeviceCode) { Q_ASSERT(m_currentTask.get() == nullptr); m_currentTask.reset(new AuthFlow(&data, useDeviceCode ? AuthFlow::Action::DeviceCode : AuthFlow::Action::Login)); 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<AuthFlow> MinecraftAccount::refresh() { if (m_currentTask) { return m_currentTask; } m_currentTask.reset(new AuthFlow(&data, AuthFlow::Action::Refresh)); 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<AuthFlow> MinecraftAccount::currentTask() { return m_currentTask; } void MinecraftAccount::authSucceeded() { m_currentTask.reset(); emit changed(); emit activityChanged(false); } void MinecraftAccount::authFailed(QString reason) { switch (m_currentTask->taskState()) { case AccountTaskState::STATE_OFFLINE: case AccountTaskState::STATE_DISABLED: { // NOTE: user will need to fix this themselves. } case AccountTaskState::STATE_FAILED_SOFT: { // NOTE: this doesn't do much. There was an error of some sort. } break; case AccountTaskState::STATE_FAILED_HARD: { if (accountType() == AccountType::MSA) { data.msaToken.token = QString(); data.msaToken.refresh_token = QString(); data.msaToken.validity = Validity::None; data.validity_ = Validity::None; } else { data.yggdrasilToken.token = QString(); data.yggdrasilToken.validity = Validity::None; data.validity_ = Validity::None; } emit changed(); } break; case AccountTaskState::STATE_FAILED_GONE: { data.validity_ = Validity::None; emit changed(); } break; case AccountTaskState::STATE_CREATED: case AccountTaskState::STATE_WORKING: case AccountTaskState::STATE_SUCCEEDED: { // Not reachable here, as they are not failures. } } m_currentTask.reset(); emit activityChanged(false); } bool MinecraftAccount::isActive() const { return !m_currentTask.isNull(); } bool MinecraftAccount::shouldRefresh() const { /* * Never refresh accounts that are being used by the game, it breaks the game session. * Always refresh accounts that have not been refreshed yet during this session. * Don't refresh broken accounts. * Refresh accounts that would expire in the next 12 hours (fresh token validity is 24 hours). */ if (isInUse()) { return false; } switch (data.validity_) { case Validity::Certain: { break; } case Validity::None: { return false; } case Validity::Assumed: { return true; } } auto now = QDateTime::currentDateTimeUtc(); auto issuedTimestamp = data.yggdrasilToken.issueInstant; auto expiresTimestamp = data.yggdrasilToken.notAfter; if (!expiresTimestamp.isValid()) { expiresTimestamp = issuedTimestamp.addSecs(24 * 3600); } if (now.secsTo(expiresTimestamp) < (12 * 3600)) { return true; } return false; } void MinecraftAccount::fillSession(AuthSessionPtr session) { if (ownsMinecraft() && !hasProfile()) { session->status = AuthSession::RequiresProfileSetup; } else { if (session->wants_online) { session->status = AuthSession::PlayableOnline; } else { session->status = AuthSession::PlayableOffline; } } // volatile auth token session->access_token = data.accessToken(); // profile name session->player_name = data.profileName(); // profile ID session->uuid = data.profileId(); if (session->uuid.isEmpty()) session->uuid = uuidFromUsername(session->player_name).toString().remove(QRegularExpression("[{}-]")); // 'legacy' or 'mojang', depending on account type session->user_type = typeString(); if (!session->access_token.isEmpty()) { session->session = "token:" + data.accessToken() + ":" + data.profileId(); } else { session->session = "-"; } } void MinecraftAccount::decrementUses() { Usable::decrementUses(); if (!isInUse()) { emit changed(); // FIXME: we now need a better way to identify accounts... qWarning() << "Profile" << data.profileId() << "is no longer in use."; } } void MinecraftAccount::incrementUses() { bool wasInUse = isInUse(); Usable::incrementUses(); if (!wasInUse) { emit changed(); // FIXME: we now need a better way to identify accounts... qWarning() << "Profile" << data.profileId() << "is now in use."; } } QUuid MinecraftAccount::uuidFromUsername(QString username) { auto input = QString("OfflinePlayer:%1").arg(username).toUtf8(); // basically a reimplementation of Java's UUID#nameUUIDFromBytes QByteArray digest = QCryptographicHash::hash(input, QCryptographicHash::Md5); #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) auto bOr = [](QByteArray& array, int index, char value) { array[index] = array.at(index) | value; }; auto bAnd = [](QByteArray& array, int index, char value) { array[index] = array.at(index) & value; }; #else auto bOr = [](QByteArray& array, qsizetype index, char value) { array[index] |= value; }; auto bAnd = [](QByteArray& array, qsizetype index, char value) { array[index] &= value; }; #endif bAnd(digest, 6, (char)0x0f); // clear version bOr(digest, 6, (char)0x30); // set to version 3 bAnd(digest, 8, (char)0x3f); // clear variant bOr(digest, 8, (char)0x80); // set to IETF variant return QUuid::fromRfc4122(digest); }
10,389
C++
.cpp
275
32.843636
123
0.684518
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,208
AccountList.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/auth/AccountList.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 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 "AccountList.h" #include "AccountData.h" #include "tasks/Task.h" #include <QDir> #include <QFile> #include <QIODevice> #include <QJsonArray> #include <QJsonDocument> #include <QJsonObject> #include <QJsonParseError> #include <QTextStream> #include <QTimer> #include <QDebug> #include <FileSystem.h> #include <QSaveFile> enum AccountListVersion { MojangMSA = 3 }; AccountList::AccountList(QObject* parent) : QAbstractListModel(parent) { m_refreshTimer = new QTimer(this); m_refreshTimer->setSingleShot(true); connect(m_refreshTimer, &QTimer::timeout, this, &AccountList::fillQueue); m_nextTimer = new QTimer(this); m_nextTimer->setSingleShot(true); connect(m_nextTimer, &QTimer::timeout, this, &AccountList::tryNext); } AccountList::~AccountList() noexcept {} int AccountList::findAccountByProfileId(const QString& profileId) const { for (int i = 0; i < count(); i++) { MinecraftAccountPtr account = at(i); if (account->profileId() == profileId) { return i; } } return -1; } MinecraftAccountPtr AccountList::getAccountByProfileName(const QString& profileName) const { for (int i = 0; i < count(); i++) { MinecraftAccountPtr account = at(i); if (account->profileName() == profileName) { return account; } } return nullptr; } const MinecraftAccountPtr AccountList::at(int i) const { return MinecraftAccountPtr(m_accounts.at(i)); } QStringList AccountList::profileNames() const { QStringList out; for (auto& account : m_accounts) { auto profileName = account->profileName(); if (profileName.isEmpty()) { continue; } out.append(profileName); } return out; } void AccountList::addAccount(const MinecraftAccountPtr account) { // NOTE: Do not allow adding something that's already there. We shouldn't let it continue // because of the signal / slot connections after this. if (m_accounts.contains(account)) { qDebug() << "Tried to add account that's already on the accounts list!"; return; } // hook up notifications for changes in the account connect(account.get(), &MinecraftAccount::changed, this, &AccountList::accountChanged); connect(account.get(), &MinecraftAccount::activityChanged, this, &AccountList::accountActivityChanged); // override/replace existing account with the same profileId auto profileId = account->profileId(); if (profileId.size()) { auto existingAccount = findAccountByProfileId(profileId); if (existingAccount != -1) { qDebug() << "Replacing old account with a new one with the same profile ID!"; MinecraftAccountPtr existingAccountPtr = m_accounts[existingAccount]; m_accounts[existingAccount] = account; if (m_defaultAccount == existingAccountPtr) { m_defaultAccount = account; } // disconnect notifications for changes in the account being replaced existingAccountPtr->disconnect(this); emit dataChanged(index(existingAccount), index(existingAccount, columnCount(QModelIndex()) - 1)); onListChanged(); return; } } // if we don't have this profileId yet, add the account to the end int row = m_accounts.count(); qDebug() << "Inserting account at index" << row; beginInsertRows(QModelIndex(), row, row); m_accounts.append(account); endInsertRows(); onListChanged(); } void AccountList::removeAccount(QModelIndex index) { int row = index.row(); if (index.isValid() && row >= 0 && row < m_accounts.size()) { auto& account = m_accounts[row]; if (account == m_defaultAccount) { m_defaultAccount = nullptr; onDefaultAccountChanged(); } account->disconnect(this); beginRemoveRows(QModelIndex(), row, row); m_accounts.removeAt(index.row()); endRemoveRows(); onListChanged(); } } MinecraftAccountPtr AccountList::defaultAccount() const { return m_defaultAccount; } void AccountList::setDefaultAccount(MinecraftAccountPtr newAccount) { if (!newAccount && m_defaultAccount) { int idx = 0; auto previousDefaultAccount = m_defaultAccount; m_defaultAccount = nullptr; for (MinecraftAccountPtr account : m_accounts) { if (account == previousDefaultAccount) { emit dataChanged(index(idx), index(idx, columnCount(QModelIndex()) - 1)); } idx++; } onDefaultAccountChanged(); } else { auto currentDefaultAccount = m_defaultAccount; int currentDefaultAccountIdx = -1; auto newDefaultAccount = m_defaultAccount; int newDefaultAccountIdx = -1; int idx = 0; for (MinecraftAccountPtr account : m_accounts) { if (account == newAccount) { newDefaultAccount = account; newDefaultAccountIdx = idx; } if (currentDefaultAccount == account) { currentDefaultAccountIdx = idx; } idx++; } if (currentDefaultAccount != newDefaultAccount) { emit dataChanged(index(currentDefaultAccountIdx), index(currentDefaultAccountIdx, columnCount(QModelIndex()) - 1)); emit dataChanged(index(newDefaultAccountIdx), index(newDefaultAccountIdx, columnCount(QModelIndex()) - 1)); m_defaultAccount = newDefaultAccount; onDefaultAccountChanged(); } } } void AccountList::accountChanged() { // the list changed. there is no doubt. onListChanged(); } void AccountList::accountActivityChanged(bool active) { MinecraftAccount* account = qobject_cast<MinecraftAccount*>(sender()); bool found = false; for (int i = 0; i < count(); i++) { if (at(i).get() == account) { emit dataChanged(index(i), index(i, columnCount(QModelIndex()) - 1)); found = true; break; } } if (found) { emit listActivityChanged(); if (active) { beginActivity(); } else { endActivity(); } } } void AccountList::onListChanged() { if (m_autosave) // TODO: Alert the user if this fails. saveList(); emit listChanged(); } void AccountList::onDefaultAccountChanged() { if (m_autosave) saveList(); emit defaultAccountChanged(); } int AccountList::count() const { return m_accounts.count(); } QVariant AccountList::data(const QModelIndex& index, int role) const { if (!index.isValid()) return QVariant(); if (index.row() > count()) return QVariant(); MinecraftAccountPtr account = at(index.row()); switch (role) { case Qt::DisplayRole: switch (index.column()) { case ProfileNameColumn: { return account->profileName(); } case NameColumn: return account->accountDisplayString(); case TypeColumn: { switch (account->accountType()) { case AccountType::MSA: { return tr("MSA", "Account type"); } case AccountType::Offline: { return tr("Offline", "Account type"); } } return tr("Unknown", "Account type"); } case StatusColumn: { switch (account->accountState()) { case AccountState::Unchecked: { return tr("Unchecked", "Account status"); } case AccountState::Offline: { return tr("Offline", "Account status"); } case AccountState::Online: { return tr("Ready", "Account status"); } case AccountState::Working: { return tr("Working", "Account status"); } case AccountState::Errored: { return tr("Errored", "Account status"); } case AccountState::Expired: { return tr("Expired", "Account status"); } case AccountState::Disabled: { return tr("Disabled", "Account status"); } case AccountState::Gone: { return tr("Gone", "Account status"); } default: { return tr("Unknown", "Account status"); } } } default: return QVariant(); } case Qt::ToolTipRole: return account->accountDisplayString(); case PointerRole: return QVariant::fromValue(account); case Qt::CheckStateRole: if (index.column() == ProfileNameColumn) { return account == m_defaultAccount ? Qt::Checked : Qt::Unchecked; } else { return QVariant(); } default: return QVariant(); } } QVariant AccountList::headerData(int section, [[maybe_unused]] Qt::Orientation orientation, int role) const { switch (role) { case Qt::DisplayRole: switch (section) { case ProfileNameColumn: return tr("Username"); case NameColumn: return tr("Account"); case TypeColumn: return tr("Type"); case StatusColumn: return tr("Status"); default: return QVariant(); } case Qt::ToolTipRole: switch (section) { case ProfileNameColumn: return tr("Minecraft username associated with the account."); case NameColumn: return tr("User name of the account."); case TypeColumn: return tr("Type of the account (MSA or Offline)"); case StatusColumn: return tr("Current status of the account."); default: return QVariant(); } default: return QVariant(); } } int AccountList::rowCount(const QModelIndex& parent) const { // Return count return parent.isValid() ? 0 : count(); } int AccountList::columnCount(const QModelIndex& parent) const { return parent.isValid() ? 0 : NUM_COLUMNS; } Qt::ItemFlags AccountList::flags(const QModelIndex& index) const { if (index.row() < 0 || index.row() >= rowCount(index.parent()) || !index.isValid()) { return Qt::NoItemFlags; } return Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable; } bool AccountList::setData(const QModelIndex& idx, const QVariant& value, int role) { if (idx.row() < 0 || idx.row() >= rowCount(idx.parent()) || !idx.isValid()) { return false; } if (role == Qt::CheckStateRole) { 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)); return true; } bool AccountList::loadList() { if (m_listFilePath.isEmpty()) { qCritical() << "Can't load Mojang account list. No file path given and no default set."; return false; } QFile file(m_listFilePath); // Try to open the file and fail if we can't. // TODO: We should probably report this error to the user. if (!file.open(QIODevice::ReadOnly)) { qCritical() << QString("Failed to read the account list file (%1).").arg(m_listFilePath).toUtf8(); return false; } // Read the file and close it. QByteArray jsonData = file.readAll(); file.close(); QJsonParseError parseError; QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonData, &parseError); // Fail if the JSON is invalid. if (parseError.error != QJsonParseError::NoError) { qCritical() << QString("Failed to parse account list file: %1 at offset %2") .arg(parseError.errorString(), QString::number(parseError.offset)) .toUtf8(); return false; } // Make sure the root is an object. if (!jsonDoc.isObject()) { qCritical() << "Invalid account list JSON: Root should be an array."; return false; } QJsonObject root = jsonDoc.object(); // Make sure the format version matches. auto listVersion = root.value("formatVersion").toVariant().toInt(); switch (listVersion) { case AccountListVersion::MojangMSA: { return loadV3(root); } break; default: { QString newName = "accounts-old.json"; qWarning() << "Unknown format version when loading account list. Existing one will be renamed to" << newName; // Attempt to rename the old version. file.rename(newName); return false; } } } bool AccountList::loadV3(QJsonObject& root) { beginResetModel(); QJsonArray accounts = root.value("accounts").toArray(); for (QJsonValue accountVal : accounts) { QJsonObject accountObj = accountVal.toObject(); MinecraftAccountPtr account = MinecraftAccount::loadFromJsonV3(accountObj); if (account.get() != nullptr) { auto profileId = account->profileId(); if (profileId.size()) { 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 (accountObj.value("active").toBool(false)) { m_defaultAccount = account; } } else { qWarning() << "Failed to load an account."; } } endResetModel(); return true; } bool AccountList::saveList() { if (m_listFilePath.isEmpty()) { qCritical() << "Can't save Mojang account list. No file path given and no default set."; return false; } // make sure the parent folder exists if (!FS::ensureFilePathExists(m_listFilePath)) return false; // make sure the file wasn't overwritten with a folder before (fixes a bug) QFileInfo finfo(m_listFilePath); if (finfo.isDir()) { QDir badDir(m_listFilePath); badDir.removeRecursively(); } qDebug() << "Writing account list to" << m_listFilePath; qDebug() << "Building JSON data structure."; // Build the JSON document to write to the list file. QJsonObject root; root.insert("formatVersion", AccountListVersion::MojangMSA); // Build a list of accounts. qDebug() << "Building account array."; QJsonArray accounts; for (MinecraftAccountPtr account : m_accounts) { QJsonObject accountObj = account->saveToJson(); if (m_defaultAccount == account) { accountObj["active"] = true; } accounts.append(accountObj); } // Insert the account list into the root object. root.insert("accounts", accounts); // Create a JSON document object to convert our JSON to bytes. QJsonDocument doc(root); // Now that we're done building the JSON object, we can write it to the file. qDebug() << "Writing account list to file."; QSaveFile file(m_listFilePath); // Try to open the file and fail if we can't. // TODO: We should probably report this error to the user. if (!file.open(QIODevice::WriteOnly)) { qCritical() << QString("Failed to read the account list file (%1).").arg(m_listFilePath).toUtf8(); return false; } // Write the JSON to the file. file.write(doc.toJson()); file.setPermissions(QFile::ReadOwner | QFile::WriteOwner | QFile::ReadUser | QFile::WriteUser); if (file.commit()) { qDebug() << "Saved account list to" << m_listFilePath; return true; } else { qDebug() << "Failed to save accounts to" << m_listFilePath; return false; } } void AccountList::setListFilePath(QString path, bool autosave) { m_listFilePath = path; m_autosave = autosave; } bool AccountList::anyAccountIsValid() { for (auto account : m_accounts) { if (account->ownsMinecraft()) { return true; } } return false; } void AccountList::fillQueue() { if (m_defaultAccount && m_defaultAccount->shouldRefresh()) { auto idToRefresh = m_defaultAccount->internalId(); m_refreshQueue.push_back(idToRefresh); qDebug() << "AccountList: Queued default account with internal ID " << idToRefresh << " to refresh first"; } for (int i = 0; i < count(); i++) { auto account = at(i); if (account == m_defaultAccount) { continue; } if (account->shouldRefresh()) { auto idToRefresh = account->internalId(); queueRefresh(idToRefresh); } } tryNext(); } void AccountList::requestRefresh(QString accountId) { auto index = m_refreshQueue.indexOf(accountId); if (index != -1) { m_refreshQueue.removeAt(index); } m_refreshQueue.push_front(accountId); qDebug() << "AccountList: Pushed account with internal ID " << accountId << " to the front of the queue"; if (!isActive()) { tryNext(); } } void AccountList::queueRefresh(QString accountId) { if (m_refreshQueue.indexOf(accountId) != -1) { return; } m_refreshQueue.push_back(accountId); qDebug() << "AccountList: Queued account with internal ID " << accountId << " to refresh"; } void AccountList::tryNext() { while (m_refreshQueue.length()) { auto accountId = m_refreshQueue.front(); m_refreshQueue.pop_front(); for (int i = 0; i < count(); i++) { auto account = at(i); if (account->internalId() == accountId) { m_currentTask = account->refresh(); if (m_currentTask) { connect(m_currentTask.get(), &Task::succeeded, this, &AccountList::authSucceeded); connect(m_currentTask.get(), &Task::failed, this, &AccountList::authFailed); m_currentTask->start(); qDebug() << "RefreshSchedule: Processing account " << account->accountDisplayString() << " with internal ID " << accountId; return; } } } qDebug() << "RefreshSchedule: Account with with internal ID " << accountId << " not found."; } // if we get here, no account needed refreshing. Schedule refresh in an hour. m_refreshTimer->start(1000 * 3600); } void AccountList::authSucceeded() { qDebug() << "RefreshSchedule: Background account refresh succeeded"; m_currentTask.reset(); m_nextTimer->start(1000 * 20); } void AccountList::authFailed(QString reason) { qDebug() << "RefreshSchedule: Background account refresh failed: " << reason; m_currentTask.reset(); m_nextTimer->start(1000 * 20); } bool AccountList::isActive() const { return m_activityCount != 0; } void AccountList::beginActivity() { bool activating = m_activityCount == 0; m_activityCount++; if (activating) { emit activityChanged(true); } } void AccountList::endActivity() { if (m_activityCount == 0) { qWarning() << m_name << " - Activity count would become below zero"; return; } bool deactivating = m_activityCount == 1; m_activityCount--; if (deactivating) { emit activityChanged(false); } }
22,042
C++
.cpp
610
27.74918
129
0.601986
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,209
AccountData.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/auth/AccountData.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 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 "AccountData.h" #include <QDebug> #include <QJsonArray> #include <QJsonDocument> #include <QJsonObject> #include <QRegularExpression> #include <QUuid> namespace { void tokenToJSONV3(QJsonObject& parent, Token t, const char* tokenName) { if (!t.persistent) { return; } QJsonObject out; if (t.issueInstant.isValid()) { out["iat"] = QJsonValue(t.issueInstant.toMSecsSinceEpoch() / 1000); } if (t.notAfter.isValid()) { out["exp"] = QJsonValue(t.notAfter.toMSecsSinceEpoch() / 1000); } bool save = false; if (!t.token.isEmpty()) { out["token"] = QJsonValue(t.token); save = true; } if (!t.refresh_token.isEmpty()) { out["refresh_token"] = QJsonValue(t.refresh_token); save = true; } if (t.extra.size()) { out["extra"] = QJsonObject::fromVariantMap(t.extra); save = true; } if (save) { parent[tokenName] = out; } } Token tokenFromJSONV3(const QJsonObject& parent, const char* tokenName) { Token out; auto tokenObject = parent.value(tokenName).toObject(); if (tokenObject.isEmpty()) { return out; } auto issueInstant = tokenObject.value("iat"); if (issueInstant.isDouble()) { out.issueInstant = QDateTime::fromMSecsSinceEpoch(((int64_t)issueInstant.toDouble()) * 1000); } auto notAfter = tokenObject.value("exp"); if (notAfter.isDouble()) { out.notAfter = QDateTime::fromMSecsSinceEpoch(((int64_t)notAfter.toDouble()) * 1000); } auto token = tokenObject.value("token"); if (token.isString()) { out.token = token.toString(); out.validity = Validity::Assumed; } auto refresh_token = tokenObject.value("refresh_token"); if (refresh_token.isString()) { out.refresh_token = refresh_token.toString(); } auto extra = tokenObject.value("extra"); if (extra.isObject()) { out.extra = extra.toObject().toVariantMap(); } return out; } void profileToJSONV3(QJsonObject& parent, MinecraftProfile p, const char* tokenName) { if (p.id.isEmpty()) { return; } QJsonObject out; out["id"] = QJsonValue(p.id); out["name"] = QJsonValue(p.name); if (!p.currentCape.isEmpty()) { out["cape"] = p.currentCape; } { QJsonObject skinObj; skinObj["id"] = p.skin.id; skinObj["url"] = p.skin.url; skinObj["variant"] = p.skin.variant; if (p.skin.data.size()) { skinObj["data"] = QString::fromLatin1(p.skin.data.toBase64()); } out["skin"] = skinObj; } QJsonArray capesArray; for (auto& cape : p.capes) { QJsonObject capeObj; capeObj["id"] = cape.id; capeObj["url"] = cape.url; capeObj["alias"] = cape.alias; if (cape.data.size()) { capeObj["data"] = QString::fromLatin1(cape.data.toBase64()); } capesArray.push_back(capeObj); } out["capes"] = capesArray; parent[tokenName] = out; } MinecraftProfile profileFromJSONV3(const QJsonObject& parent, const char* tokenName) { MinecraftProfile out; auto tokenObject = parent.value(tokenName).toObject(); if (tokenObject.isEmpty()) { return out; } { auto idV = tokenObject.value("id"); auto nameV = tokenObject.value("name"); if (!idV.isString() || !nameV.isString()) { qWarning() << "mandatory profile attributes are missing or of unexpected type"; return MinecraftProfile(); } out.name = nameV.toString(); out.id = idV.toString(); } { auto skinV = tokenObject.value("skin"); if (!skinV.isObject()) { qWarning() << "skin is missing"; return MinecraftProfile(); } auto skinObj = skinV.toObject(); auto idV = skinObj.value("id"); auto urlV = skinObj.value("url"); auto variantV = skinObj.value("variant"); if (!idV.isString() || !urlV.isString() || !variantV.isString()) { qWarning() << "mandatory skin attributes are missing or of unexpected type"; return MinecraftProfile(); } out.skin.id = idV.toString(); out.skin.url = urlV.toString(); out.skin.variant = variantV.toString(); // data for skin is optional auto dataV = skinObj.value("data"); if (dataV.isString()) { // TODO: validate base64 out.skin.data = QByteArray::fromBase64(dataV.toString().toLatin1()); } else if (!dataV.isUndefined()) { qWarning() << "skin data is something unexpected"; return MinecraftProfile(); } } { auto capesV = tokenObject.value("capes"); if (!capesV.isArray()) { qWarning() << "capes is not an array!"; return MinecraftProfile(); } auto capesArray = capesV.toArray(); for (auto capeV : capesArray) { if (!capeV.isObject()) { qWarning() << "cape is not an object!"; return MinecraftProfile(); } auto capeObj = capeV.toObject(); auto idV = capeObj.value("id"); auto urlV = capeObj.value("url"); auto aliasV = capeObj.value("alias"); if (!idV.isString() || !urlV.isString() || !aliasV.isString()) { qWarning() << "mandatory skin attributes are missing or of unexpected type"; return MinecraftProfile(); } Cape cape; cape.id = idV.toString(); cape.url = urlV.toString(); cape.alias = aliasV.toString(); // data for cape is optional. auto dataV = capeObj.value("data"); if (dataV.isString()) { // TODO: validate base64 cape.data = QByteArray::fromBase64(dataV.toString().toLatin1()); } else if (!dataV.isUndefined()) { qWarning() << "cape data is something unexpected"; return MinecraftProfile(); } out.capes[cape.id] = cape; } } // current cape { auto capeV = tokenObject.value("cape"); if (capeV.isString()) { auto currentCape = capeV.toString(); if (out.capes.contains(currentCape)) { out.currentCape = currentCape; } } } out.validity = Validity::Assumed; return out; } void entitlementToJSONV3(QJsonObject& parent, MinecraftEntitlement p) { if (p.validity == Validity::None) { return; } QJsonObject out; out["ownsMinecraft"] = QJsonValue(p.ownsMinecraft); out["canPlayMinecraft"] = QJsonValue(p.canPlayMinecraft); parent["entitlement"] = out; } bool entitlementFromJSONV3(const QJsonObject& parent, MinecraftEntitlement& out) { auto entitlementObject = parent.value("entitlement").toObject(); if (entitlementObject.isEmpty()) { return false; } { auto ownsMinecraftV = entitlementObject.value("ownsMinecraft"); auto canPlayMinecraftV = entitlementObject.value("canPlayMinecraft"); if (!ownsMinecraftV.isBool() || !canPlayMinecraftV.isBool()) { qWarning() << "mandatory attributes are missing or of unexpected type"; return false; } out.canPlayMinecraft = canPlayMinecraftV.toBool(false); out.ownsMinecraft = ownsMinecraftV.toBool(false); out.validity = Validity::Assumed; } return true; } } // namespace bool AccountData::resumeStateFromV3(QJsonObject data) { auto typeV = data.value("type"); if (!typeV.isString()) { qWarning() << "Failed to parse account data: type is missing."; return false; } auto typeS = typeV.toString(); if (typeS == "MSA") { type = AccountType::MSA; } else if (typeS == "Offline") { type = AccountType::Offline; } else { qWarning() << "Failed to parse account data: type is not recognized."; return false; } if (type == AccountType::MSA) { auto clientIDV = data.value("msa-client-id"); if (clientIDV.isString()) { msaClientID = clientIDV.toString(); } // leave msaClientID empty if it doesn't exist or isn't a string msaToken = tokenFromJSONV3(data, "msa"); userToken = tokenFromJSONV3(data, "utoken"); xboxApiToken = tokenFromJSONV3(data, "xrp-main"); mojangservicesToken = tokenFromJSONV3(data, "xrp-mc"); } yggdrasilToken = tokenFromJSONV3(data, "ygg"); // versions before 7.2 used "offline" as the offline token if (yggdrasilToken.token == "offline") yggdrasilToken.token = "0"; minecraftProfile = profileFromJSONV3(data, "profile"); if (!entitlementFromJSONV3(data, minecraftEntitlement)) { if (minecraftProfile.validity != Validity::None) { minecraftEntitlement.canPlayMinecraft = true; minecraftEntitlement.ownsMinecraft = true; minecraftEntitlement.validity = Validity::Assumed; } } validity_ = minecraftProfile.validity; return true; } QJsonObject AccountData::saveState() const { QJsonObject output; if (type == AccountType::MSA) { output["type"] = "MSA"; output["msa-client-id"] = msaClientID; tokenToJSONV3(output, msaToken, "msa"); tokenToJSONV3(output, userToken, "utoken"); tokenToJSONV3(output, xboxApiToken, "xrp-main"); tokenToJSONV3(output, mojangservicesToken, "xrp-mc"); } else if (type == AccountType::Offline) { output["type"] = "Offline"; } tokenToJSONV3(output, yggdrasilToken, "ygg"); profileToJSONV3(output, minecraftProfile, "profile"); entitlementToJSONV3(output, minecraftEntitlement); return output; } QString AccountData::accessToken() const { return yggdrasilToken.token; } QString AccountData::profileId() const { return minecraftProfile.id; } QString AccountData::profileName() const { if (minecraftProfile.name.size() == 0) { return QObject::tr("No profile (%1)").arg(accountDisplayString()); } else { return minecraftProfile.name; } } QString AccountData::accountDisplayString() const { switch (type) { case AccountType::Offline: { return QObject::tr("<Offline>"); } case AccountType::MSA: { if (xboxApiToken.extra.contains("gtg")) { return xboxApiToken.extra["gtg"].toString(); } return "Xbox profile missing"; } default: { return "Invalid Account"; } } } QString AccountData::lastError() const { return errorString; }
12,307
C++
.cpp
355
27.842254
101
0.62198
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,210
MinecraftProfileStep.cpp
PrismLauncher_PrismLauncher/launcher/minecraft/auth/steps/MinecraftProfileStep.cpp
#include "MinecraftProfileStep.h" #include <QNetworkRequest> #include "Application.h" #include "minecraft/auth/Parsers.h" #include "net/NetUtils.h" #include "net/RawHeaderProxy.h" MinecraftProfileStep::MinecraftProfileStep(AccountData* data) : AuthStep(data) {} QString MinecraftProfileStep::describe() { return tr("Fetching the Minecraft profile."); } void MinecraftProfileStep::perform() { QUrl url("https://api.minecraftservices.com/minecraft/profile"); auto headers = QList<Net::HeaderPair>{ { "Content-Type", "application/json" }, { "Accept", "application/json" }, { "Authorization", QString("Bearer %1").arg(m_data->yggdrasilToken.token).toUtf8() } }; m_response.reset(new QByteArray()); m_request = Net::Download::makeByteArray(url, m_response); m_request->addHeaderProxy(new Net::RawHeaderProxy(headers)); m_task.reset(new NetJob("MinecraftProfileStep", APPLICATION->network())); m_task->setAskRetry(false); m_task->addNetAction(m_request); connect(m_task.get(), &Task::finished, this, &MinecraftProfileStep::onRequestDone); m_task->start(); } void MinecraftProfileStep::onRequestDone() { if (m_request->error() == QNetworkReply::ContentNotFoundError) { // NOTE: Succeed even if we do not have a profile. This is a valid account state. m_data->minecraftProfile = MinecraftProfile(); emit finished(AccountTaskState::STATE_WORKING, tr("Account has no Minecraft profile.")); return; } if (m_request->error() != QNetworkReply::NoError) { qWarning() << "Error getting profile:"; qWarning() << " HTTP Status: " << m_request->replyStatusCode(); qWarning() << " Internal error no.: " << m_request->error(); qWarning() << " Error string: " << m_request->errorString(); qWarning() << " Response:"; qWarning() << QString::fromUtf8(*m_response); if (Net::isApplicationError(m_request->error())) { emit finished(AccountTaskState::STATE_FAILED_SOFT, tr("Minecraft Java profile acquisition failed: %1").arg(m_request->errorString())); } else { emit finished(AccountTaskState::STATE_OFFLINE, tr("Minecraft Java profile acquisition failed: %1").arg(m_request->errorString())); } return; } if (!Parsers::parseMinecraftProfile(*m_response, m_data->minecraftProfile)) { m_data->minecraftProfile = MinecraftProfile(); emit finished(AccountTaskState::STATE_FAILED_SOFT, tr("Minecraft Java profile response could not be parsed")); return; } emit finished(AccountTaskState::STATE_WORKING, tr("Minecraft Java profile acquisition succeeded.")); }
2,825
C++
.cpp
57
41.842105
130
0.654446
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false