From 9ec1c00887579e97c7b7a190756f6ddae583563f Mon Sep 17 00:00:00 2001 From: Sefa Eyeoglu Date: Sat, 11 Jun 2022 10:48:56 +0200 Subject: [PATCH 001/101] fix: register JavaRealArchitecture for MinecraftInstance Signed-off-by: Sefa Eyeoglu --- launcher/minecraft/MinecraftInstance.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/launcher/minecraft/MinecraftInstance.cpp b/launcher/minecraft/MinecraftInstance.cpp index 62540c75..8496adee 100644 --- a/launcher/minecraft/MinecraftInstance.cpp +++ b/launcher/minecraft/MinecraftInstance.cpp @@ -147,6 +147,7 @@ void MinecraftInstance::loadSpecificSettings() m_settings->registerPassthrough(global_settings->getSetting("JavaTimestamp"), javaOrLocation); m_settings->registerPassthrough(global_settings->getSetting("JavaVersion"), javaOrLocation); m_settings->registerPassthrough(global_settings->getSetting("JavaArchitecture"), javaOrLocation); + m_settings->registerPassthrough(global_settings->getSetting("JavaRealArchitecture"), javaOrLocation); // Window Size auto windowSetting = m_settings->registerSetting("OverrideWindow", false); From 09e85e948cdb361c306a1cccbc3557a464366a21 Mon Sep 17 00:00:00 2001 From: Sefa Eyeoglu Date: Mon, 11 Jul 2022 09:01:07 +0200 Subject: [PATCH 002/101] refactor: introduce RuntimeContext Signed-off-by: Sefa Eyeoglu --- launcher/BaseInstance.cpp | 5 ++ launcher/BaseInstance.h | 8 ++++ launcher/CMakeLists.txt | 3 +- launcher/NullInstance.h | 4 ++ launcher/RuntimeContext.h | 39 ++++++++++++++++ launcher/minecraft/Component.cpp | 2 +- launcher/minecraft/LaunchProfile.cpp | 24 +++++----- launcher/minecraft/LaunchProfile.h | 8 ++-- launcher/minecraft/Library.cpp | 32 ++++++------- launcher/minecraft/Library.h | 16 +++---- launcher/minecraft/MinecraftInstance.cpp | 29 +++++++----- launcher/minecraft/MinecraftInstance.h | 2 + launcher/minecraft/MojangVersionFormat.cpp | 9 ++-- launcher/minecraft/OpSys.cpp | 46 ------------------- launcher/minecraft/OpSys.h | 38 --------------- launcher/minecraft/PackProfile.cpp | 7 ++- launcher/minecraft/PackProfile.h | 3 ++ launcher/minecraft/Rule.cpp | 6 +-- launcher/minecraft/Rule.h | 10 ++-- launcher/minecraft/VersionFile.cpp | 8 ++-- launcher/minecraft/VersionFile.h | 3 +- launcher/minecraft/launch/ModMinecraftJar.cpp | 3 +- launcher/minecraft/launch/ScanModFolders.cpp | 1 - launcher/minecraft/update/LibrariesTask.cpp | 2 +- .../pages/instance/InstanceSettingsPage.cpp | 3 ++ tests/Library_test.cpp | 10 ++-- 26 files changed, 152 insertions(+), 169 deletions(-) create mode 100644 launcher/RuntimeContext.h delete mode 100644 launcher/minecraft/OpSys.cpp delete mode 100644 launcher/minecraft/OpSys.h diff --git a/launcher/BaseInstance.cpp b/launcher/BaseInstance.cpp index e6d4d8e3..944fd4b2 100644 --- a/launcher/BaseInstance.cpp +++ b/launcher/BaseInstance.cpp @@ -358,3 +358,8 @@ shared_qobject_ptr BaseInstance::getLaunchTask() { return m_launchProcess; } + +void BaseInstance::updateRuntimeContext() +{ + // NOOP +} diff --git a/launcher/BaseInstance.h b/launcher/BaseInstance.h index 3af104e9..b86401d6 100644 --- a/launcher/BaseInstance.h +++ b/launcher/BaseInstance.h @@ -54,6 +54,7 @@ #include "net/Mode.h" #include "minecraft/launch/MinecraftServerTarget.h" +#include "RuntimeContext.h" class QDir; class Task; @@ -219,6 +220,12 @@ public: virtual QString typeName() const = 0; + void updateRuntimeContext(); + RuntimeContext runtimeContext() const + { + return m_runtimeContext; + } + bool hasVersionBroken() const { return m_hasBrokenVersion; @@ -304,6 +311,7 @@ protected: /* data */ bool m_isRunning = false; shared_qobject_ptr m_launchProcess; QDateTime m_timeStarted; + RuntimeContext m_runtimeContext; private: /* data */ Status m_status = Status::Present; diff --git a/launcher/CMakeLists.txt b/launcher/CMakeLists.txt index e44b98eb..f7bcb1d8 100644 --- a/launcher/CMakeLists.txt +++ b/launcher/CMakeLists.txt @@ -26,6 +26,7 @@ set(CORE_SOURCES MMCZip.cpp MMCStrings.h MMCStrings.cpp + RuntimeContext.h # Basic instance manipulation tasks (derived from InstanceTask) InstanceCreationTask.h @@ -288,8 +289,6 @@ set(MINECRAFT_SOURCES minecraft/Rule.h minecraft/OneSixVersionFormat.cpp minecraft/OneSixVersionFormat.h - minecraft/OpSys.cpp - minecraft/OpSys.h minecraft/ParseUtils.cpp minecraft/ParseUtils.h minecraft/ProfileUtils.cpp diff --git a/launcher/NullInstance.h b/launcher/NullInstance.h index 53e64a05..628aff5f 100644 --- a/launcher/NullInstance.h +++ b/launcher/NullInstance.h @@ -84,4 +84,8 @@ public: QString modsRoot() const override { return QString(); } + void updateRuntimeContext() + { + // NOOP + } }; diff --git a/launcher/RuntimeContext.h b/launcher/RuntimeContext.h new file mode 100644 index 00000000..76785728 --- /dev/null +++ b/launcher/RuntimeContext.h @@ -0,0 +1,39 @@ +#pragma once + +#include +#include "settings/SettingsObject.h" + +struct RuntimeContext { + QString javaArchitecture; + QString javaRealArchitecture; + QString javaPath; + + QString mappedJavaRealArchitecture() const { + if (javaRealArchitecture == "aarch64") { + return "arm64"; + } + return javaRealArchitecture; + } + + void updateFromInstanceSettings(SettingsObjectPtr instanceSettings) { + javaArchitecture = instanceSettings->get("JavaArchitecture").toString(); + javaRealArchitecture = instanceSettings->get("JavaRealArchitecture").toString(); + javaPath = instanceSettings->get("JavaPath").toString(); + } + + static QString currentSystem() { +#if defined(Q_OS_LINUX) + return "linux"; +#elif defined(Q_OS_MACOS) + return "osx"; +#elif defined(Q_OS_WINDOWS) + return "windows"; +#elif defined(Q_OS_FREEBSD) + return "freebsd"; +#elif defined(Q_OS_OPENBSD) + return "openbsd"; +#else + return "unknown"; +#endif + } +}; diff --git a/launcher/minecraft/Component.cpp b/launcher/minecraft/Component.cpp index c7dd5e36..ebe4eac7 100644 --- a/launcher/minecraft/Component.cpp +++ b/launcher/minecraft/Component.cpp @@ -60,7 +60,7 @@ void Component::applyTo(LaunchProfile* profile) auto vfile = getVersionFile(); if(vfile) { - vfile->applyTo(profile); + vfile->applyTo(profile, m_parent->runtimeContext()); } else { diff --git a/launcher/minecraft/LaunchProfile.cpp b/launcher/minecraft/LaunchProfile.cpp index 39a342ca..9a6cea11 100644 --- a/launcher/minecraft/LaunchProfile.cpp +++ b/launcher/minecraft/LaunchProfile.cpp @@ -173,9 +173,9 @@ void LaunchProfile::applyCompatibleJavaMajors(QList& javaMajor) m_compatibleJavaMajors.append(javaMajor); } -void LaunchProfile::applyLibrary(LibraryPtr library) +void LaunchProfile::applyLibrary(LibraryPtr library, const RuntimeContext & runtimeContext) { - if(!library->isActive()) + if(!library->isActive(runtimeContext)) { return; } @@ -205,9 +205,9 @@ void LaunchProfile::applyLibrary(LibraryPtr library) } } -void LaunchProfile::applyMavenFile(LibraryPtr mavenFile) +void LaunchProfile::applyMavenFile(LibraryPtr mavenFile, const RuntimeContext & runtimeContext) { - if(!mavenFile->isActive()) + if(!mavenFile->isActive(runtimeContext)) { return; } @@ -221,10 +221,10 @@ void LaunchProfile::applyMavenFile(LibraryPtr mavenFile) m_mavenFiles.append(Library::limitedCopy(mavenFile)); } -void LaunchProfile::applyAgent(AgentPtr agent) +void LaunchProfile::applyAgent(AgentPtr agent, const RuntimeContext & runtimeContext) { auto lib = agent->library(); - if(!lib->isActive()) + if(!lib->isActive(runtimeContext)) { return; } @@ -354,7 +354,7 @@ const QList & LaunchProfile::getCompatibleJavaMajors() const } void LaunchProfile::getLibraryFiles( - const QString& architecture, + const RuntimeContext & runtimeContext, QStringList& jars, QStringList& nativeJars, const QString& overridePath, @@ -366,7 +366,7 @@ void LaunchProfile::getLibraryFiles( nativeJars.clear(); for (auto lib : getLibraries()) { - lib->getApplicableFiles(currentSystem, jars, nativeJars, native32, native64, overridePath); + lib->getApplicableFiles(runtimeContext, jars, nativeJars, native32, native64, overridePath); } // NOTE: order is important here, add main jar last to the lists if(m_mainJar) @@ -379,18 +379,18 @@ void LaunchProfile::getLibraryFiles( } else { - m_mainJar->getApplicableFiles(currentSystem, jars, nativeJars, native32, native64, overridePath); + m_mainJar->getApplicableFiles(runtimeContext, jars, nativeJars, native32, native64, overridePath); } } for (auto lib : getNativeLibraries()) { - lib->getApplicableFiles(currentSystem, jars, nativeJars, native32, native64, overridePath); + lib->getApplicableFiles(runtimeContext, jars, nativeJars, native32, native64, overridePath); } - if(architecture == "32") + if(runtimeContext.javaArchitecture == "32") { nativeJars.append(native32); } - else if(architecture == "64") + else if(runtimeContext.javaArchitecture == "64") { nativeJars.append(native64); } diff --git a/launcher/minecraft/LaunchProfile.h b/launcher/minecraft/LaunchProfile.h index b55cf661..49c1217d 100644 --- a/launcher/minecraft/LaunchProfile.h +++ b/launcher/minecraft/LaunchProfile.h @@ -56,9 +56,9 @@ public: /* application of profile variables from patches */ void applyTweakers(const QStringList &tweakers); void applyJarMods(const QList &jarMods); void applyMods(const QList &jarMods); - void applyLibrary(LibraryPtr library); - void applyMavenFile(LibraryPtr library); - void applyAgent(AgentPtr agent); + void applyLibrary(LibraryPtr library, const RuntimeContext & runtimeContext); + void applyMavenFile(LibraryPtr library, const RuntimeContext & runtimeContext); + void applyAgent(AgentPtr agent, const RuntimeContext & runtimeContext); void applyCompatibleJavaMajors(QList& javaMajor); void applyMainJar(LibraryPtr jar); void applyProblemSeverity(ProblemSeverity severity); @@ -83,7 +83,7 @@ public: /* getters for profile variables */ const QList & getCompatibleJavaMajors() const; const LibraryPtr getMainJar() const; void getLibraryFiles( - const QString & architecture, + const RuntimeContext & runtimeContext, QStringList & jars, QStringList & nativeJars, const QString & overridePath, diff --git a/launcher/minecraft/Library.cpp b/launcher/minecraft/Library.cpp index ba7aed4b..1689e27c 100644 --- a/launcher/minecraft/Library.cpp +++ b/launcher/minecraft/Library.cpp @@ -7,7 +7,7 @@ #include -void Library::getApplicableFiles(OpSys system, QStringList& jar, QStringList& native, QStringList& native32, +void Library::getApplicableFiles(const RuntimeContext & runtimeContext, QStringList& jar, QStringList& native, QStringList& native32, QStringList& native64, const QString &overridePath) const { bool local = isLocal(); @@ -21,7 +21,7 @@ void Library::getApplicableFiles(OpSys system, QStringList& jar, QStringList& na } return out.absoluteFilePath(); }; - QString raw_storage = storageSuffix(system); + QString raw_storage = storageSuffix(runtimeContext); if(isNative()) { if (raw_storage.contains("${arch}")) @@ -45,7 +45,7 @@ void Library::getApplicableFiles(OpSys system, QStringList& jar, QStringList& na } QList Library::getDownloads( - OpSys system, + const RuntimeContext & runtimeContext, class HttpMetaCache* cache, QStringList& failedLocalFiles, const QString & overridePath @@ -107,14 +107,14 @@ QList Library::getDownloads( return true; }; - QString raw_storage = storageSuffix(system); + QString raw_storage = storageSuffix(runtimeContext); if(m_mojangDownloads) { if(isNative()) { - if(m_nativeClassifiers.contains(system)) + if(m_nativeClassifiers.contains(runtimeContext.currentSystem())) { - auto nativeClassifier = m_nativeClassifiers[system]; + auto nativeClassifier = m_nativeClassifiers[runtimeContext.currentSystem()]; if(nativeClassifier.contains("${arch}")) { auto nat32Classifier = nativeClassifier; @@ -203,7 +203,7 @@ QList Library::getDownloads( return out; } -bool Library::isActive() const +bool Library::isActive(const RuntimeContext & runtimeContext) const { bool result = true; if (m_rules.empty()) @@ -223,7 +223,7 @@ bool Library::isActive() const } if (isNative()) { - result = result && m_nativeClassifiers.contains(currentSystem); + result = result && m_nativeClassifiers.contains(runtimeContext.currentSystem()); } return result; } @@ -257,7 +257,7 @@ QString Library::storagePrefix() const return m_storagePrefix; } -QString Library::filename(OpSys system) const +QString Library::filename(const RuntimeContext & runtimeContext) const { if(!m_filename.isEmpty()) { @@ -271,9 +271,9 @@ QString Library::filename(OpSys system) const // otherwise native, override classifiers. Mojang HACK! GradleSpecifier nativeSpec = m_name; - if (m_nativeClassifiers.contains(system)) + if (m_nativeClassifiers.contains(runtimeContext.currentSystem())) { - nativeSpec.setClassifier(m_nativeClassifiers[system]); + nativeSpec.setClassifier(m_nativeClassifiers[runtimeContext.currentSystem()]); } else { @@ -282,14 +282,14 @@ QString Library::filename(OpSys system) const return nativeSpec.getFileName(); } -QString Library::displayName(OpSys system) const +QString Library::displayName(const RuntimeContext & runtimeContext) const { if(!m_displayname.isEmpty()) return m_displayname; - return filename(system); + return filename(runtimeContext); } -QString Library::storageSuffix(OpSys system) const +QString Library::storageSuffix(const RuntimeContext & runtimeContext) const { // non-native? use only the gradle specifier if (!isNative()) @@ -299,9 +299,9 @@ QString Library::storageSuffix(OpSys system) const // otherwise native, override classifiers. Mojang HACK! GradleSpecifier nativeSpec = m_name; - if (m_nativeClassifiers.contains(system)) + if (m_nativeClassifiers.contains(runtimeContext.currentSystem())) { - nativeSpec.setClassifier(m_nativeClassifiers[system]); + nativeSpec.setClassifier(m_nativeClassifiers[runtimeContext.currentSystem()]); } else { diff --git a/launcher/minecraft/Library.h b/launcher/minecraft/Library.h index 0740a7ca..e0432fb8 100644 --- a/launcher/minecraft/Library.h +++ b/launcher/minecraft/Library.h @@ -10,9 +10,9 @@ #include #include "Rule.h" -#include "minecraft/OpSys.h" #include "GradleSpecifier.h" #include "MojangDownloadInfo.h" +#include "RuntimeContext.h" class Library; class MinecraftInstance; @@ -98,7 +98,7 @@ public: /* methods */ m_repositoryURL = base_url; } - void getApplicableFiles(OpSys system, QStringList & jar, QStringList & native, + void getApplicableFiles(const RuntimeContext & runtimeContext, QStringList & jar, QStringList & native, QStringList & native32, QStringList & native64, const QString & overridePath) const; void setAbsoluteUrl(const QString &absolute_url) @@ -112,7 +112,7 @@ public: /* methods */ } /// Get the file name of the library - QString filename(OpSys system) const; + QString filename(const RuntimeContext & runtimeContext) const; // DEPRECATED: set a display name, used by jar mods only void setDisplayName(const QString & displayName) @@ -121,7 +121,7 @@ public: /* methods */ } /// Get the file name of the library - QString displayName(OpSys system) const; + QString displayName(const RuntimeContext & runtimeContext) const; void setMojangDownloadInfo(MojangLibraryDownloadInfo::Ptr info) { @@ -140,7 +140,7 @@ public: /* methods */ } /// Returns true if the library should be loaded (or extracted, in case of natives) - bool isActive() const; + bool isActive(const RuntimeContext & runtimeContext) const; /// Returns true if the library is contained in an instance and false if it is shared bool isLocal() const; @@ -152,7 +152,7 @@ public: /* methods */ bool isForge() const; // Get a list of downloads for this library - QList getDownloads(OpSys system, class HttpMetaCache * cache, + QList getDownloads(const RuntimeContext & runtimeContext, class HttpMetaCache * cache, QStringList & failedLocalFiles, const QString & overridePath) const; private: /* methods */ @@ -163,7 +163,7 @@ private: /* methods */ QString storagePrefix() const; /// Get the relative file path where the library should be saved - QString storageSuffix(OpSys system) const; + QString storageSuffix(const RuntimeContext & runtimeContext) const; QString hint() const { @@ -204,7 +204,7 @@ protected: /* data */ QStringList m_extractExcludes; /// native suffixes per OS - QMap m_nativeClassifiers; + QMap m_nativeClassifiers; /// true if the library had a rules section (even empty) bool applyRules = false; diff --git a/launcher/minecraft/MinecraftInstance.cpp b/launcher/minecraft/MinecraftInstance.cpp index 8496adee..3a820951 100644 --- a/launcher/minecraft/MinecraftInstance.cpp +++ b/launcher/minecraft/MinecraftInstance.cpp @@ -191,6 +191,13 @@ void MinecraftInstance::loadSpecificSettings() qDebug() << "Instance-type specific settings were loaded!"; setSpecificSettingsLoaded(true); + + updateRuntimeContext(); +} + +void MinecraftInstance::updateRuntimeContext() +{ + m_runtimeContext.updateFromInstanceSettings(m_settings); } QString MinecraftInstance::typeName() const @@ -328,9 +335,8 @@ QDir MinecraftInstance::versionsPath() const QStringList MinecraftInstance::getClassPath() { QStringList jars, nativeJars; - auto javaArchitecture = settings()->get("JavaArchitecture").toString(); auto profile = m_components->getProfile(); - profile->getLibraryFiles(javaArchitecture, jars, nativeJars, getLocalLibraryPath(), binRoot()); + profile->getLibraryFiles(runtimeContext(), jars, nativeJars, getLocalLibraryPath(), binRoot()); return jars; } @@ -343,9 +349,8 @@ QString MinecraftInstance::getMainClass() const QStringList MinecraftInstance::getNativeJars() { QStringList jars, nativeJars; - auto javaArchitecture = settings()->get("JavaArchitecture").toString(); auto profile = m_components->getProfile(); - profile->getLibraryFiles(javaArchitecture, jars, nativeJars, getLocalLibraryPath(), binRoot()); + profile->getLibraryFiles(runtimeContext(), jars, nativeJars, getLocalLibraryPath(), binRoot()); return nativeJars; } @@ -369,7 +374,7 @@ QStringList MinecraftInstance::extraArguments() for (auto agent : agents) { QStringList jar, temp1, temp2, temp3; - agent->library()->getApplicableFiles(currentSystem, jar, temp1, temp2, temp3, getLocalLibraryPath()); + agent->library()->getApplicableFiles(runtimeContext(), jar, temp1, temp2, temp3, getLocalLibraryPath()); list.append("-javaagent:"+jar[0]+(agent->argument().isEmpty() ? "" : "="+agent->argument())); } return list; @@ -626,8 +631,7 @@ QString MinecraftInstance::createLaunchScript(AuthSessionPtr session, MinecraftS // libraries and class path. { QStringList jars, nativeJars; - auto javaArchitecture = settings()->get("JavaArchitecture").toString(); - profile->getLibraryFiles(javaArchitecture, jars, nativeJars, getLocalLibraryPath(), binRoot()); + profile->getLibraryFiles(runtimeContext(), jars, nativeJars, getLocalLibraryPath(), binRoot()); for(auto file: jars) { launchScript += "cp " + file + "\n"; @@ -683,8 +687,7 @@ QStringList MinecraftInstance::verboseDescription(AuthSessionPtr session, Minecr { out << "Libraries:"; QStringList jars, nativeJars; - auto javaArchitecture = settings->get("JavaArchitecture").toString(); - profile->getLibraryFiles(javaArchitecture, jars, nativeJars, getLocalLibraryPath(), binRoot()); + profile->getLibraryFiles(runtimeContext(), jars, nativeJars, getLocalLibraryPath(), binRoot()); auto printLibFile = [&](const QString & path) { QFileInfo info(path); @@ -749,8 +752,8 @@ QStringList MinecraftInstance::verboseDescription(AuthSessionPtr session, Minecr out << "Jar Mods:"; for(auto & jarmod: jarMods) { - auto displayname = jarmod->displayName(currentSystem); - auto realname = jarmod->filename(currentSystem); + auto displayname = jarmod->displayName(runtimeContext()); + auto realname = jarmod->filename(runtimeContext()); if(displayname != realname) { out << " " + displayname + " (" + realname + ")"; @@ -912,6 +915,7 @@ QString MinecraftInstance::getStatusbarDescription() Task::Ptr MinecraftInstance::createUpdateTask(Net::Mode mode) { + updateRuntimeContext(); switch (mode) { case Net::Mode::Offline: @@ -928,6 +932,7 @@ Task::Ptr MinecraftInstance::createUpdateTask(Net::Mode mode) shared_qobject_ptr MinecraftInstance::createLaunchTask(AuthSessionPtr session, MinecraftServerTargetPtr serverToJoin) { + updateRuntimeContext(); // FIXME: get rid of shared_from_this ... auto process = LaunchTask::create(std::dynamic_pointer_cast(shared_from_this())); auto pptr = process.get(); @@ -1158,7 +1163,7 @@ QList MinecraftInstance::getJarMods() const for (auto jarmod : profile->getJarMods()) { QStringList jar, temp1, temp2, temp3; - jarmod->getApplicableFiles(currentSystem, jar, temp1, temp2, temp3, jarmodsPath().absolutePath()); + jarmod->getApplicableFiles(runtimeContext(), jar, temp1, temp2, temp3, jarmodsPath().absolutePath()); // QString filePath = jarmodsPath().absoluteFilePath(jarmod->filename(currentSystem)); mods.push_back(new Mod(QFileInfo(jar[0]))); } diff --git a/launcher/minecraft/MinecraftInstance.h b/launcher/minecraft/MinecraftInstance.h index fe39674a..ef48b286 100644 --- a/launcher/minecraft/MinecraftInstance.h +++ b/launcher/minecraft/MinecraftInstance.h @@ -72,6 +72,8 @@ public: /** Returns whether the instance, with its version, has support for demo mode. */ [[nodiscard]] bool supportsDemo() const; + void updateRuntimeContext(); + ////// Profile management ////// std::shared_ptr getPackProfile() const; diff --git a/launcher/minecraft/MojangVersionFormat.cpp b/launcher/minecraft/MojangVersionFormat.cpp index 94c58676..e00d2c6e 100644 --- a/launcher/minecraft/MojangVersionFormat.cpp +++ b/launcher/minecraft/MojangVersionFormat.cpp @@ -362,11 +362,8 @@ LibraryPtr MojangVersionFormat::libraryFromJson(ProblemContainer & problems, con { qWarning() << filename << "contains an invalid native (skipping)"; } - OpSys opSys = OpSys_fromString(it.key()); - if (opSys != Os_Other) - { - out->m_nativeClassifiers[opSys] = it.value().toString(); - } + // FIXME: Skip unknown platforms + out->m_nativeClassifiers[it.key()] = it.value().toString(); } } if (libObj.contains("rules")) @@ -395,7 +392,7 @@ QJsonObject MojangVersionFormat::libraryToJson(Library *library) auto iter = library->m_nativeClassifiers.begin(); while (iter != library->m_nativeClassifiers.end()) { - nativeList.insert(OpSys_toString(iter.key()), iter.value()); + nativeList.insert(iter.key(), iter.value()); iter++; } libRoot.insert("natives", nativeList); diff --git a/launcher/minecraft/OpSys.cpp b/launcher/minecraft/OpSys.cpp deleted file mode 100644 index 093ec419..00000000 --- a/launcher/minecraft/OpSys.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/* Copyright 2013-2021 MultiMC Contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "OpSys.h" - -OpSys OpSys_fromString(QString name) -{ - if (name == "freebsd") - return Os_FreeBSD; - if (name == "linux") - return Os_Linux; - if (name == "windows") - return Os_Windows; - if (name == "osx") - return Os_OSX; - return Os_Other; -} - -QString OpSys_toString(OpSys name) -{ - switch (name) - { - case Os_FreeBSD: - return "freebsd"; - case Os_Linux: - return "linux"; - case Os_OSX: - return "osx"; - case Os_Windows: - return "windows"; - default: - return "other"; - } -} \ No newline at end of file diff --git a/launcher/minecraft/OpSys.h b/launcher/minecraft/OpSys.h deleted file mode 100644 index 0936f817..00000000 --- a/launcher/minecraft/OpSys.h +++ /dev/null @@ -1,38 +0,0 @@ -/* Copyright 2013-2021 MultiMC Contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once -#include -enum OpSys -{ - Os_Windows, - Os_FreeBSD, - Os_Linux, - Os_OSX, - Os_Other -}; - -OpSys OpSys_fromString(QString); -QString OpSys_toString(OpSys); - -#ifdef Q_OS_WIN32 - #define currentSystem Os_Windows -#elif defined Q_OS_MAC - #define currentSystem Os_OSX -#elif defined Q_OS_FREEBSD - #define currentSystem Os_FreeBSD -#else - #define currentSystem Os_Linux -#endif diff --git a/launcher/minecraft/PackProfile.cpp b/launcher/minecraft/PackProfile.cpp index 5e76b892..1618458f 100644 --- a/launcher/minecraft/PackProfile.cpp +++ b/launcher/minecraft/PackProfile.cpp @@ -273,6 +273,11 @@ void PackProfile::scheduleSave() 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"); @@ -784,7 +789,7 @@ bool PackProfile::removeComponent_internal(ComponentPtr patch) return true; } QStringList jar, temp1, temp2, temp3; - jarMod->getApplicableFiles(currentSystem, jar, temp1, temp2, temp3, d->m_instance->jarmodsPath().absolutePath()); + jarMod->getApplicableFiles(d->m_instance->runtimeContext(), jar, temp1, temp2, temp3, d->m_instance->jarmodsPath().absolutePath()); QFileInfo finfo (jar[0]); if(finfo.exists()) { diff --git a/launcher/minecraft/PackProfile.h b/launcher/minecraft/PackProfile.h index 918e7f7a..11057a0c 100644 --- a/launcher/minecraft/PackProfile.h +++ b/launcher/minecraft/PackProfile.h @@ -104,6 +104,9 @@ public: /// if there is a save scheduled, do it now. void saveNow(); + /// helper method, returns RuntimeContext of instance + RuntimeContext runtimeContext(); + signals: void minecraftChanged(); diff --git a/launcher/minecraft/Rule.cpp b/launcher/minecraft/Rule.cpp index af2861e3..2f41e1fb 100644 --- a/launcher/minecraft/Rule.cpp +++ b/launcher/minecraft/Rule.cpp @@ -60,10 +60,10 @@ QList> rulesFromJsonV4(const QJsonObject &objectWithRules) auto osNameVal = osObj.value("name"); if (!osNameVal.isString()) continue; - OpSys requiredOs = OpSys_fromString(osNameVal.toString()); + QString osName = osNameVal.toString(); QString versionRegex = osObj.value("version").toString(); // add a new OS rule - rules.append(OsRule::create(action, requiredOs, versionRegex)); + rules.append(OsRule::create(action, osName, versionRegex)); } return rules; } @@ -81,7 +81,7 @@ QJsonObject OsRule::toJson() ruleObj.insert("action", m_result == Allow ? QString("allow") : QString("disallow")); QJsonObject osObj; { - osObj.insert("name", OpSys_toString(m_system)); + osObj.insert("name", m_system); if(!m_version_regexp.isEmpty()) { osObj.insert("version", m_version_regexp); diff --git a/launcher/minecraft/Rule.h b/launcher/minecraft/Rule.h index 7aa34d96..2ed49d78 100644 --- a/launcher/minecraft/Rule.h +++ b/launcher/minecraft/Rule.h @@ -19,7 +19,7 @@ #include #include #include -#include "OpSys.h" +#include "RuntimeContext.h" class Library; class Rule; @@ -58,23 +58,23 @@ class OsRule : public Rule { private: // the OS - OpSys m_system; + QString m_system; // the OS version regexp QString m_version_regexp; protected: virtual bool applies(const Library *) { - return (m_system == currentSystem); + return (m_system == RuntimeContext::currentSystem()); } - OsRule(RuleAction result, OpSys system, QString version_regexp) + OsRule(RuleAction result, QString system, QString version_regexp) : Rule(result), m_system(system), m_version_regexp(version_regexp) { } public: virtual QJsonObject toJson(); - static std::shared_ptr create(RuleAction result, OpSys system, + static std::shared_ptr create(RuleAction result, QString system, QString version_regexp) { return std::shared_ptr(new OsRule(result, system, version_regexp)); diff --git a/launcher/minecraft/VersionFile.cpp b/launcher/minecraft/VersionFile.cpp index a9a0f7f4..76f41600 100644 --- a/launcher/minecraft/VersionFile.cpp +++ b/launcher/minecraft/VersionFile.cpp @@ -51,7 +51,7 @@ static bool isMinecraftVersion(const QString &uid) return uid == "net.minecraft"; } -void VersionFile::applyTo(LaunchProfile *profile) +void VersionFile::applyTo(LaunchProfile *profile, const RuntimeContext & runtimeContext) { // Only real Minecraft can set those. Don't let anything override them. if (isMinecraftVersion(uid)) @@ -77,15 +77,15 @@ void VersionFile::applyTo(LaunchProfile *profile) for (auto library : libraries) { - profile->applyLibrary(library); + profile->applyLibrary(library, runtimeContext); } for (auto mavenFile : mavenFiles) { - profile->applyMavenFile(mavenFile); + profile->applyMavenFile(mavenFile, runtimeContext); } for (auto agent : agents) { - profile->applyAgent(agent); + profile->applyAgent(agent, runtimeContext); } profile->applyProblemSeverity(getProblemSeverity()); } diff --git a/launcher/minecraft/VersionFile.h b/launcher/minecraft/VersionFile.h index d4b29719..e1b62f6a 100644 --- a/launcher/minecraft/VersionFile.h +++ b/launcher/minecraft/VersionFile.h @@ -41,7 +41,6 @@ #include #include -#include "minecraft/OpSys.h" #include "minecraft/Rule.h" #include "ProblemProvider.h" #include "Library.h" @@ -60,7 +59,7 @@ class VersionFile : public ProblemContainer friend class MojangVersionFormat; friend class OneSixVersionFormat; public: /* methods */ - void applyTo(LaunchProfile* profile); + void applyTo(LaunchProfile* profile, const RuntimeContext & runtimeContext); public: /* data */ /// PolyMC: order hint for this version file if no explicit order is set diff --git a/launcher/minecraft/launch/ModMinecraftJar.cpp b/launcher/minecraft/launch/ModMinecraftJar.cpp index 93de9d59..8e47e0e5 100644 --- a/launcher/minecraft/launch/ModMinecraftJar.cpp +++ b/launcher/minecraft/launch/ModMinecraftJar.cpp @@ -16,7 +16,6 @@ #include "ModMinecraftJar.h" #include "launch/LaunchTask.h" #include "MMCZip.h" -#include "minecraft/OpSys.h" #include "FileSystem.h" #include "minecraft/MinecraftInstance.h" #include "minecraft/PackProfile.h" @@ -50,7 +49,7 @@ void ModMinecraftJar::executeTask() { auto mainJar = profile->getMainJar(); QStringList jars, temp1, temp2, temp3, temp4; - mainJar->getApplicableFiles(currentSystem, jars, temp1, temp2, temp3, m_inst->getLocalLibraryPath()); + mainJar->getApplicableFiles(m_inst->runtimeContext(), jars, temp1, temp2, temp3, m_inst->getLocalLibraryPath()); auto sourceJarPath = jars[0]; if(!MMCZip::createModdedJar(sourceJarPath, finalJarPath, jarMods)) { diff --git a/launcher/minecraft/launch/ScanModFolders.cpp b/launcher/minecraft/launch/ScanModFolders.cpp index 2a0e21b3..2e817e0a 100644 --- a/launcher/minecraft/launch/ScanModFolders.cpp +++ b/launcher/minecraft/launch/ScanModFolders.cpp @@ -16,7 +16,6 @@ #include "ScanModFolders.h" #include "launch/LaunchTask.h" #include "MMCZip.h" -#include "minecraft/OpSys.h" #include "FileSystem.h" #include "minecraft/MinecraftInstance.h" #include "minecraft/mod/ModFolderModel.h" diff --git a/launcher/minecraft/update/LibrariesTask.cpp b/launcher/minecraft/update/LibrariesTask.cpp index aa2bf407..3b129fe1 100644 --- a/launcher/minecraft/update/LibrariesTask.cpp +++ b/launcher/minecraft/update/LibrariesTask.cpp @@ -34,7 +34,7 @@ void LibrariesTask::executeTask() emitFailed(tr("Null jar is specified in the metadata, aborting.")); return false; } - auto dls = lib->getDownloads(currentSystem, metacache.get(), errors, localPath); + auto dls = lib->getDownloads(inst->runtimeContext(), metacache.get(), errors, localPath); for(auto dl : dls) { downloadJob->addNetAction(dl); diff --git a/launcher/ui/pages/instance/InstanceSettingsPage.cpp b/launcher/ui/pages/instance/InstanceSettingsPage.cpp index 03910745..5da7f19f 100644 --- a/launcher/ui/pages/instance/InstanceSettingsPage.cpp +++ b/launcher/ui/pages/instance/InstanceSettingsPage.cpp @@ -274,6 +274,9 @@ void InstanceSettingsPage::applySettings() { m_settings->reset("JoinServerOnLaunchAddress"); } + + // FIXME: This should probably be called by a signal instead + m_instance->updateRuntimeContext(); } void InstanceSettingsPage::loadSettings() diff --git a/tests/Library_test.cpp b/tests/Library_test.cpp index 869c7673..a4ca9232 100644 --- a/tests/Library_test.cpp +++ b/tests/Library_test.cpp @@ -87,7 +87,7 @@ slots: void test_legacy_native() { Library test("test.package:testname:testversion"); - test.m_nativeClassifiers[OpSys::Os_Linux]="linux"; + test.m_nativeClassifiers["linux"] = "linux"; QCOMPARE(test.isNative(), true); test.setRepositoryURL("file://foo/bar"); { @@ -108,9 +108,9 @@ slots: void test_legacy_native_arch() { Library test("test.package:testname:testversion"); - test.m_nativeClassifiers[OpSys::Os_Linux]="linux-${arch}"; - test.m_nativeClassifiers[OpSys::Os_OSX]="osx-${arch}"; - test.m_nativeClassifiers[OpSys::Os_Windows]="windows-${arch}"; + test.m_nativeClassifiers["linux"]="linux-${arch}"; + test.m_nativeClassifiers["osx"]="osx-${arch}"; + test.m_nativeClassifiers["windows"]="windows-${arch}"; QCOMPARE(test.isNative(), true); test.setRepositoryURL("file://foo/bar"); { @@ -159,7 +159,7 @@ slots: void test_legacy_native_arch_local_override() { Library test("test.package:testname:testversion"); - test.m_nativeClassifiers[OpSys::Os_Linux]="linux-${arch}"; + test.m_nativeClassifiers["linux"]="linux-${arch}"; test.setHint("local"); QCOMPARE(test.isNative(), true); test.setRepositoryURL("file://foo/bar"); From 7bd8bd13feddded96b087bb142101f87cb0003b8 Mon Sep 17 00:00:00 2001 From: Sefa Eyeoglu Date: Sun, 7 Aug 2022 00:06:32 +0200 Subject: [PATCH 003/101] feat: support multiarch system classifiers Signed-off-by: Sefa Eyeoglu --- launcher/RuntimeContext.h | 23 ++++++++++ launcher/minecraft/Library.cpp | 31 ++++++++++---- launcher/minecraft/Library.h | 3 ++ launcher/minecraft/Rule.h | 12 +++--- tests/Library_test.cpp | 76 +++++++++++++++++++++++----------- 5 files changed, 106 insertions(+), 39 deletions(-) diff --git a/launcher/RuntimeContext.h b/launcher/RuntimeContext.h index 76785728..d98d407f 100644 --- a/launcher/RuntimeContext.h +++ b/launcher/RuntimeContext.h @@ -1,5 +1,6 @@ #pragma once +#include #include #include "settings/SettingsObject.h" @@ -7,6 +8,7 @@ struct RuntimeContext { QString javaArchitecture; QString javaRealArchitecture; QString javaPath; + QString system; QString mappedJavaRealArchitecture() const { if (javaRealArchitecture == "aarch64") { @@ -19,6 +21,27 @@ struct RuntimeContext { javaArchitecture = instanceSettings->get("JavaArchitecture").toString(); javaRealArchitecture = instanceSettings->get("JavaRealArchitecture").toString(); javaPath = instanceSettings->get("JavaPath").toString(); + system = currentSystem(); + } + + QString getClassifier() const { + return system + "-" + mappedJavaRealArchitecture(); + } + + // "Legacy" refers to the fact that Mojang assumed that these are the only two architectures + bool isLegacyArch() const { + QSet legacyArchitectures{"amd64", "x86_64", "i686"}; + return legacyArchitectures.contains(mappedJavaRealArchitecture()); + } + + bool classifierMatches(QString target) const { + // try to match precise classifier "[os]-[arch]" + bool x = target == getClassifier(); + // try to match imprecise classifier on legacy architectures "[os]" + if (!x && isLegacyArch()) + x = target == system; + + return x; } static QString currentSystem() { diff --git a/launcher/minecraft/Library.cpp b/launcher/minecraft/Library.cpp index 1689e27c..42a42d87 100644 --- a/launcher/minecraft/Library.cpp +++ b/launcher/minecraft/Library.cpp @@ -112,9 +112,9 @@ QList Library::getDownloads( { if(isNative()) { - if(m_nativeClassifiers.contains(runtimeContext.currentSystem())) + auto nativeClassifier = getCompatibleNative(runtimeContext); + if(!nativeClassifier.isNull()) { - auto nativeClassifier = m_nativeClassifiers[runtimeContext.currentSystem()]; if(nativeClassifier.contains("${arch}")) { auto nat32Classifier = nativeClassifier; @@ -215,7 +215,7 @@ bool Library::isActive(const RuntimeContext & runtimeContext) const RuleAction ruleResult = Disallow; for (auto rule : m_rules) { - RuleAction temp = rule->apply(this); + RuleAction temp = rule->apply(this, runtimeContext); if (temp != Defer) ruleResult = temp; } @@ -223,7 +223,7 @@ bool Library::isActive(const RuntimeContext & runtimeContext) const } if (isNative()) { - result = result && m_nativeClassifiers.contains(runtimeContext.currentSystem()); + result = result && !getCompatibleNative(runtimeContext).isNull(); } return result; } @@ -238,6 +238,19 @@ bool Library::isAlwaysStale() const return m_hint == "always-stale"; } +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(); +} + void Library::setStoragePrefix(QString prefix) { m_storagePrefix = prefix; @@ -271,9 +284,10 @@ QString Library::filename(const RuntimeContext & runtimeContext) const // otherwise native, override classifiers. Mojang HACK! GradleSpecifier nativeSpec = m_name; - if (m_nativeClassifiers.contains(runtimeContext.currentSystem())) + QString nativeClassifier = getCompatibleNative(runtimeContext); + if (!nativeClassifier.isNull()) { - nativeSpec.setClassifier(m_nativeClassifiers[runtimeContext.currentSystem()]); + nativeSpec.setClassifier(nativeClassifier); } else { @@ -299,9 +313,10 @@ QString Library::storageSuffix(const RuntimeContext & runtimeContext) const // otherwise native, override classifiers. Mojang HACK! GradleSpecifier nativeSpec = m_name; - if (m_nativeClassifiers.contains(runtimeContext.currentSystem())) + QString nativeClassifier = getCompatibleNative(runtimeContext); + if (!nativeClassifier.isNull()) { - nativeSpec.setClassifier(m_nativeClassifiers[runtimeContext.currentSystem()]); + nativeSpec.setClassifier(nativeClassifier); } else { diff --git a/launcher/minecraft/Library.h b/launcher/minecraft/Library.h index e0432fb8..b8fae9ec 100644 --- a/launcher/minecraft/Library.h +++ b/launcher/minecraft/Library.h @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -155,6 +156,8 @@ public: /* methods */ QList getDownloads(const RuntimeContext & runtimeContext, class HttpMetaCache * cache, QStringList & failedLocalFiles, const QString & overridePath) const; + QString getCompatibleNative(const RuntimeContext & runtimeContext) const; + private: /* methods */ /// the default storage prefix used by PolyMC static QString defaultStoragePrefix(); diff --git a/launcher/minecraft/Rule.h b/launcher/minecraft/Rule.h index 2ed49d78..4c75cee4 100644 --- a/launcher/minecraft/Rule.h +++ b/launcher/minecraft/Rule.h @@ -37,7 +37,7 @@ class Rule { protected: RuleAction m_result; - virtual bool applies(const Library *parent) = 0; + virtual bool applies(const Library *parent, const RuntimeContext & runtimeContext) = 0; public: Rule(RuleAction result) : m_result(result) @@ -45,9 +45,9 @@ public: } virtual ~Rule() {}; virtual QJsonObject toJson() = 0; - RuleAction apply(const Library *parent) + RuleAction apply(const Library *parent, const RuntimeContext & runtimeContext) { - if (applies(parent)) + if (applies(parent, runtimeContext)) return m_result; else return Defer; @@ -63,9 +63,9 @@ private: QString m_version_regexp; protected: - virtual bool applies(const Library *) + virtual bool applies(const Library *, const RuntimeContext & runtimeContext) { - return (m_system == RuntimeContext::currentSystem()); + return runtimeContext.classifierMatches(m_system); } OsRule(RuleAction result, QString system, QString version_regexp) : Rule(result), m_system(system), m_version_regexp(version_regexp) @@ -84,7 +84,7 @@ public: class ImplicitRule : public Rule { protected: - virtual bool applies(const Library *) + virtual bool applies(const Library *, const RuntimeContext & runtimeContext) { return true; } diff --git a/tests/Library_test.cpp b/tests/Library_test.cpp index a4ca9232..b9027e12 100644 --- a/tests/Library_test.cpp +++ b/tests/Library_test.cpp @@ -5,6 +5,7 @@ #include #include #include +#include class LibraryTest : public QObject { @@ -24,6 +25,14 @@ private: { return {FS::PathCombine(cache->getBasePath("libraries"), relative)}; } + + RuntimeContext dummyContext(QString system = "linux", QString arch = "64", QString realArch = "amd64") { + RuntimeContext r; + r.javaArchitecture = arch; + r.javaRealArchitecture = realArch; + r.system = system; + return r; + } private slots: void initTestCase() @@ -34,12 +43,13 @@ slots: } void test_legacy() { + RuntimeContext r = dummyContext(); Library test("test.package:testname:testversion"); QCOMPARE(test.artifactPrefix(), QString("test.package:testname")); QCOMPARE(test.isNative(), false); QStringList jar, native, native32, native64; - test.getApplicableFiles(currentSystem, jar, native, native32, native64, QString()); + test.getApplicableFiles(r, jar, native, native32, native64, QString()); QCOMPARE(jar, getStorage("test/package/testname/testversion/testname-testversion.jar")); QCOMPARE(native, {}); QCOMPARE(native32, {}); @@ -47,10 +57,11 @@ slots: } void test_legacy_url() { + RuntimeContext r = dummyContext(); QStringList failedFiles; Library test("test.package:testname:testversion"); test.setRepositoryURL("file://foo/bar"); - auto downloads = test.getDownloads(currentSystem, cache.get(), failedFiles, QString()); + auto downloads = test.getDownloads(r, cache.get(), failedFiles, QString()); QCOMPARE(downloads.size(), 1); QCOMPARE(failedFiles, {}); NetAction::Ptr dl = downloads[0]; @@ -58,27 +69,29 @@ slots: } void test_legacy_url_local_broken() { + RuntimeContext r = dummyContext(); Library test("test.package:testname:testversion"); QCOMPARE(test.isNative(), false); QStringList failedFiles; test.setHint("local"); - auto downloads = test.getDownloads(currentSystem, cache.get(), failedFiles, QString()); + auto downloads = test.getDownloads(r, cache.get(), failedFiles, QString()); QCOMPARE(downloads.size(), 0); QCOMPARE(failedFiles, {"testname-testversion.jar"}); } void test_legacy_url_local_override() { + RuntimeContext r = dummyContext(); Library test("com.paulscode:codecwav:20101023"); QCOMPARE(test.isNative(), false); QStringList failedFiles; test.setHint("local"); - auto downloads = test.getDownloads(currentSystem, cache.get(), failedFiles, QFINDTESTDATA("testdata/Library")); + auto downloads = test.getDownloads(r, cache.get(), failedFiles, QFINDTESTDATA("testdata/Library")); QCOMPARE(downloads.size(), 0); qDebug() << failedFiles; QCOMPARE(failedFiles.size(), 0); QStringList jar, native, native32, native64; - test.getApplicableFiles(currentSystem, jar, native, native32, native64, QFINDTESTDATA("testdata/Library")); + test.getApplicableFiles(r, jar, native, native32, native64, QFINDTESTDATA("testdata/Library")); QCOMPARE(jar, {QFileInfo(QFINDTESTDATA("testdata/Library/codecwav-20101023.jar")).absoluteFilePath()}); QCOMPARE(native, {}); QCOMPARE(native32, {}); @@ -86,19 +99,20 @@ slots: } void test_legacy_native() { + RuntimeContext r = dummyContext(); Library test("test.package:testname:testversion"); test.m_nativeClassifiers["linux"] = "linux"; QCOMPARE(test.isNative(), true); test.setRepositoryURL("file://foo/bar"); { QStringList jar, native, native32, native64; - test.getApplicableFiles(Os_Linux, jar, native, native32, native64, QString()); + test.getApplicableFiles(r, jar, native, native32, native64, QString()); QCOMPARE(jar, {}); QCOMPARE(native, getStorage("test/package/testname/testversion/testname-testversion-linux.jar")); QCOMPARE(native32, {}); QCOMPARE(native64, {}); QStringList failedFiles; - auto dls = test.getDownloads(Os_Linux, cache.get(), failedFiles, QString()); + auto dls = test.getDownloads(r, cache.get(), failedFiles, QString()); QCOMPARE(dls.size(), 1); QCOMPARE(failedFiles, {}); auto dl = dls[0]; @@ -107,6 +121,7 @@ slots: } void test_legacy_native_arch() { + RuntimeContext r = dummyContext(); Library test("test.package:testname:testversion"); test.m_nativeClassifiers["linux"]="linux-${arch}"; test.m_nativeClassifiers["osx"]="osx-${arch}"; @@ -115,41 +130,43 @@ slots: test.setRepositoryURL("file://foo/bar"); { QStringList jar, native, native32, native64; - test.getApplicableFiles(Os_Linux, jar, native, native32, native64, QString()); + test.getApplicableFiles(r, jar, native, native32, native64, QString()); QCOMPARE(jar, {}); QCOMPARE(native, {}); QCOMPARE(native32, getStorage("test/package/testname/testversion/testname-testversion-linux-32.jar")); QCOMPARE(native64, getStorage("test/package/testname/testversion/testname-testversion-linux-64.jar")); QStringList failedFiles; - auto dls = test.getDownloads(Os_Linux, cache.get(), failedFiles, QString()); + auto dls = test.getDownloads(r, cache.get(), failedFiles, QString()); QCOMPARE(dls.size(), 2); QCOMPARE(failedFiles, {}); QCOMPARE(dls[0]->m_url, QUrl("file://foo/bar/test/package/testname/testversion/testname-testversion-linux-32.jar")); QCOMPARE(dls[1]->m_url, QUrl("file://foo/bar/test/package/testname/testversion/testname-testversion-linux-64.jar")); } + r.system = "windows"; { QStringList jar, native, native32, native64; - test.getApplicableFiles(Os_Windows, jar, native, native32, native64, QString()); + test.getApplicableFiles(r, jar, native, native32, native64, QString()); QCOMPARE(jar, {}); QCOMPARE(native, {}); QCOMPARE(native32, getStorage("test/package/testname/testversion/testname-testversion-windows-32.jar")); QCOMPARE(native64, getStorage("test/package/testname/testversion/testname-testversion-windows-64.jar")); QStringList failedFiles; - auto dls = test.getDownloads(Os_Windows, cache.get(), failedFiles, QString()); + auto dls = test.getDownloads(r, cache.get(), failedFiles, QString()); QCOMPARE(dls.size(), 2); QCOMPARE(failedFiles, {}); QCOMPARE(dls[0]->m_url, QUrl("file://foo/bar/test/package/testname/testversion/testname-testversion-windows-32.jar")); QCOMPARE(dls[1]->m_url, QUrl("file://foo/bar/test/package/testname/testversion/testname-testversion-windows-64.jar")); } + r.system = "osx"; { QStringList jar, native, native32, native64; - test.getApplicableFiles(Os_OSX, jar, native, native32, native64, QString()); + test.getApplicableFiles(r, jar, native, native32, native64, QString()); QCOMPARE(jar, {}); QCOMPARE(native, {}); QCOMPARE(native32, getStorage("test/package/testname/testversion/testname-testversion-osx-32.jar")); QCOMPARE(native64, getStorage("test/package/testname/testversion/testname-testversion-osx-64.jar")); QStringList failedFiles; - auto dls = test.getDownloads(Os_OSX, cache.get(), failedFiles, QString()); + auto dls = test.getDownloads(r, cache.get(), failedFiles, QString()); QCOMPARE(dls.size(), 2); QCOMPARE(failedFiles, {}); QCOMPARE(dls[0]->m_url, QUrl("file://foo/bar/test/package/testname/testversion/testname-testversion-osx-32.jar")); @@ -158,6 +175,7 @@ slots: } void test_legacy_native_arch_local_override() { + RuntimeContext r = dummyContext(); Library test("test.package:testname:testversion"); test.m_nativeClassifiers["linux"]="linux-${arch}"; test.setHint("local"); @@ -165,96 +183,104 @@ slots: test.setRepositoryURL("file://foo/bar"); { QStringList jar, native, native32, native64; - test.getApplicableFiles(Os_Linux, jar, native, native32, native64, QFINDTESTDATA("testdata/Library")); + test.getApplicableFiles(r, jar, native, native32, native64, QFINDTESTDATA("testdata/Library")); QCOMPARE(jar, {}); QCOMPARE(native, {}); QCOMPARE(native32, {QFileInfo(QFINDTESTDATA("testdata/Library/testname-testversion-linux-32.jar")).absoluteFilePath()}); QCOMPARE(native64, {QFileInfo(QFINDTESTDATA("testdata/Library") + "/testname-testversion-linux-64.jar").absoluteFilePath()}); QStringList failedFiles; - auto dls = test.getDownloads(Os_Linux, cache.get(), failedFiles, QFINDTESTDATA("testdata/Library")); + auto dls = test.getDownloads(r, cache.get(), failedFiles, QFINDTESTDATA("testdata/Library")); QCOMPARE(dls.size(), 0); QCOMPARE(failedFiles, {QFileInfo(QFINDTESTDATA("testdata/Library") + "/testname-testversion-linux-64.jar").absoluteFilePath()}); } } void test_onenine() { + RuntimeContext r = dummyContext("osx"); auto test = readMojangJson(QFINDTESTDATA("testdata/Library/lib-simple.json")); { QStringList jar, native, native32, native64; - test->getApplicableFiles(Os_OSX, jar, native, native32, native64, QString()); + test->getApplicableFiles(r, jar, native, native32, native64, QString()); QCOMPARE(jar, getStorage("com/paulscode/codecwav/20101023/codecwav-20101023.jar")); QCOMPARE(native, {}); QCOMPARE(native32, {}); QCOMPARE(native64, {}); } + r.system = "linux"; { QStringList failedFiles; - auto dls = test->getDownloads(Os_Linux, cache.get(), failedFiles, QString()); + auto dls = test->getDownloads(r, cache.get(), failedFiles, QString()); QCOMPARE(dls.size(), 1); QCOMPARE(failedFiles, {}); QCOMPARE(dls[0]->m_url, QUrl("https://libraries.minecraft.net/com/paulscode/codecwav/20101023/codecwav-20101023.jar")); } + r.system = "osx"; test->setHint("local"); { QStringList jar, native, native32, native64; - test->getApplicableFiles(Os_OSX, jar, native, native32, native64, QFINDTESTDATA("testdata/Library")); + test->getApplicableFiles(r, jar, native, native32, native64, QFINDTESTDATA("testdata/Library")); QCOMPARE(jar, {QFileInfo(QFINDTESTDATA("testdata/Library/codecwav-20101023.jar")).absoluteFilePath()}); QCOMPARE(native, {}); QCOMPARE(native32, {}); QCOMPARE(native64, {}); } + r.system = "linux"; { QStringList failedFiles; - auto dls = test->getDownloads(Os_Linux, cache.get(), failedFiles, QFINDTESTDATA("testdata/Library")); + auto dls = test->getDownloads(r, cache.get(), failedFiles, QFINDTESTDATA("testdata/Library")); QCOMPARE(dls.size(), 0); QCOMPARE(failedFiles, {}); } } void test_onenine_local_override() { + RuntimeContext r = dummyContext("osx"); auto test = readMojangJson(QFINDTESTDATA("testdata/Library/lib-simple.json")); test->setHint("local"); { QStringList jar, native, native32, native64; - test->getApplicableFiles(Os_OSX, jar, native, native32, native64, QFINDTESTDATA("testdata/Library")); + test->getApplicableFiles(r, jar, native, native32, native64, QFINDTESTDATA("testdata/Library")); QCOMPARE(jar, {QFileInfo(QFINDTESTDATA("testdata/Library/codecwav-20101023.jar")).absoluteFilePath()}); QCOMPARE(native, {}); QCOMPARE(native32, {}); QCOMPARE(native64, {}); } + r.system = "linux"; { QStringList failedFiles; - auto dls = test->getDownloads(Os_Linux, cache.get(), failedFiles, QFINDTESTDATA("testdata/Library")); + auto dls = test->getDownloads(r, cache.get(), failedFiles, QFINDTESTDATA("testdata/Library")); QCOMPARE(dls.size(), 0); QCOMPARE(failedFiles, {}); } } void test_onenine_native() { + RuntimeContext r = dummyContext("osx"); auto test = readMojangJson(QFINDTESTDATA("testdata/Library/lib-native.json")); QStringList jar, native, native32, native64; - test->getApplicableFiles(Os_OSX, jar, native, native32, native64, QString()); + test->getApplicableFiles(r, jar, native, native32, native64, QString()); QCOMPARE(jar, QStringList()); QCOMPARE(native, getStorage("org/lwjgl/lwjgl/lwjgl-platform/2.9.4-nightly-20150209/lwjgl-platform-2.9.4-nightly-20150209-natives-osx.jar")); QCOMPARE(native32, {}); QCOMPARE(native64, {}); QStringList failedFiles; - auto dls = test->getDownloads(Os_OSX, cache.get(), failedFiles, QString()); + auto dls = test->getDownloads(r, cache.get(), failedFiles, QString()); QCOMPARE(dls.size(), 1); QCOMPARE(failedFiles, {}); QCOMPARE(dls[0]->m_url, QUrl("https://libraries.minecraft.net/org/lwjgl/lwjgl/lwjgl-platform/2.9.4-nightly-20150209/lwjgl-platform-2.9.4-nightly-20150209-natives-osx.jar")); } void test_onenine_native_arch() { + RuntimeContext r = dummyContext("windows"); auto test = readMojangJson(QFINDTESTDATA("testdata/Library/lib-native-arch.json")); QStringList jar, native, native32, native64; - test->getApplicableFiles(Os_Windows, jar, native, native32, native64, QString()); + test->getApplicableFiles(r, jar, native, native32, native64, QString()); QCOMPARE(jar, {}); QCOMPARE(native, {}); QCOMPARE(native32, getStorage("tv/twitch/twitch-platform/5.16/twitch-platform-5.16-natives-windows-32.jar")); QCOMPARE(native64, getStorage("tv/twitch/twitch-platform/5.16/twitch-platform-5.16-natives-windows-64.jar")); QStringList failedFiles; - auto dls = test->getDownloads(Os_Windows, cache.get(), failedFiles, QString()); + auto dls = test->getDownloads(r, cache.get(), failedFiles, QString()); QCOMPARE(dls.size(), 2); QCOMPARE(failedFiles, {}); QCOMPARE(dls[0]->m_url, QUrl("https://libraries.minecraft.net/tv/twitch/twitch-platform/5.16/twitch-platform-5.16-natives-windows-32.jar")); From 7e280de361584a70fae4426cf36ca47f694ef61a Mon Sep 17 00:00:00 2001 From: Sefa Eyeoglu Date: Mon, 8 Aug 2022 19:18:36 +0200 Subject: [PATCH 004/101] refactor: drop 64-bit check Signed-off-by: Sefa Eyeoglu --- launcher/launch/steps/CheckJava.cpp | 20 -------------------- libraries/systeminfo/include/sys.h | 4 ---- libraries/systeminfo/src/sys_apple.cpp | 12 ------------ libraries/systeminfo/src/sys_unix.cpp | 11 ----------- libraries/systeminfo/src/sys_win32.cpp | 22 ---------------------- 5 files changed, 69 deletions(-) diff --git a/launcher/launch/steps/CheckJava.cpp b/launcher/launch/steps/CheckJava.cpp index db56b652..7aeb61bf 100644 --- a/launcher/launch/steps/CheckJava.cpp +++ b/launcher/launch/steps/CheckJava.cpp @@ -121,7 +121,6 @@ void CheckJava::checkJavaFinished(JavaCheckResult result) 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); - printSystemInfo(false, false); emitFailed(QString("Could not start java!")); return; } @@ -130,7 +129,6 @@ void CheckJava::checkJavaFinished(JavaCheckResult result) 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); - printSystemInfo(false, false); emitSucceeded(); return; } @@ -138,7 +136,6 @@ void CheckJava::checkJavaFinished(JavaCheckResult result) { auto instance = m_parent->instance(); printJavaInfo(result.javaVersion.toString(), result.mojangPlatform, result.realPlatform, result.javaVendor); - printSystemInfo(true, result.is_64bit); instance->settings()->set("JavaVersion", result.javaVersion.toString()); instance->settings()->set("JavaArchitecture", result.mojangPlatform); instance->settings()->set("JavaRealArchitecture", result.realPlatform); @@ -155,20 +152,3 @@ void CheckJava::printJavaInfo(const QString& version, const QString& architectur emit logLine(QString("Java is version %1, using %2 (%3) architecture, from %4.\n\n") .arg(version, architecture, realArchitecture, vendor), MessageLevel::Launcher); } - -void CheckJava::printSystemInfo(bool javaIsKnown, bool javaIs64bit) -{ - auto cpu64 = Sys::isCPU64bit(); - auto system64 = Sys::isSystem64bit(); - if(cpu64 != system64) - { - emit logLine(QString("Your CPU architecture is not matching your system architecture. You might want to install a 64bit Operating System.\n\n"), MessageLevel::Error); - } - if(javaIsKnown) - { - if(javaIs64bit != system64) - { - emit logLine(QString("Your Java architecture is not matching your system architecture. You might want to install a 64bit Java version.\n\n"), MessageLevel::Error); - } - } -} diff --git a/libraries/systeminfo/include/sys.h b/libraries/systeminfo/include/sys.h index bd6e2486..6a6a7c82 100644 --- a/libraries/systeminfo/include/sys.h +++ b/libraries/systeminfo/include/sys.h @@ -56,8 +56,4 @@ struct DistributionInfo DistributionInfo getDistributionInfo(); uint64_t getSystemRam(); - -bool isSystem64bit(); - -bool isCPU64bit(); } diff --git a/libraries/systeminfo/src/sys_apple.cpp b/libraries/systeminfo/src/sys_apple.cpp index 6353b747..b6d62c1a 100644 --- a/libraries/systeminfo/src/sys_apple.cpp +++ b/libraries/systeminfo/src/sys_apple.cpp @@ -55,18 +55,6 @@ uint64_t Sys::getSystemRam() } } -bool Sys::isCPU64bit() -{ - // not even going to pretend I'm going to support anything else - return true; -} - -bool Sys::isSystem64bit() -{ - // yep. maybe when we have 128bit CPUs on consumer devices. - return true; -} - Sys::DistributionInfo Sys::getDistributionInfo() { DistributionInfo result; diff --git a/libraries/systeminfo/src/sys_unix.cpp b/libraries/systeminfo/src/sys_unix.cpp index b3098522..3c63e73a 100644 --- a/libraries/systeminfo/src/sys_unix.cpp +++ b/libraries/systeminfo/src/sys_unix.cpp @@ -82,17 +82,6 @@ uint64_t Sys::getSystemRam() return 0; // nothing found } -bool Sys::isCPU64bit() -{ - return isSystem64bit(); -} - -bool Sys::isSystem64bit() -{ - // kernel build arch on linux - return QSysInfo::currentCpuArchitecture() == "x86_64"; -} - Sys::DistributionInfo Sys::getDistributionInfo() { DistributionInfo systemd_info = read_os_release(); diff --git a/libraries/systeminfo/src/sys_win32.cpp b/libraries/systeminfo/src/sys_win32.cpp index 430b87e4..5bf510cf 100644 --- a/libraries/systeminfo/src/sys_win32.cpp +++ b/libraries/systeminfo/src/sys_win32.cpp @@ -27,28 +27,6 @@ uint64_t Sys::getSystemRam() return (uint64_t)status.ullTotalPhys; } -bool Sys::isSystem64bit() -{ -#if defined(_WIN64) - return true; -#elif defined(_WIN32) - BOOL f64 = false; - return IsWow64Process(GetCurrentProcess(), &f64) && f64; -#else - // it's some other kind of system... - return false; -#endif -} - -bool Sys::isCPU64bit() -{ - SYSTEM_INFO info; - ZeroMemory(&info, sizeof(SYSTEM_INFO)); - GetNativeSystemInfo(&info); - auto arch = info.wProcessorArchitecture; - return arch == PROCESSOR_ARCHITECTURE_AMD64 || arch == PROCESSOR_ARCHITECTURE_IA64; -} - Sys::DistributionInfo Sys::getDistributionInfo() { DistributionInfo result; From 98b6f901721aaeac3ba377729ef95272eba09410 Mon Sep 17 00:00:00 2001 From: Sefa Eyeoglu Date: Wed, 10 Aug 2022 17:33:55 +0200 Subject: [PATCH 005/101] fix: add more legacy architectures Signed-off-by: Sefa Eyeoglu --- launcher/RuntimeContext.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/launcher/RuntimeContext.h b/launcher/RuntimeContext.h index d98d407f..6090897c 100644 --- a/launcher/RuntimeContext.h +++ b/launcher/RuntimeContext.h @@ -30,7 +30,7 @@ struct RuntimeContext { // "Legacy" refers to the fact that Mojang assumed that these are the only two architectures bool isLegacyArch() const { - QSet legacyArchitectures{"amd64", "x86_64", "i686"}; + QSet legacyArchitectures{"amd64", "x86_64", "i386", "i686", "x86"}; return legacyArchitectures.contains(mappedJavaRealArchitecture()); } From ecf5ab75e7bbac8200cd1c4f9dd446380a365583 Mon Sep 17 00:00:00 2001 From: Sefa Eyeoglu Date: Tue, 20 Sep 2022 17:38:07 +0200 Subject: [PATCH 006/101] feat: support more formatting codes also fix some crashes Signed-off-by: Sefa Eyeoglu --- launcher/ui/widgets/InfoFrame.cpp | 59 +++++++++++++++++++------------ 1 file changed, 36 insertions(+), 23 deletions(-) diff --git a/launcher/ui/widgets/InfoFrame.cpp b/launcher/ui/widgets/InfoFrame.cpp index f78dbe16..37c807ad 100644 --- a/launcher/ui/widgets/InfoFrame.cpp +++ b/launcher/ui/widgets/InfoFrame.cpp @@ -97,14 +97,6 @@ void InfoFrame::updateWithResource(const Resource& resource) setImage(); } -// https://www.sportskeeda.com/minecraft-wiki/color-codes -static const QMap s_value_to_color = { - {'0', "#000000"}, {'1', "#0000AA"}, {'2', "#00AA00"}, {'3', "#00AAAA"}, {'4', "#AA0000"}, - {'5', "#AA00AA"}, {'6', "#FFAA00"}, {'7', "#AAAAAA"}, {'8', "#555555"}, {'9', "#5555FF"}, - {'a', "#55FF55"}, {'b', "#55FFFF"}, {'c', "#FF5555"}, {'d', "#FF55FF"}, {'e', "#FFFF55"}, - {'f', "#FFFFFF"} -}; - QString InfoFrame::renderColorCodes(QString input) { // We have to manually set the colors for use. // @@ -113,32 +105,53 @@ QString InfoFrame::renderColorCodes(QString input) { // We traverse the description and, when one of those is found, we create // a span element with that color set. // - // TODO: Make the same logic for font formatting too. // TODO: Wrap links inside tags + // https://minecraft.fandom.com/wiki/Formatting_codes#Color_codes + const QMap color_codes_map = { + {'0', "#000000"}, {'1', "#0000AA"}, {'2', "#00AA00"}, {'3', "#00AAAA"}, {'4', "#AA0000"}, + {'5', "#AA00AA"}, {'6', "#FFAA00"}, {'7', "#AAAAAA"}, {'8', "#555555"}, {'9', "#5555FF"}, + {'a', "#55FF55"}, {'b', "#55FFFF"}, {'c', "#FF5555"}, {'d', "#FF55FF"}, {'e', "#FFFF55"}, + {'f', "#FFFFFF"} + }; + // https://minecraft.fandom.com/wiki/Formatting_codes#Formatting_codes + const QMap formatting_codes_map = { + {'l', "b"}, {'m', "s"}, {'n', "u"}, {'o', "i"} + }; + QString html(""); - bool in_div = false; + QList tags{}; auto it = input.constBegin(); while (it != input.constEnd()) { - if (*it == u'§') { - if (in_div) - html += ""; + // is current char § and is there a following char + if (*it == u'§' && (it + 1) != input.constEnd()) { + auto const& code = *(++it); // incrementing here! - auto const& num = *(++it); - html += QString("").arg(s_value_to_color.constFind(num).value()); + auto const color_entry = color_codes_map.constFind(code); + auto const tag_entry = formatting_codes_map.constFind(code); - in_div = true; - - it++; + if (color_entry != color_codes_map.constEnd()) { // color code + html += QString("").arg(color_entry.value()); + tags << "span"; + } else if (tag_entry != formatting_codes_map.constEnd()) { // formatting code + html += QString("<%1>").arg(tag_entry.value()); + tags << tag_entry.value(); + } else if (code == 'r') { // reset all formatting + while (!tags.isEmpty()) { + html += QString("").arg(tags.takeLast()); + } + } else { // pass unknown codes through + html += QString("§%1").arg(code); + } + } else { + html += *it; } - - html += *it; it++; } - - if (in_div) - html += ""; + while (!tags.isEmpty()) { + html += QString("").arg(tags.takeLast()); + } html += ""; html.replace("\n", "
"); From 777ab3416f12c620daf111fb57ac357f5fc2af46 Mon Sep 17 00:00:00 2001 From: Sefa Eyeoglu Date: Tue, 20 Sep 2022 18:01:43 +0200 Subject: [PATCH 007/101] feat: also format resource/texture pack names Signed-off-by: Sefa Eyeoglu --- launcher/ui/widgets/InfoFrame.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/launcher/ui/widgets/InfoFrame.cpp b/launcher/ui/widgets/InfoFrame.cpp index 37c807ad..fdc581b4 100644 --- a/launcher/ui/widgets/InfoFrame.cpp +++ b/launcher/ui/widgets/InfoFrame.cpp @@ -160,14 +160,14 @@ QString InfoFrame::renderColorCodes(QString input) { void InfoFrame::updateWithResourcePack(ResourcePack& resource_pack) { - setName(resource_pack.name()); + setName(renderColorCodes(resource_pack.name())); setDescription(renderColorCodes(resource_pack.description())); setImage(resource_pack.image({64, 64})); } void InfoFrame::updateWithTexturePack(TexturePack& texture_pack) { - setName(texture_pack.name()); + setName(renderColorCodes(texture_pack.name())); setDescription(renderColorCodes(texture_pack.description())); setImage(texture_pack.image({64, 64})); } From 1862f3c124e090c1f27fa26babf65f14b8af8a37 Mon Sep 17 00:00:00 2001 From: flow Date: Fri, 29 Jul 2022 13:50:08 -0300 Subject: [PATCH 008/101] fix: set icon sizes correctly in ProjectItemDelegate no more dumb hacks with icons!! Signed-off-by: flow --- launcher/ui/widgets/ProjectItem.cpp | 37 ++++++++++++++++++++++------- 1 file changed, 29 insertions(+), 8 deletions(-) diff --git a/launcher/ui/widgets/ProjectItem.cpp b/launcher/ui/widgets/ProjectItem.cpp index 56ae35fb..01be88d9 100644 --- a/launcher/ui/widgets/ProjectItem.cpp +++ b/launcher/ui/widgets/ProjectItem.cpp @@ -14,9 +14,7 @@ void ProjectItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& o QStyleOptionViewItem opt(option); initStyleOption(&opt, index); - auto& rect = opt.rect; - auto icon_width = rect.height(), icon_height = rect.height(); - auto remaining_width = rect.width() - icon_width; + auto rect = opt.rect; if (opt.state & QStyle::State_Selected) { painter->fillRect(rect, opt.palette.highlight()); @@ -25,11 +23,34 @@ void ProjectItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& o painter->fillRect(rect, opt.palette.window()); } - { // Icon painting - // Square-sized, occupying the left portion - opt.icon.paint(painter, rect.x(), rect.y(), icon_width, icon_height); + // The default icon size will be a square (and height is usually the lower value). + auto icon_width = rect.height(), icon_height = rect.height(); + int icon_x_margin = (rect.height() - icon_width) / 2; + int icon_y_margin = (rect.height() - icon_height) / 2; + + if (!opt.icon.isNull()) { // Icon painting + { + auto icon_size = opt.decorationSize; + icon_width = icon_size.width(); + icon_height = icon_size.height(); + + icon_x_margin = (rect.height() - icon_width) / 2; + icon_y_margin = (rect.height() - icon_height) / 2; + } + + // Centralize icon with a margin to separate from the other elements + int x = rect.x() + icon_x_margin; + int y = rect.y() + icon_y_margin; + + // Prevent 'scaling null pixmap' warnings + if (icon_width > 0 && icon_height > 0) + opt.icon.paint(painter, x, y, icon_width, icon_height); } + // Change the rect so that funther painting is easier + auto remaining_width = rect.width() - icon_width - 2 * icon_x_margin; + rect.setRect(rect.x() + icon_width + 2 * icon_x_margin, rect.y(), remaining_width, rect.height()); + { // Title painting auto title = index.data(UserDataTypes::TITLE).toString(); @@ -46,7 +67,7 @@ void ProjectItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& o painter->setFont(font); // On the top, aligned to the left after the icon - painter->drawText(rect.x() + icon_width, rect.y() + QFontMetrics(font).height(), title); + painter->drawText(rect.x(), rect.y() + QFontMetrics(font).height(), title); painter->restore(); } @@ -70,7 +91,7 @@ void ProjectItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& o } // On the bottom, aligned to the left after the icon, and featuring at most two lines of text (with some margin space to spare) - painter->drawText(rect.x() + icon_width, rect.y() + rect.height() - 2.2 * opt.fontMetrics.height(), remaining_width, + painter->drawText(rect.x(), rect.y() + rect.height() - 2.2 * opt.fontMetrics.height(), remaining_width, 2 * opt.fontMetrics.height(), Qt::TextWordWrap, description); } From ee4a82929365d817d64b37e0e7064bb217a3d66b Mon Sep 17 00:00:00 2001 From: flow Date: Fri, 23 Sep 2022 16:58:25 -0300 Subject: [PATCH 009/101] fix: remove manual icon resize in ModModel THis fixes a FIXME, now that we fixed the issue :o Signed-off-by: flow --- launcher/ui/pages/modplatform/ModModel.cpp | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/launcher/ui/pages/modplatform/ModModel.cpp b/launcher/ui/pages/modplatform/ModModel.cpp index 029e2be0..68dbd500 100644 --- a/launcher/ui/pages/modplatform/ModModel.cpp +++ b/launcher/ui/pages/modplatform/ModModel.cpp @@ -62,11 +62,7 @@ auto ListModel::data(const QModelIndex& index, int role) const -> QVariant } case Qt::DecorationRole: { if (m_logoMap.contains(pack.logoName)) { - auto icon = m_logoMap.value(pack.logoName); - // FIXME: This doesn't really belong here, but Qt doesn't offer a good way right now ;( - auto icon_scaled = QIcon(icon.pixmap(48, 48).scaledToWidth(48)); - - return icon_scaled; + return m_logoMap.value(pack.logoName); } QIcon icon = APPLICATION->getThemedIcon("screenshot-placeholder"); // un-const-ify this From 3df8594f19563cd50ac73200ee8512b7c6ceec96 Mon Sep 17 00:00:00 2001 From: flow Date: Thu, 28 Jul 2022 23:00:00 -0300 Subject: [PATCH 010/101] feat: change project item delegate for modrinth modpacks more info! \ ^-^/ Signed-off-by: flow --- .../modplatform/modrinth/ModrinthModel.cpp | 54 +++++++++++-------- .../modplatform/modrinth/ModrinthPage.cpp | 4 ++ 2 files changed, 36 insertions(+), 22 deletions(-) diff --git a/launcher/ui/pages/modplatform/modrinth/ModrinthModel.cpp b/launcher/ui/pages/modplatform/modrinth/ModrinthModel.cpp index 614be434..03b73510 100644 --- a/launcher/ui/pages/modplatform/modrinth/ModrinthModel.cpp +++ b/launcher/ui/pages/modplatform/modrinth/ModrinthModel.cpp @@ -41,6 +41,7 @@ #include "minecraft/MinecraftInstance.h" #include "minecraft/PackProfile.h" #include "ui/dialogs/ModDownloadDialog.h" +#include "ui/widgets/ProjectItem.h" #include @@ -74,31 +75,40 @@ auto ModpackListModel::data(const QModelIndex& index, int role) const -> QVarian } Modrinth::Modpack pack = modpacks.at(pos); - if (role == Qt::DisplayRole) { - return pack.name; - } else if (role == Qt::ToolTipRole) { - if (pack.description.length() > 100) { - // some magic to prevent to long tooltips and replace html linebreaks - QString edit = pack.description.left(97); - edit = edit.left(edit.lastIndexOf("
")).left(edit.lastIndexOf(" ")).append("..."); - return edit; + switch (role) { + case Qt::ToolTipRole: { + if (pack.description.length() > 100) { + // some magic to prevent to long tooltips and replace html linebreaks + QString edit = pack.description.left(97); + edit = edit.left(edit.lastIndexOf("
")).left(edit.lastIndexOf(" ")).append("..."); + return edit; + } + return pack.description; } - return pack.description; - } else if (role == Qt::DecorationRole) { - if (m_logoMap.contains(pack.iconName)) { - auto icon = m_logoMap.value(pack.iconName); - // FIXME: This doesn't really belong here, but Qt doesn't offer a good way right now ;( - auto icon_scaled = QIcon(icon.pixmap(48, 48).scaledToWidth(48)); + case Qt::DecorationRole: { + if (m_logoMap.contains(pack.iconName)) + return m_logoMap.value(pack.iconName); - return icon_scaled; + QIcon icon = APPLICATION->getThemedIcon("screenshot-placeholder"); + ((ModpackListModel*)this)->requestLogo(pack.iconName, pack.iconUrl.toString()); + return icon; } - QIcon icon = APPLICATION->getThemedIcon("screenshot-placeholder"); - ((ModpackListModel*)this)->requestLogo(pack.iconName, pack.iconUrl.toString()); - return icon; - } else if (role == Qt::UserRole) { - QVariant v; - v.setValue(pack); - return v; + case Qt::UserRole: { + QVariant v; + v.setValue(pack); + return v; + } + case Qt::SizeHintRole: + return QSize(0, 58); + // Custom data + case UserDataTypes::TITLE: + return pack.name; + case UserDataTypes::DESCRIPTION: + return pack.description; + case UserDataTypes::SELECTED: + return false; + default: + break; } return {}; diff --git a/launcher/ui/pages/modplatform/modrinth/ModrinthPage.cpp b/launcher/ui/pages/modplatform/modrinth/ModrinthPage.cpp index df29c0c3..8ee9bff5 100644 --- a/launcher/ui/pages/modplatform/modrinth/ModrinthPage.cpp +++ b/launcher/ui/pages/modplatform/modrinth/ModrinthPage.cpp @@ -43,6 +43,8 @@ #include "InstanceImportTask.h" #include "Json.h" +#include "ui/widgets/ProjectItem.h" + #include #include @@ -70,6 +72,8 @@ ModrinthPage::ModrinthPage(NewInstanceDialog* dialog, QWidget* parent) : QWidget connect(ui->sortByBox, SIGNAL(currentIndexChanged(int)), this, SLOT(triggerSearch())); connect(ui->packView->selectionModel(), &QItemSelectionModel::currentChanged, this, &ModrinthPage::onSelectionChanged); connect(ui->versionSelectionBox, &QComboBox::currentTextChanged, this, &ModrinthPage::onVersionSelectionChanged); + + ui->packView->setItemDelegate(new ProjectItemDelegate(this)); } ModrinthPage::~ModrinthPage() From e7380e70a3a615b69da863918bec58e41b82cdd1 Mon Sep 17 00:00:00 2001 From: flow Date: Fri, 23 Sep 2022 18:05:58 -0300 Subject: [PATCH 011/101] fix: use placeholder icon when the project has no icon in MR Projects with no icon return a null icon URL in Modrinth's API. Signed-off-by: flow --- launcher/ui/pages/modplatform/ModModel.cpp | 2 +- launcher/ui/pages/modplatform/modrinth/ModrinthModel.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/launcher/ui/pages/modplatform/ModModel.cpp b/launcher/ui/pages/modplatform/ModModel.cpp index 68dbd500..8961fadd 100644 --- a/launcher/ui/pages/modplatform/ModModel.cpp +++ b/launcher/ui/pages/modplatform/ModModel.cpp @@ -171,7 +171,7 @@ void ListModel::getLogo(const QString& logo, const QString& logoUrl, LogoCallbac void ListModel::requestLogo(QString logo, QString url) { - if (m_loadingLogos.contains(logo) || m_failedLogos.contains(logo)) { + if (m_loadingLogos.contains(logo) || m_failedLogos.contains(logo) || url.isEmpty()) { return; } diff --git a/launcher/ui/pages/modplatform/modrinth/ModrinthModel.cpp b/launcher/ui/pages/modplatform/modrinth/ModrinthModel.cpp index 03b73510..fd7a3537 100644 --- a/launcher/ui/pages/modplatform/modrinth/ModrinthModel.cpp +++ b/launcher/ui/pages/modplatform/modrinth/ModrinthModel.cpp @@ -227,7 +227,7 @@ void ModpackListModel::getLogo(const QString& logo, const QString& logoUrl, Logo void ModpackListModel::requestLogo(QString logo, QString url) { - if (m_loadingLogos.contains(logo) || m_failedLogos.contains(logo)) { + if (m_loadingLogos.contains(logo) || m_failedLogos.contains(logo) || url.isEmpty()) { return; } From 600c49f7f0482e6ca5cf977a99c225ccd97c4ae2 Mon Sep 17 00:00:00 2001 From: Trial97 Date: Sat, 24 Sep 2022 00:06:36 +0300 Subject: [PATCH 012/101] Replaced tomlc99 with tomlplusplus Signed-off-by: Trial97 --- .gitmodules | 4 + CMakeLists.txt | 2 +- COPYING.md | 30 +- launcher/CMakeLists.txt | 2 +- .../minecraft/mod/tasks/LocalModParseTask.cpp | 268 +- launcher/modplatform/packwiz/Packwiz.cpp | 156 +- libraries/README.md | 16 +- libraries/tomlc99/CMakeLists.txt | 10 - libraries/tomlc99/LICENSE | 22 - libraries/tomlc99/README.md | 197 -- libraries/tomlc99/include/toml.h | 175 -- libraries/tomlc99/src/toml.c | 2300 ----------------- libraries/tomlplusplus | 1 + 13 files changed, 194 insertions(+), 2989 deletions(-) delete mode 100644 libraries/tomlc99/CMakeLists.txt delete mode 100644 libraries/tomlc99/LICENSE delete mode 100644 libraries/tomlc99/README.md delete mode 100644 libraries/tomlc99/include/toml.h delete mode 100644 libraries/tomlc99/src/toml.c create mode 160000 libraries/tomlplusplus diff --git a/.gitmodules b/.gitmodules index 08b94c96..b29a0477 100644 --- a/.gitmodules +++ b/.gitmodules @@ -6,3 +6,7 @@ [submodule "libraries/quazip"] path = libraries/quazip url = https://github.com/stachenov/quazip.git +[submodule "libraries/tomlplusplus"] + path = libraries/tomlplusplus + url = https://github.com/marzer/tomlplusplus.git + shallow = true diff --git a/CMakeLists.txt b/CMakeLists.txt index 7100ab1b..364e16d6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -312,7 +312,7 @@ endif() add_subdirectory(libraries/rainbow) # Qt extension for colors add_subdirectory(libraries/LocalPeer) # fork of a library from Qt solutions add_subdirectory(libraries/classparser) # class parser library -add_subdirectory(libraries/tomlc99) # toml parser +add_subdirectory(libraries/tomlplusplus) # toml parser add_subdirectory(libraries/katabasis) # An OAuth2 library that tried to do too much add_subdirectory(libraries/gamemode) add_subdirectory(libraries/murmur2) # Hash for usage with the CurseForge API diff --git a/COPYING.md b/COPYING.md index c94c51c3..11c1fc3a 100644 --- a/COPYING.md +++ b/COPYING.md @@ -315,30 +315,24 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -## tomlc99 +## tomlplusplus MIT License - Copyright (c) 2017 CK Tan - https://github.com/cktan/tomlc99 + Copyright (c) Mark Gillard - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + documentation files (the "Software"), to deal in the Software without restriction, including without limitation the + rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to the following conditions: - The above copyright notice and this permission notice shall be included in all - copies or substantial portions of the Software. + The above copyright notice and this permission notice shall be included in all copies or substantial portions of the + Software. - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE. + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## O2 (Katabasis fork) diff --git a/launcher/CMakeLists.txt b/launcher/CMakeLists.txt index 848d2e51..8fdbec5b 100644 --- a/launcher/CMakeLists.txt +++ b/launcher/CMakeLists.txt @@ -965,7 +965,7 @@ target_link_libraries(Launcher_logic Launcher_murmur2 nbt++ ${ZLIB_LIBRARIES} - tomlc99 + tomlplusplus::tomlplusplus BuildConfig Katabasis Qt${QT_VERSION_MAJOR}::Widgets diff --git a/launcher/minecraft/mod/tasks/LocalModParseTask.cpp b/launcher/minecraft/mod/tasks/LocalModParseTask.cpp index 8a6e54d8..ae8e95ff 100644 --- a/launcher/minecraft/mod/tasks/LocalModParseTask.cpp +++ b/launcher/minecraft/mod/tasks/LocalModParseTask.cpp @@ -1,17 +1,17 @@ #include "LocalModParseTask.h" -#include -#include -#include -#include -#include #include #include -#include +#include +#include +#include +#include +#include +#include +#include "FileSystem.h" #include "Json.h" #include "settings/INIFile.h" -#include "FileSystem.h" namespace { @@ -22,8 +22,7 @@ namespace { // https://github.com/MinecraftForge/FML/wiki/FML-mod-information-file/5bf6a2d05145ec79387acc0d45c958642fb049fc ModDetails ReadMCModInfo(QByteArray contents) { - auto getInfoFromArray = [&](QJsonArray arr) -> ModDetails - { + auto getInfoFromArray = [&](QJsonArray arr) -> ModDetails { if (!arr.at(0).isObject()) { return {}; } @@ -32,16 +31,14 @@ ModDetails ReadMCModInfo(QByteArray contents) 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") { + if (name != "Example Mod") { details.name = name; } details.version = firstObj.value("version").toString(); auto homeurl = firstObj.value("url").toString().trimmed(); - if(!homeurl.isEmpty()) - { + if (!homeurl.isEmpty()) { // fix up url. - if (!homeurl.startsWith("http://") && !homeurl.startsWith("https://") && !homeurl.startsWith("ftp://")) - { + if (!homeurl.startsWith("http://") && !homeurl.startsWith("https://") && !homeurl.startsWith("ftp://")) { homeurl.prepend("http://"); } } @@ -53,8 +50,7 @@ ModDetails ReadMCModInfo(QByteArray contents) authors = firstObj.value("authors").toArray(); } - for (auto author: authors) - { + for (auto author : authors) { details.authors.append(author.toString()); } return details; @@ -62,14 +58,11 @@ ModDetails ReadMCModInfo(QByteArray contents) QJsonParseError jsonError; QJsonDocument jsonDoc = QJsonDocument::fromJson(contents, &jsonError); // this is the very old format that had just the array - if (jsonDoc.isArray()) - { + if (jsonDoc.isArray()) { return getInfoFromArray(jsonDoc.array()); - } - else if (jsonDoc.isObject()) - { + } else if (jsonDoc.isObject()) { auto val = jsonDoc.object().value("modinfoversion"); - if(val.isUndefined()) { + if (val.isUndefined()) { val = jsonDoc.object().value("modListVersion"); } @@ -79,18 +72,16 @@ ModDetails ReadMCModInfo(QByteArray contents) if (version < 0) version = Json::ensureString(val, "").toInt(); - if (version != 2) - { + if (version != 2) { qCritical() << "BAD stuff happened to mod json:"; qCritical() << contents; return {}; } auto arrVal = jsonDoc.object().value("modlist"); - if(arrVal.isUndefined()) { + if (arrVal.isUndefined()) { arrVal = jsonDoc.object().value("modList"); } - if (arrVal.isArray()) - { + if (arrVal.isArray()) { return getInfoFromArray(arrVal.toArray()); } } @@ -102,109 +93,77 @@ ModDetails ReadMCModTOML(QByteArray contents) { ModDetails details; - char errbuf[200]; - // top-level table - toml_table_t* tomlData = toml_parse(contents.data(), errbuf, sizeof(errbuf)); - - if(!tomlData) - { + // auto tomlData = toml::parse(contents.toStdString()); + toml::table tomlData; +#if TOML_EXCEPTIONS + try { + tomlData = toml::parse(contents.toStdString()); + } catch (const toml::parse_error& err) { return {}; } +#else + tomlData = toml::parse(contents.toStdString()); + if (!tomlData) { + return {}; + } +#endif // array defined by [[mods]] - toml_array_t* tomlModsArr = toml_array_in(tomlData, "mods"); - if(!tomlModsArr) - { + 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 - toml_table_t* tomlModsTable0 = toml_table_at(tomlModsArr, 0); - if(!tomlModsTable0) - { + 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 (!tomlModsTable0) { + qWarning() << "Corrupted mods.toml? [[mods]] was not a table!"; + return {}; + } // mandatory properties - always in [[mods]] - toml_datum_t modIdDatum = toml_string_in(tomlModsTable0, "modId"); - if(modIdDatum.ok) - { - details.mod_id = modIdDatum.u.s; - // library says this is required for strings - free(modIdDatum.u.s); + if (auto modIdDatum = (*modsTable)["modId"].as_string()) { + details.mod_id = QString::fromStdString(modIdDatum->get()); } - toml_datum_t versionDatum = toml_string_in(tomlModsTable0, "version"); - if(versionDatum.ok) - { - details.version = versionDatum.u.s; - free(versionDatum.u.s); + if (auto versionDatum = (*modsTable)["version"].as_string()) { + details.version = QString::fromStdString(versionDatum->get()); } - toml_datum_t displayNameDatum = toml_string_in(tomlModsTable0, "displayName"); - if(displayNameDatum.ok) - { - details.name = displayNameDatum.u.s; - free(displayNameDatum.u.s); + if (auto displayNameDatum = (*modsTable)["displayName"].as_string()) { + details.name = QString::fromStdString(displayNameDatum->get()); } - toml_datum_t descriptionDatum = toml_string_in(tomlModsTable0, "description"); - if(descriptionDatum.ok) - { - details.description = descriptionDatum.u.s; - free(descriptionDatum.u.s); + if (auto descriptionDatum = (*modsTable)["description"].as_string()) { + details.description = QString::fromStdString(descriptionDatum->get()); } // optional properties - can be in the root table or [[mods]] - toml_datum_t authorsDatum = toml_string_in(tomlData, "authors"); QString authors = ""; - if(authorsDatum.ok) - { - authors = authorsDatum.u.s; - free(authorsDatum.u.s); + if (auto authorsDatum = tomlData["authors"].as_string()) { + authors = QString::fromStdString(authorsDatum->get()); + } else if (auto authorsDatum = (*modsTable)["authors"].as_string()) { + authors = QString::fromStdString(authorsDatum->get()); } - else - { - authorsDatum = toml_string_in(tomlModsTable0, "authors"); - if(authorsDatum.ok) - { - authors = authorsDatum.u.s; - free(authorsDatum.u.s); - } - } - if(!authors.isEmpty()) - { + if (!authors.isEmpty()) { details.authors.append(authors); } - toml_datum_t homeurlDatum = toml_string_in(tomlData, "displayURL"); QString homeurl = ""; - if(homeurlDatum.ok) - { - homeurl = homeurlDatum.u.s; - free(homeurlDatum.u.s); + if (auto homeurlDatum = tomlData["displayURL"].as_string()) { + homeurl = QString::fromStdString(homeurlDatum->get()); + } else if (auto homeurlDatum = (*modsTable)["displayURL"].as_string()) { + homeurl = QString::fromStdString(homeurlDatum->get()); } - else - { - homeurlDatum = toml_string_in(tomlModsTable0, "displayURL"); - if(homeurlDatum.ok) - { - homeurl = homeurlDatum.u.s; - free(homeurlDatum.u.s); - } - } - if(!homeurl.isEmpty()) - { - // fix up url. - if (!homeurl.startsWith("http://") && !homeurl.startsWith("https://") && !homeurl.startsWith("ftp://")) - { - homeurl.prepend("http://"); - } + // fix up url. + if (!homeurl.isEmpty() && !homeurl.startsWith("http://") && !homeurl.startsWith("https://") && !homeurl.startsWith("ftp://")) { + homeurl.prepend("http://"); } details.homeurl = homeurl; - // this seems to be recursive, so it should free everything - toml_free(tomlData); - return details; } @@ -224,25 +183,20 @@ ModDetails ReadFabricModInfo(QByteArray contents) details.name = object.contains("name") ? object.value("name").toString() : details.mod_id; details.description = object.value("description").toString(); - if (schemaVersion >= 1) - { + if (schemaVersion >= 1) { QJsonArray authors = object.value("authors").toArray(); - for (auto author: authors) - { - if(author.isObject()) { + for (auto author : authors) { + if (author.isObject()) { details.authors.append(author.toObject().value("name").toString()); - } - else { + } else { details.authors.append(author.toString()); } } - if (object.contains("contact")) - { + if (object.contains("contact")) { QJsonObject contact = object.value("contact").toObject(); - if (contact.contains("homepage")) - { + if (contact.contains("homepage")) { details.homeurl = contact.value("homepage").toString(); } } @@ -261,8 +215,7 @@ ModDetails ReadQuiltModInfo(QByteArray contents) ModDetails details; // https://github.com/QuiltMC/rfcs/blob/be6ba280d785395fefa90a43db48e5bfc1d15eb4/specification/0002-quilt.mod.json.md - if (schemaVersion == 1) - { + if (schemaVersion == 1) { auto modInfo = Json::requireObject(object.value("quilt_loader"), "Quilt mod info"); details.mod_id = Json::requireString(modInfo.value("id"), "Mod ID"); @@ -280,8 +233,7 @@ ModDetails ReadQuiltModInfo(QByteArray contents) auto modContact = Json::ensureObject(modMetadata.value("contact")); - if (modContact.contains("homepage")) - { + if (modContact.contains("homepage")) { details.homeurl = Json::requireString(modContact.value("homepage")); } } @@ -314,21 +266,17 @@ ModDetails ReadLiteModInfo(QByteArray contents) QJsonParseError jsonError; QJsonDocument jsonDoc = QJsonDocument::fromJson(contents, &jsonError); auto object = jsonDoc.object(); - if (object.contains("name")) - { + if (object.contains("name")) { details.mod_id = details.name = object.value("name").toString(); } - if (object.contains("version")) - { + if (object.contains("version")) { details.version = object.value("version").toString(""); - } - else - { + } else { details.version = object.value("revision").toString(""); } details.mcversion = object.value("mcversion").toString(); auto author = object.value("author").toString(); - if(!author.isEmpty()) { + if (!author.isEmpty()) { details.authors.append(author); } details.description = object.value("description").toString(); @@ -336,14 +284,10 @@ ModDetails ReadLiteModInfo(QByteArray contents) return details; } -} +} // namespace -LocalModParseTask::LocalModParseTask(int token, ResourceType type, const QFileInfo& modFile): - Task(nullptr, false), - m_token(token), - m_type(type), - m_modFile(modFile), - m_result(new Result()) +LocalModParseTask::LocalModParseTask(int token, ResourceType type, const QFileInfo& modFile) + : Task(nullptr, false), m_token(token), m_type(type), m_modFile(modFile), m_result(new Result()) {} void LocalModParseTask::processAsZip() @@ -354,10 +298,8 @@ void LocalModParseTask::processAsZip() QuaZipFile file(&zip); - if (zip.setCurrentFile("META-INF/mods.toml")) - { - if (!file.open(QIODevice::ReadOnly)) - { + if (zip.setCurrentFile("META-INF/mods.toml")) { + if (!file.open(QIODevice::ReadOnly)) { zip.close(); return; } @@ -366,12 +308,9 @@ void LocalModParseTask::processAsZip() file.close(); // to replace ${file.jarVersion} with the actual version, as needed - if (m_result->details.version == "${file.jarVersion}") - { - if (zip.setCurrentFile("META-INF/MANIFEST.MF")) - { - if (!file.open(QIODevice::ReadOnly)) - { + if (m_result->details.version == "${file.jarVersion}") { + if (zip.setCurrentFile("META-INF/MANIFEST.MF")) { + if (!file.open(QIODevice::ReadOnly)) { zip.close(); return; } @@ -379,10 +318,8 @@ void LocalModParseTask::processAsZip() // 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: ")) - { + for (auto& line : manifestLines) { + if (QString(line).startsWith("Implementation-Version: ")) { manifestVersion = QString(line).remove("Implementation-Version: "); break; } @@ -390,8 +327,7 @@ void LocalModParseTask::processAsZip() // 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 == "") - { + if (manifestVersion.contains("task ':jar' property 'archiveVersion'") || manifestVersion == "") { manifestVersion = "NONE"; } @@ -403,11 +339,8 @@ void LocalModParseTask::processAsZip() zip.close(); return; - } - else if (zip.setCurrentFile("mcmod.info")) - { - if (!file.open(QIODevice::ReadOnly)) - { + } else if (zip.setCurrentFile("mcmod.info")) { + if (!file.open(QIODevice::ReadOnly)) { zip.close(); return; } @@ -416,11 +349,8 @@ void LocalModParseTask::processAsZip() file.close(); zip.close(); return; - } - else if (zip.setCurrentFile("quilt.mod.json")) - { - if (!file.open(QIODevice::ReadOnly)) - { + } else if (zip.setCurrentFile("quilt.mod.json")) { + if (!file.open(QIODevice::ReadOnly)) { zip.close(); return; } @@ -429,11 +359,8 @@ void LocalModParseTask::processAsZip() file.close(); zip.close(); return; - } - else if (zip.setCurrentFile("fabric.mod.json")) - { - if (!file.open(QIODevice::ReadOnly)) - { + } else if (zip.setCurrentFile("fabric.mod.json")) { + if (!file.open(QIODevice::ReadOnly)) { zip.close(); return; } @@ -442,11 +369,8 @@ void LocalModParseTask::processAsZip() file.close(); zip.close(); return; - } - else if (zip.setCurrentFile("forgeversion.properties")) - { - if (!file.open(QIODevice::ReadOnly)) - { + } else if (zip.setCurrentFile("forgeversion.properties")) { + if (!file.open(QIODevice::ReadOnly)) { zip.close(); return; } @@ -463,8 +387,7 @@ void LocalModParseTask::processAsZip() void LocalModParseTask::processAsFolder() { QFileInfo mcmod_info(FS::PathCombine(m_modFile.filePath(), "mcmod.info")); - if (mcmod_info.isFile()) - { + if (mcmod_info.isFile()) { QFile mcmod(mcmod_info.filePath()); if (!mcmod.open(QIODevice::ReadOnly)) return; @@ -483,10 +406,8 @@ void LocalModParseTask::processAsLitemod() QuaZipFile file(&zip); - if (zip.setCurrentFile("litemod.json")) - { - if (!file.open(QIODevice::ReadOnly)) - { + if (zip.setCurrentFile("litemod.json")) { + if (!file.open(QIODevice::ReadOnly)) { zip.close(); return; } @@ -505,8 +426,7 @@ bool LocalModParseTask::abort() void LocalModParseTask::executeTask() { - switch(m_type) - { + switch (m_type) { case ResourceType::ZIPFILE: processAsZip(); break; diff --git a/launcher/modplatform/packwiz/Packwiz.cpp b/launcher/modplatform/packwiz/Packwiz.cpp index c3561093..b1fe963e 100644 --- a/launcher/modplatform/packwiz/Packwiz.cpp +++ b/launcher/modplatform/packwiz/Packwiz.cpp @@ -1,20 +1,20 @@ // SPDX-License-Identifier: GPL-3.0-only /* -* PolyMC - Minecraft Launcher -* Copyright (c) 2022 flowln -* -* 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 . -*/ + * PolyMC - Minecraft Launcher + * Copyright (c) 2022 flowln + * + * 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 . + */ #include "Packwiz.h" @@ -22,9 +22,7 @@ #include #include -#include "toml.h" -#include "FileSystem.h" - +#include #include "minecraft/mod/Mod.h" #include "modplatform/ModIndex.h" @@ -44,7 +42,7 @@ auto getRealIndexName(QDir& index_dir, QString normalized_fname, bool should_fin } } - if(should_find_match && !QString::compare(normalized_fname, real_fname, Qt::CaseSensitive)){ + if (should_find_match && !QString::compare(normalized_fname, real_fname, Qt::CaseSensitive)) { qCritical() << "Could not find a match for a valid metadata file!"; qCritical() << "File: " << normalized_fname; return {}; @@ -57,7 +55,7 @@ auto getRealIndexName(QDir& index_dir, QString normalized_fname, bool should_fin // Helpers static inline auto indexFileName(QString const& mod_slug) -> QString { - if(mod_slug.endsWith(".pw.toml")) + if (mod_slug.endsWith(".pw.toml")) return mod_slug; return QString("%1.pw.toml").arg(mod_slug); } @@ -65,32 +63,28 @@ static inline auto indexFileName(QString const& mod_slug) -> QString static ModPlatform::ProviderCapabilities ProviderCaps; // Helper functions for extracting data from the TOML file -auto stringEntry(toml_table_t* parent, const char* entry_name) -> QString +auto stringEntry(toml::table table, const std::string entry_name) -> QString { - toml_datum_t var = toml_string_in(parent, entry_name); - if (!var.ok) { - qCritical() << QString("Failed to read str property '%1' in mod metadata.").arg(entry_name); + auto node = table[entry_name]; + if (!node) { + qCritical() << QString::fromStdString("Failed to read str property '" + entry_name + "' in mod metadata."); return {}; } - QString tmp = var.u.s; - free(var.u.s); - - return tmp; + return QString::fromStdString(node.value_or("")); } -auto intEntry(toml_table_t* parent, const char* entry_name) -> int +auto intEntry(toml::table table, const std::string entry_name) -> int { - toml_datum_t var = toml_int_in(parent, entry_name); - if (!var.ok) { - qCritical() << QString("Failed to read int property '%1' in mod metadata.").arg(entry_name); + auto node = table[entry_name]; + if (!node) { + qCritical() << QString::fromStdString("Failed to read int property '" + entry_name + "' in mod metadata."); return {}; } - return var.u.i; + return node.value_or(0); } - auto V1::createModFormat(QDir& index_dir, ModPlatform::IndexedPack& mod_pack, ModPlatform::IndexedVersion& mod_version) -> Mod { Mod mod; @@ -99,10 +93,9 @@ auto V1::createModFormat(QDir& index_dir, ModPlatform::IndexedPack& mod_pack, Mo mod.name = mod_pack.name; mod.filename = mod_version.fileName; - if(mod_pack.provider == ModPlatform::Provider::FLAME){ + if (mod_pack.provider == ModPlatform::Provider::FLAME) { mod.mode = "metadata:curseforge"; - } - else { + } else { mod.mode = "url"; mod.url = mod_version.downloadUrl; } @@ -120,8 +113,8 @@ auto V1::createModFormat(QDir& index_dir, ModPlatform::IndexedPack& mod_pack, Mo auto V1::createModFormat(QDir& index_dir, ::Mod& internal_mod, QString slug) -> Mod { // Try getting metadata if it exists - Mod mod { getIndexForMod(index_dir, slug) }; - if(mod.isValid()) + Mod mod{ getIndexForMod(index_dir, slug) }; + if (mod.isValid()) return mod; qWarning() << QString("Tried to create mod metadata with a Mod without metadata!"); @@ -131,7 +124,7 @@ auto V1::createModFormat(QDir& index_dir, ::Mod& internal_mod, QString slug) -> void V1::updateModIndex(QDir& index_dir, Mod& mod) { - if(!mod.isValid()){ + if (!mod.isValid()) { qCritical() << QString("Tried to update metadata of an invalid mod!"); return; } @@ -150,7 +143,9 @@ void V1::updateModIndex(QDir& index_dir, Mod& mod) // TODO: We should do more stuff here, as the user is likely trying to // override a file. In this case, check versions and ask the user what // they want to do! - if (index_file.exists()) { index_file.remove(); } + if (index_file.exists()) { + index_file.remove(); + } if (!index_file.open(QIODevice::ReadWrite)) { qCritical() << QString("Could not open file %1!").arg(indexFileName(mod.name)); @@ -174,15 +169,15 @@ void V1::updateModIndex(QDir& index_dir, Mod& mod) in_stream << QString("\n[update]\n"); in_stream << QString("[update.%1]\n").arg(ProviderCaps.name(mod.provider)); - switch(mod.provider){ - case(ModPlatform::Provider::FLAME): - in_stream << QString("file-id = %1\n").arg(mod.file_id.toString()); - in_stream << QString("project-id = %1\n").arg(mod.project_id.toString()); - break; - case(ModPlatform::Provider::MODRINTH): - addToStream("mod-id", mod.mod_id().toString()); - addToStream("version", mod.version().toString()); - break; + switch (mod.provider) { + case (ModPlatform::Provider::FLAME): + in_stream << QString("file-id = %1\n").arg(mod.file_id.toString()); + in_stream << QString("project-id = %1\n").arg(mod.project_id.toString()); + break; + case (ModPlatform::Provider::MODRINTH): + addToStream("mod-id", mod.mod_id().toString()); + addToStream("version", mod.version().toString()); + break; } } @@ -230,27 +225,25 @@ auto V1::getIndexForMod(QDir& index_dir, QString slug) -> Mod if (real_fname.isEmpty()) return {}; - QFile index_file(index_dir.absoluteFilePath(real_fname)); - - if (!index_file.open(QIODevice::ReadOnly)) { - qWarning() << QString("Failed to open mod metadata for %1").arg(slug); + toml::table table; +#if TOML_EXCEPTIONS + try { + table = toml::parse_file(index_dir.absoluteFilePath(real_fname).toStdString()); + } catch (const toml::parse_error& err) { + qWarning() << QString("Could not open file %1!").arg(normalized_fname); + qWarning() << "Reason: " << QString(err.what()); return {}; } - - toml_table_t* table = nullptr; - - // NOLINTNEXTLINE(modernize-avoid-c-arrays) - char errbuf[200]; - auto file_bytearray = index_file.readAll(); - table = toml_parse(file_bytearray.data(), errbuf, sizeof(errbuf)); - - index_file.close(); - +#else + table = toml::parse_file(index_dir.absoluteFilePath(real_fname).toStdString()); if (!table) { qWarning() << QString("Could not open file %1!").arg(normalized_fname); - qWarning() << "Reason: " << QString(errbuf); + qWarning() << "Reason: " << QString(table.error().what()); return {}; } +#endif + + // index_file.close(); mod.slug = slug; @@ -261,45 +254,42 @@ auto V1::getIndexForMod(QDir& index_dir, QString slug) -> Mod } { // [download] info - toml_table_t* download_table = toml_table_in(table, "download"); + auto download_table = table["download"].as_table(); if (!download_table) { qCritical() << QString("No [download] section found on mod metadata!"); return {}; } - mod.mode = stringEntry(download_table, "mode"); - mod.url = stringEntry(download_table, "url"); - mod.hash_format = stringEntry(download_table, "hash-format"); - mod.hash = stringEntry(download_table, "hash"); + mod.mode = stringEntry(*download_table, "mode"); + mod.url = stringEntry(*download_table, "url"); + mod.hash_format = stringEntry(*download_table, "hash-format"); + mod.hash = stringEntry(*download_table, "hash"); } - { // [update] info + { // [update] info using Provider = ModPlatform::Provider; - toml_table_t* update_table = toml_table_in(table, "update"); - if (!update_table) { + auto update_table = table["update"]; + if (!update_table || !update_table.is_table()) { qCritical() << QString("No [update] section found on mod metadata!"); return {}; } - toml_table_t* mod_provider_table = nullptr; - if ((mod_provider_table = toml_table_in(update_table, ProviderCaps.name(Provider::FLAME)))) { + toml::table* mod_provider_table = nullptr; + if ((mod_provider_table = update_table[ProviderCaps.name(Provider::FLAME)].as_table())) { mod.provider = Provider::FLAME; - mod.file_id = intEntry(mod_provider_table, "file-id"); - mod.project_id = intEntry(mod_provider_table, "project-id"); - } else if ((mod_provider_table = toml_table_in(update_table, ProviderCaps.name(Provider::MODRINTH)))) { + mod.file_id = intEntry(*mod_provider_table, "file-id"); + mod.project_id = intEntry(*mod_provider_table, "project-id"); + } else if ((mod_provider_table = update_table[ProviderCaps.name(Provider::MODRINTH)].as_table())) { mod.provider = Provider::MODRINTH; - mod.mod_id() = stringEntry(mod_provider_table, "mod-id"); - mod.version() = stringEntry(mod_provider_table, "version"); + mod.mod_id() = stringEntry(*mod_provider_table, "mod-id"); + mod.version() = stringEntry(*mod_provider_table, "version"); } else { qCritical() << QString("No mod provider on mod metadata!"); return {}; } - } - toml_free(table); - return mod; } diff --git a/libraries/README.md b/libraries/README.md index 8e4bd61b..6297cd9b 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -44,17 +44,17 @@ Java launcher part for Minecraft. It: -* Starts a process -* Waits for a launch script on stdin -* Consumes the launch script you feed it -* Proceeds with launch when it gets the `launcher` command +- Starts a process +- Waits for a launch script on stdin +- Consumes the launch script you feed it +- Proceeds with launch when it gets the `launcher` command This means the process is essentially idle until the final command is sent. You can, for example, attach a profiler before you send it. A `legacy` and `onesix` launchers are available. -* `legacy` is intended for use with Minecraft versions < 1.6 and is deprecated. -* `onesix` can handle launching any Minecraft version, at the cost of some extra features `legacy` enables (custom window icon and title). +- `legacy` is intended for use with Minecraft versions < 1.6 and is deprecated. +- `onesix` can handle launching any Minecraft version, at the cost of some extra features `legacy` enables (custom window icon and title). Example (some parts have been censored): @@ -177,11 +177,11 @@ A PolyMC-specific library for probing system information. Apache 2.0 -## tomlc99 +## tomlplusplus A TOML language parser. Used by Forge 1.14+ to store mod metadata. -See [github repo](https://github.com/cktan/tomlc99). +See [github repo](https://github.com/marzer/tomlplusplus). Licenced under the MIT licence. diff --git a/libraries/tomlc99/CMakeLists.txt b/libraries/tomlc99/CMakeLists.txt deleted file mode 100644 index 60786923..00000000 --- a/libraries/tomlc99/CMakeLists.txt +++ /dev/null @@ -1,10 +0,0 @@ -project(tomlc99) - -set(tomlc99_SOURCES -include/toml.h -src/toml.c -) - -add_library(tomlc99 STATIC ${tomlc99_SOURCES}) - -target_include_directories(tomlc99 PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) diff --git a/libraries/tomlc99/LICENSE b/libraries/tomlc99/LICENSE deleted file mode 100644 index a3292b16..00000000 --- a/libraries/tomlc99/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -MIT License - -Copyright (c) 2017 CK Tan -https://github.com/cktan/tomlc99 - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/libraries/tomlc99/README.md b/libraries/tomlc99/README.md deleted file mode 100644 index e5fe9480..00000000 --- a/libraries/tomlc99/README.md +++ /dev/null @@ -1,197 +0,0 @@ -# tomlc99 - -TOML in c99; v1.0 compliant. - -If you are looking for a C++ library, you might try this wrapper: [https://github.com/cktan/tomlcpp](https://github.com/cktan/tomlcpp). - -* Compatible with [TOML v1.0.0](https://toml.io/en/v1.0.0). -* Tested with multiple test suites, including -[BurntSushi/toml-test](https://github.com/BurntSushi/toml-test) and -[iarna/toml-spec-tests](https://github.com/iarna/toml-spec-tests). -* Provides very simple and intuitive interface. - -## Usage - -Please see the `toml.h` file for details. What follows is a simple example that -parses this config file: - -```toml -[server] - host = "www.example.com" - port = [ 8080, 8181, 8282 ] -``` - -The steps for getting values from our file is usually : - -1. Parse the TOML file. -2. Traverse and locate a table in TOML. -3. Extract values from the table. -4. Free up allocated memory. - -Below is an example of parsing the values from the example table. - -```c -#include -#include -#include -#include -#include "toml.h" - -static void error(const char* msg, const char* msg1) -{ - fprintf(stderr, "ERROR: %s%s\n", msg, msg1?msg1:""); - exit(1); -} - - -int main() -{ - FILE* fp; - char errbuf[200]; - - // 1. Read and parse toml file - fp = fopen("sample.toml", "r"); - if (!fp) { - error("cannot open sample.toml - ", strerror(errno)); - } - - toml_table_t* conf = toml_parse_file(fp, errbuf, sizeof(errbuf)); - fclose(fp); - - if (!conf) { - error("cannot parse - ", errbuf); - } - - // 2. Traverse to a table. - toml_table_t* server = toml_table_in(conf, "server"); - if (!server) { - error("missing [server]", ""); - } - - // 3. Extract values - toml_datum_t host = toml_string_in(server, "host"); - if (!host.ok) { - error("cannot read server.host", ""); - } - - toml_array_t* portarray = toml_array_in(server, "port"); - if (!portarray) { - error("cannot read server.port", ""); - } - - printf("host: %s\n", host.u.s); - printf("port: "); - for (int i = 0; ; i++) { - toml_datum_t port = toml_int_at(portarray, i); - if (!port.ok) break; - printf("%d ", (int)port.u.i); - } - printf("\n"); - - // 4. Free memory - free(host.u.s); - toml_free(conf); - return 0; -} -``` - -### Accessing Table Content - -TOML tables are dictionaries where lookups are done using string keys. In -general, all access functions on tables are named `toml_*_in(...)`. - -In the normal case, you know the key and its content type, and retrievals can be done -using one of these functions: - -```c -toml_string_in(tab, key); -toml_bool_in(tab, key); -toml_int_in(tab, key); -toml_double_in(tab, key); -toml_timestamp_in(tab, key); -toml_table_in(tab, key); -toml_array_in(tab, key); -``` - -You can also interrogate the keys in a table using an integer index: - -```c -toml_table_t* tab = toml_parse_file(...); -for (int i = 0; ; i++) { - const char* key = toml_key_in(tab, i); - if (!key) break; - printf("key %d: %s\n", i, key); -} -``` - -### Accessing Array Content - -TOML arrays can be deref-ed using integer indices. In general, all access methods on arrays are named `toml_*_at()`. - -To obtain the size of an array: - -```c -int size = toml_array_nelem(arr); -``` - -To obtain the content of an array, use a valid index and call one of these functions: - -```c -toml_string_at(arr, idx); -toml_bool_at(arr, idx); -toml_int_at(arr, idx); -toml_double_at(arr, idx); -toml_timestamp_at(arr, idx); -toml_table_at(arr, idx); -toml_array_at(arr, idx); -``` - -### toml_datum_t - -Some `toml_*_at` and `toml_*_in` functions return a toml_datum_t -structure. The `ok` flag in the structure indicates if the function -call was successful. If so, you may proceed to read the value -corresponding to the type of the content. - -For example: - -```c -toml_datum_t host = toml_string_in(tab, "host"); -if (host.ok) { - printf("host: %s\n", host.u.s); - free(host.u.s); /* FREE applies to string and timestamp types only */ -} -``` - -**IMPORTANT: if the accessed value is a string or a timestamp, you must call `free(datum.u.s)` or `free(datum.u.ts)` respectively after usage.** - -## Building and installing - -A normal *make* suffices. You can also simply include the -`toml.c` and `toml.h` files in your project. - -Invoking `make install` will install the header and library files into -/usr/local/{include,lib}. - -Alternatively, specify `make install prefix=/a/file/path` to install into -/a/file/path/{include,lib}. - -## Testing - -To test against the standard test set provided by BurntSushi/toml-test: - -```sh -% make -% cd test1 -% bash build.sh # do this once -% bash run.sh # this will run the test suite -``` - -To test against the standard test set provided by iarna/toml: - -```sh -% make -% cd test2 -% bash build.sh # do this once -% bash run.sh # this will run the test suite -``` diff --git a/libraries/tomlc99/include/toml.h b/libraries/tomlc99/include/toml.h deleted file mode 100644 index b91ef890..00000000 --- a/libraries/tomlc99/include/toml.h +++ /dev/null @@ -1,175 +0,0 @@ -/* - MIT License - - Copyright (c) 2017 - 2019 CK Tan - https://github.com/cktan/tomlc99 - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all - copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE. -*/ -#ifndef TOML_H -#define TOML_H - - -#include -#include - - -#ifdef __cplusplus -#define TOML_EXTERN extern "C" -#else -#define TOML_EXTERN extern -#endif - -typedef struct toml_timestamp_t toml_timestamp_t; -typedef struct toml_table_t toml_table_t; -typedef struct toml_array_t toml_array_t; -typedef struct toml_datum_t toml_datum_t; - -/* Parse a file. Return a table on success, or 0 otherwise. - * Caller must toml_free(the-return-value) after use. - */ -TOML_EXTERN toml_table_t* toml_parse_file(FILE* fp, - char* errbuf, - int errbufsz); - -/* Parse a string containing the full config. - * Return a table on success, or 0 otherwise. - * Caller must toml_free(the-return-value) after use. - */ -TOML_EXTERN toml_table_t* toml_parse(char* conf, /* NUL terminated, please. */ - char* errbuf, - int errbufsz); - -/* Free the table returned by toml_parse() or toml_parse_file(). Once - * this function is called, any handles accessed through this tab - * directly or indirectly are no longer valid. - */ -TOML_EXTERN void toml_free(toml_table_t* tab); - - -/* Timestamp types. The year, month, day, hour, minute, second, z - * fields may be NULL if they are not relevant. e.g. In a DATE - * type, the hour, minute, second and z fields will be NULLs. - */ -struct toml_timestamp_t { - struct { /* internal. do not use. */ - int year, month, day; - int hour, minute, second, millisec; - char z[10]; - } __buffer; - int *year, *month, *day; - int *hour, *minute, *second, *millisec; - char* z; -}; - - -/*----------------------------------------------------------------- - * Enhanced access methods - */ -struct toml_datum_t { - int ok; - union { - toml_timestamp_t* ts; /* ts must be freed after use */ - char* s; /* string value. s must be freed after use */ - int b; /* bool value */ - int64_t i; /* int value */ - double d; /* double value */ - } u; -}; - -/* on arrays: */ -/* ... retrieve size of array. */ -TOML_EXTERN int toml_array_nelem(const toml_array_t* arr); -/* ... retrieve values using index. */ -TOML_EXTERN toml_datum_t toml_string_at(const toml_array_t* arr, int idx); -TOML_EXTERN toml_datum_t toml_bool_at(const toml_array_t* arr, int idx); -TOML_EXTERN toml_datum_t toml_int_at(const toml_array_t* arr, int idx); -TOML_EXTERN toml_datum_t toml_double_at(const toml_array_t* arr, int idx); -TOML_EXTERN toml_datum_t toml_timestamp_at(const toml_array_t* arr, int idx); -/* ... retrieve array or table using index. */ -TOML_EXTERN toml_array_t* toml_array_at(const toml_array_t* arr, int idx); -TOML_EXTERN toml_table_t* toml_table_at(const toml_array_t* arr, int idx); - -/* on tables: */ -/* ... retrieve the key in table at keyidx. Return 0 if out of range. */ -TOML_EXTERN const char* toml_key_in(const toml_table_t* tab, int keyidx); -/* ... retrieve values using key. */ -TOML_EXTERN toml_datum_t toml_string_in(const toml_table_t* arr, const char* key); -TOML_EXTERN toml_datum_t toml_bool_in(const toml_table_t* arr, const char* key); -TOML_EXTERN toml_datum_t toml_int_in(const toml_table_t* arr, const char* key); -TOML_EXTERN toml_datum_t toml_double_in(const toml_table_t* arr, const char* key); -TOML_EXTERN toml_datum_t toml_timestamp_in(const toml_table_t* arr, const char* key); -/* .. retrieve array or table using key. */ -TOML_EXTERN toml_array_t* toml_array_in(const toml_table_t* tab, - const char* key); -TOML_EXTERN toml_table_t* toml_table_in(const toml_table_t* tab, - const char* key); - -/*----------------------------------------------------------------- - * lesser used - */ -/* Return the array kind: 't'able, 'a'rray, 'v'alue, 'm'ixed */ -TOML_EXTERN char toml_array_kind(const toml_array_t* arr); - -/* For array kind 'v'alue, return the type of values - i:int, d:double, b:bool, s:string, t:time, D:date, T:timestamp, 'm'ixed - 0 if unknown -*/ -TOML_EXTERN char toml_array_type(const toml_array_t* arr); - -/* Return the key of an array */ -TOML_EXTERN const char* toml_array_key(const toml_array_t* arr); - -/* Return the number of key-values in a table */ -TOML_EXTERN int toml_table_nkval(const toml_table_t* tab); - -/* Return the number of arrays in a table */ -TOML_EXTERN int toml_table_narr(const toml_table_t* tab); - -/* Return the number of sub-tables in a table */ -TOML_EXTERN int toml_table_ntab(const toml_table_t* tab); - -/* Return the key of a table*/ -TOML_EXTERN const char* toml_table_key(const toml_table_t* tab); - -/*-------------------------------------------------------------- - * misc - */ -TOML_EXTERN int toml_utf8_to_ucs(const char* orig, int len, int64_t* ret); -TOML_EXTERN int toml_ucs_to_utf8(int64_t code, char buf[6]); -TOML_EXTERN void toml_set_memutil(void* (*xxmalloc)(size_t), - void (*xxfree)(void*)); - - -/*-------------------------------------------------------------- - * deprecated - */ -/* A raw value, must be processed by toml_rto* before using. */ -typedef const char* toml_raw_t; -TOML_EXTERN toml_raw_t toml_raw_in(const toml_table_t* tab, const char* key); -TOML_EXTERN toml_raw_t toml_raw_at(const toml_array_t* arr, int idx); -TOML_EXTERN int toml_rtos(toml_raw_t s, char** ret); -TOML_EXTERN int toml_rtob(toml_raw_t s, int* ret); -TOML_EXTERN int toml_rtoi(toml_raw_t s, int64_t* ret); -TOML_EXTERN int toml_rtod(toml_raw_t s, double* ret); -TOML_EXTERN int toml_rtod_ex(toml_raw_t s, double* ret, char* buf, int buflen); -TOML_EXTERN int toml_rtots(toml_raw_t s, toml_timestamp_t* ret); - - -#endif /* TOML_H */ diff --git a/libraries/tomlc99/src/toml.c b/libraries/tomlc99/src/toml.c deleted file mode 100644 index e46e62e6..00000000 --- a/libraries/tomlc99/src/toml.c +++ /dev/null @@ -1,2300 +0,0 @@ -/* - - MIT License - - Copyright (c) 2017 - 2021 CK Tan - https://github.com/cktan/tomlc99 - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all - copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE. - -*/ -#define _POSIX_C_SOURCE 200809L -#include -#include -#include -#include -#include -#include -#include -#include -#include "toml.h" - - -static void* (*ppmalloc)(size_t) = malloc; -static void (*ppfree)(void*) = free; - -void toml_set_memutil(void* (*xxmalloc)(size_t), - void (*xxfree)(void*)) -{ - if (xxmalloc) ppmalloc = xxmalloc; - if (xxfree) ppfree = xxfree; -} - - -#define MALLOC(a) ppmalloc(a) -#define FREE(a) ppfree(a) - -static void* CALLOC(size_t nmemb, size_t sz) -{ - int nb = sz * nmemb; - void* p = MALLOC(nb); - if (p) { - memset(p, 0, nb); - } - return p; -} - - -static char* STRDUP(const char* s) -{ - int len = strlen(s); - char* p = MALLOC(len+1); - if (p) { - memcpy(p, s, len); - p[len] = 0; - } - return p; -} - -static char* STRNDUP(const char* s, size_t n) -{ - size_t len = strnlen(s, n); - char* p = MALLOC(len+1); - if (p) { - memcpy(p, s, len); - p[len] = 0; - } - return p; -} - - - -/** - * Convert a char in utf8 into UCS, and store it in *ret. - * Return #bytes consumed or -1 on failure. - */ -int toml_utf8_to_ucs(const char* orig, int len, int64_t* ret) -{ - const unsigned char* buf = (const unsigned char*) orig; - unsigned i = *buf++; - int64_t v; - - /* 0x00000000 - 0x0000007F: - 0xxxxxxx - */ - if (0 == (i >> 7)) { - if (len < 1) return -1; - v = i; - return *ret = v, 1; - } - /* 0x00000080 - 0x000007FF: - 110xxxxx 10xxxxxx - */ - if (0x6 == (i >> 5)) { - if (len < 2) return -1; - v = i & 0x1f; - for (int j = 0; j < 1; j++) { - i = *buf++; - if (0x2 != (i >> 6)) return -1; - v = (v << 6) | (i & 0x3f); - } - return *ret = v, (const char*) buf - orig; - } - - /* 0x00000800 - 0x0000FFFF: - 1110xxxx 10xxxxxx 10xxxxxx - */ - if (0xE == (i >> 4)) { - if (len < 3) return -1; - v = i & 0x0F; - for (int j = 0; j < 2; j++) { - i = *buf++; - if (0x2 != (i >> 6)) return -1; - v = (v << 6) | (i & 0x3f); - } - return *ret = v, (const char*) buf - orig; - } - - /* 0x00010000 - 0x001FFFFF: - 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx - */ - if (0x1E == (i >> 3)) { - if (len < 4) return -1; - v = i & 0x07; - for (int j = 0; j < 3; j++) { - i = *buf++; - if (0x2 != (i >> 6)) return -1; - v = (v << 6) | (i & 0x3f); - } - return *ret = v, (const char*) buf - orig; - } - - /* 0x00200000 - 0x03FFFFFF: - 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx - */ - if (0x3E == (i >> 2)) { - if (len < 5) return -1; - v = i & 0x03; - for (int j = 0; j < 4; j++) { - i = *buf++; - if (0x2 != (i >> 6)) return -1; - v = (v << 6) | (i & 0x3f); - } - return *ret = v, (const char*) buf - orig; - } - - /* 0x04000000 - 0x7FFFFFFF: - 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx - */ - if (0x7e == (i >> 1)) { - if (len < 6) return -1; - v = i & 0x01; - for (int j = 0; j < 5; j++) { - i = *buf++; - if (0x2 != (i >> 6)) return -1; - v = (v << 6) | (i & 0x3f); - } - return *ret = v, (const char*) buf - orig; - } - return -1; -} - - -/** - * Convert a UCS char to utf8 code, and return it in buf. - * Return #bytes used in buf to encode the char, or - * -1 on error. - */ -int toml_ucs_to_utf8(int64_t code, char buf[6]) -{ - /* http://stackoverflow.com/questions/6240055/manually-converting-unicode-codepoints-into-utf-8-and-utf-16 */ - /* The UCS code values 0xd800–0xdfff (UTF-16 surrogates) as well - * as 0xfffe and 0xffff (UCS noncharacters) should not appear in - * conforming UTF-8 streams. - */ - if (0xd800 <= code && code <= 0xdfff) return -1; - if (0xfffe <= code && code <= 0xffff) return -1; - - /* 0x00000000 - 0x0000007F: - 0xxxxxxx - */ - if (code < 0) return -1; - if (code <= 0x7F) { - buf[0] = (unsigned char) code; - return 1; - } - - /* 0x00000080 - 0x000007FF: - 110xxxxx 10xxxxxx - */ - if (code <= 0x000007FF) { - buf[0] = 0xc0 | (code >> 6); - buf[1] = 0x80 | (code & 0x3f); - return 2; - } - - /* 0x00000800 - 0x0000FFFF: - 1110xxxx 10xxxxxx 10xxxxxx - */ - if (code <= 0x0000FFFF) { - buf[0] = 0xe0 | (code >> 12); - buf[1] = 0x80 | ((code >> 6) & 0x3f); - buf[2] = 0x80 | (code & 0x3f); - return 3; - } - - /* 0x00010000 - 0x001FFFFF: - 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx - */ - if (code <= 0x001FFFFF) { - buf[0] = 0xf0 | (code >> 18); - buf[1] = 0x80 | ((code >> 12) & 0x3f); - buf[2] = 0x80 | ((code >> 6) & 0x3f); - buf[3] = 0x80 | (code & 0x3f); - return 4; - } - - /* 0x00200000 - 0x03FFFFFF: - 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx - */ - if (code <= 0x03FFFFFF) { - buf[0] = 0xf8 | (code >> 24); - buf[1] = 0x80 | ((code >> 18) & 0x3f); - buf[2] = 0x80 | ((code >> 12) & 0x3f); - buf[3] = 0x80 | ((code >> 6) & 0x3f); - buf[4] = 0x80 | (code & 0x3f); - return 5; - } - - /* 0x04000000 - 0x7FFFFFFF: - 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx - */ - if (code <= 0x7FFFFFFF) { - buf[0] = 0xfc | (code >> 30); - buf[1] = 0x80 | ((code >> 24) & 0x3f); - buf[2] = 0x80 | ((code >> 18) & 0x3f); - buf[3] = 0x80 | ((code >> 12) & 0x3f); - buf[4] = 0x80 | ((code >> 6) & 0x3f); - buf[5] = 0x80 | (code & 0x3f); - return 6; - } - - return -1; -} - -/* - * TOML has 3 data structures: value, array, table. - * Each of them can have identification key. - */ -typedef struct toml_keyval_t toml_keyval_t; -struct toml_keyval_t { - const char* key; /* key to this value */ - const char* val; /* the raw value */ -}; - -typedef struct toml_arritem_t toml_arritem_t; -struct toml_arritem_t { - int valtype; /* for value kind: 'i'nt, 'd'ouble, 'b'ool, 's'tring, 't'ime, 'D'ate, 'T'imestamp */ - char* val; - toml_array_t* arr; - toml_table_t* tab; -}; - - -struct toml_array_t { - const char* key; /* key to this array */ - int kind; /* element kind: 'v'alue, 'a'rray, or 't'able, 'm'ixed */ - int type; /* for value kind: 'i'nt, 'd'ouble, 'b'ool, 's'tring, 't'ime, 'D'ate, 'T'imestamp, 'm'ixed */ - - int nitem; /* number of elements */ - toml_arritem_t* item; -}; - - -struct toml_table_t { - const char* key; /* key to this table */ - bool implicit; /* table was created implicitly */ - bool readonly; /* no more modification allowed */ - - /* key-values in the table */ - int nkval; - toml_keyval_t** kval; - - /* arrays in the table */ - int narr; - toml_array_t** arr; - - /* tables in the table */ - int ntab; - toml_table_t** tab; -}; - - -static inline void xfree(const void* x) { if (x) FREE((void*)(intptr_t)x); } - - -enum tokentype_t { - INVALID, - DOT, - COMMA, - EQUAL, - LBRACE, - RBRACE, - NEWLINE, - LBRACKET, - RBRACKET, - STRING, -}; -typedef enum tokentype_t tokentype_t; - -typedef struct token_t token_t; -struct token_t { - tokentype_t tok; - int lineno; - char* ptr; /* points into context->start */ - int len; - int eof; -}; - - -typedef struct context_t context_t; -struct context_t { - char* start; - char* stop; - char* errbuf; - int errbufsz; - - token_t tok; - toml_table_t* root; - toml_table_t* curtab; - - struct { - int top; - char* key[10]; - token_t tok[10]; - } tpath; - -}; - -#define STRINGIFY(x) #x -#define TOSTRING(x) STRINGIFY(x) -#define FLINE __FILE__ ":" TOSTRING(__LINE__) - -static int next_token(context_t* ctx, int dotisspecial); - -/* - Error reporting. Call when an error is detected. Always return -1. -*/ -static int e_outofmemory(context_t* ctx, const char* fline) -{ - snprintf(ctx->errbuf, ctx->errbufsz, "ERROR: out of memory (%s)", fline); - return -1; -} - - -static int e_internal(context_t* ctx, const char* fline) -{ - snprintf(ctx->errbuf, ctx->errbufsz, "internal error (%s)", fline); - return -1; -} - -static int e_syntax(context_t* ctx, int lineno, const char* msg) -{ - snprintf(ctx->errbuf, ctx->errbufsz, "line %d: %s", lineno, msg); - return -1; -} - -static int e_badkey(context_t* ctx, int lineno) -{ - snprintf(ctx->errbuf, ctx->errbufsz, "line %d: bad key", lineno); - return -1; -} - -static int e_keyexists(context_t* ctx, int lineno) -{ - snprintf(ctx->errbuf, ctx->errbufsz, "line %d: key exists", lineno); - return -1; -} - -static int e_forbid(context_t* ctx, int lineno, const char* msg) -{ - snprintf(ctx->errbuf, ctx->errbufsz, "line %d: %s", lineno, msg); - return -1; -} - -static void* expand(void* p, int sz, int newsz) -{ - void* s = MALLOC(newsz); - if (!s) return 0; - - memcpy(s, p, sz); - FREE(p); - return s; -} - -static void** expand_ptrarr(void** p, int n) -{ - void** s = MALLOC((n+1) * sizeof(void*)); - if (!s) return 0; - - s[n] = 0; - memcpy(s, p, n * sizeof(void*)); - FREE(p); - return s; -} - -static toml_arritem_t* expand_arritem(toml_arritem_t* p, int n) -{ - toml_arritem_t* pp = expand(p, n*sizeof(*p), (n+1)*sizeof(*p)); - if (!pp) return 0; - - memset(&pp[n], 0, sizeof(pp[n])); - return pp; -} - - -static char* norm_lit_str(const char* src, int srclen, - int multiline, - char* errbuf, int errbufsz) -{ - char* dst = 0; /* will write to dst[] and return it */ - int max = 0; /* max size of dst[] */ - int off = 0; /* cur offset in dst[] */ - const char* sp = src; - const char* sq = src + srclen; - int ch; - - /* scan forward on src */ - for (;;) { - if (off >= max - 10) { /* have some slack for misc stuff */ - int newmax = max + 50; - char* x = expand(dst, max, newmax); - if (!x) { - xfree(dst); - snprintf(errbuf, errbufsz, "out of memory"); - return 0; - } - dst = x; - max = newmax; - } - - /* finished? */ - if (sp >= sq) break; - - ch = *sp++; - /* control characters other than tab is not allowed */ - if ((0 <= ch && ch <= 0x08) - || (0x0a <= ch && ch <= 0x1f) - || (ch == 0x7f)) { - if (! (multiline && (ch == '\r' || ch == '\n'))) { - xfree(dst); - snprintf(errbuf, errbufsz, "invalid char U+%04x", ch); - return 0; - } - } - - // a plain copy suffice - dst[off++] = ch; - } - - dst[off++] = 0; - return dst; -} - - - - -/* - * Convert src to raw unescaped utf-8 string. - * Returns NULL if error with errmsg in errbuf. - */ -static char* norm_basic_str(const char* src, int srclen, - int multiline, - char* errbuf, int errbufsz) -{ - char* dst = 0; /* will write to dst[] and return it */ - int max = 0; /* max size of dst[] */ - int off = 0; /* cur offset in dst[] */ - const char* sp = src; - const char* sq = src + srclen; - int ch; - - /* scan forward on src */ - for (;;) { - if (off >= max - 10) { /* have some slack for misc stuff */ - int newmax = max + 50; - char* x = expand(dst, max, newmax); - if (!x) { - xfree(dst); - snprintf(errbuf, errbufsz, "out of memory"); - return 0; - } - dst = x; - max = newmax; - } - - /* finished? */ - if (sp >= sq) break; - - ch = *sp++; - if (ch != '\\') { - /* these chars must be escaped: U+0000 to U+0008, U+000A to U+001F, U+007F */ - if ((0 <= ch && ch <= 0x08) - || (0x0a <= ch && ch <= 0x1f) - || (ch == 0x7f)) { - if (! (multiline && (ch == '\r' || ch == '\n'))) { - xfree(dst); - snprintf(errbuf, errbufsz, "invalid char U+%04x", ch); - return 0; - } - } - - // a plain copy suffice - dst[off++] = ch; - continue; - } - - /* ch was backslash. we expect the escape char. */ - if (sp >= sq) { - snprintf(errbuf, errbufsz, "last backslash is invalid"); - xfree(dst); - return 0; - } - - /* for multi-line, we want to kill line-ending-backslash ... */ - if (multiline) { - - // if there is only whitespace after the backslash ... - if (sp[strspn(sp, " \t\r")] == '\n') { - /* skip all the following whitespaces */ - sp += strspn(sp, " \t\r\n"); - continue; - } - } - - /* get the escaped char */ - ch = *sp++; - switch (ch) { - case 'u': case 'U': - { - int64_t ucs = 0; - int nhex = (ch == 'u' ? 4 : 8); - for (int i = 0; i < nhex; i++) { - if (sp >= sq) { - snprintf(errbuf, errbufsz, "\\%c expects %d hex chars", ch, nhex); - xfree(dst); - return 0; - } - ch = *sp++; - int v = ('0' <= ch && ch <= '9') - ? ch - '0' - : (('A' <= ch && ch <= 'F') ? ch - 'A' + 10 : -1); - if (-1 == v) { - snprintf(errbuf, errbufsz, "invalid hex chars for \\u or \\U"); - xfree(dst); - return 0; - } - ucs = ucs * 16 + v; - } - int n = toml_ucs_to_utf8(ucs, &dst[off]); - if (-1 == n) { - snprintf(errbuf, errbufsz, "illegal ucs code in \\u or \\U"); - xfree(dst); - return 0; - } - off += n; - } - continue; - - case 'b': ch = '\b'; break; - case 't': ch = '\t'; break; - case 'n': ch = '\n'; break; - case 'f': ch = '\f'; break; - case 'r': ch = '\r'; break; - case '"': ch = '"'; break; - case '\\': ch = '\\'; break; - default: - snprintf(errbuf, errbufsz, "illegal escape char \\%c", ch); - xfree(dst); - return 0; - } - - dst[off++] = ch; - } - - // Cap with NUL and return it. - dst[off++] = 0; - return dst; -} - - -/* Normalize a key. Convert all special chars to raw unescaped utf-8 chars. */ -static char* normalize_key(context_t* ctx, token_t strtok) -{ - const char* sp = strtok.ptr; - const char* sq = strtok.ptr + strtok.len; - int lineno = strtok.lineno; - char* ret; - int ch = *sp; - char ebuf[80]; - - /* handle quoted string */ - if (ch == '\'' || ch == '\"') { - /* if ''' or """, take 3 chars off front and back. Else, take 1 char off. */ - int multiline = 0; - if (sp[1] == ch && sp[2] == ch) { - sp += 3, sq -= 3; - multiline = 1; - } - else - sp++, sq--; - - if (ch == '\'') { - /* for single quote, take it verbatim. */ - if (! (ret = STRNDUP(sp, sq - sp))) { - e_outofmemory(ctx, FLINE); - return 0; - } - } else { - /* for double quote, we need to normalize */ - ret = norm_basic_str(sp, sq - sp, multiline, ebuf, sizeof(ebuf)); - if (!ret) { - e_syntax(ctx, lineno, ebuf); - return 0; - } - } - - /* newlines are not allowed in keys */ - if (strchr(ret, '\n')) { - xfree(ret); - e_badkey(ctx, lineno); - return 0; - } - return ret; - } - - /* for bare-key allow only this regex: [A-Za-z0-9_-]+ */ - const char* xp; - for (xp = sp; xp != sq; xp++) { - int k = *xp; - if (isalnum(k)) continue; - if (k == '_' || k == '-') continue; - e_badkey(ctx, lineno); - return 0; - } - - /* dup and return it */ - if (! (ret = STRNDUP(sp, sq - sp))) { - e_outofmemory(ctx, FLINE); - return 0; - } - return ret; -} - - -/* - * Look up key in tab. Return 0 if not found, or - * 'v'alue, 'a'rray or 't'able depending on the element. - */ -static int check_key(toml_table_t* tab, const char* key, - toml_keyval_t** ret_val, - toml_array_t** ret_arr, - toml_table_t** ret_tab) -{ - int i; - void* dummy; - - if (!ret_tab) ret_tab = (toml_table_t**) &dummy; - if (!ret_arr) ret_arr = (toml_array_t**) &dummy; - if (!ret_val) ret_val = (toml_keyval_t**) &dummy; - - *ret_tab = 0; *ret_arr = 0; *ret_val = 0; - - for (i = 0; i < tab->nkval; i++) { - if (0 == strcmp(key, tab->kval[i]->key)) { - *ret_val = tab->kval[i]; - return 'v'; - } - } - for (i = 0; i < tab->narr; i++) { - if (0 == strcmp(key, tab->arr[i]->key)) { - *ret_arr = tab->arr[i]; - return 'a'; - } - } - for (i = 0; i < tab->ntab; i++) { - if (0 == strcmp(key, tab->tab[i]->key)) { - *ret_tab = tab->tab[i]; - return 't'; - } - } - return 0; -} - - -static int key_kind(toml_table_t* tab, const char* key) -{ - return check_key(tab, key, 0, 0, 0); -} - -/* Create a keyval in the table. - */ -static toml_keyval_t* create_keyval_in_table(context_t* ctx, toml_table_t* tab, token_t keytok) -{ - /* first, normalize the key to be used for lookup. - * remember to free it if we error out. - */ - char* newkey = normalize_key(ctx, keytok); - if (!newkey) return 0; - - /* if key exists: error out. */ - toml_keyval_t* dest = 0; - if (key_kind(tab, newkey)) { - xfree(newkey); - e_keyexists(ctx, keytok.lineno); - return 0; - } - - /* make a new entry */ - int n = tab->nkval; - toml_keyval_t** base; - if (0 == (base = (toml_keyval_t**) expand_ptrarr((void**)tab->kval, n))) { - xfree(newkey); - e_outofmemory(ctx, FLINE); - return 0; - } - tab->kval = base; - - if (0 == (base[n] = (toml_keyval_t*) CALLOC(1, sizeof(*base[n])))) { - xfree(newkey); - e_outofmemory(ctx, FLINE); - return 0; - } - dest = tab->kval[tab->nkval++]; - - /* save the key in the new value struct */ - dest->key = newkey; - return dest; -} - - -/* Create a table in the table. - */ -static toml_table_t* create_keytable_in_table(context_t* ctx, toml_table_t* tab, token_t keytok) -{ - /* first, normalize the key to be used for lookup. - * remember to free it if we error out. - */ - char* newkey = normalize_key(ctx, keytok); - if (!newkey) return 0; - - /* if key exists: error out */ - toml_table_t* dest = 0; - if (check_key(tab, newkey, 0, 0, &dest)) { - xfree(newkey); /* don't need this anymore */ - - /* special case: if table exists, but was created implicitly ... */ - if (dest && dest->implicit) { - /* we make it explicit now, and simply return it. */ - dest->implicit = false; - return dest; - } - e_keyexists(ctx, keytok.lineno); - return 0; - } - - /* create a new table entry */ - int n = tab->ntab; - toml_table_t** base; - if (0 == (base = (toml_table_t**) expand_ptrarr((void**)tab->tab, n))) { - xfree(newkey); - e_outofmemory(ctx, FLINE); - return 0; - } - tab->tab = base; - - if (0 == (base[n] = (toml_table_t*) CALLOC(1, sizeof(*base[n])))) { - xfree(newkey); - e_outofmemory(ctx, FLINE); - return 0; - } - dest = tab->tab[tab->ntab++]; - - /* save the key in the new table struct */ - dest->key = newkey; - return dest; -} - - -/* Create an array in the table. - */ -static toml_array_t* create_keyarray_in_table(context_t* ctx, - toml_table_t* tab, - token_t keytok, - char kind) -{ - /* first, normalize the key to be used for lookup. - * remember to free it if we error out. - */ - char* newkey = normalize_key(ctx, keytok); - if (!newkey) return 0; - - /* if key exists: error out */ - if (key_kind(tab, newkey)) { - xfree(newkey); /* don't need this anymore */ - e_keyexists(ctx, keytok.lineno); - return 0; - } - - /* make a new array entry */ - int n = tab->narr; - toml_array_t** base; - if (0 == (base = (toml_array_t**) expand_ptrarr((void**)tab->arr, n))) { - xfree(newkey); - e_outofmemory(ctx, FLINE); - return 0; - } - tab->arr = base; - - if (0 == (base[n] = (toml_array_t*) CALLOC(1, sizeof(*base[n])))) { - xfree(newkey); - e_outofmemory(ctx, FLINE); - return 0; - } - toml_array_t* dest = tab->arr[tab->narr++]; - - /* save the key in the new array struct */ - dest->key = newkey; - dest->kind = kind; - return dest; -} - - -static toml_arritem_t* create_value_in_array(context_t* ctx, - toml_array_t* parent) -{ - const int n = parent->nitem; - toml_arritem_t* base = expand_arritem(parent->item, n); - if (!base) { - e_outofmemory(ctx, FLINE); - return 0; - } - parent->item = base; - parent->nitem++; - return &parent->item[n]; -} - -/* Create an array in an array - */ -static toml_array_t* create_array_in_array(context_t* ctx, - toml_array_t* parent) -{ - const int n = parent->nitem; - toml_arritem_t* base = expand_arritem(parent->item, n); - if (!base) { - e_outofmemory(ctx, FLINE); - return 0; - } - toml_array_t* ret = (toml_array_t*) CALLOC(1, sizeof(toml_array_t)); - if (!ret) { - e_outofmemory(ctx, FLINE); - return 0; - } - base[n].arr = ret; - parent->item = base; - parent->nitem++; - return ret; -} - -/* Create a table in an array - */ -static toml_table_t* create_table_in_array(context_t* ctx, - toml_array_t* parent) -{ - int n = parent->nitem; - toml_arritem_t* base = expand_arritem(parent->item, n); - if (!base) { - e_outofmemory(ctx, FLINE); - return 0; - } - toml_table_t* ret = (toml_table_t*) CALLOC(1, sizeof(toml_table_t)); - if (!ret) { - e_outofmemory(ctx, FLINE); - return 0; - } - base[n].tab = ret; - parent->item = base; - parent->nitem++; - return ret; -} - - -static int skip_newlines(context_t* ctx, int isdotspecial) -{ - while (ctx->tok.tok == NEWLINE) { - if (next_token(ctx, isdotspecial)) return -1; - if (ctx->tok.eof) break; - } - return 0; -} - - -static int parse_keyval(context_t* ctx, toml_table_t* tab); - -static inline int eat_token(context_t* ctx, tokentype_t typ, int isdotspecial, const char* fline) -{ - if (ctx->tok.tok != typ) - return e_internal(ctx, fline); - - if (next_token(ctx, isdotspecial)) - return -1; - - return 0; -} - - - -/* We are at '{ ... }'. - * Parse the table. - */ -static int parse_inline_table(context_t* ctx, toml_table_t* tab) -{ - if (eat_token(ctx, LBRACE, 1, FLINE)) - return -1; - - for (;;) { - if (ctx->tok.tok == NEWLINE) - return e_syntax(ctx, ctx->tok.lineno, "newline not allowed in inline table"); - - /* until } */ - if (ctx->tok.tok == RBRACE) - break; - - if (ctx->tok.tok != STRING) - return e_syntax(ctx, ctx->tok.lineno, "expect a string"); - - if (parse_keyval(ctx, tab)) - return -1; - - if (ctx->tok.tok == NEWLINE) - return e_syntax(ctx, ctx->tok.lineno, "newline not allowed in inline table"); - - /* on comma, continue to scan for next keyval */ - if (ctx->tok.tok == COMMA) { - if (eat_token(ctx, COMMA, 1, FLINE)) - return -1; - continue; - } - break; - } - - if (eat_token(ctx, RBRACE, 1, FLINE)) - return -1; - - tab->readonly = 1; - - return 0; -} - -static int valtype(const char* val) -{ - toml_timestamp_t ts; - if (*val == '\'' || *val == '"') return 's'; - if (0 == toml_rtob(val, 0)) return 'b'; - if (0 == toml_rtoi(val, 0)) return 'i'; - if (0 == toml_rtod(val, 0)) return 'd'; - if (0 == toml_rtots(val, &ts)) { - if (ts.year && ts.hour) return 'T'; /* timestamp */ - if (ts.year) return 'D'; /* date */ - return 't'; /* time */ - } - return 'u'; /* unknown */ -} - - -/* We are at '[...]' */ -static int parse_array(context_t* ctx, toml_array_t* arr) -{ - if (eat_token(ctx, LBRACKET, 0, FLINE)) return -1; - - for (;;) { - if (skip_newlines(ctx, 0)) return -1; - - /* until ] */ - if (ctx->tok.tok == RBRACKET) break; - - switch (ctx->tok.tok) { - case STRING: - { - /* set array kind if this will be the first entry */ - if (arr->kind == 0) - arr->kind = 'v'; - else if (arr->kind != 'v') - arr->kind = 'm'; - - char* val = ctx->tok.ptr; - int vlen = ctx->tok.len; - - /* make a new value in array */ - toml_arritem_t* newval = create_value_in_array(ctx, arr); - if (!newval) - return e_outofmemory(ctx, FLINE); - - if (! (newval->val = STRNDUP(val, vlen))) - return e_outofmemory(ctx, FLINE); - - newval->valtype = valtype(newval->val); - - /* set array type if this is the first entry */ - if (arr->nitem == 1) - arr->type = newval->valtype; - else if (arr->type != newval->valtype) - arr->type = 'm'; /* mixed */ - - if (eat_token(ctx, STRING, 0, FLINE)) return -1; - break; - } - - case LBRACKET: - { /* [ [array], [array] ... ] */ - /* set the array kind if this will be the first entry */ - if (arr->kind == 0) - arr->kind = 'a'; - else if (arr->kind != 'a') - arr->kind = 'm'; - - toml_array_t* subarr = create_array_in_array(ctx, arr); - if (!subarr) return -1; - if (parse_array(ctx, subarr)) return -1; - break; - } - - case LBRACE: - { /* [ {table}, {table} ... ] */ - /* set the array kind if this will be the first entry */ - if (arr->kind == 0) - arr->kind = 't'; - else if (arr->kind != 't') - arr->kind = 'm'; - - toml_table_t* subtab = create_table_in_array(ctx, arr); - if (!subtab) return -1; - if (parse_inline_table(ctx, subtab)) return -1; - break; - } - - default: - return e_syntax(ctx, ctx->tok.lineno, "syntax error"); - } - - if (skip_newlines(ctx, 0)) return -1; - - /* on comma, continue to scan for next element */ - if (ctx->tok.tok == COMMA) { - if (eat_token(ctx, COMMA, 0, FLINE)) return -1; - continue; - } - break; - } - - if (eat_token(ctx, RBRACKET, 1, FLINE)) return -1; - return 0; -} - - -/* handle lines like these: - key = "value" - key = [ array ] - key = { table } -*/ -static int parse_keyval(context_t* ctx, toml_table_t* tab) -{ - if (tab->readonly) { - return e_forbid(ctx, ctx->tok.lineno, "cannot insert new entry into existing table"); - } - - token_t key = ctx->tok; - if (eat_token(ctx, STRING, 1, FLINE)) return -1; - - if (ctx->tok.tok == DOT) { - /* handle inline dotted key. - e.g. - physical.color = "orange" - physical.shape = "round" - */ - toml_table_t* subtab = 0; - { - char* subtabstr = normalize_key(ctx, key); - if (!subtabstr) return -1; - - subtab = toml_table_in(tab, subtabstr); - xfree(subtabstr); - } - if (!subtab) { - subtab = create_keytable_in_table(ctx, tab, key); - if (!subtab) return -1; - } - if (next_token(ctx, 1)) return -1; - if (parse_keyval(ctx, subtab)) return -1; - return 0; - } - - if (ctx->tok.tok != EQUAL) { - return e_syntax(ctx, ctx->tok.lineno, "missing ="); - } - - if (next_token(ctx, 0)) return -1; - - switch (ctx->tok.tok) { - case STRING: - { /* key = "value" */ - toml_keyval_t* keyval = create_keyval_in_table(ctx, tab, key); - if (!keyval) return -1; - token_t val = ctx->tok; - - assert(keyval->val == 0); - if (! (keyval->val = STRNDUP(val.ptr, val.len))) - return e_outofmemory(ctx, FLINE); - - if (next_token(ctx, 1)) return -1; - - return 0; - } - - case LBRACKET: - { /* key = [ array ] */ - toml_array_t* arr = create_keyarray_in_table(ctx, tab, key, 0); - if (!arr) return -1; - if (parse_array(ctx, arr)) return -1; - return 0; - } - - case LBRACE: - { /* key = { table } */ - toml_table_t* nxttab = create_keytable_in_table(ctx, tab, key); - if (!nxttab) return -1; - if (parse_inline_table(ctx, nxttab)) return -1; - return 0; - } - - default: - return e_syntax(ctx, ctx->tok.lineno, "syntax error"); - } - return 0; -} - - -typedef struct tabpath_t tabpath_t; -struct tabpath_t { - int cnt; - token_t key[10]; -}; - -/* at [x.y.z] or [[x.y.z]] - * Scan forward and fill tabpath until it enters ] or ]] - * There will be at least one entry on return. - */ -static int fill_tabpath(context_t* ctx) -{ - int lineno = ctx->tok.lineno; - int i; - - /* clear tpath */ - for (i = 0; i < ctx->tpath.top; i++) { - char** p = &ctx->tpath.key[i]; - xfree(*p); - *p = 0; - } - ctx->tpath.top = 0; - - for (;;) { - if (ctx->tpath.top >= 10) - return e_syntax(ctx, lineno, "table path is too deep; max allowed is 10."); - - if (ctx->tok.tok != STRING) - return e_syntax(ctx, lineno, "invalid or missing key"); - - char* key = normalize_key(ctx, ctx->tok); - if (!key) return -1; - ctx->tpath.tok[ctx->tpath.top] = ctx->tok; - ctx->tpath.key[ctx->tpath.top] = key; - ctx->tpath.top++; - - if (next_token(ctx, 1)) return -1; - - if (ctx->tok.tok == RBRACKET) break; - - if (ctx->tok.tok != DOT) - return e_syntax(ctx, lineno, "invalid key"); - - if (next_token(ctx, 1)) return -1; - } - - if (ctx->tpath.top <= 0) - return e_syntax(ctx, lineno, "empty table selector"); - - return 0; -} - - -/* Walk tabpath from the root, and create new tables on the way. - * Sets ctx->curtab to the final table. - */ -static int walk_tabpath(context_t* ctx) -{ - /* start from root */ - toml_table_t* curtab = ctx->root; - - for (int i = 0; i < ctx->tpath.top; i++) { - const char* key = ctx->tpath.key[i]; - - toml_keyval_t* nextval = 0; - toml_array_t* nextarr = 0; - toml_table_t* nexttab = 0; - switch (check_key(curtab, key, &nextval, &nextarr, &nexttab)) { - case 't': - /* found a table. nexttab is where we will go next. */ - break; - - case 'a': - /* found an array. nexttab is the last table in the array. */ - if (nextarr->kind != 't') - return e_internal(ctx, FLINE); - - if (nextarr->nitem == 0) - return e_internal(ctx, FLINE); - - nexttab = nextarr->item[nextarr->nitem-1].tab; - break; - - case 'v': - return e_keyexists(ctx, ctx->tpath.tok[i].lineno); - - default: - { /* Not found. Let's create an implicit table. */ - int n = curtab->ntab; - toml_table_t** base = (toml_table_t**) expand_ptrarr((void**)curtab->tab, n); - if (0 == base) - return e_outofmemory(ctx, FLINE); - - curtab->tab = base; - - if (0 == (base[n] = (toml_table_t*) CALLOC(1, sizeof(*base[n])))) - return e_outofmemory(ctx, FLINE); - - if (0 == (base[n]->key = STRDUP(key))) - return e_outofmemory(ctx, FLINE); - - nexttab = curtab->tab[curtab->ntab++]; - - /* tabs created by walk_tabpath are considered implicit */ - nexttab->implicit = true; - } - break; - } - - /* switch to next tab */ - curtab = nexttab; - } - - /* save it */ - ctx->curtab = curtab; - - return 0; -} - - -/* handle lines like [x.y.z] or [[x.y.z]] */ -static int parse_select(context_t* ctx) -{ - assert(ctx->tok.tok == LBRACKET); - - /* true if [[ */ - int llb = (ctx->tok.ptr + 1 < ctx->stop && ctx->tok.ptr[1] == '['); - /* need to detect '[[' on our own because next_token() will skip whitespace, - and '[ [' would be taken as '[[', which is wrong. */ - - /* eat [ or [[ */ - if (eat_token(ctx, LBRACKET, 1, FLINE)) return -1; - if (llb) { - assert(ctx->tok.tok == LBRACKET); - if (eat_token(ctx, LBRACKET, 1, FLINE)) return -1; - } - - if (fill_tabpath(ctx)) return -1; - - /* For [x.y.z] or [[x.y.z]], remove z from tpath. - */ - token_t z = ctx->tpath.tok[ctx->tpath.top-1]; - xfree(ctx->tpath.key[ctx->tpath.top-1]); - ctx->tpath.top--; - - /* set up ctx->curtab */ - if (walk_tabpath(ctx)) return -1; - - if (! llb) { - /* [x.y.z] -> create z = {} in x.y */ - toml_table_t* curtab = create_keytable_in_table(ctx, ctx->curtab, z); - if (!curtab) return -1; - ctx->curtab = curtab; - } else { - /* [[x.y.z]] -> create z = [] in x.y */ - toml_array_t* arr = 0; - { - char* zstr = normalize_key(ctx, z); - if (!zstr) return -1; - arr = toml_array_in(ctx->curtab, zstr); - xfree(zstr); - } - if (!arr) { - arr = create_keyarray_in_table(ctx, ctx->curtab, z, 't'); - if (!arr) return -1; - } - if (arr->kind != 't') - return e_syntax(ctx, z.lineno, "array mismatch"); - - /* add to z[] */ - toml_table_t* dest; - { - toml_table_t* t = create_table_in_array(ctx, arr); - if (!t) return -1; - - if (0 == (t->key = STRDUP("__anon__"))) - return e_outofmemory(ctx, FLINE); - - dest = t; - } - - ctx->curtab = dest; - } - - if (ctx->tok.tok != RBRACKET) { - return e_syntax(ctx, ctx->tok.lineno, "expects ]"); - } - if (llb) { - if (! (ctx->tok.ptr + 1 < ctx->stop && ctx->tok.ptr[1] == ']')) { - return e_syntax(ctx, ctx->tok.lineno, "expects ]]"); - } - if (eat_token(ctx, RBRACKET, 1, FLINE)) return -1; - } - - if (eat_token(ctx, RBRACKET, 1, FLINE)) - return -1; - - if (ctx->tok.tok != NEWLINE) - return e_syntax(ctx, ctx->tok.lineno, "extra chars after ] or ]]"); - - return 0; -} - - - - -toml_table_t* toml_parse(char* conf, - char* errbuf, - int errbufsz) -{ - context_t ctx; - - // clear errbuf - if (errbufsz <= 0) errbufsz = 0; - if (errbufsz > 0) errbuf[0] = 0; - - // init context - memset(&ctx, 0, sizeof(ctx)); - ctx.start = conf; - ctx.stop = ctx.start + strlen(conf); - ctx.errbuf = errbuf; - ctx.errbufsz = errbufsz; - - // start with an artificial newline of length 0 - ctx.tok.tok = NEWLINE; - ctx.tok.lineno = 1; - ctx.tok.ptr = conf; - ctx.tok.len = 0; - - // make a root table - if (0 == (ctx.root = CALLOC(1, sizeof(*ctx.root)))) { - e_outofmemory(&ctx, FLINE); - // Do not goto fail, root table not set up yet - return 0; - } - - // set root as default table - ctx.curtab = ctx.root; - - /* Scan forward until EOF */ - for (token_t tok = ctx.tok; ! tok.eof ; tok = ctx.tok) { - switch (tok.tok) { - - case NEWLINE: - if (next_token(&ctx, 1)) goto fail; - break; - - case STRING: - if (parse_keyval(&ctx, ctx.curtab)) goto fail; - - if (ctx.tok.tok != NEWLINE) { - e_syntax(&ctx, ctx.tok.lineno, "extra chars after value"); - goto fail; - } - - if (eat_token(&ctx, NEWLINE, 1, FLINE)) goto fail; - break; - - case LBRACKET: /* [ x.y.z ] or [[ x.y.z ]] */ - if (parse_select(&ctx)) goto fail; - break; - - default: - e_syntax(&ctx, tok.lineno, "syntax error"); - goto fail; - } - } - - /* success */ - for (int i = 0; i < ctx.tpath.top; i++) xfree(ctx.tpath.key[i]); - return ctx.root; - -fail: - // Something bad has happened. Free resources and return error. - for (int i = 0; i < ctx.tpath.top; i++) xfree(ctx.tpath.key[i]); - toml_free(ctx.root); - return 0; -} - - -toml_table_t* toml_parse_file(FILE* fp, - char* errbuf, - int errbufsz) -{ - int bufsz = 0; - char* buf = 0; - int off = 0; - - /* read from fp into buf */ - while (! feof(fp)) { - - if (off == bufsz) { - int xsz = bufsz + 1000; - char* x = expand(buf, bufsz, xsz); - if (!x) { - snprintf(errbuf, errbufsz, "out of memory"); - xfree(buf); - return 0; - } - buf = x; - bufsz = xsz; - } - - errno = 0; - int n = fread(buf + off, 1, bufsz - off, fp); - if (ferror(fp)) { - snprintf(errbuf, errbufsz, "%s", - errno ? strerror(errno) : "Error reading file"); - xfree(buf); - return 0; - } - off += n; - } - - /* tag on a NUL to cap the string */ - if (off == bufsz) { - int xsz = bufsz + 1; - char* x = expand(buf, bufsz, xsz); - if (!x) { - snprintf(errbuf, errbufsz, "out of memory"); - xfree(buf); - return 0; - } - buf = x; - bufsz = xsz; - } - buf[off] = 0; - - /* parse it, cleanup and finish */ - toml_table_t* ret = toml_parse(buf, errbuf, errbufsz); - xfree(buf); - return ret; -} - - -static void xfree_kval(toml_keyval_t* p) -{ - if (!p) return; - xfree(p->key); - xfree(p->val); - xfree(p); -} - -static void xfree_tab(toml_table_t* p); - -static void xfree_arr(toml_array_t* p) -{ - if (!p) return; - - xfree(p->key); - const int n = p->nitem; - for (int i = 0; i < n; i++) { - toml_arritem_t* a = &p->item[i]; - if (a->val) - xfree(a->val); - else if (a->arr) - xfree_arr(a->arr); - else if (a->tab) - xfree_tab(a->tab); - } - xfree(p->item); - xfree(p); -} - - -static void xfree_tab(toml_table_t* p) -{ - int i; - - if (!p) return; - - xfree(p->key); - - for (i = 0; i < p->nkval; i++) xfree_kval(p->kval[i]); - xfree(p->kval); - - for (i = 0; i < p->narr; i++) xfree_arr(p->arr[i]); - xfree(p->arr); - - for (i = 0; i < p->ntab; i++) xfree_tab(p->tab[i]); - xfree(p->tab); - - xfree(p); -} - - -void toml_free(toml_table_t* tab) -{ - xfree_tab(tab); -} - - -static void set_token(context_t* ctx, tokentype_t tok, int lineno, char* ptr, int len) -{ - token_t t; - t.tok = tok; - t.lineno = lineno; - t.ptr = ptr; - t.len = len; - t.eof = 0; - ctx->tok = t; -} - -static void set_eof(context_t* ctx, int lineno) -{ - set_token(ctx, NEWLINE, lineno, ctx->stop, 0); - ctx->tok.eof = 1; -} - - -/* Scan p for n digits compositing entirely of [0-9] */ -static int scan_digits(const char* p, int n) -{ - int ret = 0; - for ( ; n > 0 && isdigit(*p); n--, p++) { - ret = 10 * ret + (*p - '0'); - } - return n ? -1 : ret; -} - -static int scan_date(const char* p, int* YY, int* MM, int* DD) -{ - int year, month, day; - year = scan_digits(p, 4); - month = (year >= 0 && p[4] == '-') ? scan_digits(p+5, 2) : -1; - day = (month >= 0 && p[7] == '-') ? scan_digits(p+8, 2) : -1; - if (YY) *YY = year; - if (MM) *MM = month; - if (DD) *DD = day; - return (year >= 0 && month >= 0 && day >= 0) ? 0 : -1; -} - -static int scan_time(const char* p, int* hh, int* mm, int* ss) -{ - int hour, minute, second; - hour = scan_digits(p, 2); - minute = (hour >= 0 && p[2] == ':') ? scan_digits(p+3, 2) : -1; - second = (minute >= 0 && p[5] == ':') ? scan_digits(p+6, 2) : -1; - if (hh) *hh = hour; - if (mm) *mm = minute; - if (ss) *ss = second; - return (hour >= 0 && minute >= 0 && second >= 0) ? 0 : -1; -} - - -static int scan_string(context_t* ctx, char* p, int lineno, int dotisspecial) -{ - char* orig = p; - if (0 == strncmp(p, "'''", 3)) { - char* q = p + 3; - - while (1) { - q = strstr(q, "'''"); - if (0 == q) { - return e_syntax(ctx, lineno, "unterminated triple-s-quote"); - } - while (q[3] == '\'') q++; - break; - } - - set_token(ctx, STRING, lineno, orig, q + 3 - orig); - return 0; - } - - if (0 == strncmp(p, "\"\"\"", 3)) { - char* q = p + 3; - - while (1) { - q = strstr(q, "\"\"\""); - if (0 == q) { - return e_syntax(ctx, lineno, "unterminated triple-d-quote"); - } - if (q[-1] == '\\') { - q++; - continue; - } - while (q[3] == '\"') q++; - break; - } - - // the string is [p+3, q-1] - - int hexreq = 0; /* #hex required */ - int escape = 0; - for (p += 3; p < q; p++) { - if (escape) { - escape = 0; - if (strchr("btnfr\"\\", *p)) continue; - if (*p == 'u') { hexreq = 4; continue; } - if (*p == 'U') { hexreq = 8; continue; } - if (p[strspn(p, " \t\r")] == '\n') continue; /* allow for line ending backslash */ - return e_syntax(ctx, lineno, "bad escape char"); - } - if (hexreq) { - hexreq--; - if (strchr("0123456789ABCDEF", *p)) continue; - return e_syntax(ctx, lineno, "expect hex char"); - } - if (*p == '\\') { escape = 1; continue; } - } - if (escape) - return e_syntax(ctx, lineno, "expect an escape char"); - if (hexreq) - return e_syntax(ctx, lineno, "expected more hex char"); - - set_token(ctx, STRING, lineno, orig, q + 3 - orig); - return 0; - } - - if ('\'' == *p) { - for (p++; *p && *p != '\n' && *p != '\''; p++); - if (*p != '\'') { - return e_syntax(ctx, lineno, "unterminated s-quote"); - } - - set_token(ctx, STRING, lineno, orig, p + 1 - orig); - return 0; - } - - if ('\"' == *p) { - int hexreq = 0; /* #hex required */ - int escape = 0; - for (p++; *p; p++) { - if (escape) { - escape = 0; - if (strchr("btnfr\"\\", *p)) continue; - if (*p == 'u') { hexreq = 4; continue; } - if (*p == 'U') { hexreq = 8; continue; } - return e_syntax(ctx, lineno, "bad escape char"); - } - if (hexreq) { - hexreq--; - if (strchr("0123456789ABCDEF", *p)) continue; - return e_syntax(ctx, lineno, "expect hex char"); - } - if (*p == '\\') { escape = 1; continue; } - if (*p == '\'') { - if (p[1] == '\'' && p[2] == '\'') { - return e_syntax(ctx, lineno, "triple-s-quote inside string lit"); - } - continue; - } - if (*p == '\n') break; - if (*p == '"') break; - } - if (*p != '"') { - return e_syntax(ctx, lineno, "unterminated quote"); - } - - set_token(ctx, STRING, lineno, orig, p + 1 - orig); - return 0; - } - - /* check for timestamp without quotes */ - if (0 == scan_date(p, 0, 0, 0) || 0 == scan_time(p, 0, 0, 0)) { - // forward thru the timestamp - for ( ; strchr("0123456789.:+-T Z", toupper(*p)); p++); - // squeeze out any spaces at end of string - for ( ; p[-1] == ' '; p--); - // tokenize - set_token(ctx, STRING, lineno, orig, p - orig); - return 0; - } - - /* literals */ - for ( ; *p && *p != '\n'; p++) { - int ch = *p; - if (ch == '.' && dotisspecial) break; - if ('A' <= ch && ch <= 'Z') continue; - if ('a' <= ch && ch <= 'z') continue; - if (strchr("0123456789+-_.", ch)) continue; - break; - } - - set_token(ctx, STRING, lineno, orig, p - orig); - return 0; -} - - -static int next_token(context_t* ctx, int dotisspecial) -{ - int lineno = ctx->tok.lineno; - char* p = ctx->tok.ptr; - int i; - - /* eat this tok */ - for (i = 0; i < ctx->tok.len; i++) { - if (*p++ == '\n') - lineno++; - } - - /* make next tok */ - while (p < ctx->stop) { - /* skip comment. stop just before the \n. */ - if (*p == '#') { - for (p++; p < ctx->stop && *p != '\n'; p++); - continue; - } - - if (dotisspecial && *p == '.') { - set_token(ctx, DOT, lineno, p, 1); - return 0; - } - - switch (*p) { - case ',': set_token(ctx, COMMA, lineno, p, 1); return 0; - case '=': set_token(ctx, EQUAL, lineno, p, 1); return 0; - case '{': set_token(ctx, LBRACE, lineno, p, 1); return 0; - case '}': set_token(ctx, RBRACE, lineno, p, 1); return 0; - case '[': set_token(ctx, LBRACKET, lineno, p, 1); return 0; - case ']': set_token(ctx, RBRACKET, lineno, p, 1); return 0; - case '\n': set_token(ctx, NEWLINE, lineno, p, 1); return 0; - case '\r': case ' ': case '\t': - /* ignore white spaces */ - p++; - continue; - } - - return scan_string(ctx, p, lineno, dotisspecial); - } - - set_eof(ctx, lineno); - return 0; -} - - -const char* toml_key_in(const toml_table_t* tab, int keyidx) -{ - if (keyidx < tab->nkval) return tab->kval[keyidx]->key; - - keyidx -= tab->nkval; - if (keyidx < tab->narr) return tab->arr[keyidx]->key; - - keyidx -= tab->narr; - if (keyidx < tab->ntab) return tab->tab[keyidx]->key; - - return 0; -} - -toml_raw_t toml_raw_in(const toml_table_t* tab, const char* key) -{ - int i; - for (i = 0; i < tab->nkval; i++) { - if (0 == strcmp(key, tab->kval[i]->key)) - return tab->kval[i]->val; - } - return 0; -} - -toml_array_t* toml_array_in(const toml_table_t* tab, const char* key) -{ - int i; - for (i = 0; i < tab->narr; i++) { - if (0 == strcmp(key, tab->arr[i]->key)) - return tab->arr[i]; - } - return 0; -} - - -toml_table_t* toml_table_in(const toml_table_t* tab, const char* key) -{ - int i; - for (i = 0; i < tab->ntab; i++) { - if (0 == strcmp(key, tab->tab[i]->key)) - return tab->tab[i]; - } - return 0; -} - -toml_raw_t toml_raw_at(const toml_array_t* arr, int idx) -{ - return (0 <= idx && idx < arr->nitem) ? arr->item[idx].val : 0; -} - -char toml_array_kind(const toml_array_t* arr) -{ - return arr->kind; -} - -char toml_array_type(const toml_array_t* arr) -{ - if (arr->kind != 'v') - return 0; - - if (arr->nitem == 0) - return 0; - - return arr->type; -} - - -int toml_array_nelem(const toml_array_t* arr) -{ - return arr->nitem; -} - -const char* toml_array_key(const toml_array_t* arr) -{ - return arr ? arr->key : (const char*) NULL; -} - -int toml_table_nkval(const toml_table_t* tab) -{ - return tab->nkval; -} - -int toml_table_narr(const toml_table_t* tab) -{ - return tab->narr; -} - -int toml_table_ntab(const toml_table_t* tab) -{ - return tab->ntab; -} - -const char* toml_table_key(const toml_table_t* tab) -{ - return tab ? tab->key : (const char*) NULL; -} - -toml_array_t* toml_array_at(const toml_array_t* arr, int idx) -{ - return (0 <= idx && idx < arr->nitem) ? arr->item[idx].arr : 0; -} - -toml_table_t* toml_table_at(const toml_array_t* arr, int idx) -{ - return (0 <= idx && idx < arr->nitem) ? arr->item[idx].tab : 0; -} - - -int toml_rtots(toml_raw_t src_, toml_timestamp_t* ret) -{ - if (! src_) return -1; - - const char* p = src_; - int must_parse_time = 0; - - memset(ret, 0, sizeof(*ret)); - - int* year = &ret->__buffer.year; - int* month = &ret->__buffer.month; - int* day = &ret->__buffer.day; - int* hour = &ret->__buffer.hour; - int* minute = &ret->__buffer.minute; - int* second = &ret->__buffer.second; - int* millisec = &ret->__buffer.millisec; - - /* parse date YYYY-MM-DD */ - if (0 == scan_date(p, year, month, day)) { - ret->year = year; - ret->month = month; - ret->day = day; - - p += 10; - if (*p) { - // parse the T or space separator - if (*p != 'T' && *p != ' ') return -1; - must_parse_time = 1; - p++; - } - } - - /* parse time HH:MM:SS */ - if (0 == scan_time(p, hour, minute, second)) { - ret->hour = hour; - ret->minute = minute; - ret->second = second; - - /* optionally, parse millisec */ - p += 8; - if (*p == '.') { - char* qq; - p++; - errno = 0; - *millisec = strtol(p, &qq, 0); - if (errno) { - return -1; - } - while (*millisec > 999) { - *millisec /= 10; - } - - ret->millisec = millisec; - p = qq; - } - - if (*p) { - /* parse and copy Z */ - char* z = ret->__buffer.z; - ret->z = z; - if (*p == 'Z' || *p == 'z') { - *z++ = 'Z'; p++; - *z = 0; - - } else if (*p == '+' || *p == '-') { - *z++ = *p++; - - if (! (isdigit(p[0]) && isdigit(p[1]))) return -1; - *z++ = *p++; - *z++ = *p++; - - if (*p == ':') { - *z++ = *p++; - - if (! (isdigit(p[0]) && isdigit(p[1]))) return -1; - *z++ = *p++; - *z++ = *p++; - } - - *z = 0; - } - } - } - if (*p != 0) - return -1; - - if (must_parse_time && !ret->hour) - return -1; - - return 0; -} - - -/* Raw to boolean */ -int toml_rtob(toml_raw_t src, int* ret_) -{ - if (!src) return -1; - int dummy; - int* ret = ret_ ? ret_ : &dummy; - - if (0 == strcmp(src, "true")) { - *ret = 1; - return 0; - } - if (0 == strcmp(src, "false")) { - *ret = 0; - return 0; - } - return -1; -} - - -/* Raw to integer */ -int toml_rtoi(toml_raw_t src, int64_t* ret_) -{ - if (!src) return -1; - - char buf[100]; - char* p = buf; - char* q = p + sizeof(buf); - const char* s = src; - int base = 0; - int64_t dummy; - int64_t* ret = ret_ ? ret_ : &dummy; - - - /* allow +/- */ - if (s[0] == '+' || s[0] == '-') - *p++ = *s++; - - /* disallow +_100 */ - if (s[0] == '_') - return -1; - - /* if 0 ... */ - if ('0' == s[0]) { - switch (s[1]) { - case 'x': base = 16; s += 2; break; - case 'o': base = 8; s += 2; break; - case 'b': base = 2; s += 2; break; - case '\0': return *ret = 0, 0; - default: - /* ensure no other digits after it */ - if (s[1]) return -1; - } - } - - /* just strip underscores and pass to strtoll */ - while (*s && p < q) { - int ch = *s++; - switch (ch) { - case '_': - // disallow '__' - if (s[0] == '_') return -1; - continue; /* skip _ */ - default: - break; - } - *p++ = ch; - } - if (*s || p == q) return -1; - - /* last char cannot be '_' */ - if (s[-1] == '_') return -1; - - /* cap with NUL */ - *p = 0; - - /* Run strtoll on buf to get the integer */ - char* endp; - errno = 0; - *ret = strtoll(buf, &endp, base); - return (errno || *endp) ? -1 : 0; -} - - -int toml_rtod_ex(toml_raw_t src, double* ret_, char* buf, int buflen) -{ - if (!src) return -1; - - char* p = buf; - char* q = p + buflen; - const char* s = src; - double dummy; - double* ret = ret_ ? ret_ : &dummy; - - - /* allow +/- */ - if (s[0] == '+' || s[0] == '-') - *p++ = *s++; - - /* disallow +_1.00 */ - if (s[0] == '_') - return -1; - - /* decimal point, if used, must be surrounded by at least one digit on each side */ - { - char* dot = strchr(s, '.'); - if (dot) { - if (dot == s || !isdigit(dot[-1]) || !isdigit(dot[1])) - return -1; - } - } - - /* zero must be followed by . or 'e', or NUL */ - if (s[0] == '0' && s[1] && !strchr("eE.", s[1])) - return -1; - - /* just strip underscores and pass to strtod */ - while (*s && p < q) { - int ch = *s++; - if (ch == '_') { - // disallow '__' - if (s[0] == '_') return -1; - // disallow last char '_' - if (s[0] == 0) return -1; - continue; /* skip _ */ - } - *p++ = ch; - } - if (*s || p == q) return -1; /* reached end of string or buffer is full? */ - - /* cap with NUL */ - *p = 0; - - /* Run strtod on buf to get the value */ - char* endp; - errno = 0; - *ret = strtod(buf, &endp); - return (errno || *endp) ? -1 : 0; -} - -int toml_rtod(toml_raw_t src, double* ret_) -{ - char buf[100]; - return toml_rtod_ex(src, ret_, buf, sizeof(buf)); -} - - - - -int toml_rtos(toml_raw_t src, char** ret) -{ - int multiline = 0; - const char* sp; - const char* sq; - - *ret = 0; - if (!src) return -1; - - int qchar = src[0]; - int srclen = strlen(src); - if (! (qchar == '\'' || qchar == '"')) { - return -1; - } - - // triple quotes? - if (qchar == src[1] && qchar == src[2]) { - multiline = 1; - sp = src + 3; - sq = src + srclen - 3; - /* last 3 chars in src must be qchar */ - if (! (sp <= sq && sq[0] == qchar && sq[1] == qchar && sq[2] == qchar)) - return -1; - - /* skip new line immediate after qchar */ - if (sp[0] == '\n') - sp++; - else if (sp[0] == '\r' && sp[1] == '\n') - sp += 2; - - } else { - sp = src + 1; - sq = src + srclen - 1; - /* last char in src must be qchar */ - if (! (sp <= sq && *sq == qchar)) - return -1; - } - - if (qchar == '\'') { - *ret = norm_lit_str(sp, sq - sp, - multiline, - 0, 0); - } else { - *ret = norm_basic_str(sp, sq - sp, - multiline, - 0, 0); - } - - return *ret ? 0 : -1; -} - - -toml_datum_t toml_string_at(const toml_array_t* arr, int idx) -{ - toml_datum_t ret; - memset(&ret, 0, sizeof(ret)); - ret.ok = (0 == toml_rtos(toml_raw_at(arr, idx), &ret.u.s)); - return ret; -} - -toml_datum_t toml_bool_at(const toml_array_t* arr, int idx) -{ - toml_datum_t ret; - memset(&ret, 0, sizeof(ret)); - ret.ok = (0 == toml_rtob(toml_raw_at(arr, idx), &ret.u.b)); - return ret; -} - -toml_datum_t toml_int_at(const toml_array_t* arr, int idx) -{ - toml_datum_t ret; - memset(&ret, 0, sizeof(ret)); - ret.ok = (0 == toml_rtoi(toml_raw_at(arr, idx), &ret.u.i)); - return ret; -} - -toml_datum_t toml_double_at(const toml_array_t* arr, int idx) -{ - toml_datum_t ret; - memset(&ret, 0, sizeof(ret)); - ret.ok = (0 == toml_rtod(toml_raw_at(arr, idx), &ret.u.d)); - return ret; -} - -toml_datum_t toml_timestamp_at(const toml_array_t* arr, int idx) -{ - toml_timestamp_t ts; - toml_datum_t ret; - memset(&ret, 0, sizeof(ret)); - ret.ok = (0 == toml_rtots(toml_raw_at(arr, idx), &ts)); - if (ret.ok) { - ret.ok = !!(ret.u.ts = malloc(sizeof(*ret.u.ts))); - if (ret.ok) { - *ret.u.ts = ts; - if (ret.u.ts->year) ret.u.ts->year = &ret.u.ts->__buffer.year; - if (ret.u.ts->month) ret.u.ts->month = &ret.u.ts->__buffer.month; - if (ret.u.ts->day) ret.u.ts->day = &ret.u.ts->__buffer.day; - if (ret.u.ts->hour) ret.u.ts->hour = &ret.u.ts->__buffer.hour; - if (ret.u.ts->minute) ret.u.ts->minute = &ret.u.ts->__buffer.minute; - if (ret.u.ts->second) ret.u.ts->second = &ret.u.ts->__buffer.second; - if (ret.u.ts->millisec) ret.u.ts->millisec = &ret.u.ts->__buffer.millisec; - if (ret.u.ts->z) ret.u.ts->z = ret.u.ts->__buffer.z; - } - } - return ret; -} - -toml_datum_t toml_string_in(const toml_table_t* arr, const char* key) -{ - toml_datum_t ret; - memset(&ret, 0, sizeof(ret)); - toml_raw_t raw = toml_raw_in(arr, key); - if (raw) { - ret.ok = (0 == toml_rtos(raw, &ret.u.s)); - } - return ret; -} - -toml_datum_t toml_bool_in(const toml_table_t* arr, const char* key) -{ - toml_datum_t ret; - memset(&ret, 0, sizeof(ret)); - ret.ok = (0 == toml_rtob(toml_raw_in(arr, key), &ret.u.b)); - return ret; -} - -toml_datum_t toml_int_in(const toml_table_t* arr, const char* key) -{ - toml_datum_t ret; - memset(&ret, 0, sizeof(ret)); - ret.ok = (0 == toml_rtoi(toml_raw_in(arr, key), &ret.u.i)); - return ret; -} - -toml_datum_t toml_double_in(const toml_table_t* arr, const char* key) -{ - toml_datum_t ret; - memset(&ret, 0, sizeof(ret)); - ret.ok = (0 == toml_rtod(toml_raw_in(arr, key), &ret.u.d)); - return ret; -} - -toml_datum_t toml_timestamp_in(const toml_table_t* arr, const char* key) -{ - toml_timestamp_t ts; - toml_datum_t ret; - memset(&ret, 0, sizeof(ret)); - ret.ok = (0 == toml_rtots(toml_raw_in(arr, key), &ts)); - if (ret.ok) { - ret.ok = !!(ret.u.ts = malloc(sizeof(*ret.u.ts))); - if (ret.ok) { - *ret.u.ts = ts; - if (ret.u.ts->year) ret.u.ts->year = &ret.u.ts->__buffer.year; - if (ret.u.ts->month) ret.u.ts->month = &ret.u.ts->__buffer.month; - if (ret.u.ts->day) ret.u.ts->day = &ret.u.ts->__buffer.day; - if (ret.u.ts->hour) ret.u.ts->hour = &ret.u.ts->__buffer.hour; - if (ret.u.ts->minute) ret.u.ts->minute = &ret.u.ts->__buffer.minute; - if (ret.u.ts->second) ret.u.ts->second = &ret.u.ts->__buffer.second; - if (ret.u.ts->millisec) ret.u.ts->millisec = &ret.u.ts->__buffer.millisec; - if (ret.u.ts->z) ret.u.ts->z = ret.u.ts->__buffer.z; - } - } - return ret; -} diff --git a/libraries/tomlplusplus b/libraries/tomlplusplus new file mode 160000 index 00000000..fb8ce803 --- /dev/null +++ b/libraries/tomlplusplus @@ -0,0 +1 @@ +Subproject commit fb8ce80350bcde1d109e9b4d7a571bbc2f29a8bd From a1800ec23f016054b4fd346a86e2fcf8df448bb8 Mon Sep 17 00:00:00 2001 From: Trial97 Date: Sun, 25 Sep 2022 00:20:01 +0300 Subject: [PATCH 013/101] Prefer the system tomlplusplus Signed-off-by: Trial97 --- CMakeLists.txt | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 364e16d6..109db157 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -312,7 +312,15 @@ endif() add_subdirectory(libraries/rainbow) # Qt extension for colors add_subdirectory(libraries/LocalPeer) # fork of a library from Qt solutions add_subdirectory(libraries/classparser) # class parser library -add_subdirectory(libraries/tomlplusplus) # toml parser +if(NOT Launcher_FORCE_BUNDLED_LIBS) + find_package(tomlplusplus 3.2.0 QUIET) +endif() +if(NOT tomlplusplus_FOUND) + message(STATUS "Using bundled tomlplusplus") + add_subdirectory(libraries/tomlplusplus) # toml parser +else() + message(STATUS "Using system tomlplusplus") +endif() add_subdirectory(libraries/katabasis) # An OAuth2 library that tried to do too much add_subdirectory(libraries/gamemode) add_subdirectory(libraries/murmur2) # Hash for usage with the CurseForge API From ed261f0af98b67f1da4f6247c4b422000575bb45 Mon Sep 17 00:00:00 2001 From: Alexandru Ionut Tripon Date: Sun, 25 Sep 2022 20:38:55 +0300 Subject: [PATCH 014/101] Update launcher/minecraft/mod/tasks/LocalModParseTask.cpp Co-authored-by: flow Signed-off-by: Alexandru Ionut Tripon --- launcher/minecraft/mod/tasks/LocalModParseTask.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/launcher/minecraft/mod/tasks/LocalModParseTask.cpp b/launcher/minecraft/mod/tasks/LocalModParseTask.cpp index ae8e95ff..a694e7b2 100644 --- a/launcher/minecraft/mod/tasks/LocalModParseTask.cpp +++ b/launcher/minecraft/mod/tasks/LocalModParseTask.cpp @@ -93,7 +93,6 @@ ModDetails ReadMCModTOML(QByteArray contents) { ModDetails details; - // auto tomlData = toml::parse(contents.toStdString()); toml::table tomlData; #if TOML_EXCEPTIONS try { From 1cdadafdf8b59988fb8d89a29d0698620e09dfb5 Mon Sep 17 00:00:00 2001 From: Sefa Eyeoglu Date: Mon, 26 Sep 2022 12:30:49 +0200 Subject: [PATCH 015/101] refactor: use QCommandLineParser instead Signed-off-by: Sefa Eyeoglu --- launcher/Application.cpp | 95 ++------- launcher/Commandline.cpp | 408 --------------------------------------- launcher/Commandline.h | 213 -------------------- 3 files changed, 20 insertions(+), 696 deletions(-) diff --git a/launcher/Application.cpp b/launcher/Application.cpp index 0d1db11c..7ac36e71 100644 --- a/launcher/Application.cpp +++ b/launcher/Application.cpp @@ -78,6 +78,7 @@ #include #include +#include #include #include #include @@ -110,7 +111,6 @@ #include "translations/TranslationsModel.h" #include "meta/Index.h" -#include #include #include #include @@ -136,8 +136,6 @@ static const QLatin1String liveCheckFile("live.check"); -using namespace Commandline; - #define MACOS_HINT "If you are on macOS Sierra, you might have to move the app to your /Applications or ~/Applications folder. "\ "This usually fixes the problem and you can move the application elsewhere afterwards.\n"\ "\n" @@ -242,80 +240,27 @@ Application::Application(int &argc, char **argv) : QApplication(argc, argv) this->setQuitOnLastWindowClosed(false); // Commandline parsing - QHash args; - { - Parser parser(FlagStyle::GNU, ArgumentStyle::SpaceAndEquals); + QCommandLineParser parser; + parser.setApplicationDescription(BuildConfig.LAUNCHER_NAME); - // --help - parser.addSwitch("help"); - parser.addShortOpt("help", 'h'); - parser.addDocumentation("help", "Display this help and exit."); - // --version - parser.addSwitch("version"); - parser.addShortOpt("version", 'V'); - parser.addDocumentation("version", "Display program version and exit."); - // --dir - parser.addOption("dir"); - parser.addShortOpt("dir", 'd'); - parser.addDocumentation("dir", "Use the supplied folder as application root instead of the binary location (use '.' for current)"); - // --launch - parser.addOption("launch"); - parser.addShortOpt("launch", 'l'); - parser.addDocumentation("launch", "Launch the specified instance (by instance ID)"); - // --server - parser.addOption("server"); - parser.addShortOpt("server", 's'); - parser.addDocumentation("server", "Join the specified server on launch (only valid in combination with --launch)"); - // --profile - parser.addOption("profile"); - parser.addShortOpt("profile", 'a'); - parser.addDocumentation("profile", "Use the account specified by its profile name (only valid in combination with --launch)"); - // --alive - parser.addSwitch("alive"); - parser.addDocumentation("alive", "Write a small '" + liveCheckFile + "' file after the launcher starts"); - // --import - parser.addOption("import"); - parser.addShortOpt("import", 'I'); - parser.addDocumentation("import", "Import instance from specified zip (local path or URL)"); + parser.addOptions({ + {{"d", "dir"}, "Use a custom path as application root (use '.' for current directory)", "directory"}, + {{"l", "launch"}, "Launch the specified instance (by instance ID)", "instance"}, + {{"s", "server"}, "Join the specified server on launch (only valid in combination with --launch)", "address"}, + {{"a", "profile"}, "Use the account specified by its profile name (only valid in combination with --launch)", "profile"}, + {"alive", "Write a small '" + liveCheckFile + "' file after the launcher starts"}, + {{"I", "import"}, "Import instance from specified zip (local path or URL)", "file"} + }); + parser.addHelpOption(); + parser.addVersionOption(); - // parse the arguments - try - { - args = parser.parse(arguments()); - } - catch (const ParsingError &e) - { - std::cerr << "CommandLineError: " << e.what() << std::endl; - if(argc > 0) - std::cerr << "Try '" << argv[0] << " -h' to get help on command line parameters." - << std::endl; - m_status = Application::Failed; - return; - } + parser.process(arguments()); - // display help and exit - if (args["help"].toBool()) - { - std::cout << qPrintable(parser.compileHelp(arguments()[0])); - m_status = Application::Succeeded; - return; - } - - // display version and exit - if (args["version"].toBool()) - { - std::cout << "Version " << BuildConfig.printableVersionString().toStdString() << std::endl; - std::cout << "Git " << BuildConfig.GIT_COMMIT.toStdString() << std::endl; - m_status = Application::Succeeded; - return; - } - } - - m_instanceIdToLaunch = args["launch"].toString(); - m_serverToJoin = args["server"].toString(); - m_profileToUse = args["profile"].toString(); - m_liveCheck = args["alive"].toBool(); - m_zipToImport = args["import"].toUrl(); + m_instanceIdToLaunch = parser.value("launch"); + m_serverToJoin = parser.value("server"); + m_profileToUse = parser.value("profile"); + m_liveCheck = parser.isSet("alive"); + m_zipToImport = parser.value("import"); // error if --launch is missing with --server or --profile if((!m_serverToJoin.isEmpty() || !m_profileToUse.isEmpty()) && m_instanceIdToLaunch.isEmpty()) @@ -346,7 +291,7 @@ Application::Application(int &argc, char **argv) : QApplication(argc, argv) QString adjustedBy; QString dataPath; // change folder - QString dirParam = args["dir"].toString(); + QString dirParam = parser.value("dir"); if (!dirParam.isEmpty()) { // the dir param. it makes multimc data path point to whatever the user specified diff --git a/launcher/Commandline.cpp b/launcher/Commandline.cpp index 8e7356bb..6d97918d 100644 --- a/launcher/Commandline.cpp +++ b/launcher/Commandline.cpp @@ -92,412 +92,4 @@ QStringList splitArgs(QString args) argv << current; return argv; } - -Parser::Parser(FlagStyle::Enum flagStyle, ArgumentStyle::Enum argStyle) -{ - m_flagStyle = flagStyle; - m_argStyle = argStyle; -} - -// styles setter/getter -void Parser::setArgumentStyle(ArgumentStyle::Enum style) -{ - m_argStyle = style; -} -ArgumentStyle::Enum Parser::argumentStyle() -{ - return m_argStyle; -} - -void Parser::setFlagStyle(FlagStyle::Enum style) -{ - m_flagStyle = style; -} -FlagStyle::Enum Parser::flagStyle() -{ - return m_flagStyle; -} - -// setup methods -void Parser::addSwitch(QString name, bool def) -{ - if (m_params.contains(name)) - throw "Name not unique"; - - OptionDef *param = new OptionDef; - param->type = otSwitch; - param->name = name; - param->metavar = QString("<%1>").arg(name); - param->def = def; - - m_options[name] = param; - m_params[name] = (CommonDef *)param; - m_optionList.append(param); -} - -void Parser::addOption(QString name, QVariant def) -{ - if (m_params.contains(name)) - throw "Name not unique"; - - OptionDef *param = new OptionDef; - param->type = otOption; - param->name = name; - param->metavar = QString("<%1>").arg(name); - param->def = def; - - m_options[name] = param; - m_params[name] = (CommonDef *)param; - m_optionList.append(param); -} - -void Parser::addArgument(QString name, bool required, QVariant def) -{ - if (m_params.contains(name)) - throw "Name not unique"; - - PositionalDef *param = new PositionalDef; - param->name = name; - param->def = def; - param->required = required; - param->metavar = name; - - m_positionals.append(param); - m_params[name] = (CommonDef *)param; -} - -void Parser::addDocumentation(QString name, QString doc, QString metavar) -{ - if (!m_params.contains(name)) - throw "Name does not exist"; - - CommonDef *param = m_params[name]; - param->doc = doc; - if (!metavar.isNull()) - param->metavar = metavar; -} - -void Parser::addShortOpt(QString name, QChar flag) -{ - if (!m_params.contains(name)) - throw "Name does not exist"; - if (!m_options.contains(name)) - throw "Name is not an Option or Swtich"; - - OptionDef *param = m_options[name]; - m_flags[flag] = param; - param->flag = flag; -} - -// help methods -QString Parser::compileHelp(QString progName, int helpIndent, bool useFlags) -{ - QStringList help; - help << compileUsage(progName, useFlags) << "\r\n"; - - // positionals - if (!m_positionals.isEmpty()) - { - help << "\r\n"; - help << "Positional arguments:\r\n"; - QListIterator it2(m_positionals); - while (it2.hasNext()) - { - PositionalDef *param = it2.next(); - help << " " << param->metavar; - help << " " << QString(helpIndent - param->metavar.length() - 1, ' '); - help << param->doc << "\r\n"; - } - } - - // Options - if (!m_optionList.isEmpty()) - { - help << "\r\n"; - QString optPrefix, flagPrefix; - getPrefix(optPrefix, flagPrefix); - - help << "Options & Switches:\r\n"; - QListIterator it(m_optionList); - while (it.hasNext()) - { - OptionDef *option = it.next(); - help << " "; - int nameLength = optPrefix.length() + option->name.length(); - if (!option->flag.isNull()) - { - nameLength += 3 + flagPrefix.length(); - help << flagPrefix << option->flag << ", "; - } - help << optPrefix << option->name; - if (option->type == otOption) - { - QString arg = QString("%1%2").arg( - ((m_argStyle == ArgumentStyle::Equals) ? "=" : " "), option->metavar); - nameLength += arg.length(); - help << arg; - } - help << " " << QString(helpIndent - nameLength - 1, ' '); - help << option->doc << "\r\n"; - } - } - - return help.join(""); -} - -QString Parser::compileUsage(QString progName, bool useFlags) -{ - QStringList usage; - usage << "Usage: " << progName; - - QString optPrefix, flagPrefix; - getPrefix(optPrefix, flagPrefix); - - // options - QListIterator it(m_optionList); - while (it.hasNext()) - { - OptionDef *option = it.next(); - usage << " ["; - if (!option->flag.isNull() && useFlags) - usage << flagPrefix << option->flag; - else - usage << optPrefix << option->name; - if (option->type == otOption) - usage << ((m_argStyle == ArgumentStyle::Equals) ? "=" : " ") << option->metavar; - usage << "]"; - } - - // arguments - QListIterator it2(m_positionals); - while (it2.hasNext()) - { - PositionalDef *param = it2.next(); - usage << " " << (param->required ? "<" : "["); - usage << param->metavar; - usage << (param->required ? ">" : "]"); - } - - return usage.join(""); -} - -// parsing -QHash Parser::parse(QStringList argv) -{ - QHash map; - - QStringListIterator it(argv); - QString programName = it.next(); - - QString optionPrefix; - QString flagPrefix; - QListIterator positionals(m_positionals); - QStringList expecting; - - getPrefix(optionPrefix, flagPrefix); - - while (it.hasNext()) - { - QString arg = it.next(); - - if (!expecting.isEmpty()) - // we were expecting an argument - { - QString name = expecting.first(); -/* - if (map.contains(name)) - throw ParsingError( - QString("Option %2%1 was given multiple times").arg(name, optionPrefix)); -*/ - map[name] = QVariant(arg); - - expecting.removeFirst(); - continue; - } - - if (arg.startsWith(optionPrefix)) - // we have an option - { - // qDebug("Found option %s", qPrintable(arg)); - - QString name = arg.mid(optionPrefix.length()); - QString equals; - - if ((m_argStyle == ArgumentStyle::Equals || - m_argStyle == ArgumentStyle::SpaceAndEquals) && - name.contains("=")) - { - int i = name.indexOf("="); - equals = name.mid(i + 1); - name = name.left(i); - } - - if (m_options.contains(name)) - { - /* - if (map.contains(name)) - throw ParsingError(QString("Option %2%1 was given multiple times") - .arg(name, optionPrefix)); -*/ - OptionDef *option = m_options[name]; - if (option->type == otSwitch) - map[name] = true; - else // if (option->type == otOption) - { - if (m_argStyle == ArgumentStyle::Space) - expecting.append(name); - else if (!equals.isNull()) - map[name] = equals; - else if (m_argStyle == ArgumentStyle::SpaceAndEquals) - expecting.append(name); - else - throw ParsingError(QString("Option %2%1 reqires an argument.") - .arg(name, optionPrefix)); - } - - continue; - } - - throw ParsingError(QString("Unknown Option %2%1").arg(name, optionPrefix)); - } - - if (arg.startsWith(flagPrefix)) - // we have (a) flag(s) - { - // qDebug("Found flags %s", qPrintable(arg)); - - QString flags = arg.mid(flagPrefix.length()); - QString equals; - - if ((m_argStyle == ArgumentStyle::Equals || - m_argStyle == ArgumentStyle::SpaceAndEquals) && - flags.contains("=")) - { - int i = flags.indexOf("="); - equals = flags.mid(i + 1); - flags = flags.left(i); - } - - for (int i = 0; i < flags.length(); i++) - { - QChar flag = flags.at(i); - - if (!m_flags.contains(flag)) - throw ParsingError(QString("Unknown flag %2%1").arg(flag, flagPrefix)); - - OptionDef *option = m_flags[flag]; -/* - if (map.contains(option->name)) - throw ParsingError(QString("Option %2%1 was given multiple times") - .arg(option->name, optionPrefix)); -*/ - if (option->type == otSwitch) - map[option->name] = true; - else // if (option->type == otOption) - { - if (m_argStyle == ArgumentStyle::Space) - expecting.append(option->name); - else if (!equals.isNull()) - if (i == flags.length() - 1) - map[option->name] = equals; - else - throw ParsingError(QString("Flag %4%2 of Argument-requiring Option " - "%1 not last flag in %4%3") - .arg(option->name, flag, flags, flagPrefix)); - else if (m_argStyle == ArgumentStyle::SpaceAndEquals) - expecting.append(option->name); - else - throw ParsingError(QString("Option %1 reqires an argument. (flag %3%2)") - .arg(option->name, flag, flagPrefix)); - } - } - - continue; - } - - // must be a positional argument - if (!positionals.hasNext()) - throw ParsingError(QString("Don't know what to do with '%1'").arg(arg)); - - PositionalDef *param = positionals.next(); - - map[param->name] = arg; - } - - // check if we're missing something - if (!expecting.isEmpty()) - throw ParsingError(QString("Was still expecting arguments for %2%1").arg( - expecting.join(QString(", ") + optionPrefix), optionPrefix)); - - while (positionals.hasNext()) - { - PositionalDef *param = positionals.next(); - if (param->required) - throw ParsingError( - QString("Missing required positional argument '%1'").arg(param->name)); - else - map[param->name] = param->def; - } - - // fill out gaps - QListIterator iter(m_optionList); - while (iter.hasNext()) - { - OptionDef *option = iter.next(); - if (!map.contains(option->name)) - map[option->name] = option->def; - } - - return map; -} - -// clear defs -void Parser::clear() -{ - m_flags.clear(); - m_params.clear(); - m_options.clear(); - - QMutableListIterator it(m_optionList); - while (it.hasNext()) - { - OptionDef *option = it.next(); - it.remove(); - delete option; - } - - QMutableListIterator it2(m_positionals); - while (it2.hasNext()) - { - PositionalDef *arg = it2.next(); - it2.remove(); - delete arg; - } -} - -// Destructor -Parser::~Parser() -{ - clear(); -} - -// getPrefix -void Parser::getPrefix(QString &opt, QString &flag) -{ - if (m_flagStyle == FlagStyle::Windows) - opt = flag = "/"; - else if (m_flagStyle == FlagStyle::Unix) - opt = flag = "-"; - // else if (m_flagStyle == FlagStyle::GNU) - else - { - opt = "--"; - flag = "-"; - } -} - -// ParsingError -ParsingError::ParsingError(const QString &what) : std::runtime_error(what.toStdString()) -{ -} } diff --git a/launcher/Commandline.h b/launcher/Commandline.h index a4e7aa61..8bd79180 100644 --- a/launcher/Commandline.h +++ b/launcher/Commandline.h @@ -17,12 +17,7 @@ #pragma once -#include -#include - #include -#include -#include #include /** @@ -39,212 +34,4 @@ namespace Commandline * @return a QStringList containing all arguments */ QStringList splitArgs(QString args); - -/** - * @brief The FlagStyle enum - * Specifies how flags are decorated - */ - -namespace FlagStyle -{ -enum Enum -{ - GNU, /**< --option and -o (GNU Style) */ - Unix, /**< -option and -o (Unix Style) */ - Windows, /**< /option and /o (Windows Style) */ -#ifdef Q_OS_WIN32 - Default = Windows -#else - Default = GNU -#endif -}; -} - -/** - * @brief The ArgumentStyle enum - */ -namespace ArgumentStyle -{ -enum Enum -{ - Space, /**< --option value */ - Equals, /**< --option=value */ - SpaceAndEquals, /**< --option[= ]value */ -#ifdef Q_OS_WIN32 - Default = Equals -#else - Default = SpaceAndEquals -#endif -}; -} - -/** - * @brief The ParsingError class - */ -class ParsingError : public std::runtime_error -{ -public: - ParsingError(const QString &what); -}; - -/** - * @brief The Parser class - */ -class Parser -{ -public: - /** - * @brief Parser constructor - * @param flagStyle the FlagStyle to use in this Parser - * @param argStyle the ArgumentStyle to use in this Parser - */ - Parser(FlagStyle::Enum flagStyle = FlagStyle::Default, - ArgumentStyle::Enum argStyle = ArgumentStyle::Default); - - /** - * @brief set the flag style - * @param style - */ - void setFlagStyle(FlagStyle::Enum style); - - /** - * @brief get the flag style - * @return - */ - FlagStyle::Enum flagStyle(); - - /** - * @brief set the argument style - * @param style - */ - void setArgumentStyle(ArgumentStyle::Enum style); - - /** - * @brief get the argument style - * @return - */ - ArgumentStyle::Enum argumentStyle(); - - /** - * @brief define a boolean switch - * @param name the parameter name - * @param def the default value - */ - void addSwitch(QString name, bool def = false); - - /** - * @brief define an option that takes an additional argument - * @param name the parameter name - * @param def the default value - */ - void addOption(QString name, QVariant def = QVariant()); - - /** - * @brief define a positional argument - * @param name the parameter name - * @param required wether this argument is required - * @param def the default value - */ - void addArgument(QString name, bool required = true, QVariant def = QVariant()); - - /** - * @brief adds a flag to an existing parameter - * @param name the (existing) parameter name - * @param flag the flag character - * @see addSwitch addArgument addOption - * Note: any one parameter can only have one flag - */ - void addShortOpt(QString name, QChar flag); - - /** - * @brief adds documentation to a Parameter - * @param name the parameter name - * @param metavar a string to be displayed as placeholder for the value - * @param doc a QString containing the documentation - * Note: on positional arguments, metavar replaces the name as displayed. - * on options , metavar replaces the value placeholder - */ - void addDocumentation(QString name, QString doc, QString metavar = QString()); - - /** - * @brief generate a help message - * @param progName the program name to use in the help message - * @param helpIndent how much the parameter documentation should be indented - * @param flagsInUsage whether we should use flags instead of options in the usage - * @return a help message - */ - QString compileHelp(QString progName, int helpIndent = 22, bool flagsInUsage = true); - - /** - * @brief generate a short usage message - * @param progName the program name to use in the usage message - * @param useFlags whether we should use flags instead of options - * @return a usage message - */ - QString compileUsage(QString progName, bool useFlags = true); - - /** - * @brief parse - * @param argv a QStringList containing the program ARGV - * @return a QHash mapping argument names to their values - */ - QHash parse(QStringList argv); - - /** - * @brief clear all definitions - */ - void clear(); - - ~Parser(); - -private: - FlagStyle::Enum m_flagStyle; - ArgumentStyle::Enum m_argStyle; - - enum OptionType - { - otSwitch, - otOption - }; - - // Important: the common part MUST BE COMMON ON ALL THREE structs - struct CommonDef - { - QString name; - QString doc; - QString metavar; - QVariant def; - }; - - struct OptionDef - { - // common - QString name; - QString doc; - QString metavar; - QVariant def; - // option - OptionType type; - QChar flag; - }; - - struct PositionalDef - { - // common - QString name; - QString doc; - QString metavar; - QVariant def; - // positional - bool required; - }; - - QHash m_options; - QHash m_flags; - QHash m_params; - QList m_positionals; - QList m_optionList; - - void getPrefix(QString &opt, QString &flag); -}; } From 11c44c676c12cee5cf2e76303af2c8a791a44b77 Mon Sep 17 00:00:00 2001 From: Sefa Eyeoglu Date: Mon, 26 Sep 2022 13:27:42 +0200 Subject: [PATCH 016/101] fix: remove unused MACOS_HINT Signed-off-by: Sefa Eyeoglu --- launcher/Application.cpp | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/launcher/Application.cpp b/launcher/Application.cpp index 7ac36e71..e08ea7f4 100644 --- a/launcher/Application.cpp +++ b/launcher/Application.cpp @@ -136,10 +136,6 @@ static const QLatin1String liveCheckFile("live.check"); -#define MACOS_HINT "If you are on macOS Sierra, you might have to move the app to your /Applications or ~/Applications folder. "\ - "This usually fixes the problem and you can move the application elsewhere afterwards.\n"\ - "\n" - namespace { void appDebugOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg) { @@ -330,9 +326,6 @@ Application::Application(int &argc, char **argv) : QApplication(argc, argv) QString( "The launcher data folder could not be created.\n" "\n" -#if defined(Q_OS_MAC) - MACOS_HINT -#endif "Make sure you have the right permissions to the launcher data folder and any folder needed to access it.\n" "(%1)\n" "\n" @@ -348,9 +341,6 @@ Application::Application(int &argc, char **argv) : QApplication(argc, argv) QString( "The launcher data folder could not be opened.\n" "\n" -#if defined(Q_OS_MAC) - MACOS_HINT -#endif "Make sure you have the right permissions to the launcher data folder.\n" "(%1)\n" "\n" @@ -431,9 +421,6 @@ Application::Application(int &argc, char **argv) : QApplication(argc, argv) QString( "The launcher couldn't create a log file - the data folder is not writable.\n" "\n" - #if defined(Q_OS_MAC) - MACOS_HINT - #endif "Make sure you have write permissions to the data folder.\n" "(%1)\n" "\n" From aad4f8d1f7ff5f777253d3cc114fd55f8333370f Mon Sep 17 00:00:00 2001 From: Sefa Eyeoglu Date: Mon, 26 Sep 2022 13:38:45 +0200 Subject: [PATCH 017/101] fix: update Git modules Signed-off-by: Sefa Eyeoglu --- .gitmodules | 3 --- 1 file changed, 3 deletions(-) diff --git a/.gitmodules b/.gitmodules index b29a0477..534ffd37 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,12 +1,9 @@ [submodule "depends/libnbtplusplus"] path = libraries/libnbtplusplus url = https://github.com/PolyMC/libnbtplusplus.git - pushurl = git@github.com:PolyMC/libnbtplusplus.git - [submodule "libraries/quazip"] path = libraries/quazip url = https://github.com/stachenov/quazip.git [submodule "libraries/tomlplusplus"] path = libraries/tomlplusplus url = https://github.com/marzer/tomlplusplus.git - shallow = true From 62841c5b238b86f5a01eac5c156f15d51e886597 Mon Sep 17 00:00:00 2001 From: Sefa Eyeoglu Date: Mon, 26 Sep 2022 13:40:31 +0200 Subject: [PATCH 018/101] fix: pin tomlplusplus to latest release Signed-off-by: Sefa Eyeoglu --- libraries/tomlplusplus | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/tomlplusplus b/libraries/tomlplusplus index fb8ce803..4b166b69 160000 --- a/libraries/tomlplusplus +++ b/libraries/tomlplusplus @@ -1 +1 @@ -Subproject commit fb8ce80350bcde1d109e9b4d7a571bbc2f29a8bd +Subproject commit 4b166b69f28e70a416a1a04a98f365d2aeb90de8 From 7c6bb80cee123d7bdd140d2892a3f473f972ebc8 Mon Sep 17 00:00:00 2001 From: Sefa Eyeoglu Date: Mon, 26 Sep 2022 13:43:26 +0200 Subject: [PATCH 019/101] fix: move toml++ find call Signed-off-by: Sefa Eyeoglu --- CMakeLists.txt | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 109db157..46192414 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -192,6 +192,11 @@ if (Qt5_POSITION_INDEPENDENT_CODE) SET(CMAKE_POSITION_INDEPENDENT_CODE ON) endif() +# Find toml++ +if(NOT Launcher_FORCE_BUNDLED_LIBS) + find_package(tomlplusplus 3.2.0 QUIET) +endif() + ####################################### Program Info ####################################### set(Launcher_APP_BINARY_NAME "polymc" CACHE STRING "Name of the Launcher binary") @@ -312,9 +317,6 @@ endif() add_subdirectory(libraries/rainbow) # Qt extension for colors add_subdirectory(libraries/LocalPeer) # fork of a library from Qt solutions add_subdirectory(libraries/classparser) # class parser library -if(NOT Launcher_FORCE_BUNDLED_LIBS) - find_package(tomlplusplus 3.2.0 QUIET) -endif() if(NOT tomlplusplus_FOUND) message(STATUS "Using bundled tomlplusplus") add_subdirectory(libraries/tomlplusplus) # toml parser From 0f59a1dde12f94eaff71f6f6b3d8d271c2dcce26 Mon Sep 17 00:00:00 2001 From: Sefa Eyeoglu Date: Mon, 26 Sep 2022 15:42:45 +0200 Subject: [PATCH 020/101] fix(nix): add tomlplusplus Signed-off-by: Sefa Eyeoglu --- flake.lock | 19 ++++++++++++++++++- flake.nix | 7 ++++--- nix/default.nix | 6 ++++++ 3 files changed, 28 insertions(+), 4 deletions(-) diff --git a/flake.lock b/flake.lock index bfc9ac6d..a72286bb 100644 --- a/flake.lock +++ b/flake.lock @@ -52,7 +52,24 @@ "inputs": { "flake-compat": "flake-compat", "libnbtplusplus": "libnbtplusplus", - "nixpkgs": "nixpkgs" + "nixpkgs": "nixpkgs", + "tomlplusplus": "tomlplusplus" + } + }, + "tomlplusplus": { + "flake": false, + "locked": { + "lastModified": 1664034574, + "narHash": "sha256-EFMAl6tsTvkgK0DWC/pZfOIq06b2e5SnxJa1ngGRIQA=", + "owner": "marzer", + "repo": "tomlplusplus", + "rev": "8aa5c8b2a4ff2c440d4630addf64fa4f62146170", + "type": "github" + }, + "original": { + "owner": "marzer", + "repo": "tomlplusplus", + "type": "github" } } }, diff --git a/flake.nix b/flake.nix index 51bc1fda..93192725 100644 --- a/flake.nix +++ b/flake.nix @@ -5,9 +5,10 @@ nixpkgs.url = "github:nixos/nixpkgs/nixpkgs-unstable"; flake-compat = { url = "github:edolstra/flake-compat"; flake = false; }; libnbtplusplus = { url = "github:PolyMC/libnbtplusplus"; flake = false; }; + tomlplusplus = { url = "github:marzer/tomlplusplus"; flake = false; }; }; - outputs = { self, nixpkgs, libnbtplusplus, ... }: + outputs = { self, nixpkgs, libnbtplusplus, tomlplusplus, ... }: let # User-friendly version number. version = builtins.substring 0 8 self.lastModifiedDate; @@ -22,8 +23,8 @@ pkgs = forAllSystems (system: nixpkgs.legacyPackages.${system}); packagesFn = pkgs: rec { - polymc = pkgs.libsForQt5.callPackage ./nix { inherit version self libnbtplusplus; }; - polymc-qt6 = pkgs.qt6Packages.callPackage ./nix { inherit version self libnbtplusplus; }; + polymc = pkgs.libsForQt5.callPackage ./nix { inherit version self libnbtplusplus tomlplusplus; }; + polymc-qt6 = pkgs.qt6Packages.callPackage ./nix { inherit version self libnbtplusplus tomlplusplus; }; }; in { diff --git a/nix/default.nix b/nix/default.nix index 42ddda18..88b540ab 100644 --- a/nix/default.nix +++ b/nix/default.nix @@ -21,6 +21,7 @@ , self , version , libnbtplusplus +, tomlplusplus , enableLTO ? false }: @@ -59,6 +60,11 @@ stdenv.mkDerivation rec { mkdir source/libraries/libnbtplusplus cp -a ${libnbtplusplus}/* source/libraries/libnbtplusplus chmod a+r+w source/libraries/libnbtplusplus/* + # Copy tomlplusplus + rm -rf source/libraries/tomlplusplus + mkdir source/libraries/tomlplusplus + cp -a ${tomlplusplus}/* source/libraries/tomlplusplus + chmod a+r+w source/libraries/tomlplusplus/* ''; cmakeFlags = [ From be3d780720688ea7869fc4a5744c99c7a84ec167 Mon Sep 17 00:00:00 2001 From: Vedant <83997633+vedantmgoyal2009@users.noreply.github.com> Date: Fri, 30 Sep 2022 22:51:47 +0530 Subject: [PATCH 021/101] Update winget.yml Signed-off-by: Vedant <83997633+vedantmgoyal2009@users.noreply.github.com> --- .github/workflows/winget.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/winget.yml b/.github/workflows/winget.yml index 98981e80..d3f787b6 100644 --- a/.github/workflows/winget.yml +++ b/.github/workflows/winget.yml @@ -7,8 +7,9 @@ jobs: publish: runs-on: windows-latest steps: - - uses: vedantmgoyal2009/winget-releaser@latest + - uses: vedantmgoyal2009/winget-releaser@v1 with: identifier: PolyMC.PolyMC + version: ${{ github.event.release.tag_name }} installers-regex: 'PolyMC-Windows-Setup-.+\.exe$' token: ${{ secrets.WINGET_TOKEN }} From 7ccafdc99321e82ee0f504a573a5c978480374a2 Mon Sep 17 00:00:00 2001 From: Sefa Eyeoglu Date: Fri, 30 Sep 2022 19:56:01 +0200 Subject: [PATCH 022/101] fix: add missing includes to fix Qt 6.4 build Signed-off-by: Sefa Eyeoglu --- launcher/ui/themes/BrightTheme.cpp | 2 ++ launcher/ui/themes/DarkTheme.cpp | 2 ++ 2 files changed, 4 insertions(+) diff --git a/launcher/ui/themes/BrightTheme.cpp b/launcher/ui/themes/BrightTheme.cpp index b9188bdd..7469edfc 100644 --- a/launcher/ui/themes/BrightTheme.cpp +++ b/launcher/ui/themes/BrightTheme.cpp @@ -1,5 +1,7 @@ #include "BrightTheme.h" +#include + QString BrightTheme::id() { return "bright"; diff --git a/launcher/ui/themes/DarkTheme.cpp b/launcher/ui/themes/DarkTheme.cpp index 712a9d3e..c2a6a8df 100644 --- a/launcher/ui/themes/DarkTheme.cpp +++ b/launcher/ui/themes/DarkTheme.cpp @@ -1,5 +1,7 @@ #include "DarkTheme.h" +#include + QString DarkTheme::id() { return "dark"; From 8e43d9713349af3834f51a4c6632b8b054415268 Mon Sep 17 00:00:00 2001 From: stoltsvensk <104643560+stoltsvensk@users.noreply.github.com> Date: Sat, 1 Oct 2022 16:47:23 +0200 Subject: [PATCH 023/101] Microsoft account only Signed-off-by: stoltsvensk <104643560+stoltsvensk@users.noreply.github.com> --- launcher/LaunchController.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/launcher/LaunchController.cpp b/launcher/LaunchController.cpp index 830fcf82..56e920f0 100644 --- a/launcher/LaunchController.cpp +++ b/launcher/LaunchController.cpp @@ -93,7 +93,7 @@ void LaunchController::decideAccount() auto reply = CustomMessageBox::selectable( m_parentWidget, tr("No Accounts"), - tr("In order to play Minecraft, you must have at least one Mojang or Microsoft " + tr("In order to play Minecraft, you must have at least one Microsoft " "account logged in. " "Would you like to open the account manager to add an account now?"), QMessageBox::Information, From 41276403dfe219f71f37b0610cebd7270ce3a9c6 Mon Sep 17 00:00:00 2001 From: DioEgizio <83089242+DioEgizio@users.noreply.github.com> Date: Sun, 2 Oct 2022 12:20:28 +0200 Subject: [PATCH 024/101] feat(actions): add codeql code scanning Signed-off-by: DioEgizio <83089242+DioEgizio@users.noreply.github.com> --- .github/workflows/build.yml | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index ae8947ab..f455416d 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -64,6 +64,12 @@ jobs: with: submodules: 'true' + - name: Initialize CodeQL + if: runner.os == 'Linux' && matrix.qt_ver == 6 + uses: github/codeql-action/init@v2 + with: + languages: cpp, java + - name: 'Setup MSYS2' if: runner.os == 'Windows' uses: msys2/setup-msys2@v2 @@ -209,6 +215,14 @@ jobs: run: | ctest --test-dir build --output-on-failure + ## + # CODE SCAN + ## + + - name: Perform CodeQL Analysis + if: runner.os == 'Linux' && matrix.qt_ver == 6 + uses: github/codeql-action/analyze@v2 + ## # PACKAGE BUILDS ## From 23b3990f99d2614f932f331138afa30a7ad1c413 Mon Sep 17 00:00:00 2001 From: DioEgizio <83089242+DioEgizio@users.noreply.github.com> Date: Sun, 2 Oct 2022 15:11:06 +0200 Subject: [PATCH 025/101] feat(code scanning): enable security-and-quality query Signed-off-by: DioEgizio <83089242+DioEgizio@users.noreply.github.com> --- .github/workflows/build.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index f455416d..9f377e58 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -68,6 +68,7 @@ jobs: if: runner.os == 'Linux' && matrix.qt_ver == 6 uses: github/codeql-action/init@v2 with: + queries: security-and-quality languages: cpp, java - name: 'Setup MSYS2' From 80e9eed35a537482897555eac641dad12b921064 Mon Sep 17 00:00:00 2001 From: DioEgizio <83089242+DioEgizio@users.noreply.github.com> Date: Sun, 2 Oct 2022 15:30:38 +0200 Subject: [PATCH 026/101] fix: remove old unused lgtm.yml, exclude cpp/fixme-comment Signed-off-by: DioEgizio <83089242+DioEgizio@users.noreply.github.com> --- .github/codeql/codeql-config.yml | 3 +++ .github/workflows/build.yml | 1 + lgtm.yml | 2 -- 3 files changed, 4 insertions(+), 2 deletions(-) create mode 100644 .github/codeql/codeql-config.yml delete mode 100644 lgtm.yml diff --git a/.github/codeql/codeql-config.yml b/.github/codeql/codeql-config.yml new file mode 100644 index 00000000..70acfdfd --- /dev/null +++ b/.github/codeql/codeql-config.yml @@ -0,0 +1,3 @@ +query-filters: + - exclude: + id: cpp/fixme-comment diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 9f377e58..6a9f393c 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -68,6 +68,7 @@ jobs: if: runner.os == 'Linux' && matrix.qt_ver == 6 uses: github/codeql-action/init@v2 with: + config-file: ./.github/codeql/codeql-config.yml queries: security-and-quality languages: cpp, java diff --git a/lgtm.yml b/lgtm.yml deleted file mode 100644 index 39cd3036..00000000 --- a/lgtm.yml +++ /dev/null @@ -1,2 +0,0 @@ -queries: - - exclude: "cpp/fixme-comment" # We like to use FIXME From 6ebc9abb8090cdbf78ab71f071ccd1f495eb7c0e Mon Sep 17 00:00:00 2001 From: Sefa Eyeoglu Date: Thu, 6 Oct 2022 14:46:12 +0200 Subject: [PATCH 027/101] fix: update capabilities before first-run wizard On first run, the condition for the wizard would return, before running updateCapabilities(). This moves that call up, as its only dependency is the settings system. Signed-off-by: Sefa Eyeoglu --- launcher/Application.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/launcher/Application.cpp b/launcher/Application.cpp index e08ea7f4..968dd08e 100644 --- a/launcher/Application.cpp +++ b/launcher/Application.cpp @@ -859,12 +859,13 @@ Application::Application(int &argc, char **argv) : QApplication(argc, argv) qDebug() << "<> Application theme set."; } + updateCapabilities(); + if(createSetupWizard()) { return; } - updateCapabilities(); performMainStartupAction(); } From f26049009e0482193b2a9d0d037ba7cb8ca82def Mon Sep 17 00:00:00 2001 From: DioEgizio <83089242+DioEgizio@users.noreply.github.com> Date: Sat, 8 Oct 2022 16:20:46 +0200 Subject: [PATCH 028/101] fix: mod updating isn't upcoming anymore :p Signed-off-by: DioEgizio <83089242+DioEgizio@users.noreply.github.com> --- launcher/ui/pages/global/LauncherPage.ui | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/launcher/ui/pages/global/LauncherPage.ui b/launcher/ui/pages/global/LauncherPage.ui index 645f7ef6..0d14f147 100644 --- a/launcher/ui/pages/global/LauncherPage.ui +++ b/launcher/ui/pages/global/LauncherPage.ui @@ -176,7 +176,7 @@ - <html><head/><body><p><span style=" font-weight:600; color:#f5c211;">Warning</span><span style=" color:#f5c211;">: Disabling mod metadata may also disable some upcoming QoL features, such as mod updating!</span></p></body></html> + <html><head/><body><p><span style=" font-weight:600; color:#f5c211;">Warning</span><span style=" color:#f5c211;">: Disabling mod metadata may also disable some QoL features, such as mod updating!</span></p></body></html> true From ea3be17220697326d3e508fc8c77d4e9bfbcf59f Mon Sep 17 00:00:00 2001 From: flow Date: Tue, 2 Aug 2022 15:17:54 -0300 Subject: [PATCH 029/101] feat: add widget for a text browser with image support Signed-off-by: flow --- launcher/CMakeLists.txt | 4 + .../ui/widgets/ProjectDescriptionPage.cpp | 17 +++ launcher/ui/widgets/ProjectDescriptionPage.h | 24 ++++ .../ui/widgets/VariableSizedImageObject.cpp | 118 ++++++++++++++++++ .../ui/widgets/VariableSizedImageObject.h | 55 ++++++++ 5 files changed, 218 insertions(+) create mode 100644 launcher/ui/widgets/ProjectDescriptionPage.cpp create mode 100644 launcher/ui/widgets/ProjectDescriptionPage.h create mode 100644 launcher/ui/widgets/VariableSizedImageObject.cpp create mode 100644 launcher/ui/widgets/VariableSizedImageObject.h diff --git a/launcher/CMakeLists.txt b/launcher/CMakeLists.txt index 0bdfcd44..044160a4 100644 --- a/launcher/CMakeLists.txt +++ b/launcher/CMakeLists.txt @@ -855,6 +855,10 @@ SET(LAUNCHER_SOURCES ui/widgets/PageContainer.cpp ui/widgets/PageContainer.h ui/widgets/PageContainer_p.h + ui/widgets/ProjectDescriptionPage.h + ui/widgets/ProjectDescriptionPage.cpp + ui/widgets/VariableSizedImageObject.h + ui/widgets/VariableSizedImageObject.cpp ui/widgets/ProjectItem.h ui/widgets/ProjectItem.cpp ui/widgets/VersionListView.cpp diff --git a/launcher/ui/widgets/ProjectDescriptionPage.cpp b/launcher/ui/widgets/ProjectDescriptionPage.cpp new file mode 100644 index 00000000..2e6f6d97 --- /dev/null +++ b/launcher/ui/widgets/ProjectDescriptionPage.cpp @@ -0,0 +1,17 @@ +#include "ProjectDescriptionPage.h" + +#include "VariableSizedImageObject.h" + +#include + +ProjectDescriptionPage::ProjectDescriptionPage(QWidget* parent) : QTextBrowser(parent), m_image_text_object(new VariableSizedImageObject) +{ + m_image_text_object->setParent(this); + document()->documentLayout()->registerHandler(QTextFormat::ImageObject, m_image_text_object.get()); +} + +void ProjectDescriptionPage::setMetaEntry(QString entry) +{ + if (m_image_text_object) + m_image_text_object->setMetaEntry(entry); +} diff --git a/launcher/ui/widgets/ProjectDescriptionPage.h b/launcher/ui/widgets/ProjectDescriptionPage.h new file mode 100644 index 00000000..8387d3fb --- /dev/null +++ b/launcher/ui/widgets/ProjectDescriptionPage.h @@ -0,0 +1,24 @@ +#pragma once + +#include + +#include "QObjectPtr.h" + +QT_BEGIN_NAMESPACE +class VariableSizedImageObject; +QT_END_NAMESPACE + +/** This subclasses QTextBrowser to provide additional capabilities + * to it, like allowing for images to be shown. + */ +class ProjectDescriptionPage final : public QTextBrowser { + Q_OBJECT + + public: + ProjectDescriptionPage(QWidget* parent = nullptr); + + void setMetaEntry(QString entry); + + private: + shared_qobject_ptr m_image_text_object; +}; diff --git a/launcher/ui/widgets/VariableSizedImageObject.cpp b/launcher/ui/widgets/VariableSizedImageObject.cpp new file mode 100644 index 00000000..0efdecab --- /dev/null +++ b/launcher/ui/widgets/VariableSizedImageObject.cpp @@ -0,0 +1,118 @@ +// SPDX-License-Identifier: GPL-3.0-only +/* + * PolyMC - Minecraft Launcher + * Copyright (c) 2022 flowln + * + * 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 . + */ + +#include "VariableSizedImageObject.h" + +#include +#include +#include +#include + +#include "Application.h" + +#include "net/NetJob.h" + +enum FormatProperties { ImageData = QTextFormat::UserProperty + 1 }; + +QSizeF VariableSizedImageObject::intrinsicSize(QTextDocument* doc, int posInDocument, const QTextFormat& format) +{ + Q_UNUSED(posInDocument); + + auto image = qvariant_cast(format.property(ImageData)); + auto size = image.size(); + + // Get the width of the text content to make the image similar sized. + // doc->textWidth() includes the margin, so we need to remove it. + auto doc_width = doc->textWidth() - 2 * doc->documentMargin(); + + if (size.width() > doc_width) + size *= doc_width / (double)size.width(); + + return { size }; +} +void VariableSizedImageObject::drawObject(QPainter* painter, + const QRectF& rect, + QTextDocument* doc, + int posInDocument, + const QTextFormat& format) +{ + if (!format.hasProperty(ImageData)) { + QUrl image_url{ qvariant_cast(format.property(QTextFormat::ImageName)) }; + if (m_fetching_images.contains(image_url)) + return; + + loadImage(doc, image_url, posInDocument); + return; + } + + auto image = qvariant_cast(format.property(ImageData)); + + painter->setRenderHint(QPainter::RenderHint::SmoothPixmapTransform); + painter->drawImage(rect, image); +} + +void VariableSizedImageObject::parseImage(QTextDocument* doc, QImage image, int posInDocument) +{ + QTextCursor cursor(doc); + cursor.setPosition(posInDocument); + cursor.setKeepPositionOnInsert(true); + + auto image_char_format = cursor.charFormat(); + + image_char_format.setObjectType(QTextFormat::ImageObject); + image_char_format.setProperty(ImageData, image); + + // Qt doesn't allow us to modify the properties of an existing object in the document. + // So we remove the old one and add the new one with the ImageData property set. + cursor.deleteChar(); + cursor.insertText(QString(QChar::ObjectReplacementCharacter), image_char_format); +} + +void VariableSizedImageObject::loadImage(QTextDocument* doc, const QUrl& source, int posInDocument) +{ + m_fetching_images.append(source); + + MetaEntryPtr entry = APPLICATION->metacache()->resolveEntry( + m_meta_entry, + QString("images/%1").arg(QString(QCryptographicHash::hash(source.toEncoded(), QCryptographicHash::Algorithm::Sha1).toHex()))); + + auto job = new NetJob(QString("Load Image: %1").arg(source.fileName()), APPLICATION->network()); + job->addNetAction(Net::Download::makeCached(source, entry)); + + auto full_entry_path = entry->getFullPath(); + auto source_url = source; + connect(job, &NetJob::succeeded, [this, doc, full_entry_path, source_url, posInDocument] { + qDebug() << "Loaded resource at" << full_entry_path; + + QImage image(full_entry_path); + doc->addResource(QTextDocument::ImageResource, source_url, image); + + parseImage(doc, image, posInDocument); + + // This size hack is needed to prevent the content from being laid out in an area smaller + // than the total width available (weird). + auto size = doc->pageSize(); + doc->adjustSize(); + doc->setPageSize(size); + + m_fetching_images.removeOne(source_url); + }); + connect(job, &NetJob::finished, job, &NetJob::deleteLater); + + job->start(); +} diff --git a/launcher/ui/widgets/VariableSizedImageObject.h b/launcher/ui/widgets/VariableSizedImageObject.h new file mode 100644 index 00000000..11563a37 --- /dev/null +++ b/launcher/ui/widgets/VariableSizedImageObject.h @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: GPL-3.0-only +/* + * PolyMC - Minecraft Launcher + * Copyright (c) 2022 flowln + * + * 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 . + */ + +#pragma once + +#include +#include +#include +#include + +/** Custom image text object to be used instead of the normal one in ProjectDescriptionPage. + * + * Why? Because we want to re-scale images dynamically based on the document's size, in order to + * not have images being weirdly cropped out in different resolutions. + */ +class VariableSizedImageObject : public QObject, public QTextObjectInterface { + Q_OBJECT + Q_INTERFACES(QTextObjectInterface) + + public: + QSizeF intrinsicSize(QTextDocument* doc, int posInDocument, const QTextFormat& format) override; + void drawObject(QPainter* painter, const QRectF& rect, QTextDocument* doc, int posInDocument, const QTextFormat& format) override; + + void setMetaEntry(QString meta_entry) { m_meta_entry = meta_entry; } + + protected: + /** Adds the image to the document, in the given position. + */ + void parseImage(QTextDocument* doc, QImage image, int posInDocument); + + /** Loads an image from an external source, and adds it to the document. + * + * This uses m_meta_entry to cache the image. + */ + void loadImage(QTextDocument* doc, const QUrl& source, int posInDocument); + + QString m_meta_entry; + + QList m_fetching_images; +}; From db158a5735e18442f76118f1f6a060e6c3680e33 Mon Sep 17 00:00:00 2001 From: flow Date: Sat, 10 Sep 2022 18:49:00 -0300 Subject: [PATCH 030/101] feat: add image support for mod pages Signed-off-by: flow --- launcher/ui/pages/modplatform/ModPage.ui | 9 ++++++++- launcher/ui/pages/modplatform/flame/FlameModPage.cpp | 2 ++ .../ui/pages/modplatform/modrinth/ModrinthModPage.cpp | 2 ++ 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/launcher/ui/pages/modplatform/ModPage.ui b/launcher/ui/pages/modplatform/ModPage.ui index afcd9bb7..943f02aa 100644 --- a/launcher/ui/pages/modplatform/ModPage.ui +++ b/launcher/ui/pages/modplatform/ModPage.ui @@ -14,7 +14,7 @@ - + true @@ -98,6 +98,13 @@ + + + ProjectDescriptionPage + QTextBrowser +
ui/widgets/ProjectDescriptionPage.h
+
+
searchEdit searchButton diff --git a/launcher/ui/pages/modplatform/flame/FlameModPage.cpp b/launcher/ui/pages/modplatform/flame/FlameModPage.cpp index 772fd2e0..b497d1fe 100644 --- a/launcher/ui/pages/modplatform/flame/FlameModPage.cpp +++ b/launcher/ui/pages/modplatform/flame/FlameModPage.cpp @@ -59,6 +59,8 @@ FlameModPage::FlameModPage(ModDownloadDialog* dialog, BaseInstance* instance) connect(ui->packView->selectionModel(), &QItemSelectionModel::currentChanged, this, &FlameModPage::onSelectionChanged); connect(ui->versionSelectionBox, &QComboBox::currentTextChanged, this, &FlameModPage::onVersionSelectionChanged); connect(ui->modSelectionButton, &QPushButton::clicked, this, &FlameModPage::onModSelected); + + ui->packDescription->setMetaEntry(metaEntryBase()); } auto FlameModPage::validateVersion(ModPlatform::IndexedVersion& ver, QString mineVer, ModAPI::ModLoaderTypes loaders) const -> bool diff --git a/launcher/ui/pages/modplatform/modrinth/ModrinthModPage.cpp b/launcher/ui/pages/modplatform/modrinth/ModrinthModPage.cpp index 5fa00b9b..62e417c8 100644 --- a/launcher/ui/pages/modplatform/modrinth/ModrinthModPage.cpp +++ b/launcher/ui/pages/modplatform/modrinth/ModrinthModPage.cpp @@ -59,6 +59,8 @@ ModrinthModPage::ModrinthModPage(ModDownloadDialog* dialog, BaseInstance* instan connect(ui->packView->selectionModel(), &QItemSelectionModel::currentChanged, this, &ModrinthModPage::onSelectionChanged); connect(ui->versionSelectionBox, &QComboBox::currentTextChanged, this, &ModrinthModPage::onVersionSelectionChanged); connect(ui->modSelectionButton, &QPushButton::clicked, this, &ModrinthModPage::onModSelected); + + ui->packDescription->setMetaEntry(metaEntryBase()); } auto ModrinthModPage::validateVersion(ModPlatform::IndexedVersion& ver, QString mineVer, ModAPI::ModLoaderTypes loaders) const -> bool From d99976f5d7e13f0e2432028b9dd8b38ded8bcc18 Mon Sep 17 00:00:00 2001 From: flow Date: Tue, 2 Aug 2022 15:14:25 -0300 Subject: [PATCH 031/101] fix: make mod and modpack caches separate for Modrinth This makes it similar to CF mods / modpacks. The mods cache is maintained with the same name because it most likely has more data it in, so this commit will affect existing caches as minimally as possible. Signed-off-by: flow --- launcher/Application.cpp | 1 + launcher/ui/pages/modplatform/modrinth/ModrinthModel.cpp | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/launcher/Application.cpp b/launcher/Application.cpp index e08ea7f4..64adc6e9 100644 --- a/launcher/Application.cpp +++ b/launcher/Application.cpp @@ -809,6 +809,7 @@ Application::Application(int &argc, char **argv) : QApplication(argc, argv) m_metacache->addBase("FlamePacks", QDir("cache/FlamePacks").absolutePath()); m_metacache->addBase("FlameMods", QDir("cache/FlameMods").absolutePath()); m_metacache->addBase("ModrinthPacks", QDir("cache/ModrinthPacks").absolutePath()); + m_metacache->addBase("ModrinthModpacks", QDir("cache/ModrinthModpacks").absolutePath()); m_metacache->addBase("root", QDir::currentPath()); m_metacache->addBase("translations", QDir("translations").absolutePath()); m_metacache->addBase("icons", QDir("cache/icons").absolutePath()); diff --git a/launcher/ui/pages/modplatform/modrinth/ModrinthModel.cpp b/launcher/ui/pages/modplatform/modrinth/ModrinthModel.cpp index fd7a3537..a0e9ab19 100644 --- a/launcher/ui/pages/modplatform/modrinth/ModrinthModel.cpp +++ b/launcher/ui/pages/modplatform/modrinth/ModrinthModel.cpp @@ -218,7 +218,7 @@ void ModpackListModel::getLogo(const QString& logo, const QString& logoUrl, Logo { if (m_logoMap.contains(logo)) { callback(APPLICATION->metacache() - ->resolveEntry("ModrinthPacks", QString("logos/%1").arg(logo.section(".", 0, 0))) + ->resolveEntry(m_parent->metaEntryBase(), QString("logos/%1").arg(logo.section(".", 0, 0))) ->getFullPath()); } else { requestLogo(logo, logoUrl); @@ -232,7 +232,7 @@ void ModpackListModel::requestLogo(QString logo, QString url) } MetaEntryPtr entry = - APPLICATION->metacache()->resolveEntry("ModrinthPacks", QString("logos/%1").arg(logo.section(".", 0, 0))); + APPLICATION->metacache()->resolveEntry(m_parent->metaEntryBase(), QString("logos/%1").arg(logo.section(".", 0, 0))); auto job = new NetJob(QString("%1 Icon Download %2").arg(m_parent->debugName()).arg(logo), APPLICATION->network()); job->addNetAction(Net::Download::makeCached(QUrl(url), entry)); From 60f19f305e4e4540f337a4dbcc96536c14e23e82 Mon Sep 17 00:00:00 2001 From: flow Date: Sat, 10 Sep 2022 18:49:31 -0300 Subject: [PATCH 032/101] feat: add image support for modrinth modpack pages Signed-off-by: flow --- launcher/ui/pages/modplatform/modrinth/ModrinthPage.cpp | 1 + launcher/ui/pages/modplatform/modrinth/ModrinthPage.ui | 9 ++++++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/launcher/ui/pages/modplatform/modrinth/ModrinthPage.cpp b/launcher/ui/pages/modplatform/modrinth/ModrinthPage.cpp index cea6cdee..70f1388a 100644 --- a/launcher/ui/pages/modplatform/modrinth/ModrinthPage.cpp +++ b/launcher/ui/pages/modplatform/modrinth/ModrinthPage.cpp @@ -74,6 +74,7 @@ ModrinthPage::ModrinthPage(NewInstanceDialog* dialog, QWidget* parent) : QWidget connect(ui->versionSelectionBox, &QComboBox::currentTextChanged, this, &ModrinthPage::onVersionSelectionChanged); ui->packView->setItemDelegate(new ProjectItemDelegate(this)); + ui->packDescription->setMetaEntry(metaEntryBase()); } ModrinthPage::~ModrinthPage() diff --git a/launcher/ui/pages/modplatform/modrinth/ModrinthPage.ui b/launcher/ui/pages/modplatform/modrinth/ModrinthPage.ui index 6a34701d..6d8b2b67 100644 --- a/launcher/ui/pages/modplatform/modrinth/ModrinthPage.ui +++ b/launcher/ui/pages/modplatform/modrinth/ModrinthPage.ui @@ -66,7 +66,7 @@
- + true @@ -99,6 +99,13 @@ + + + ProjectDescriptionPage + QTextBrowser +
ui/widgets/ProjectDescriptionPage.h
+
+
searchEdit searchButton From d7992ab29d07c6d26377f6db1cfca6059aace471 Mon Sep 17 00:00:00 2001 From: flow Date: Sat, 10 Sep 2022 19:00:47 -0300 Subject: [PATCH 033/101] feat: add image support for FTB packs Signed-off-by: flow --- launcher/ui/pages/modplatform/ftb/FtbPage.cpp | 2 ++ launcher/ui/pages/modplatform/ftb/FtbPage.ui | 9 ++++++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/launcher/ui/pages/modplatform/ftb/FtbPage.cpp b/launcher/ui/pages/modplatform/ftb/FtbPage.cpp index 8975d74e..34734eaf 100644 --- a/launcher/ui/pages/modplatform/ftb/FtbPage.cpp +++ b/launcher/ui/pages/modplatform/ftb/FtbPage.cpp @@ -73,6 +73,8 @@ FtbPage::FtbPage(NewInstanceDialog* dialog, QWidget *parent) connect(ui->sortByBox, &QComboBox::currentTextChanged, this, &FtbPage::onSortingSelectionChanged); connect(ui->packView->selectionModel(), &QItemSelectionModel::currentChanged, this, &FtbPage::onSelectionChanged); connect(ui->versionSelectionBox, &QComboBox::currentTextChanged, this, &FtbPage::onVersionSelectionChanged); + + ui->packDescription->setMetaEntry("FTBPacks"); } FtbPage::~FtbPage() diff --git a/launcher/ui/pages/modplatform/ftb/FtbPage.ui b/launcher/ui/pages/modplatform/ftb/FtbPage.ui index 850bf091..8de0f4e6 100644 --- a/launcher/ui/pages/modplatform/ftb/FtbPage.ui +++ b/launcher/ui/pages/modplatform/ftb/FtbPage.ui @@ -57,7 +57,7 @@ - + true @@ -70,6 +70,13 @@ + + + ProjectDescriptionPage + QTextBrowser +
ui/widgets/ProjectDescriptionPage.h
+
+
searchEdit versionSelectionBox From ebee50eedc751680bc7b7b407b984574d3433498 Mon Sep 17 00:00:00 2001 From: Trisave <42098407+Protrikk@users.noreply.github.com> Date: Sat, 8 Oct 2022 19:33:24 +0200 Subject: [PATCH 034/101] Improve default light and dark themes (#1174) --- launcher/ui/themes/BrightTheme.cpp | 26 +++++++++++++------------- launcher/ui/themes/DarkTheme.cpp | 14 +++++++------- 2 files changed, 20 insertions(+), 20 deletions(-) diff --git a/launcher/ui/themes/BrightTheme.cpp b/launcher/ui/themes/BrightTheme.cpp index 7469edfc..696ffdfb 100644 --- a/launcher/ui/themes/BrightTheme.cpp +++ b/launcher/ui/themes/BrightTheme.cpp @@ -20,19 +20,19 @@ bool BrightTheme::hasColorScheme() QPalette BrightTheme::colorScheme() { QPalette brightPalette; - brightPalette.setColor(QPalette::Window, QColor(239,240,241)); - brightPalette.setColor(QPalette::WindowText, QColor(49,54,59)); - brightPalette.setColor(QPalette::Base, QColor(252,252,252)); - brightPalette.setColor(QPalette::AlternateBase, QColor(239,240,241)); - brightPalette.setColor(QPalette::ToolTipBase, QColor(49,54,59)); - brightPalette.setColor(QPalette::ToolTipText, QColor(239,240,241)); - brightPalette.setColor(QPalette::Text, QColor(49,54,59)); - brightPalette.setColor(QPalette::Button, QColor(239,240,241)); - brightPalette.setColor(QPalette::ButtonText, QColor(49,54,59)); + brightPalette.setColor(QPalette::Window, QColor(255,255,255)); + brightPalette.setColor(QPalette::WindowText, QColor(17,17,17)); + brightPalette.setColor(QPalette::Base, QColor(250,250,250)); + brightPalette.setColor(QPalette::AlternateBase, QColor(240,240,240)); + brightPalette.setColor(QPalette::ToolTipBase, QColor(17,17,17)); + brightPalette.setColor(QPalette::ToolTipText, QColor(255,255,255)); + brightPalette.setColor(QPalette::Text, Qt::black); + brightPalette.setColor(QPalette::Button, QColor(249,249,249)); + brightPalette.setColor(QPalette::ButtonText, Qt::black); brightPalette.setColor(QPalette::BrightText, Qt::red); - brightPalette.setColor(QPalette::Link, QColor(41, 128, 185)); - brightPalette.setColor(QPalette::Highlight, QColor(61, 174, 233)); - brightPalette.setColor(QPalette::HighlightedText, QColor(239,240,241)); + brightPalette.setColor(QPalette::Link, QColor(37,137,164)); + brightPalette.setColor(QPalette::Highlight, QColor(137,207,84)); + brightPalette.setColor(QPalette::HighlightedText, Qt::black); return fadeInactive(brightPalette, fadeAmount(), fadeColor()); } @@ -43,7 +43,7 @@ double BrightTheme::fadeAmount() QColor BrightTheme::fadeColor() { - return QColor(239,240,241); + return QColor(255,255,255); } bool BrightTheme::hasStyleSheet() diff --git a/launcher/ui/themes/DarkTheme.cpp b/launcher/ui/themes/DarkTheme.cpp index c2a6a8df..07a2efd2 100644 --- a/launcher/ui/themes/DarkTheme.cpp +++ b/launcher/ui/themes/DarkTheme.cpp @@ -20,18 +20,18 @@ bool DarkTheme::hasColorScheme() QPalette DarkTheme::colorScheme() { QPalette darkPalette; - darkPalette.setColor(QPalette::Window, QColor(49,54,59)); + darkPalette.setColor(QPalette::Window, QColor(49,49,49)); darkPalette.setColor(QPalette::WindowText, Qt::white); - darkPalette.setColor(QPalette::Base, QColor(35,38,41)); - darkPalette.setColor(QPalette::AlternateBase, QColor(49,54,59)); + darkPalette.setColor(QPalette::Base, QColor(34,34,34)); + darkPalette.setColor(QPalette::AlternateBase, QColor(42,42,42)); darkPalette.setColor(QPalette::ToolTipBase, Qt::white); darkPalette.setColor(QPalette::ToolTipText, Qt::white); darkPalette.setColor(QPalette::Text, Qt::white); - darkPalette.setColor(QPalette::Button, QColor(49,54,59)); + darkPalette.setColor(QPalette::Button, QColor(48,48,48)); darkPalette.setColor(QPalette::ButtonText, Qt::white); darkPalette.setColor(QPalette::BrightText, Qt::red); - darkPalette.setColor(QPalette::Link, QColor(42, 130, 218)); - darkPalette.setColor(QPalette::Highlight, QColor(42, 130, 218)); + darkPalette.setColor(QPalette::Link, QColor(47,163,198)); + darkPalette.setColor(QPalette::Highlight, QColor(145,205,92)); darkPalette.setColor(QPalette::HighlightedText, Qt::black); darkPalette.setColor(QPalette::PlaceholderText, Qt::darkGray); return fadeInactive(darkPalette, fadeAmount(), fadeColor()); @@ -44,7 +44,7 @@ double DarkTheme::fadeAmount() QColor DarkTheme::fadeColor() { - return QColor(49,54,59); + return QColor(49,49,49); } bool DarkTheme::hasStyleSheet() From 3111e6a7212ae914041fce6d851d7662975dc1be Mon Sep 17 00:00:00 2001 From: Sefa Eyeoglu Date: Sat, 8 Oct 2022 20:09:53 +0200 Subject: [PATCH 035/101] chore: add missing license headers Signed-off-by: Sefa Eyeoglu --- launcher/NullInstance.h | 35 ++++++++++++++++ launcher/RuntimeContext.h | 18 +++++++++ launcher/minecraft/Component.cpp | 35 ++++++++++++++++ launcher/minecraft/Library.cpp | 35 ++++++++++++++++ launcher/minecraft/Library.h | 35 ++++++++++++++++ launcher/minecraft/MinecraftInstance.h | 35 ++++++++++++++++ launcher/minecraft/PackProfile.h | 40 ++++++++++++++----- launcher/minecraft/Rule.cpp | 40 ++++++++++++++----- launcher/minecraft/Rule.h | 40 ++++++++++++++----- launcher/minecraft/launch/ModMinecraftJar.cpp | 40 ++++++++++++++----- launcher/minecraft/launch/ScanModFolders.cpp | 40 ++++++++++++++----- launcher/minecraft/update/FoldersTask.cpp | 35 ++++++++++++++++ tests/Library_test.cpp | 35 ++++++++++++++++ 13 files changed, 413 insertions(+), 50 deletions(-) diff --git a/launcher/NullInstance.h b/launcher/NullInstance.h index 628aff5f..53edfa0b 100644 --- a/launcher/NullInstance.h +++ b/launcher/NullInstance.h @@ -1,3 +1,38 @@ +// SPDX-License-Identifier: GPL-3.0-only +/* + * PolyMC - Minecraft Launcher + * Copyright (C) 2022 Sefa Eyeoglu + * + * 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 . + * + * This file incorporates work covered by the following copyright and + * permission notice: + * + * Copyright 2013-2021 MultiMC Contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + #pragma once #include "BaseInstance.h" #include "launch/LaunchTask.h" diff --git a/launcher/RuntimeContext.h b/launcher/RuntimeContext.h index 6090897c..c1b71318 100644 --- a/launcher/RuntimeContext.h +++ b/launcher/RuntimeContext.h @@ -1,3 +1,21 @@ +// SPDX-License-Identifier: GPL-3.0-only +/* + * PolyMC - Minecraft Launcher + * Copyright (C) 2022 Sefa Eyeoglu + * + * 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 . + */ + #pragma once #include diff --git a/launcher/minecraft/Component.cpp b/launcher/minecraft/Component.cpp index ebe4eac7..7e5b6058 100644 --- a/launcher/minecraft/Component.cpp +++ b/launcher/minecraft/Component.cpp @@ -1,3 +1,38 @@ +// SPDX-License-Identifier: GPL-3.0-only +/* + * PolyMC - Minecraft Launcher + * Copyright (C) 2022 Sefa Eyeoglu + * + * 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 . + * + * 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 #include #include "Component.h" diff --git a/launcher/minecraft/Library.cpp b/launcher/minecraft/Library.cpp index 42a42d87..cb2b5254 100644 --- a/launcher/minecraft/Library.cpp +++ b/launcher/minecraft/Library.cpp @@ -1,3 +1,38 @@ +// SPDX-License-Identifier: GPL-3.0-only +/* + * PolyMC - Minecraft Launcher + * Copyright (C) 2022 Sefa Eyeoglu + * + * 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 . + * + * 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" diff --git a/launcher/minecraft/Library.h b/launcher/minecraft/Library.h index b8fae9ec..950aec9d 100644 --- a/launcher/minecraft/Library.h +++ b/launcher/minecraft/Library.h @@ -1,3 +1,38 @@ +// SPDX-License-Identifier: GPL-3.0-only +/* + * PolyMC - Minecraft Launcher + * Copyright (C) 2022 Sefa Eyeoglu + * + * 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 . + * + * This file incorporates work covered by the following copyright and + * permission notice: + * + * Copyright 2013-2021 MultiMC Contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + #pragma once #include #include diff --git a/launcher/minecraft/MinecraftInstance.h b/launcher/minecraft/MinecraftInstance.h index ef48b286..1895d187 100644 --- a/launcher/minecraft/MinecraftInstance.h +++ b/launcher/minecraft/MinecraftInstance.h @@ -1,3 +1,38 @@ +// SPDX-License-Identifier: GPL-3.0-only +/* + * PolyMC - Minecraft Launcher + * Copyright (C) 2022 Sefa Eyeoglu + * + * 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 . + * + * This file incorporates work covered by the following copyright and + * permission notice: + * + * Copyright 2013-2021 MultiMC Contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + #pragma once #include "BaseInstance.h" #include diff --git a/launcher/minecraft/PackProfile.h b/launcher/minecraft/PackProfile.h index 11057a0c..807511a2 100644 --- a/launcher/minecraft/PackProfile.h +++ b/launcher/minecraft/PackProfile.h @@ -1,16 +1,36 @@ -/* Copyright 2013-2021 MultiMC Contributors +// SPDX-License-Identifier: GPL-3.0-only +/* + * PolyMC - Minecraft Launcher + * Copyright (C) 2022 Sefa Eyeoglu * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, version 3. * - * http://www.apache.org/licenses/LICENSE-2.0 + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * This file incorporates work covered by the following copyright and + * permission notice: + * + * Copyright 2013-2021 MultiMC Contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ #pragma once diff --git a/launcher/minecraft/Rule.cpp b/launcher/minecraft/Rule.cpp index 2f41e1fb..ff3d75f2 100644 --- a/launcher/minecraft/Rule.cpp +++ b/launcher/minecraft/Rule.cpp @@ -1,16 +1,36 @@ -/* Copyright 2013-2021 MultiMC Contributors +// SPDX-License-Identifier: GPL-3.0-only +/* + * PolyMC - Minecraft Launcher + * Copyright (C) 2022 Sefa Eyeoglu * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, version 3. * - * http://www.apache.org/licenses/LICENSE-2.0 + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * 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 diff --git a/launcher/minecraft/Rule.h b/launcher/minecraft/Rule.h index 4c75cee4..236f9a87 100644 --- a/launcher/minecraft/Rule.h +++ b/launcher/minecraft/Rule.h @@ -1,16 +1,36 @@ -/* Copyright 2013-2021 MultiMC Contributors +// SPDX-License-Identifier: GPL-3.0-only +/* + * PolyMC - Minecraft Launcher + * Copyright (C) 2022 Sefa Eyeoglu * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, version 3. * - * http://www.apache.org/licenses/LICENSE-2.0 + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * This file incorporates work covered by the following copyright and + * permission notice: + * + * Copyright 2013-2021 MultiMC Contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ #pragma once diff --git a/launcher/minecraft/launch/ModMinecraftJar.cpp b/launcher/minecraft/launch/ModMinecraftJar.cpp index 8e47e0e5..1d6eecf2 100644 --- a/launcher/minecraft/launch/ModMinecraftJar.cpp +++ b/launcher/minecraft/launch/ModMinecraftJar.cpp @@ -1,16 +1,36 @@ -/* Copyright 2013-2021 MultiMC Contributors +// SPDX-License-Identifier: GPL-3.0-only +/* + * PolyMC - Minecraft Launcher + * Copyright (C) 2022 Sefa Eyeoglu * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, version 3. * - * http://www.apache.org/licenses/LICENSE-2.0 + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * 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 "ModMinecraftJar.h" diff --git a/launcher/minecraft/launch/ScanModFolders.cpp b/launcher/minecraft/launch/ScanModFolders.cpp index 2e817e0a..bdffeadd 100644 --- a/launcher/minecraft/launch/ScanModFolders.cpp +++ b/launcher/minecraft/launch/ScanModFolders.cpp @@ -1,16 +1,36 @@ -/* Copyright 2013-2021 MultiMC Contributors +// SPDX-License-Identifier: GPL-3.0-only +/* + * PolyMC - Minecraft Launcher + * Copyright (C) 2022 Sefa Eyeoglu * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, version 3. * - * http://www.apache.org/licenses/LICENSE-2.0 + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * 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 "ScanModFolders.h" diff --git a/launcher/minecraft/update/FoldersTask.cpp b/launcher/minecraft/update/FoldersTask.cpp index 22768bd9..b9ee9d98 100644 --- a/launcher/minecraft/update/FoldersTask.cpp +++ b/launcher/minecraft/update/FoldersTask.cpp @@ -1,3 +1,38 @@ +// SPDX-License-Identifier: GPL-3.0-only +/* + * PolyMC - Minecraft Launcher + * Copyright (C) 2022 Sefa Eyeoglu + * + * 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 . + * + * 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 "FoldersTask.h" #include "minecraft/MinecraftInstance.h" #include diff --git a/tests/Library_test.cpp b/tests/Library_test.cpp index b9027e12..db8380c7 100644 --- a/tests/Library_test.cpp +++ b/tests/Library_test.cpp @@ -1,3 +1,38 @@ +// SPDX-License-Identifier: GPL-3.0-only +/* + * PolyMC - Minecraft Launcher + * Copyright (C) 2022 Sefa Eyeoglu + * + * 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 . + * + * 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 #include From fecf1ffcb935c69aaba1049dfa5291615fa7aefa Mon Sep 17 00:00:00 2001 From: Ozynt <104643560+Ozynt@users.noreply.github.com> Date: Sun, 9 Oct 2022 13:19:38 +0200 Subject: [PATCH 036/101] Update LaunchController.cpp Signed-off-by: Ozynt <104643560+Ozynt@users.noreply.github.com> --- launcher/LaunchController.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/launcher/LaunchController.cpp b/launcher/LaunchController.cpp index 56e920f0..15ce2545 100644 --- a/launcher/LaunchController.cpp +++ b/launcher/LaunchController.cpp @@ -93,8 +93,8 @@ void LaunchController::decideAccount() auto reply = CustomMessageBox::selectable( m_parentWidget, tr("No Accounts"), - tr("In order to play Minecraft, you must have at least one Microsoft " - "account logged in. " + tr("In order to play Minecraft, you must have at least one Microsoft or Mojang " + "account logged in. Mojang accounts are only usable offline." "Would you like to open the account manager to add an account now?"), QMessageBox::Information, QMessageBox::Yes | QMessageBox::No From 7e67fd8c7931c5ddfc166cc711e518ea52309c3d Mon Sep 17 00:00:00 2001 From: Ozynt <104643560+Ozynt@users.noreply.github.com> Date: Sun, 9 Oct 2022 13:20:50 +0200 Subject: [PATCH 037/101] Update LaunchController.cpp Signed-off-by: Ozynt <104643560+Ozynt@users.noreply.github.com> --- launcher/LaunchController.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/launcher/LaunchController.cpp b/launcher/LaunchController.cpp index 15ce2545..e61c5f67 100644 --- a/launcher/LaunchController.cpp +++ b/launcher/LaunchController.cpp @@ -94,7 +94,7 @@ void LaunchController::decideAccount() m_parentWidget, tr("No Accounts"), tr("In order to play Minecraft, you must have at least one Microsoft or Mojang " - "account logged in. Mojang accounts are only usable offline." + "account logged in. Mojang accounts can only be used offline. " "Would you like to open the account manager to add an account now?"), QMessageBox::Information, QMessageBox::Yes | QMessageBox::No From 71f3c6b461eb296a3d1604e3534c9a4ab3d43397 Mon Sep 17 00:00:00 2001 From: Sefa Eyeoglu Date: Mon, 10 Oct 2022 12:45:44 +0200 Subject: [PATCH 038/101] feat: add clear metadata action Signed-off-by: Sefa Eyeoglu --- launcher/net/HttpMetaCache.cpp | 12 ++++++++++++ launcher/net/HttpMetaCache.h | 1 + launcher/ui/MainWindow.cpp | 17 +++++++++++++++++ launcher/ui/MainWindow.h | 2 ++ 4 files changed, 32 insertions(+) diff --git a/launcher/net/HttpMetaCache.cpp b/launcher/net/HttpMetaCache.cpp index 9606ddb6..42198b71 100644 --- a/launcher/net/HttpMetaCache.cpp +++ b/launcher/net/HttpMetaCache.cpp @@ -162,6 +162,18 @@ auto HttpMetaCache::evictEntry(MetaEntryPtr entry) -> bool return true; } +void HttpMetaCache::evictAll() +{ + for (QString& base : m_entries.keys()) { + EntryMap& map = m_entries[base]; + qDebug() << "Evicting base" << base; + for (MetaEntryPtr entry : map.entry_list) { + if (!evictEntry(entry)) + qWarning() << "Unexpected missing cache entry" << entry->basePath; + } + } +} + auto HttpMetaCache::staleEntry(QString base, QString resource_path) -> MetaEntryPtr { auto foo = new MetaEntry(); diff --git a/launcher/net/HttpMetaCache.h b/launcher/net/HttpMetaCache.h index c0b12318..2a07d65a 100644 --- a/launcher/net/HttpMetaCache.h +++ b/launcher/net/HttpMetaCache.h @@ -113,6 +113,7 @@ class HttpMetaCache : public QObject { // evict selected entry from cache auto evictEntry(MetaEntryPtr entry) -> bool; + void evictAll(); void addBase(QString base, QString base_root); diff --git a/launcher/ui/MainWindow.cpp b/launcher/ui/MainWindow.cpp index 5729b44d..bd53b532 100644 --- a/launcher/ui/MainWindow.cpp +++ b/launcher/ui/MainWindow.cpp @@ -258,6 +258,7 @@ public: QMenu * helpMenu = nullptr; TranslatedToolButton helpMenuButton; + TranslatedAction actionClearMetadata; TranslatedAction actionReportBug; TranslatedAction actionDISCORD; TranslatedAction actionMATRIX; @@ -347,6 +348,13 @@ public: actionUndoTrashInstance->setShortcut(QKeySequence("Ctrl+Z")); all_actions.append(&actionUndoTrashInstance); + actionClearMetadata = TranslatedAction(MainWindow); + actionClearMetadata->setObjectName(QStringLiteral("actionClearMetadata")); + actionClearMetadata->setIcon(APPLICATION->getThemedIcon("refresh")); + actionClearMetadata.setTextId(QT_TRANSLATE_NOOP("MainWindow", "&Clear Metadata Cache")); + actionClearMetadata.setTooltipId(QT_TRANSLATE_NOOP("MainWindow", "Clear cached metadata")); + all_actions.append(&actionClearMetadata); + if (!BuildConfig.BUG_TRACKER_URL.isEmpty()) { actionReportBug = TranslatedAction(MainWindow); actionReportBug->setObjectName(QStringLiteral("actionReportBug")); @@ -445,6 +453,8 @@ public: helpMenu = new QMenu(MainWindow); helpMenu->setToolTipsVisible(true); + helpMenu->addAction(actionClearMetadata); + if (!BuildConfig.BUG_TRACKER_URL.isEmpty()) { helpMenu->addAction(actionReportBug); } @@ -537,6 +547,8 @@ public: helpMenu = menuBar->addMenu(tr("&Help")); helpMenu->setSeparatorsCollapsible(false); + helpMenu->addAction(actionClearMetadata); + helpMenu->addSeparator(); helpMenu->addAction(actionAbout); helpMenu->addAction(actionOpenWiki); helpMenu->addAction(actionNewsMenuBar); @@ -1980,6 +1992,11 @@ void MainWindow::on_actionReportBug_triggered() DesktopServices::openUrl(QUrl(BuildConfig.BUG_TRACKER_URL)); } +void MainWindow::on_actionClearMetadata_triggered() +{ + APPLICATION->metacache()->evictAll(); +} + void MainWindow::on_actionOpenWiki_triggered() { DesktopServices::openUrl(QUrl(BuildConfig.HELP_URL.arg(""))); diff --git a/launcher/ui/MainWindow.h b/launcher/ui/MainWindow.h index 8b41bf94..d01f0448 100644 --- a/launcher/ui/MainWindow.h +++ b/launcher/ui/MainWindow.h @@ -130,6 +130,8 @@ private slots: void on_actionReportBug_triggered(); + void on_actionClearMetadata_triggered(); + void on_actionOpenWiki_triggered(); void on_actionMoreNews_triggered(); From 93a2e0f777668b12fe4f678d1def5deafd11f101 Mon Sep 17 00:00:00 2001 From: Tayou Date: Mon, 10 Oct 2022 23:20:21 +0200 Subject: [PATCH 039/101] Merge Launch Buttons Signed-off-by: Tayou --- launcher/ui/MainWindow.cpp | 19 +++---------------- 1 file changed, 3 insertions(+), 16 deletions(-) diff --git a/launcher/ui/MainWindow.cpp b/launcher/ui/MainWindow.cpp index 5729b44d..efd6b398 100644 --- a/launcher/ui/MainWindow.cpp +++ b/launcher/ui/MainWindow.cpp @@ -792,7 +792,6 @@ public: instanceToolBar->addSeparator(); instanceToolBar->addAction(actionLaunchInstance); - instanceToolBar->addAction(actionLaunchInstanceOffline); instanceToolBar->addAction(actionKillInstance); instanceToolBar->addSeparator(); @@ -1197,7 +1196,6 @@ void MainWindow::updateMainToolBar() void MainWindow::updateToolsMenu() { QToolButton *launchButton = dynamic_cast(ui->instanceToolBar->widgetForAction(ui->actionLaunchInstance)); - QToolButton *launchOfflineButton = dynamic_cast(ui->instanceToolBar->widgetForAction(ui->actionLaunchInstanceOffline)); bool currentInstanceRunning = m_selectedInstance && m_selectedInstance->isRunning(); @@ -1206,9 +1204,7 @@ void MainWindow::updateToolsMenu() ui->actionLaunchInstanceDemo->setDisabled(!m_selectedInstance || currentInstanceRunning); QMenu *launchMenu = ui->actionLaunchInstance->menu(); - QMenu *launchOfflineMenu = ui->actionLaunchInstanceOffline->menu(); launchButton->setPopupMode(QToolButton::MenuButtonPopup); - launchOfflineButton->setPopupMode(QToolButton::MenuButtonPopup); if (launchMenu) { launchMenu->clear(); @@ -1217,19 +1213,12 @@ void MainWindow::updateToolsMenu() { launchMenu = new QMenu(this); } - if (launchOfflineMenu) { - launchOfflineMenu->clear(); - } - else - { - launchOfflineMenu = new QMenu(this); - } QAction *normalLaunch = launchMenu->addAction(tr("Launch")); normalLaunch->setShortcut(QKeySequence::Open); - QAction *normalLaunchOffline = launchOfflineMenu->addAction(tr("Launch Offline")); + QAction *normalLaunchOffline = launchMenu->addAction(tr("Launch Offline")); normalLaunchOffline->setShortcut(QKeySequence(tr("Ctrl+Shift+O"))); - QAction *normalLaunchDemo = launchOfflineMenu->addAction(tr("Launch Demo")); + QAction *normalLaunchDemo = launchMenu->addAction(tr("Launch Demo")); normalLaunchDemo->setShortcut(QKeySequence(tr("Ctrl+Alt+O"))); if (m_selectedInstance) { @@ -1262,11 +1251,10 @@ void MainWindow::updateToolsMenu() QString profilersTitle = tr("Profilers"); launchMenu->addSeparator()->setText(profilersTitle); - launchOfflineMenu->addSeparator()->setText(profilersTitle); for (auto profiler : APPLICATION->profilers().values()) { QAction *profilerAction = launchMenu->addAction(profiler->name()); - QAction *profilerOfflineAction = launchOfflineMenu->addAction(profiler->name()); + QAction *profilerOfflineAction = launchMenu->addAction(profiler->name() + " Offline"); QString error; if (!profiler->check(&error)) { @@ -1297,7 +1285,6 @@ void MainWindow::updateToolsMenu() } } ui->actionLaunchInstance->setMenu(launchMenu); - ui->actionLaunchInstanceOffline->setMenu(launchOfflineMenu); } void MainWindow::repopulateAccountsMenu() From aaba99dc10acc6585caae18afc87a33053b55e4b Mon Sep 17 00:00:00 2001 From: Tayou <31988415+TayouVR@users.noreply.github.com> Date: Tue, 11 Oct 2022 14:58:34 +0200 Subject: [PATCH 040/101] Update launcher/ui/MainWindow.cpp make " Offline" string for profilers translatable Co-authored-by: Sefa Eyeoglu Signed-off-by: Tayou <31988415+TayouVR@users.noreply.github.com> --- launcher/ui/MainWindow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/launcher/ui/MainWindow.cpp b/launcher/ui/MainWindow.cpp index efd6b398..124de8e3 100644 --- a/launcher/ui/MainWindow.cpp +++ b/launcher/ui/MainWindow.cpp @@ -1254,7 +1254,7 @@ void MainWindow::updateToolsMenu() for (auto profiler : APPLICATION->profilers().values()) { QAction *profilerAction = launchMenu->addAction(profiler->name()); - QAction *profilerOfflineAction = launchMenu->addAction(profiler->name() + " Offline"); + QAction *profilerOfflineAction = launchMenu->addAction(tr("%1 Offline").arg(profiler->name())); QString error; if (!profiler->check(&error)) { From d194b02e28132df3ea3da961299e969614b8a185 Mon Sep 17 00:00:00 2001 From: flow Date: Tue, 11 Oct 2022 14:19:29 -0300 Subject: [PATCH 041/101] fix: prevent images overriding content when changing pages Signed-off-by: flow --- launcher/ui/pages/modplatform/ModPage.cpp | 1 + .../pages/modplatform/modrinth/ModrinthPage.cpp | 1 + launcher/ui/widgets/ProjectDescriptionPage.cpp | 6 ++++++ launcher/ui/widgets/ProjectDescriptionPage.h | 8 ++++++++ launcher/ui/widgets/VariableSizedImageObject.cpp | 13 +++++++++++-- launcher/ui/widgets/VariableSizedImageObject.h | 15 ++++++++++++--- 6 files changed, 39 insertions(+), 5 deletions(-) diff --git a/launcher/ui/pages/modplatform/ModPage.cpp b/launcher/ui/pages/modplatform/ModPage.cpp index 4fce0242..153bb049 100644 --- a/launcher/ui/pages/modplatform/ModPage.cpp +++ b/launcher/ui/pages/modplatform/ModPage.cpp @@ -350,4 +350,5 @@ void ModPage::updateUi() HoeDown h; ui->packDescription->setHtml(text + (current.extraData.body.isEmpty() ? current.description : h.process(current.extraData.body.toUtf8()))); + ui->packDescription->flush(); } diff --git a/launcher/ui/pages/modplatform/modrinth/ModrinthPage.cpp b/launcher/ui/pages/modplatform/modrinth/ModrinthPage.cpp index 70f1388a..4482774c 100644 --- a/launcher/ui/pages/modplatform/modrinth/ModrinthPage.cpp +++ b/launcher/ui/pages/modplatform/modrinth/ModrinthPage.cpp @@ -284,6 +284,7 @@ void ModrinthPage::updateUI() text += h.process(current.extra.body.toUtf8()); ui->packDescription->setHtml(text + current.description); + ui->packDescription->flush(); } void ModrinthPage::suggestCurrent() diff --git a/launcher/ui/widgets/ProjectDescriptionPage.cpp b/launcher/ui/widgets/ProjectDescriptionPage.cpp index 2e6f6d97..c7e79a17 100644 --- a/launcher/ui/widgets/ProjectDescriptionPage.cpp +++ b/launcher/ui/widgets/ProjectDescriptionPage.cpp @@ -15,3 +15,9 @@ void ProjectDescriptionPage::setMetaEntry(QString entry) if (m_image_text_object) m_image_text_object->setMetaEntry(entry); } + +void ProjectDescriptionPage::flush() +{ + if (m_image_text_object) + m_image_text_object->flush(); +} diff --git a/launcher/ui/widgets/ProjectDescriptionPage.h b/launcher/ui/widgets/ProjectDescriptionPage.h index 8387d3fb..3dd85302 100644 --- a/launcher/ui/widgets/ProjectDescriptionPage.h +++ b/launcher/ui/widgets/ProjectDescriptionPage.h @@ -19,6 +19,14 @@ class ProjectDescriptionPage final : public QTextBrowser { void setMetaEntry(QString entry); + public slots: + /** Flushes the current processing happening in the page. + * + * Should be called when changing the page's content entirely, to + * prevent old tasks from changing the new content. + */ + void flush(); + private: shared_qobject_ptr m_image_text_object; }; diff --git a/launcher/ui/widgets/VariableSizedImageObject.cpp b/launcher/ui/widgets/VariableSizedImageObject.cpp index 0efdecab..e57f7e95 100644 --- a/launcher/ui/widgets/VariableSizedImageObject.cpp +++ b/launcher/ui/widgets/VariableSizedImageObject.cpp @@ -66,6 +66,11 @@ void VariableSizedImageObject::drawObject(QPainter* painter, painter->drawImage(rect, image); } +void VariableSizedImageObject::flush() +{ + m_fetching_images.clear(); +} + void VariableSizedImageObject::parseImage(QTextDocument* doc, QImage image, int posInDocument) { QTextCursor cursor(doc); @@ -85,7 +90,7 @@ void VariableSizedImageObject::parseImage(QTextDocument* doc, QImage image, int void VariableSizedImageObject::loadImage(QTextDocument* doc, const QUrl& source, int posInDocument) { - m_fetching_images.append(source); + m_fetching_images.insert(source); MetaEntryPtr entry = APPLICATION->metacache()->resolveEntry( m_meta_entry, @@ -99,6 +104,10 @@ void VariableSizedImageObject::loadImage(QTextDocument* doc, const QUrl& source, connect(job, &NetJob::succeeded, [this, doc, full_entry_path, source_url, posInDocument] { qDebug() << "Loaded resource at" << full_entry_path; + // If we flushed, don't proceed. + if (!m_fetching_images.contains(source_url)) + return; + QImage image(full_entry_path); doc->addResource(QTextDocument::ImageResource, source_url, image); @@ -110,7 +119,7 @@ void VariableSizedImageObject::loadImage(QTextDocument* doc, const QUrl& source, doc->adjustSize(); doc->setPageSize(size); - m_fetching_images.removeOne(source_url); + m_fetching_images.remove(source_url); }); connect(job, &NetJob::finished, job, &NetJob::deleteLater); diff --git a/launcher/ui/widgets/VariableSizedImageObject.h b/launcher/ui/widgets/VariableSizedImageObject.h index 11563a37..137487ee 100644 --- a/launcher/ui/widgets/VariableSizedImageObject.h +++ b/launcher/ui/widgets/VariableSizedImageObject.h @@ -28,7 +28,7 @@ * Why? Because we want to re-scale images dynamically based on the document's size, in order to * not have images being weirdly cropped out in different resolutions. */ -class VariableSizedImageObject : public QObject, public QTextObjectInterface { +class VariableSizedImageObject final : public QObject, public QTextObjectInterface { Q_OBJECT Q_INTERFACES(QTextObjectInterface) @@ -38,7 +38,15 @@ class VariableSizedImageObject : public QObject, public QTextObjectInterface { void setMetaEntry(QString meta_entry) { m_meta_entry = meta_entry; } - protected: + public slots: + /** Stops all currently loading images from modifying the document. + * + * This does not stop the ongoing network tasks, it only prevents their result + * from impacting the document any further. + */ + void flush(); + + private: /** Adds the image to the document, in the given position. */ void parseImage(QTextDocument* doc, QImage image, int posInDocument); @@ -49,7 +57,8 @@ class VariableSizedImageObject : public QObject, public QTextObjectInterface { */ void loadImage(QTextDocument* doc, const QUrl& source, int posInDocument); + private: QString m_meta_entry; - QList m_fetching_images; + QSet m_fetching_images; }; From fda3f1352e203bc119f092e30b25356345342c18 Mon Sep 17 00:00:00 2001 From: flow Date: Tue, 11 Oct 2022 16:11:08 -0300 Subject: [PATCH 042/101] feat: add image support for the news reader :^) Signed-off-by: flow --- launcher/ui/dialogs/NewsDialog.cpp | 4 ++++ launcher/ui/dialogs/NewsDialog.ui | 9 ++++++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/launcher/ui/dialogs/NewsDialog.cpp b/launcher/ui/dialogs/NewsDialog.cpp index d3b21627..e1b5dd74 100644 --- a/launcher/ui/dialogs/NewsDialog.cpp +++ b/launcher/ui/dialogs/NewsDialog.cpp @@ -20,7 +20,9 @@ NewsDialog::NewsDialog(QList entries, QWidget* parent) : QDialog(p auto article_entry = m_entries.constFind(first_item->text()).value(); ui->articleTitleLabel->setText(QString("
%2").arg(article_entry->link, first_item->text())); + ui->currentArticleContentBrowser->setText(article_entry->content); + ui->currentArticleContentBrowser->flush(); } NewsDialog::~NewsDialog() @@ -33,7 +35,9 @@ void NewsDialog::selectedArticleChanged(const QString& new_title) auto const& article_entry = m_entries.constFind(new_title).value(); ui->articleTitleLabel->setText(QString("%2").arg(article_entry->link, new_title)); + ui->currentArticleContentBrowser->setText(article_entry->content); + ui->currentArticleContentBrowser->flush(); } void NewsDialog::toggleArticleList() diff --git a/launcher/ui/dialogs/NewsDialog.ui b/launcher/ui/dialogs/NewsDialog.ui index 2aaa08f1..08f35a0b 100644 --- a/launcher/ui/dialogs/NewsDialog.ui +++ b/launcher/ui/dialogs/NewsDialog.ui @@ -49,7 +49,7 @@ - + Qt::LinksAccessibleByKeyboard|Qt::LinksAccessibleByMouse|Qt::TextBrowserInteraction|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse @@ -91,6 +91,13 @@ + + + ProjectDescriptionPage + QTextBrowser +
ui/widgets/ProjectDescriptionPage.h
+
+
From b2a5d8daf4e006e11c9bc67b10a88f9f5f51ba54 Mon Sep 17 00:00:00 2001 From: flow Date: Wed, 12 Oct 2022 10:26:14 -0300 Subject: [PATCH 043/101] fix: don't include opted out versions with the 'Any' filter on the MD Signed-off-by: flow --- launcher/ui/pages/modplatform/ModPage.cpp | 4 +++- launcher/ui/pages/modplatform/ModPage.h | 1 + launcher/ui/pages/modplatform/flame/FlameModPage.cpp | 5 +++++ launcher/ui/pages/modplatform/flame/FlameModPage.h | 1 + 4 files changed, 10 insertions(+), 1 deletion(-) diff --git a/launcher/ui/pages/modplatform/ModPage.cpp b/launcher/ui/pages/modplatform/ModPage.cpp index 4fce0242..2af9a10a 100644 --- a/launcher/ui/pages/modplatform/ModPage.cpp +++ b/launcher/ui/pages/modplatform/ModPage.cpp @@ -265,7 +265,9 @@ void ModPage::updateModVersions(int prev_count) break; } } - if(valid || m_filter->versions.size() == 0) + + // Only add the version if it's valid or using the 'Any' filter, but never if the version is opted out + if ((valid || m_filter->versions.empty()) && !optedOut(version)) ui->versionSelectionBox->addItem(version.version, QVariant(i)); } if (ui->versionSelectionBox->count() == 0 && prev_count != 0) { diff --git a/launcher/ui/pages/modplatform/ModPage.h b/launcher/ui/pages/modplatform/ModPage.h index 3f31651c..ae3d7e77 100644 --- a/launcher/ui/pages/modplatform/ModPage.h +++ b/launcher/ui/pages/modplatform/ModPage.h @@ -51,6 +51,7 @@ class ModPage : public QWidget, public BasePage { auto shouldDisplay() const -> bool override = 0; virtual auto validateVersion(ModPlatform::IndexedVersion& ver, QString mineVer, ModAPI::ModLoaderTypes loaders = ModAPI::Unspecified) const -> bool = 0; + virtual bool optedOut(ModPlatform::IndexedVersion& ver) const { return false; }; auto apiProvider() -> ModAPI* { return api.get(); }; auto getFilter() const -> const std::shared_ptr { return m_filter; } diff --git a/launcher/ui/pages/modplatform/flame/FlameModPage.cpp b/launcher/ui/pages/modplatform/flame/FlameModPage.cpp index 772fd2e0..54a7be04 100644 --- a/launcher/ui/pages/modplatform/flame/FlameModPage.cpp +++ b/launcher/ui/pages/modplatform/flame/FlameModPage.cpp @@ -67,6 +67,11 @@ auto FlameModPage::validateVersion(ModPlatform::IndexedVersion& ver, QString min return ver.mcVersion.contains(mineVer) && !ver.downloadUrl.isEmpty(); } +bool FlameModPage::optedOut(ModPlatform::IndexedVersion& ver) const +{ + return ver.downloadUrl.isEmpty(); +} + // I don't know why, but doing this on the parent class makes it so that // other mod providers start loading before being selected, at least with // my Qt, so we need to implement this in every derived class... diff --git a/launcher/ui/pages/modplatform/flame/FlameModPage.h b/launcher/ui/pages/modplatform/flame/FlameModPage.h index 2cd484cb..50dedd6f 100644 --- a/launcher/ui/pages/modplatform/flame/FlameModPage.h +++ b/launcher/ui/pages/modplatform/flame/FlameModPage.h @@ -61,6 +61,7 @@ class FlameModPage : public ModPage { inline auto metaEntryBase() const -> QString override { return "FlameMods"; }; auto validateVersion(ModPlatform::IndexedVersion& ver, QString mineVer, ModAPI::ModLoaderTypes loaders = ModAPI::Unspecified) const -> bool override; + bool optedOut(ModPlatform::IndexedVersion& ver) const override; auto shouldDisplay() const -> bool override; }; From 83654a193e8856e00bcdbe4f87d209e52c380a62 Mon Sep 17 00:00:00 2001 From: flow Date: Thu, 13 Oct 2022 13:27:52 -0300 Subject: [PATCH 044/101] refactor+fix: Make FTB install task similar to other install tasks In particular, this changes the order so that the instance gets created before downloading the mods (like other install tasks), and the mod download directly puts the files in the staging folder (like the others), instead of that weird makeCached and copy stuff. This fixes some issues with modpack downloads from FTB, like creating an instance with no mods in it. Signed-off-by: flow --- .../modpacksch/FTBPackInstallTask.cpp | 144 ++++++++---------- .../modpacksch/FTBPackInstallTask.h | 7 +- 2 files changed, 64 insertions(+), 87 deletions(-) diff --git a/launcher/modplatform/modpacksch/FTBPackInstallTask.cpp b/launcher/modplatform/modpacksch/FTBPackInstallTask.cpp index 97ce1dc6..cc926d45 100644 --- a/launcher/modplatform/modpacksch/FTBPackInstallTask.cpp +++ b/launcher/modplatform/modpacksch/FTBPackInstallTask.cpp @@ -58,6 +58,9 @@ PackInstallTask::PackInstallTask(Modpack pack, QString version, QWidget* parent) bool PackInstallTask::abort() { + if (!canAbort()) + return false; + bool aborted = true; if (m_net_job) @@ -65,14 +68,12 @@ bool PackInstallTask::abort() if (m_mod_id_resolver_task) aborted &= m_mod_id_resolver_task->abort(); - if (aborted) - emitAborted(); - - return aborted; + return aborted ? InstanceTask::abort() : false; } void PackInstallTask::executeTask() { + setAbortable(true); setStatus(tr("Getting the manifest...")); // Find pack version @@ -129,6 +130,7 @@ void PackInstallTask::onManifestDownloadSucceeded() void PackInstallTask::resolveMods() { + setAbortable(true); setStatus(tr("Resolving mods...")); setProgress(0, 100); @@ -169,8 +171,6 @@ void PackInstallTask::resolveMods() void PackInstallTask::onResolveModsSucceeded() { - m_abortable = false; - QString text; QList urls; auto anyBlocked = false; @@ -209,94 +209,23 @@ void PackInstallTask::onResolveModsSucceeded() urls); if (message_dialog->exec() == QDialog::Accepted) - downloadPack(); + createInstance(); else abort(); } else { - downloadPack(); + createInstance(); } } -void PackInstallTask::downloadPack() +void PackInstallTask::createInstance() { - setStatus(tr("Downloading mods...")); + setAbortable(false); - auto* jobPtr = new NetJob(tr("Mod download"), APPLICATION->network()); - for (auto const& file : m_version.files) { - if (file.serverOnly || file.url.isEmpty()) - continue; - - QFileInfo file_info(file.name); - auto cacheName = file_info.completeBaseName() + "-" + file.sha1 + "." + file_info.suffix(); - - auto entry = APPLICATION->metacache()->resolveEntry("ModpacksCHPacks", cacheName); - entry->setStale(true); - - auto relpath = FS::PathCombine("minecraft", file.path, file.name); - auto path = FS::PathCombine(m_stagingPath, relpath); - - if (m_files_to_copy.contains(path)) { - qWarning() << "Ignoring" << file.url << "as a file of that path is already downloading."; - continue; - } - - qDebug() << "Will download" << file.url << "to" << path; - m_files_to_copy[path] = entry->getFullPath(); - - auto dl = Net::Download::makeCached(file.url, entry); - if (!file.sha1.isEmpty()) { - auto rawSha1 = QByteArray::fromHex(file.sha1.toLatin1()); - dl->addValidator(new Net::ChecksumValidator(QCryptographicHash::Sha1, rawSha1)); - } - - jobPtr->addNetAction(dl); - } - - connect(jobPtr, &NetJob::succeeded, this, &PackInstallTask::onModDownloadSucceeded); - connect(jobPtr, &NetJob::failed, this, &PackInstallTask::onModDownloadFailed); - connect(jobPtr, &NetJob::progress, this, &PackInstallTask::setProgress); - - m_net_job = jobPtr; - jobPtr->start(); - - m_abortable = true; -} - -void PackInstallTask::onModDownloadSucceeded() -{ - m_net_job.reset(); - install(); -} - -void PackInstallTask::install() -{ - setStatus(tr("Copying modpack files...")); - setProgress(0, m_files_to_copy.size()); - QCoreApplication::processEvents(); - - m_abortable = false; - - int i = 0; - for (auto iter = m_files_to_copy.constBegin(); iter != m_files_to_copy.constEnd(); iter++) { - auto& to = iter.key(); - auto& from = iter.value(); - FS::copy fileCopyOperation(from, to); - if (!fileCopyOperation()) { - qWarning() << "Failed to copy" << from << "to" << to; - emitFailed(tr("Failed to copy files")); - return; - } - - setProgress(i++, m_files_to_copy.size()); - QCoreApplication::processEvents(); - } - - setStatus(tr("Installing modpack...")); + setStatus(tr("Creating the instance...")); QCoreApplication::processEvents(); auto instanceConfigPath = FS::PathCombine(m_stagingPath, "instance.cfg"); auto instanceSettings = std::make_shared(instanceConfigPath); - instanceSettings->suspendSave(); MinecraftInstance instance(m_globalSettings, instanceSettings, m_stagingPath); auto components = instance.getPackProfile(); @@ -337,8 +266,53 @@ void PackInstallTask::install() instance.setName(name()); instance.setIconKey(m_instIcon); instance.setManagedPack("modpacksch", QString::number(m_pack.id), m_pack.name, QString::number(m_version.id), m_version.name); - instanceSettings->resumeSave(); + instance.saveNow(); + + onCreateInstanceSucceeded(); +} + +void PackInstallTask::onCreateInstanceSucceeded() +{ + downloadPack(); +} + +void PackInstallTask::downloadPack() +{ + setAbortable(true); + + setStatus(tr("Downloading mods...")); + + auto* jobPtr = new NetJob(tr("Mod download"), APPLICATION->network()); + for (auto const& file : m_version.files) { + if (file.serverOnly || file.url.isEmpty()) + continue; + + auto path = FS::PathCombine(m_stagingPath, ".minecraft", file.path, file.name); + qDebug() << "Will try to download" << file.url << "to" << path; + + QFileInfo file_info(file.name); + + auto dl = Net::Download::makeFile(file.url, path); + if (!file.sha1.isEmpty()) { + auto rawSha1 = QByteArray::fromHex(file.sha1.toLatin1()); + dl->addValidator(new Net::ChecksumValidator(QCryptographicHash::Sha1, rawSha1)); + } + + jobPtr->addNetAction(dl); + } + + connect(jobPtr, &NetJob::succeeded, this, &PackInstallTask::onModDownloadSucceeded); + connect(jobPtr, &NetJob::failed, this, &PackInstallTask::onModDownloadFailed); + connect(jobPtr, &NetJob::progress, this, &PackInstallTask::setProgress); + + m_net_job = jobPtr; + jobPtr->start(); +} + +void PackInstallTask::onModDownloadSucceeded() +{ + m_net_job.reset(); emitSucceeded(); } @@ -352,6 +326,10 @@ void PackInstallTask::onResolveModsFailed(QString reason) m_net_job.reset(); emitFailed(reason); } +void PackInstallTask::onCreateInstanceFailed(QString reason) +{ + emitFailed(reason); +} void PackInstallTask::onModDownloadFailed(QString reason) { m_net_job.reset(); diff --git a/launcher/modplatform/modpacksch/FTBPackInstallTask.h b/launcher/modplatform/modpacksch/FTBPackInstallTask.h index e63ca0df..7c6fbeb9 100644 --- a/launcher/modplatform/modpacksch/FTBPackInstallTask.h +++ b/launcher/modplatform/modpacksch/FTBPackInstallTask.h @@ -56,7 +56,6 @@ public: explicit PackInstallTask(Modpack pack, QString version, QWidget* parent = nullptr); ~PackInstallTask() override = default; - bool canAbort() const override { return m_abortable; } bool abort() override; protected: @@ -65,20 +64,20 @@ protected: private slots: void onManifestDownloadSucceeded(); void onResolveModsSucceeded(); + void onCreateInstanceSucceeded(); void onModDownloadSucceeded(); void onManifestDownloadFailed(QString reason); void onResolveModsFailed(QString reason); + void onCreateInstanceFailed(QString reason); void onModDownloadFailed(QString reason); private: void resolveMods(); + void createInstance(); void downloadPack(); - void install(); private: - bool m_abortable = true; - NetJob::Ptr m_net_job = nullptr; shared_qobject_ptr m_mod_id_resolver_task = nullptr; From f26be005716818b643a0c8b1373dbe83e4cdcfbf Mon Sep 17 00:00:00 2001 From: flow Date: Thu, 13 Oct 2022 13:49:06 -0300 Subject: [PATCH 045/101] fix: abort search if we're already trying to download a pack Meaning we don't have to wait for the searches to finish in the background to finally start the modpack download, when we have already selected it -_- Signed-off-by: flow --- launcher/ui/dialogs/NewInstanceDialog.cpp | 8 ++++++++ launcher/ui/pages/modplatform/ftb/FtbListModel.cpp | 11 +++++++++++ launcher/ui/pages/modplatform/ftb/FtbListModel.h | 5 +++++ launcher/ui/pages/modplatform/ftb/FtbPage.cpp | 6 ++++++ launcher/ui/pages/modplatform/ftb/FtbPage.h | 1 + 5 files changed, 31 insertions(+) diff --git a/launcher/ui/dialogs/NewInstanceDialog.cpp b/launcher/ui/dialogs/NewInstanceDialog.cpp index d203795a..df182f09 100644 --- a/launcher/ui/dialogs/NewInstanceDialog.cpp +++ b/launcher/ui/dialogs/NewInstanceDialog.cpp @@ -139,6 +139,10 @@ NewInstanceDialog::NewInstanceDialog(const QString & initialGroup, const QString void NewInstanceDialog::reject() { APPLICATION->settings()->set("NewInstanceGeometry", saveGeometry().toBase64()); + + // This is just so that the pages get the close() call and can react to it, if needed. + m_container->prepareToClose(); + QDialog::reject(); } @@ -146,6 +150,10 @@ void NewInstanceDialog::accept() { APPLICATION->settings()->set("NewInstanceGeometry", saveGeometry().toBase64()); importIconNow(); + + // This is just so that the pages get the close() call and can react to it, if needed. + m_container->prepareToClose(); + QDialog::accept(); } diff --git a/launcher/ui/pages/modplatform/ftb/FtbListModel.cpp b/launcher/ui/pages/modplatform/ftb/FtbListModel.cpp index ad15b6e6..3a149944 100644 --- a/launcher/ui/pages/modplatform/ftb/FtbListModel.cpp +++ b/launcher/ui/pages/modplatform/ftb/FtbListModel.cpp @@ -103,6 +103,8 @@ void ListModel::getLogo(const QString &logo, const QString &logoUrl, LogoCallbac void ListModel::request() { + m_aborted = false; + beginResetModel(); modpacks.clear(); endResetModel(); @@ -117,6 +119,12 @@ void ListModel::request() QObject::connect(netJob, &NetJob::failed, this, &ListModel::requestFailed); } +void ListModel::abortRequest() +{ + m_aborted = jobPtr->abort(); + jobPtr.reset(); +} + void ListModel::requestFinished() { jobPtr.reset(); @@ -162,6 +170,9 @@ void ListModel::requestPack() void ListModel::packRequestFinished() { + if (!jobPtr || m_aborted) + return; + jobPtr.reset(); remainingPacks.removeOne(currentPack); diff --git a/launcher/ui/pages/modplatform/ftb/FtbListModel.h b/launcher/ui/pages/modplatform/ftb/FtbListModel.h index 314cb789..cbf215c4 100644 --- a/launcher/ui/pages/modplatform/ftb/FtbListModel.h +++ b/launcher/ui/pages/modplatform/ftb/FtbListModel.h @@ -47,9 +47,12 @@ public: QVariant data(const QModelIndex &index, int role) const override; void request(); + void abortRequest(); void getLogo(const QString &logo, const QString &logoUrl, LogoCallback callback); + [[nodiscard]] bool isMakingRequest() const { return jobPtr.get(); } + private slots: void requestFinished(); void requestFailed(QString reason); @@ -65,6 +68,8 @@ private: void requestLogo(QString file, QString url); private: + bool m_aborted = false; + QList modpacks; LogoMap m_logoMap; diff --git a/launcher/ui/pages/modplatform/ftb/FtbPage.cpp b/launcher/ui/pages/modplatform/ftb/FtbPage.cpp index 8975d74e..1fe28124 100644 --- a/launcher/ui/pages/modplatform/ftb/FtbPage.cpp +++ b/launcher/ui/pages/modplatform/ftb/FtbPage.cpp @@ -114,6 +114,12 @@ void FtbPage::openedImpl() suggestCurrent(); } +void FtbPage::closedImpl() +{ + if (listModel->isMakingRequest()) + listModel->abortRequest(); +} + void FtbPage::suggestCurrent() { if(!isOpened) diff --git a/launcher/ui/pages/modplatform/ftb/FtbPage.h b/launcher/ui/pages/modplatform/ftb/FtbPage.h index 90c8e7fd..631ae7f5 100644 --- a/launcher/ui/pages/modplatform/ftb/FtbPage.h +++ b/launcher/ui/pages/modplatform/ftb/FtbPage.h @@ -78,6 +78,7 @@ public: void retranslate() override; void openedImpl() override; + void closedImpl() override; bool eventFilter(QObject * watched, QEvent * event) override; From dfa220ef02f23ff734dec6247f4a124a7a144c7a Mon Sep 17 00:00:00 2001 From: flow Date: Thu, 13 Oct 2022 15:10:35 -0300 Subject: [PATCH 046/101] fix: issues with aborts (again) i hate it Signed-off-by: flow --- launcher/modplatform/flame/FileResolvingTask.cpp | 5 +++-- .../modplatform/modpacksch/FTBPackInstallTask.cpp | 15 +++++++++++---- launcher/ui/dialogs/ProgressDialog.cpp | 5 +++-- launcher/ui/pages/modplatform/ftb/FtbListModel.h | 1 + launcher/ui/pages/modplatform/ftb/FtbPage.cpp | 2 +- 5 files changed, 19 insertions(+), 9 deletions(-) diff --git a/launcher/modplatform/flame/FileResolvingTask.cpp b/launcher/modplatform/flame/FileResolvingTask.cpp index 058d2471..1e7f5559 100644 --- a/launcher/modplatform/flame/FileResolvingTask.cpp +++ b/launcher/modplatform/flame/FileResolvingTask.cpp @@ -9,9 +9,10 @@ Flame::FileResolvingTask::FileResolvingTask(const shared_qobject_ptrabort(); - return true; + aborted &= m_dljob->abort(); + return aborted ? Task::abort() : false; } void Flame::FileResolvingTask::executeTask() diff --git a/launcher/modplatform/modpacksch/FTBPackInstallTask.cpp b/launcher/modplatform/modpacksch/FTBPackInstallTask.cpp index cc926d45..7b112d8f 100644 --- a/launcher/modplatform/modpacksch/FTBPackInstallTask.cpp +++ b/launcher/modplatform/modpacksch/FTBPackInstallTask.cpp @@ -73,8 +73,8 @@ bool PackInstallTask::abort() void PackInstallTask::executeTask() { - setAbortable(true); setStatus(tr("Getting the manifest...")); + setAbortable(false); // Find pack version auto version_it = std::find_if(m_pack.versions.constBegin(), m_pack.versions.constEnd(), @@ -94,10 +94,12 @@ void PackInstallTask::executeTask() QObject::connect(netJob, &NetJob::succeeded, this, &PackInstallTask::onManifestDownloadSucceeded); QObject::connect(netJob, &NetJob::failed, this, &PackInstallTask::onManifestDownloadFailed); + QObject::connect(netJob, &NetJob::aborted, this, &PackInstallTask::abort); QObject::connect(netJob, &NetJob::progress, this, &PackInstallTask::setProgress); m_net_job = netJob; + setAbortable(true); netJob->start(); } @@ -130,8 +132,8 @@ void PackInstallTask::onManifestDownloadSucceeded() void PackInstallTask::resolveMods() { - setAbortable(true); setStatus(tr("Resolving mods...")); + setAbortable(false); setProgress(0, 100); m_file_id_map.clear(); @@ -164,8 +166,11 @@ void PackInstallTask::resolveMods() connect(m_mod_id_resolver_task.get(), &Flame::FileResolvingTask::succeeded, this, &PackInstallTask::onResolveModsSucceeded); connect(m_mod_id_resolver_task.get(), &Flame::FileResolvingTask::failed, this, &PackInstallTask::onResolveModsFailed); + connect(m_mod_id_resolver_task.get(), &Flame::FileResolvingTask::aborted, this, &PackInstallTask::abort); connect(m_mod_id_resolver_task.get(), &Flame::FileResolvingTask::progress, this, &PackInstallTask::setProgress); + setAbortable(true); + m_mod_id_resolver_task->start(); } @@ -279,9 +284,8 @@ void PackInstallTask::onCreateInstanceSucceeded() void PackInstallTask::downloadPack() { - setAbortable(true); - setStatus(tr("Downloading mods...")); + setAbortable(false); auto* jobPtr = new NetJob(tr("Mod download"), APPLICATION->network()); for (auto const& file : m_version.files) { @@ -304,9 +308,12 @@ void PackInstallTask::downloadPack() connect(jobPtr, &NetJob::succeeded, this, &PackInstallTask::onModDownloadSucceeded); connect(jobPtr, &NetJob::failed, this, &PackInstallTask::onModDownloadFailed); + connect(jobPtr, &NetJob::aborted, this, &PackInstallTask::abort); connect(jobPtr, &NetJob::progress, this, &PackInstallTask::setProgress); m_net_job = jobPtr; + + setAbortable(true); jobPtr->start(); } diff --git a/launcher/ui/dialogs/ProgressDialog.cpp b/launcher/ui/dialogs/ProgressDialog.cpp index 258a32e4..68dd4d17 100644 --- a/launcher/ui/dialogs/ProgressDialog.cpp +++ b/launcher/ui/dialogs/ProgressDialog.cpp @@ -25,6 +25,7 @@ ProgressDialog::ProgressDialog(QWidget* parent) : QDialog(parent), ui(new Ui::Pr { ui->setupUi(this); this->setWindowFlags(this->windowFlags() & ~Qt::WindowContextHelpButtonHint); + setAttribute(Qt::WidgetAttribute::WA_QuitOnClose, true); setSkipButton(false); changeProgress(0, 100); } @@ -67,7 +68,7 @@ int ProgressDialog::execWithTask(Task* task) return QDialog::DialogCode::Accepted; } - QDialog::DialogCode result; + QDialog::DialogCode result {}; if (handleImmediateResult(result)) { return result; } @@ -80,7 +81,7 @@ int ProgressDialog::execWithTask(Task* task) connect(task, &Task::stepStatus, this, &ProgressDialog::changeStatus); connect(task, &Task::progress, this, &ProgressDialog::changeProgress); - connect(task, &Task::aborted, [this] { QDialog::reject(); }); + connect(task, &Task::aborted, this, &ProgressDialog::hide); connect(task, &Task::abortStatusChanged, ui->skipButton, &QPushButton::setEnabled); m_is_multi_step = task->isMultiStep(); diff --git a/launcher/ui/pages/modplatform/ftb/FtbListModel.h b/launcher/ui/pages/modplatform/ftb/FtbListModel.h index cbf215c4..d7a120f0 100644 --- a/launcher/ui/pages/modplatform/ftb/FtbListModel.h +++ b/launcher/ui/pages/modplatform/ftb/FtbListModel.h @@ -52,6 +52,7 @@ public: void getLogo(const QString &logo, const QString &logoUrl, LogoCallback callback); [[nodiscard]] bool isMakingRequest() const { return jobPtr.get(); } + [[nodiscard]] bool wasAborted() const { return m_aborted; } private slots: void requestFinished(); diff --git a/launcher/ui/pages/modplatform/ftb/FtbPage.cpp b/launcher/ui/pages/modplatform/ftb/FtbPage.cpp index 1fe28124..34a3d1c0 100644 --- a/launcher/ui/pages/modplatform/ftb/FtbPage.cpp +++ b/launcher/ui/pages/modplatform/ftb/FtbPage.cpp @@ -105,7 +105,7 @@ void FtbPage::retranslate() void FtbPage::openedImpl() { - if(!initialised) + if(!initialised || listModel->wasAborted()) { listModel->request(); initialised = true; From 2901039a485c27c686ebadebf8b67a5126ce9df0 Mon Sep 17 00:00:00 2001 From: DioEgizio <83089242+DioEgizio@users.noreply.github.com> Date: Sat, 1 Oct 2022 09:19:59 +0200 Subject: [PATCH 047/101] feat(actions): macOS-Legacy package still no updater part though Signed-off-by: DioEgizio <83089242+DioEgizio@users.noreply.github.com> --- .github/workflows/build.yml | 22 ++++++++++++++++++---- .github/workflows/trigger_release.yml | 2 ++ 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 6a9f393c..1740f12a 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -39,12 +39,21 @@ jobs: qt_ver: 6 - os: macos-12 + name: macOS macosx_deployment_target: 10.15 qt_ver: 6 qt_host: mac qt_version: '6.3.0' qt_modules: 'qt5compat qtimageformats' + - os: macos-12 + name: macOS-Legacy + macosx_deployment_target: 10.13 + qt_ver: 5 + qt_host: mac + qt_version: '5.15.2' + qt_modules: '' + runs-on: ${{ matrix.os }} env: @@ -148,7 +157,7 @@ jobs: sudo apt-get -y install qtbase5-dev qtchooser qt5-qmake qtbase5-dev-tools libqt5core5a libqt5network5 libqt5gui5 - name: Install Qt (macOS and AppImage) - if: matrix.qt_ver == 6 && runner.os != 'Windows' + if: runner.os == 'Linux' && matrix.qt_ver == 6 || runner.os == 'macOS' uses: jurplel/install-qt-action@v3 with: version: ${{ matrix.qt_version }} @@ -172,9 +181,14 @@ jobs: ## - name: Configure CMake (macOS) - if: runner.os == 'macOS' + if: runner.os == 'macOS' && matrix.qt_ver == 6 run: | - cmake -S . -B ${{ env.BUILD_DIR }} -DCMAKE_INSTALL_PREFIX=${{ env.INSTALL_DIR }} -DCMAKE_BUILD_TYPE=${{ inputs.build_type }} -DENABLE_LTO=ON -DCMAKE_OSX_ARCHITECTURES="x86_64;arm64" -DLauncher_BUILD_PLATFORM=macOS -DCMAKE_C_COMPILER_LAUNCHER=${{ env.CCACHE_VAR }} -DCMAKE_CXX_COMPILER_LAUNCHER=${{ env.CCACHE_VAR }} -DLauncher_QT_VERSION_MAJOR=${{ matrix.qt_ver }} -G Ninja + cmake -S . -B ${{ env.BUILD_DIR }} -DCMAKE_INSTALL_PREFIX=${{ env.INSTALL_DIR }} -DCMAKE_BUILD_TYPE=${{ inputs.build_type }} -DENABLE_LTO=ON -DLauncher_BUILD_PLATFORM=${{ matrix.name }} -DCMAKE_C_COMPILER_LAUNCHER=${{ env.CCACHE_VAR }} -DCMAKE_CXX_COMPILER_LAUNCHER=${{ env.CCACHE_VAR }} -DLauncher_QT_VERSION_MAJOR=${{ matrix.qt_ver }} -DCMAKE_OSX_ARCHITECTURES="x86_64;arm64" -G Ninja + + - name: Configure CMake (macOS-Legacy) + if: runner.os == 'macOS' && matrix.qt_ver == 5 + run: | + cmake -S . -B ${{ env.BUILD_DIR }} -DCMAKE_INSTALL_PREFIX=${{ env.INSTALL_DIR }} -DCMAKE_BUILD_TYPE=${{ inputs.build_type }} -DENABLE_LTO=ON -DLauncher_BUILD_PLATFORM=${{ matrix.name }} -DCMAKE_C_COMPILER_LAUNCHER=${{ env.CCACHE_VAR }} -DCMAKE_CXX_COMPILER_LAUNCHER=${{ env.CCACHE_VAR }} -DLauncher_QT_VERSION_MAJOR=${{ matrix.qt_ver }} -G Ninja - name: Configure CMake (Windows) if: runner.os == 'Windows' @@ -339,7 +353,7 @@ jobs: if: runner.os == 'macOS' uses: actions/upload-artifact@v3 with: - name: PolyMC-${{ runner.os }}-${{ env.VERSION }}-${{ inputs.build_type }} + name: PolyMC-${{ matrix.name }}-${{ env.VERSION }}-${{ inputs.build_type }} path: PolyMC.tar.gz - name: Upload binary zip (Windows) diff --git a/.github/workflows/trigger_release.yml b/.github/workflows/trigger_release.yml index 45ef7281..71180d7a 100644 --- a/.github/workflows/trigger_release.yml +++ b/.github/workflows/trigger_release.yml @@ -40,6 +40,7 @@ jobs: mv PolyMC-Linux-Portable*/PolyMC-portable.tar.gz PolyMC-Linux-Portable-${{ env.VERSION }}.tar.gz mv PolyMC-Linux*/PolyMC.tar.gz PolyMC-Linux-${{ env.VERSION }}.tar.gz mv PolyMC-*.AppImage/PolyMC-*.AppImage PolyMC-Linux-${{ env.VERSION }}-x86_64.AppImage + mv PolyMC-macOS-Legacy*/PolyMC.tar.gz PolyMC-macOS-Legacy-${{ env.VERSION }}.tar.gz mv PolyMC-macOS*/PolyMC.tar.gz PolyMC-macOS-${{ env.VERSION }}.tar.gz tar -czf PolyMC-${{ env.VERSION }}.tar.gz PolyMC-${{ env.VERSION }} @@ -80,4 +81,5 @@ jobs: PolyMC-Windows-Portable-${{ env.VERSION }}.zip PolyMC-Windows-Setup-${{ env.VERSION }}.exe PolyMC-macOS-${{ env.VERSION }}.tar.gz + PolyMC-macOS-Legacy-${{ env.VERSION }}.tar.gz PolyMC-${{ env.VERSION }}.tar.gz From 5bdb3703ede735129d7eb57c0b1f6d2c497e3fa2 Mon Sep 17 00:00:00 2001 From: DioEgizio <83089242+DioEgizio@users.noreply.github.com> Date: Sun, 2 Oct 2022 08:30:19 +0200 Subject: [PATCH 048/101] fix: stop forcing libc++ on macOS Signed-off-by: DioEgizio <83089242+DioEgizio@users.noreply.github.com> --- CMakeLists.txt | 3 --- 1 file changed, 3 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 46192414..4d1d3d87 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -33,9 +33,6 @@ set(CMAKE_CXX_STANDARD 17) set(CMAKE_C_STANDARD 11) include(GenerateExportHeader) set(CMAKE_CXX_FLAGS "-Wall -pedantic -fstack-protector-strong --param=ssp-buffer-size=4 ${CMAKE_CXX_FLAGS}") -if(UNIX AND APPLE) - set(CMAKE_CXX_FLAGS "-stdlib=libc++ ${CMAKE_CXX_FLAGS}") -endif() # Fix build with Qt 5.13 set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DQT_NO_DEPRECATED_WARNINGS=Y") From c520faed6d0e5e9472622f848ad8512b6c71c8e0 Mon Sep 17 00:00:00 2001 From: flow Date: Thu, 13 Oct 2022 18:37:44 -0300 Subject: [PATCH 049/101] feat: add gulrak/filesystem submodule ... for old macs that don't have std::filesystem in their stdlib. Signed-off-by: flow --- .gitmodules | 3 +++ CMakeLists.txt | 1 + launcher/CMakeLists.txt | 1 + libraries/README.md | 8 ++++++++ libraries/filesystem | 1 + 5 files changed, 14 insertions(+) create mode 160000 libraries/filesystem diff --git a/.gitmodules b/.gitmodules index 534ffd37..efd5de29 100644 --- a/.gitmodules +++ b/.gitmodules @@ -7,3 +7,6 @@ [submodule "libraries/tomlplusplus"] path = libraries/tomlplusplus url = https://github.com/marzer/tomlplusplus.git +[submodule "libraries/filesystem"] + path = libraries/filesystem + url = https://github.com/gulrak/filesystem diff --git a/CMakeLists.txt b/CMakeLists.txt index 4d1d3d87..05ea9f66 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -323,6 +323,7 @@ endif() add_subdirectory(libraries/katabasis) # An OAuth2 library that tried to do too much add_subdirectory(libraries/gamemode) add_subdirectory(libraries/murmur2) # Hash for usage with the CurseForge API +add_subdirectory(libraries/filesystem) # Implementation of std::filesystem for old C++, for usage in old macOS ############################### Built Artifacts ############################### diff --git a/launcher/CMakeLists.txt b/launcher/CMakeLists.txt index c5894268..d04f3e4d 100644 --- a/launcher/CMakeLists.txt +++ b/launcher/CMakeLists.txt @@ -976,6 +976,7 @@ target_link_libraries(Launcher_logic BuildConfig Katabasis Qt${QT_VERSION_MAJOR}::Widgets + ghc_filesystem ) if (UNIX AND NOT CYGWIN AND NOT APPLE) diff --git a/libraries/README.md b/libraries/README.md index 6297cd9b..dfb57a65 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -10,6 +10,14 @@ This library has served as a base for some (much more full-featured and advanced Copyright belongs to Petr Mrázek, unless explicitly stated otherwise in the source files. Available under the Apache 2.0 license. +## filesystem + +Gulrak's implementation of C++17 std::filesystem for C++11 /C++14/C++17/C++20 on Windows, macOS, Linux and FreeBSD. + +See [github repo](https://github.com/gulrak/filesystem). + +MIT licensed. + ## gamemode A performance optimization daemon. diff --git a/libraries/filesystem b/libraries/filesystem new file mode 160000 index 00000000..cd6805e9 --- /dev/null +++ b/libraries/filesystem @@ -0,0 +1 @@ +Subproject commit cd6805e94dd5d6346be1b75a54cdc27787319dd2 From 124097d3a50ba4ae97478ce7d33e5d33690cef75 Mon Sep 17 00:00:00 2001 From: flow Date: Thu, 13 Oct 2022 18:38:52 -0300 Subject: [PATCH 050/101] feat!: use ghc/filesystem in place of std's one if needed Signed-off-by: flow --- launcher/FileSystem.cpp | 31 ++++++++++++++++++++++++------- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/launcher/FileSystem.cpp b/launcher/FileSystem.cpp index 5d179641..c2db0dbc 100644 --- a/launcher/FileSystem.cpp +++ b/launcher/FileSystem.cpp @@ -59,7 +59,24 @@ #include #endif +// Snippet from https://github.com/gulrak/filesystem#using-it-as-single-file-header + +#ifdef __APPLE__ +#include // 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() && (!defined(__MAC_OS_X_VERSION_MIN_REQUIRED) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 101500) +#define GHC_USE_STD_FS #include +namespace fs = std::filesystem; +#endif // MacOS min version check +#endif // Other OSes version check + +#ifndef GHC_USE_STD_FS +#include +namespace fs = ghc::filesystem; +#endif #if defined Q_OS_WIN32 @@ -147,7 +164,7 @@ bool ensureFolderPathExists(QString foldernamepath) bool copy::operator()(const QString& offset) { - using copy_opts = std::filesystem::copy_options; + using copy_opts = fs::copy_options; // NOTE always deep copy on windows. the alternatives are too messy. #if defined Q_OS_WIN32 @@ -159,7 +176,7 @@ bool copy::operator()(const QString& offset) std::error_code err; - std::filesystem::copy_options opt = copy_opts::none; + fs::copy_options opt = copy_opts::none; // The default behavior is to follow symlinks if (!m_followSymlinks) @@ -182,7 +199,7 @@ bool copy::operator()(const QString& offset) auto dst_path = PathCombine(dst, relative_path); ensureFilePathExists(dst_path); - std::filesystem::copy(toStdString(src_path), toStdString(dst_path), opt, err); + fs::copy(toStdString(src_path), toStdString(dst_path), opt, err); if (err) { qWarning() << "Failed to copy files:" << QString::fromStdString(err.message()); qDebug() << "Source file:" << src_path; @@ -197,7 +214,7 @@ bool deletePath(QString path) { std::error_code err; - std::filesystem::remove_all(toStdString(path), err); + fs::remove_all(toStdString(path), err); if (err) { qWarning() << "Failed to remove files:" << QString::fromStdString(err.message()); @@ -376,15 +393,15 @@ bool createShortCut(QString location, QString dest, QStringList args, QString na bool overrideFolder(QString overwritten_path, QString override_path) { - using copy_opts = std::filesystem::copy_options; + using copy_opts = fs::copy_options; if (!FS::ensureFolderPathExists(overwritten_path)) return false; std::error_code err; - std::filesystem::copy_options opt = copy_opts::recursive | copy_opts::overwrite_existing; + fs::copy_options opt = copy_opts::recursive | copy_opts::overwrite_existing; - std::filesystem::copy(toStdString(override_path), toStdString(overwritten_path), opt, err); + fs::copy(toStdString(override_path), toStdString(overwritten_path), opt, err); if (err) { qCritical() << QString("Failed to apply override from %1 to %2").arg(override_path, overwritten_path); From 2aff7bac4aa5dc39b2b68eb2f9d894be832d48c9 Mon Sep 17 00:00:00 2001 From: DioEgizio <83089242+DioEgizio@users.noreply.github.com> Date: Fri, 14 Oct 2022 14:12:51 +0200 Subject: [PATCH 051/101] fix: disable updater on macOS-Legacy Signed-off-by: DioEgizio <83089242+DioEgizio@users.noreply.github.com> --- .github/workflows/build.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 1740f12a..6d001cfc 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -188,7 +188,7 @@ jobs: - name: Configure CMake (macOS-Legacy) if: runner.os == 'macOS' && matrix.qt_ver == 5 run: | - cmake -S . -B ${{ env.BUILD_DIR }} -DCMAKE_INSTALL_PREFIX=${{ env.INSTALL_DIR }} -DCMAKE_BUILD_TYPE=${{ inputs.build_type }} -DENABLE_LTO=ON -DLauncher_BUILD_PLATFORM=${{ matrix.name }} -DCMAKE_C_COMPILER_LAUNCHER=${{ env.CCACHE_VAR }} -DCMAKE_CXX_COMPILER_LAUNCHER=${{ env.CCACHE_VAR }} -DLauncher_QT_VERSION_MAJOR=${{ matrix.qt_ver }} -G Ninja + cmake -S . -B ${{ env.BUILD_DIR }} -DCMAKE_INSTALL_PREFIX=${{ env.INSTALL_DIR }} -DCMAKE_BUILD_TYPE=${{ inputs.build_type }} -DENABLE_LTO=ON -DLauncher_BUILD_PLATFORM=${{ matrix.name }} -DCMAKE_C_COMPILER_LAUNCHER=${{ env.CCACHE_VAR }} -DCMAKE_CXX_COMPILER_LAUNCHER=${{ env.CCACHE_VAR }} -DLauncher_QT_VERSION_MAJOR=${{ matrix.qt_ver }} -DMACOSX_SPARKLE_UPDATE_PUBLIC_KEY="" -DMACOSX_SPARKLE_UPDATE_FEED_URL="" -G Ninja - name: Configure CMake (Windows) if: runner.os == 'Windows' @@ -254,7 +254,7 @@ jobs: tar -czf ../PolyMC.tar.gz * - name: Make Sparkle signature (macOS) - if: runner.os == 'macOS' + if: matrix.name == 'macOS' run: | if [ '${{ secrets.SPARKLE_ED25519_KEY }}' != '' ]; then brew install openssl@3 From 89e45a61b33ed7ae73aa9903149530462fd760b6 Mon Sep 17 00:00:00 2001 From: DioEgizio <83089242+DioEgizio@users.noreply.github.com> Date: Fri, 14 Oct 2022 16:45:13 +0200 Subject: [PATCH 052/101] fix: workaround ghc::filesystem bug Signed-off-by: DioEgizio <83089242+DioEgizio@users.noreply.github.com> --- CMakeLists.txt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index 05ea9f66..45dd691d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -194,6 +194,9 @@ if(NOT Launcher_FORCE_BUNDLED_LIBS) find_package(tomlplusplus 3.2.0 QUIET) endif() +# Workaround ghc::filesystem bug +set(GHC_FILESYSTEM_WITH_INSTALL OFF) + ####################################### Program Info ####################################### set(Launcher_APP_BINARY_NAME "polymc" CACHE STRING "Name of the Launcher binary") From c90a88b6b6cf1b7d0fe2b6784de880762201f4a9 Mon Sep 17 00:00:00 2001 From: flow Date: Fri, 14 Oct 2022 12:18:06 -0300 Subject: [PATCH 053/101] fix: correct ftb legacy too Signed-off-by: flow --- .../legacy_ftb/PackInstallTask.cpp | 41 +++++++++---------- 1 file changed, 19 insertions(+), 22 deletions(-) diff --git a/launcher/modplatform/legacy_ftb/PackInstallTask.cpp b/launcher/modplatform/legacy_ftb/PackInstallTask.cpp index 209ad884..06b3788b 100644 --- a/launcher/modplatform/legacy_ftb/PackInstallTask.cpp +++ b/launcher/modplatform/legacy_ftb/PackInstallTask.cpp @@ -65,48 +65,42 @@ void PackInstallTask::executeTask() void PackInstallTask::downloadPack() { setStatus(tr("Downloading zip for %1").arg(m_pack.name)); + setAbortable(false); + + archivePath = QString("%1/%2/%3").arg(m_pack.dir, m_version.replace(".", "_"), m_pack.file); - auto packoffset = QString("%1/%2/%3").arg(m_pack.dir, m_version.replace(".", "_"), m_pack.file); - auto entry = APPLICATION->metacache()->resolveEntry("FTBPacks", packoffset); netJobContainer = new NetJob("Download FTB Pack", m_network); - - entry->setStale(true); QString url; - if(m_pack.type == PackType::Private) - { - url = QString(BuildConfig.LEGACY_FTB_CDN_BASE_URL + "privatepacks/%1").arg(packoffset); + if (m_pack.type == PackType::Private) { + url = QString(BuildConfig.LEGACY_FTB_CDN_BASE_URL + "privatepacks/%1").arg(archivePath); + } else { + url = QString(BuildConfig.LEGACY_FTB_CDN_BASE_URL + "modpacks/%1").arg(archivePath); } - else - { - url = QString(BuildConfig.LEGACY_FTB_CDN_BASE_URL + "modpacks/%1").arg(packoffset); - } - netJobContainer->addNetAction(Net::Download::makeCached(url, entry)); - archivePath = entry->getFullPath(); + netJobContainer->addNetAction(Net::Download::makeFile(url, archivePath)); connect(netJobContainer.get(), &NetJob::succeeded, this, &PackInstallTask::onDownloadSucceeded); connect(netJobContainer.get(), &NetJob::failed, this, &PackInstallTask::onDownloadFailed); connect(netJobContainer.get(), &NetJob::progress, this, &PackInstallTask::onDownloadProgress); connect(netJobContainer.get(), &NetJob::aborted, this, &PackInstallTask::onDownloadAborted); + netJobContainer->start(); + setAbortable(true); progress(1, 4); } void PackInstallTask::onDownloadSucceeded() { - abortable = false; unzip(); } void PackInstallTask::onDownloadFailed(QString reason) { - abortable = false; emitFailed(reason); } void PackInstallTask::onDownloadProgress(qint64 current, qint64 total) { - abortable = true; progress(current, total * 4); setStatus(tr("Downloading zip for %1 (%2%)").arg(m_pack.name).arg(current / 10)); } @@ -118,8 +112,10 @@ void PackInstallTask::onDownloadAborted() void PackInstallTask::unzip() { - progress(2, 4); setStatus(tr("Extracting modpack")); + setAbortable(false); + progress(2, 4); + QDir extractDir(m_stagingPath); m_packZip.reset(new QuaZip(archivePath)); @@ -151,8 +147,8 @@ void PackInstallTask::onUnzipCanceled() void PackInstallTask::install() { - progress(3, 4); setStatus(tr("Installing modpack")); + progress(3, 4); QDir unzipMcDir(m_stagingPath + "/unzip/minecraft"); if(unzipMcDir.exists()) { @@ -247,11 +243,12 @@ void PackInstallTask::install() bool PackInstallTask::abort() { - if(abortable) - { - return netJobContainer->abort(); + if (!canAbort()) { + return false; } - return false; + + netJobContainer->abort(); + return InstanceTask::abort(); } } From 545944cb0de33438b0584785a900045eb35ecd58 Mon Sep 17 00:00:00 2001 From: Sefa Eyeoglu Date: Sat, 15 Oct 2022 12:41:16 +0200 Subject: [PATCH 054/101] refactor: support armhf Signed-off-by: Sefa Eyeoglu --- launcher/RuntimeContext.h | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/launcher/RuntimeContext.h b/launcher/RuntimeContext.h index c1b71318..bc2ed5c8 100644 --- a/launcher/RuntimeContext.h +++ b/launcher/RuntimeContext.h @@ -29,9 +29,14 @@ struct RuntimeContext { QString system; QString mappedJavaRealArchitecture() const { - if (javaRealArchitecture == "aarch64") { + if (javaRealArchitecture == "amd64") + return "x86_64"; + if (javaRealArchitecture == "i386" || javaRealArchitecture == "i686") + return "x86"; + if (javaRealArchitecture == "aarch64") return "arm64"; - } + if (javaRealArchitecture == "arm" || javaRealArchitecture == "armhf") + return "arm32"; return javaRealArchitecture; } @@ -48,8 +53,8 @@ struct RuntimeContext { // "Legacy" refers to the fact that Mojang assumed that these are the only two architectures bool isLegacyArch() const { - QSet legacyArchitectures{"amd64", "x86_64", "i386", "i686", "x86"}; - return legacyArchitectures.contains(mappedJavaRealArchitecture()); + const QString mapped = mappedJavaRealArchitecture(); + return mapped == "x86_64" || mapped == "x86"; } bool classifierMatches(QString target) const { From 3b92ec8e82ca9334e72e7c1a9eddbb0c492277d0 Mon Sep 17 00:00:00 2001 From: Sefa Eyeoglu Date: Sat, 15 Oct 2022 12:43:15 +0200 Subject: [PATCH 055/101] chore: clang-format RuntimeContext Signed-off-by: Sefa Eyeoglu --- launcher/RuntimeContext.h | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/launcher/RuntimeContext.h b/launcher/RuntimeContext.h index bc2ed5c8..70e7d0d1 100644 --- a/launcher/RuntimeContext.h +++ b/launcher/RuntimeContext.h @@ -28,7 +28,8 @@ struct RuntimeContext { QString javaPath; QString system; - QString mappedJavaRealArchitecture() const { + QString mappedJavaRealArchitecture() const + { if (javaRealArchitecture == "amd64") return "x86_64"; if (javaRealArchitecture == "i386" || javaRealArchitecture == "i686") @@ -40,24 +41,25 @@ struct RuntimeContext { return javaRealArchitecture; } - void updateFromInstanceSettings(SettingsObjectPtr instanceSettings) { + void updateFromInstanceSettings(SettingsObjectPtr instanceSettings) + { javaArchitecture = instanceSettings->get("JavaArchitecture").toString(); javaRealArchitecture = instanceSettings->get("JavaRealArchitecture").toString(); javaPath = instanceSettings->get("JavaPath").toString(); system = currentSystem(); } - QString getClassifier() const { - return system + "-" + mappedJavaRealArchitecture(); - } + QString getClassifier() const { return system + "-" + mappedJavaRealArchitecture(); } // "Legacy" refers to the fact that Mojang assumed that these are the only two architectures - bool isLegacyArch() const { + bool isLegacyArch() const + { const QString mapped = mappedJavaRealArchitecture(); return mapped == "x86_64" || mapped == "x86"; } - bool classifierMatches(QString target) const { + bool classifierMatches(QString target) const + { // try to match precise classifier "[os]-[arch]" bool x = target == getClassifier(); // try to match imprecise classifier on legacy architectures "[os]" @@ -67,7 +69,8 @@ struct RuntimeContext { return x; } - static QString currentSystem() { + static QString currentSystem() + { #if defined(Q_OS_LINUX) return "linux"; #elif defined(Q_OS_MACOS) From 303628bb0579f13d3ceac915b3caaf4d7fc9b2db Mon Sep 17 00:00:00 2001 From: Sefa Eyeoglu Date: Sat, 15 Oct 2022 13:13:34 +0200 Subject: [PATCH 056/101] refactor: support system ghc-filesystem Signed-off-by: Sefa Eyeoglu --- CMakeLists.txt | 17 ++++++++++++----- launcher/CMakeLists.txt | 2 +- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 45dd691d..310cec59 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -189,13 +189,13 @@ if (Qt5_POSITION_INDEPENDENT_CODE) SET(CMAKE_POSITION_INDEPENDENT_CODE ON) endif() -# Find toml++ if(NOT Launcher_FORCE_BUNDLED_LIBS) + # Find toml++ find_package(tomlplusplus 3.2.0 QUIET) -endif() -# Workaround ghc::filesystem bug -set(GHC_FILESYSTEM_WITH_INSTALL OFF) + # Find ghc_filesystem + find_package(ghc_filesystem QUIET) +endif() ####################################### Program Info ####################################### @@ -326,7 +326,14 @@ endif() add_subdirectory(libraries/katabasis) # An OAuth2 library that tried to do too much add_subdirectory(libraries/gamemode) add_subdirectory(libraries/murmur2) # Hash for usage with the CurseForge API -add_subdirectory(libraries/filesystem) # Implementation of std::filesystem for old C++, for usage in old macOS +if (NOT ghc_filesystem_FOUND) + message(STATUS "Using bundled ghc_filesystem") + set(GHC_FILESYSTEM_WITH_INSTALL OFF) # Workaround ghc::filesystem bug + add_subdirectory(libraries/filesystem) # Implementation of std::filesystem for old C++, for usage in old macOS + add_library(ghcFilesystem::ghc_filesystem ALIAS ghc_filesystem) +else() + message(STATUS "Using system ghc_filesystem") +endif() ############################### Built Artifacts ############################### diff --git a/launcher/CMakeLists.txt b/launcher/CMakeLists.txt index d04f3e4d..c7d0d68c 100644 --- a/launcher/CMakeLists.txt +++ b/launcher/CMakeLists.txt @@ -976,7 +976,7 @@ target_link_libraries(Launcher_logic BuildConfig Katabasis Qt${QT_VERSION_MAJOR}::Widgets - ghc_filesystem + ghcFilesystem::ghc_filesystem ) if (UNIX AND NOT CYGWIN AND NOT APPLE) From 03d077e915cf2bf06474b17e51e0c664f57eb348 Mon Sep 17 00:00:00 2001 From: Sefa Eyeoglu Date: Sat, 15 Oct 2022 13:13:56 +0200 Subject: [PATCH 057/101] fix(nix): add ghc_filesystem dependency Signed-off-by: Sefa Eyeoglu --- nix/default.nix | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/nix/default.nix b/nix/default.nix index 88b540ab..19136cad 100644 --- a/nix/default.nix +++ b/nix/default.nix @@ -5,6 +5,7 @@ , ninja , jdk8 , jdk +, ghc_filesystem , zlib , file , wrapQtAppsHook @@ -49,7 +50,7 @@ stdenv.mkDerivation rec { src = lib.cleanSource self; - nativeBuildInputs = [ cmake extra-cmake-modules ninja jdk file wrapQtAppsHook ]; + nativeBuildInputs = [ cmake extra-cmake-modules ninja jdk ghc_filesystem file wrapQtAppsHook ]; buildInputs = [ qtbase quazip zlib ]; dontWrapQtApps = true; From 8bc529be3dae2d0a515f55812c24ee669b4f34bf Mon Sep 17 00:00:00 2001 From: flow Date: Sat, 15 Oct 2022 09:20:31 -0300 Subject: [PATCH 058/101] fix: include hidden files when copying instances fixes instance ccopy on linux .-. Signed-off-by: flow --- launcher/FileSystem.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/launcher/FileSystem.cpp b/launcher/FileSystem.cpp index 5d179641..7ab32513 100644 --- a/launcher/FileSystem.cpp +++ b/launcher/FileSystem.cpp @@ -170,7 +170,7 @@ bool copy::operator()(const QString& offset) // blacklisted paths, so we iterate over the source directory, and if there's no blacklist // match, we copy the file. QDir src_dir(src); - QDirIterator source_it(src, QDir::Filter::Files, QDirIterator::Subdirectories); + QDirIterator source_it(src, QDir::Filter::Files | QDir::Filter::Hidden, QDirIterator::Subdirectories); while (source_it.hasNext()) { auto src_path = source_it.next(); From 82d7f9f5a46fe0d66aa907825cf784efc13f8792 Mon Sep 17 00:00:00 2001 From: flow Date: Sat, 15 Oct 2022 09:34:47 -0300 Subject: [PATCH 059/101] chore(tests): add test for FS copy with dot folders/files Signed-off-by: flow --- tests/FileSystem_test.cpp | 36 ++++++++++++++++++ .../.secret_folder/.secret_file.txt | Bin 0 -> 29 bytes 2 files changed, 36 insertions(+) create mode 100644 tests/testdata/FileSystem/test_folder/.secret_folder/.secret_file.txt diff --git a/tests/FileSystem_test.cpp b/tests/FileSystem_test.cpp index 4efb90ac..47a963b0 100644 --- a/tests/FileSystem_test.cpp +++ b/tests/FileSystem_test.cpp @@ -147,6 +147,42 @@ slots: f(); } + void test_copy_with_dot_hidden() + { + QString folder = QFINDTESTDATA("testdata/FileSystem/test_folder"); + auto f = [&folder]() + { + QTemporaryDir tempDir; + tempDir.setAutoRemove(true); + qDebug() << "From:" << folder << "To:" << tempDir.path(); + + QDir target_dir(FS::PathCombine(tempDir.path(), "test_folder")); + qDebug() << tempDir.path(); + qDebug() << target_dir.path(); + FS::copy c(folder, target_dir.path()); + c(); + + auto filter = QDir::Filter::Files | QDir::Filter::Dirs | QDir::Filter::Hidden; + + for (auto entry: target_dir.entryList(filter)) { + qDebug() << entry; + } + + QVERIFY(target_dir.entryList(filter).contains(".secret_folder")); + target_dir.cd(".secret_folder"); + QVERIFY(target_dir.entryList(filter).contains(".secret_file.txt")); + }; + + // first try variant without trailing / + QVERIFY(!folder.endsWith('/')); + f(); + + // then variant with trailing / + folder.append('/'); + QVERIFY(folder.endsWith('/')); + f(); + } + void test_getDesktop() { QCOMPARE(FS::getDesktopDir(), QStandardPaths::writableLocation(QStandardPaths::DesktopLocation)); diff --git a/tests/testdata/FileSystem/test_folder/.secret_folder/.secret_file.txt b/tests/testdata/FileSystem/test_folder/.secret_folder/.secret_file.txt new file mode 100644 index 0000000000000000000000000000000000000000..65e37085f46700c2d2c1b21efb9c56f52802bb41 GIT binary patch literal 29 hcmd1L2LXlRg8cmKN`=(K;*!)Nh1B$P1*`mgE&!?n3Yh=^ literal 0 HcmV?d00001 From 87d35f0d16d3be56020f9e6295cc8bfa0c657d27 Mon Sep 17 00:00:00 2001 From: DioEgizio <83089242+DioEgizio@users.noreply.github.com> Date: Sat, 15 Oct 2022 20:15:46 +0200 Subject: [PATCH 060/101] fix: remove some unused libs Signed-off-by: DioEgizio <83089242+DioEgizio@users.noreply.github.com> --- CMakeLists.txt | 2 - launcher/CMakeLists.txt | 1 - libraries/README.md | 16 +- libraries/classparser/CMakeLists.txt | 42 - libraries/classparser/include/classparser.h | 27 - .../classparser/include/classparser_config.h | 22 - libraries/classparser/src/annotations.cpp | 85 -- libraries/classparser/src/annotations.h | 278 ---- libraries/classparser/src/classfile.h | 156 --- libraries/classparser/src/classparser.cpp | 83 -- libraries/classparser/src/constants.h | 232 ---- libraries/classparser/src/errors.h | 8 - libraries/classparser/src/javaendian.h | 59 - libraries/classparser/src/membuffer.h | 63 - libraries/xz-embedded/CMakeLists.txt | 26 - libraries/xz-embedded/include/xz.h | 321 ----- libraries/xz-embedded/src/xz_config.h | 119 -- libraries/xz-embedded/src/xz_crc32.c | 61 - libraries/xz-embedded/src/xz_crc64.c | 52 - libraries/xz-embedded/src/xz_dec_bcj.c | 588 -------- libraries/xz-embedded/src/xz_dec_lzma2.c | 1231 ----------------- libraries/xz-embedded/src/xz_dec_stream.c | 860 ------------ libraries/xz-embedded/src/xz_lzma2.h | 204 --- libraries/xz-embedded/src/xz_private.h | 150 -- libraries/xz-embedded/src/xz_stream.h | 62 - libraries/xz-embedded/xzminidec.c | 144 -- 26 files changed, 1 insertion(+), 4891 deletions(-) delete mode 100644 libraries/classparser/CMakeLists.txt delete mode 100644 libraries/classparser/include/classparser.h delete mode 100644 libraries/classparser/include/classparser_config.h delete mode 100644 libraries/classparser/src/annotations.cpp delete mode 100644 libraries/classparser/src/annotations.h delete mode 100644 libraries/classparser/src/classfile.h delete mode 100644 libraries/classparser/src/classparser.cpp delete mode 100644 libraries/classparser/src/constants.h delete mode 100644 libraries/classparser/src/errors.h delete mode 100644 libraries/classparser/src/javaendian.h delete mode 100644 libraries/classparser/src/membuffer.h delete mode 100644 libraries/xz-embedded/CMakeLists.txt delete mode 100644 libraries/xz-embedded/include/xz.h delete mode 100644 libraries/xz-embedded/src/xz_config.h delete mode 100644 libraries/xz-embedded/src/xz_crc32.c delete mode 100644 libraries/xz-embedded/src/xz_crc64.c delete mode 100644 libraries/xz-embedded/src/xz_dec_bcj.c delete mode 100644 libraries/xz-embedded/src/xz_dec_lzma2.c delete mode 100644 libraries/xz-embedded/src/xz_dec_stream.c delete mode 100644 libraries/xz-embedded/src/xz_lzma2.h delete mode 100644 libraries/xz-embedded/src/xz_private.h delete mode 100644 libraries/xz-embedded/src/xz_stream.h delete mode 100644 libraries/xz-embedded/xzminidec.c diff --git a/CMakeLists.txt b/CMakeLists.txt index 310cec59..caecddbd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -305,7 +305,6 @@ add_subdirectory(libraries/systeminfo) # system information library add_subdirectory(libraries/hoedown) # markdown parser add_subdirectory(libraries/launcher) # java based launcher part for Minecraft add_subdirectory(libraries/javacheck) # java compatibility checker -add_subdirectory(libraries/xz-embedded) # xz compression if (FORCE_BUNDLED_QUAZIP) message(STATUS "Using bundled QuaZip") set(BUILD_SHARED_LIBS 0) # link statically to avoid conflicts. @@ -316,7 +315,6 @@ else() endif() add_subdirectory(libraries/rainbow) # Qt extension for colors add_subdirectory(libraries/LocalPeer) # fork of a library from Qt solutions -add_subdirectory(libraries/classparser) # class parser library if(NOT tomlplusplus_FOUND) message(STATUS "Using bundled tomlplusplus") add_subdirectory(libraries/tomlplusplus) # toml parser diff --git a/launcher/CMakeLists.txt b/launcher/CMakeLists.txt index c7d0d68c..6ad91a85 100644 --- a/launcher/CMakeLists.txt +++ b/launcher/CMakeLists.txt @@ -968,7 +968,6 @@ add_library(Launcher_logic STATIC ${LOGIC_SOURCES} ${LAUNCHER_SOURCES} ${LAUNCHE target_include_directories(Launcher_logic PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) target_link_libraries(Launcher_logic systeminfo - Launcher_classparser Launcher_murmur2 nbt++ ${ZLIB_LIBRARIES} diff --git a/libraries/README.md b/libraries/README.md index dfb57a65..9a26dd69 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -2,14 +2,6 @@ This folder has third-party or otherwise external libraries needed for other parts to work. -## classparser - -A simplistic parser for Java class files. - -This library has served as a base for some (much more full-featured and advanced) work under NDA for AVG. It, however, should NOT be confused with that work. - -Copyright belongs to Petr Mrázek, unless explicitly stated otherwise in the source files. Available under the Apache 2.0 license. - ## filesystem Gulrak's implementation of C++17 std::filesystem for C++11 /C++14/C++17/C++20 on Windows, macOS, Linux and FreeBSD. @@ -191,10 +183,4 @@ A TOML language parser. Used by Forge 1.14+ to store mod metadata. See [github repo](https://github.com/marzer/tomlplusplus). -Licenced under the MIT licence. - -## xz-embedded - -Tiny implementation of LZMA2 de/compression. This format was only used by Forge to save bandwidth. - -Public domain. +Licenced under the MIT licence. \ No newline at end of file diff --git a/libraries/classparser/CMakeLists.txt b/libraries/classparser/CMakeLists.txt deleted file mode 100644 index 05412c30..00000000 --- a/libraries/classparser/CMakeLists.txt +++ /dev/null @@ -1,42 +0,0 @@ -project(classparser) - -set(CMAKE_AUTOMOC ON) - -######## Check endianness ######## -include(TestBigEndian) -test_big_endian(BIGENDIAN) -if(${BIGENDIAN}) - add_definitions(-DMULTIMC_BIG_ENDIAN) -endif(${BIGENDIAN}) - -# Find Qt -if(QT_VERSION_MAJOR EQUAL 5) - find_package(Qt5 COMPONENTS Core REQUIRED) -elseif(Launcher_QT_VERSION_MAJOR EQUAL 6) - find_package(Qt6 COMPONENTS Core REQUIRED) -endif() - -set(CLASSPARSER_HEADERS -# Public headers -include/classparser_config.h -include/classparser.h - -# Private headers -src/annotations.h -src/classfile.h -src/constants.h -src/errors.h -src/javaendian.h -src/membuffer.h -) - -set(CLASSPARSER_SOURCES -src/classparser.cpp -src/annotations.cpp -) - -add_definitions(-DCLASSPARSER_LIBRARY) - -add_library(Launcher_classparser STATIC ${CLASSPARSER_SOURCES} ${CLASSPARSER_HEADERS}) -target_include_directories(Launcher_classparser PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include") -target_link_libraries(Launcher_classparser QuaZip::QuaZip Qt${QT_VERSION_MAJOR}::Core) diff --git a/libraries/classparser/include/classparser.h b/libraries/classparser/include/classparser.h deleted file mode 100644 index 3660026b..00000000 --- a/libraries/classparser/include/classparser.h +++ /dev/null @@ -1,27 +0,0 @@ -/* Copyright 2013-2021 MultiMC Contributors - * - * Authors: Orochimarufan - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#pragma once -#include -#include "classparser_config.h" - -namespace classparser -{ -/** - * @brief Get the version from a minecraft.jar by parsing its class files. Expensive! - */ -QString GetMinecraftJarVersion(QString jar); -} diff --git a/libraries/classparser/include/classparser_config.h b/libraries/classparser/include/classparser_config.h deleted file mode 100644 index 7bfae7cc..00000000 --- a/libraries/classparser/include/classparser_config.h +++ /dev/null @@ -1,22 +0,0 @@ -/* Copyright 2013-2021 MultiMC Contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include - -#ifdef CLASSPARSER_LIBRARY -#define CLASSPARSER_EXPORT Q_DECL_EXPORT -#else -#define CLASSPARSER_EXPORT Q_DECL_IMPORT -#endif diff --git a/libraries/classparser/src/annotations.cpp b/libraries/classparser/src/annotations.cpp deleted file mode 100644 index 89b201bc..00000000 --- a/libraries/classparser/src/annotations.cpp +++ /dev/null @@ -1,85 +0,0 @@ -#include "classfile.h" -#include "annotations.h" -#include - -namespace java -{ -std::string annotation::toString() -{ - std::ostringstream ss; - ss << "Annotation type : " << type_index << " - " << pool[type_index].str_data << std::endl; - ss << "Contains " << name_val_pairs.size() << " pairs:" << std::endl; - for (unsigned i = 0; i < name_val_pairs.size(); i++) - { - std::pair &val = name_val_pairs[i]; - auto name_idx = val.first; - ss << pool[name_idx].str_data << "(" << name_idx << ")" - << " = " << val.second->toString() << std::endl; - } - return ss.str(); -} - -annotation *annotation::read(util::membuffer &input, constant_pool &pool) -{ - uint16_t type_index = 0; - input.read_be(type_index); - annotation *ann = new annotation(type_index, pool); - - uint16_t num_pairs = 0; - input.read_be(num_pairs); - while (num_pairs) - { - uint16_t name_idx = 0; - // read name index - input.read_be(name_idx); - auto elem = element_value::readElementValue(input, pool); - // read value - ann->add_pair(name_idx, elem); - num_pairs--; - } - return ann; -} - -element_value *element_value::readElementValue(util::membuffer &input, - java::constant_pool &pool) -{ - element_value_type type = INVALID; - input.read(type); - uint16_t index = 0; - uint16_t index2 = 0; - std::vector vals; - switch (type) - { - case PRIMITIVE_BYTE: - case PRIMITIVE_CHAR: - case PRIMITIVE_DOUBLE: - case PRIMITIVE_FLOAT: - case PRIMITIVE_INT: - case PRIMITIVE_LONG: - case PRIMITIVE_SHORT: - case PRIMITIVE_BOOLEAN: - case STRING: - input.read_be(index); - return new element_value_simple(type, index, pool); - case ENUM_CONSTANT: - input.read_be(index); - input.read_be(index2); - return new element_value_enum(type, index, index2, pool); - case CLASS: // Class - input.read_be(index); - return new element_value_class(type, index, pool); - case ANNOTATION: // Annotation - // FIXME: runtime visibility info needs to be passed from parent - return new element_value_annotation(ANNOTATION, annotation::read(input, pool), pool); - case ARRAY: // Array - input.read_be(index); - for (int i = 0; i < index; i++) - { - vals.push_back(element_value::readElementValue(input, pool)); - } - return new element_value_array(ARRAY, vals, pool); - default: - throw java::classfile_exception(); - } -} -} diff --git a/libraries/classparser/src/annotations.h b/libraries/classparser/src/annotations.h deleted file mode 100644 index 15bf05a4..00000000 --- a/libraries/classparser/src/annotations.h +++ /dev/null @@ -1,278 +0,0 @@ -#pragma once -#include "classfile.h" -#include -#include - -namespace java -{ -enum element_value_type : uint8_t -{ - INVALID = 0, - STRING = 's', - ENUM_CONSTANT = 'e', - CLASS = 'c', - ANNOTATION = '@', - ARRAY = '[', // one array dimension - PRIMITIVE_INT = 'I', // integer - PRIMITIVE_BYTE = 'B', // signed byte - PRIMITIVE_CHAR = 'C', // Unicode character code point in the Basic Multilingual Plane, - // encoded with UTF-16 - PRIMITIVE_DOUBLE = 'D', // double-precision floating-point value - PRIMITIVE_FLOAT = 'F', // single-precision floating-point value - PRIMITIVE_LONG = 'J', // long integer - PRIMITIVE_SHORT = 'S', // signed short - PRIMITIVE_BOOLEAN = 'Z' // true or false -}; -/** - * The element_value structure is a discriminated union representing the value of an - *element-value pair. - * It is used to represent element values in all attributes that describe annotations - * - RuntimeVisibleAnnotations - * - RuntimeInvisibleAnnotations - * - RuntimeVisibleParameterAnnotations - * - RuntimeInvisibleParameterAnnotations). - * - * The element_value structure has the following format: - */ -class element_value -{ -protected: - element_value_type type; - constant_pool &pool; - -public: - element_value(element_value_type type, constant_pool &pool) : type(type), pool(pool) {}; - virtual ~element_value() {} - - element_value_type getElementValueType() - { - return type; - } - - virtual std::string toString() = 0; - - static element_value *readElementValue(util::membuffer &input, constant_pool &pool); -}; - -/** - * Each value of the annotations table represents a single runtime-visible annotation on a - * program element. - * The annotation structure has the following format: - */ -class annotation -{ -public: - typedef std::vector> value_list; - -protected: - /** - * The value of the type_index item must be a valid index into the constant_pool table. - * The constant_pool entry at that index must be a CONSTANT_Utf8_info (§4.4.7) structure - * representing a field descriptor representing the annotation type corresponding - * to the annotation represented by this annotation structure. - */ - uint16_t type_index; - /** - * map between element_name_index and value. - * - * The value of the element_name_index item must be a valid index into the constant_pool - *table. - * The constant_pool entry at that index must be a CONSTANT_Utf8_info (§4.4.7) structure - *representing - * a valid field descriptor (§4.3.2) that denotes the name of the annotation type element - *represented - * by this element_value_pairs entry. - */ - value_list name_val_pairs; - /** - * Reference to the parent constant pool - */ - constant_pool &pool; - -public: - annotation(uint16_t type_index, constant_pool &pool) - : type_index(type_index), pool(pool) {}; - ~annotation() - { - for (unsigned i = 0; i < name_val_pairs.size(); i++) - { - delete name_val_pairs[i].second; - } - } - void add_pair(uint16_t key, element_value *value) - { - name_val_pairs.push_back(std::make_pair(key, value)); - } - ; - value_list::const_iterator begin() - { - return name_val_pairs.cbegin(); - } - value_list::const_iterator end() - { - return name_val_pairs.cend(); - } - std::string toString(); - static annotation *read(util::membuffer &input, constant_pool &pool); -}; -typedef std::vector annotation_table; - -/// type for simple value annotation elements -class element_value_simple : public element_value -{ -protected: - /// index of the constant in the constant pool - uint16_t index; - -public: - element_value_simple(element_value_type type, uint16_t index, constant_pool &pool) - : element_value(type, pool), index(index) { - // TODO: verify consistency - }; - uint16_t getIndex() - { - return index; - } - virtual std::string toString() - { - return pool[index].toString(); - } - ; -}; -/// The enum_const_value item is used if the tag item is 'e'. -class element_value_enum : public element_value -{ -protected: - /** - * The value of the type_name_index item must be a valid index into the constant_pool table. - * The constant_pool entry at that index must be a CONSTANT_Utf8_info (§4.4.7) structure - * representing a valid field descriptor (§4.3.2) that denotes the internal form of the - * binary - * name (§4.2.1) of the type of the enum constant represented by this element_value - * structure. - */ - uint16_t typeIndex; - /** - * The value of the const_name_index item must be a valid index into the constant_pool - * table. - * The constant_pool entry at that index must be a CONSTANT_Utf8_info (§4.4.7) structure - * representing the simple name of the enum constant represented by this element_value - * structure. - */ - uint16_t valueIndex; - -public: - element_value_enum(element_value_type type, uint16_t typeIndex, uint16_t valueIndex, - constant_pool &pool) - : element_value(type, pool), typeIndex(typeIndex), valueIndex(valueIndex) - { - // TODO: verify consistency - } - uint16_t getValueIndex() - { - return valueIndex; - } - uint16_t getTypeIndex() - { - return typeIndex; - } - virtual std::string toString() - { - return "enum value"; - } - ; -}; - -class element_value_class : public element_value -{ -protected: - /** - * The class_info_index item must be a valid index into the constant_pool table. - * The constant_pool entry at that index must be a CONSTANT_Utf8_info (§4.4.7) structure - * representing the return descriptor (§4.3.3) of the type that is reified by the class - * represented by this element_value structure. - * - * For example, 'V' for Void.class, 'Ljava/lang/Object;' for Object, etc. - * - * Or in plain english, you can store type information in annotations. Yay. - */ - uint16_t classIndex; - -public: - element_value_class(element_value_type type, uint16_t classIndex, constant_pool &pool) - : element_value(type, pool), classIndex(classIndex) - { - // TODO: verify consistency - } - uint16_t getIndex() - { - return classIndex; - } - virtual std::string toString() - { - return "class"; - } - ; -}; - -/// nested annotations... yay -class element_value_annotation : public element_value -{ -private: - annotation *nestedAnnotation; - -public: - element_value_annotation(element_value_type type, annotation *nestedAnnotation, - constant_pool &pool) - : element_value(type, pool), nestedAnnotation(nestedAnnotation) {}; - ~element_value_annotation() - { - if (nestedAnnotation) - { - delete nestedAnnotation; - nestedAnnotation = nullptr; - } - } - virtual std::string toString() - { - return "nested annotation"; - } - ; -}; - -/// and arrays! -class element_value_array : public element_value -{ -public: - typedef std::vector elem_vec; - -protected: - elem_vec values; - -public: - element_value_array(element_value_type type, std::vector &values, - constant_pool &pool) - : element_value(type, pool), values(values) {}; - ~element_value_array() - { - for (unsigned i = 0; i < values.size(); i++) - { - delete values[i]; - } - } - ; - elem_vec::const_iterator begin() - { - return values.cbegin(); - } - elem_vec::const_iterator end() - { - return values.cend(); - } - virtual std::string toString() - { - return "array"; - } - ; -}; -} \ No newline at end of file diff --git a/libraries/classparser/src/classfile.h b/libraries/classparser/src/classfile.h deleted file mode 100644 index d629dde1..00000000 --- a/libraries/classparser/src/classfile.h +++ /dev/null @@ -1,156 +0,0 @@ -#pragma once -#include "membuffer.h" -#include "constants.h" -#include "annotations.h" -#include -namespace java -{ -/** - * Class representing a Java .class file - */ -class classfile : public util::membuffer -{ -public: - classfile(char *data, std::size_t size) : membuffer(data, size) - { - valid = false; - is_synthetic = false; - read_be(magic); - if (magic != 0xCAFEBABE) - throw classfile_exception(); - read_be(minor_version); - read_be(major_version); - constants.load(*this); - read_be(access_flags); - read_be(this_class); - read_be(super_class); - - // Interfaces - uint16_t iface_count = 0; - read_be(iface_count); - while (iface_count) - { - uint16_t iface; - read_be(iface); - interfaces.push_back(iface); - iface_count--; - } - - // Fields - // read fields (and attributes from inside fields) (and possible inner classes. yay for - // recursion!) - // for now though, we will ignore all attributes - /* - * field_info - * { - * u2 access_flags; - * u2 name_index; - * u2 descriptor_index; - * u2 attributes_count; - * attribute_info attributes[attributes_count]; - * } - */ - uint16_t field_count = 0; - read_be(field_count); - while (field_count) - { - // skip field stuff - skip(6); - // and skip field attributes - uint16_t attr_count = 0; - read_be(attr_count); - while (attr_count) - { - skip(2); - uint32_t attr_length = 0; - read_be(attr_length); - skip(attr_length); - attr_count--; - } - field_count--; - } - - // class methods - /* - * method_info - * { - * u2 access_flags; - * u2 name_index; - * u2 descriptor_index; - * u2 attributes_count; - * attribute_info attributes[attributes_count]; - * } - */ - uint16_t method_count = 0; - read_be(method_count); - while (method_count) - { - skip(6); - // and skip method attributes - uint16_t attr_count = 0; - read_be(attr_count); - while (attr_count) - { - skip(2); - uint32_t attr_length = 0; - read_be(attr_length); - skip(attr_length); - attr_count--; - } - method_count--; - } - - // class attributes - // there are many kinds of attributes. this is just the generic wrapper structure. - // type is decided by attribute name. extensions to the standard are *possible* - // class annotations are one kind of a attribute (one per class) - /* - * attribute_info - * { - * u2 attribute_name_index; - * u4 attribute_length; - * u1 info[attribute_length]; - * } - */ - uint16_t class_attr_count = 0; - read_be(class_attr_count); - while (class_attr_count) - { - uint16_t name_idx = 0; - read_be(name_idx); - uint32_t attr_length = 0; - read_be(attr_length); - - auto name = constants[name_idx]; - if (name.str_data == "RuntimeVisibleAnnotations") - { - uint16_t num_annotations = 0; - read_be(num_annotations); - while (num_annotations) - { - visible_class_annotations.push_back(annotation::read(*this, constants)); - num_annotations--; - } - } - else - skip(attr_length); - class_attr_count--; - } - valid = true; - } - ; - bool valid; - bool is_synthetic; - uint32_t magic; - uint16_t minor_version; - uint16_t major_version; - constant_pool constants; - uint16_t access_flags; - uint16_t this_class; - uint16_t super_class; - // interfaces this class implements ? must be. investigate. - std::vector interfaces; - // FIXME: doesn't free up memory on delete - java::annotation_table visible_class_annotations; -}; -} diff --git a/libraries/classparser/src/classparser.cpp b/libraries/classparser/src/classparser.cpp deleted file mode 100644 index 601521f6..00000000 --- a/libraries/classparser/src/classparser.cpp +++ /dev/null @@ -1,83 +0,0 @@ -/* Copyright 2013-2021 MultiMC Contributors - * - * Authors: Orochimarufan - * - * 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 "classfile.h" -#include "classparser.h" - -#include -#include -#include - -namespace classparser -{ - -QString GetMinecraftJarVersion(QString jarName) -{ - QString version; - - // check if minecraft.jar exists - QFile jar(jarName); - if (!jar.exists()) - return version; - - // open minecraft.jar - QuaZip zip(&jar); - if (!zip.open(QuaZip::mdUnzip)) - return version; - - // open Minecraft.class - zip.setCurrentFile("net/minecraft/client/Minecraft.class", QuaZip::csSensitive); - QuaZipFile Minecraft(&zip); - if (!Minecraft.open(QuaZipFile::ReadOnly)) - return version; - - // read Minecraft.class - qint64 size = Minecraft.size(); - char *classfile = new char[size]; - Minecraft.read(classfile, size); - - // parse Minecraft.class - try - { - char *temp = classfile; - java::classfile MinecraftClass(temp, size); - java::constant_pool constants = MinecraftClass.constants; - for (java::constant_pool::container_type::const_iterator iter = constants.begin(); - iter != constants.end(); iter++) - { - const java::constant &constant = *iter; - if (constant.type != java::constant_type_t::j_string_data) - continue; - const std::string &str = constant.str_data; - qDebug() << QString::fromStdString(str); - if (str.compare(0, 20, "Minecraft Minecraft ") == 0) - { - version = str.substr(20).data(); - break; - } - } - } - catch (const java::classfile_exception &) { } - - // clean up - delete[] classfile; - Minecraft.close(); - zip.close(); - jar.close(); - - return version; -} -} diff --git a/libraries/classparser/src/constants.h b/libraries/classparser/src/constants.h deleted file mode 100644 index 47b325b9..00000000 --- a/libraries/classparser/src/constants.h +++ /dev/null @@ -1,232 +0,0 @@ -#pragma once -#include "errors.h" -#include "membuffer.h" -#include - -namespace java -{ -enum class constant_type_t : uint8_t -{ - j_hole = 0, // HACK: this is a hole in the array, because java is crazy - j_string_data = 1, - j_int = 3, - j_float = 4, - j_long = 5, - j_double = 6, - j_class = 7, - j_string = 8, - j_fieldref = 9, - j_methodref = 10, - j_interface_methodref = 11, - j_nameandtype = 12 - // FIXME: missing some constant types, see https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.4 -}; - -struct ref_type_t -{ - /** - * Class reference: - * an index within the constant pool to a UTF-8 string containing - * the fully qualified class name (in internal format) - * Used for j_class, j_fieldref, j_methodref and j_interface_methodref - */ - uint16_t class_idx; - // used for j_fieldref, j_methodref and j_interface_methodref - uint16_t name_and_type_idx; -}; - -struct name_and_type_t -{ - uint16_t name_index; - uint16_t descriptor_index; -}; - -class constant -{ -public: - constant_type_t type = constant_type_t::j_hole; - - constant(util::membuffer &buf) - { - buf.read(type); - - // load data depending on type - switch (type) - { - case constant_type_t::j_float: - buf.read_be(data.int_data); - break; - case constant_type_t::j_int: - buf.read_be(data.int_data); // same as float data really - break; - case constant_type_t::j_double: - buf.read_be(data.long_data); - break; - case constant_type_t::j_long: - buf.read_be(data.long_data); // same as double - break; - case constant_type_t::j_class: - buf.read_be(data.ref_type.class_idx); - break; - case constant_type_t::j_fieldref: - case constant_type_t::j_methodref: - case constant_type_t::j_interface_methodref: - buf.read_be(data.ref_type.class_idx); - buf.read_be(data.ref_type.name_and_type_idx); - break; - case constant_type_t::j_string: - buf.read_be(data.index); - break; - case constant_type_t::j_string_data: - // HACK HACK: for now, we call these UTF-8 and do no further processing. - // Later, we should do some decoding. It's really modified UTF-8 - // * U+0000 is represented as 0xC0,0x80 invalid character - // * any single zero byte ends the string - // * characters above U+10000 are encoded like in CESU-8 - buf.read_jstr(str_data); - break; - case constant_type_t::j_nameandtype: - buf.read_be(data.name_and_type.name_index); - buf.read_be(data.name_and_type.descriptor_index); - break; - default: - // invalid constant type! - throw classfile_exception(); - } - } - constant(int) - { - } - - std::string toString() - { - std::ostringstream ss; - switch (type) - { - case constant_type_t::j_hole: - ss << "Fake legacy entry"; - break; - case constant_type_t::j_float: - ss << "Float: " << data.float_data; - break; - case constant_type_t::j_double: - ss << "Double: " << data.double_data; - break; - case constant_type_t::j_int: - ss << "Int: " << data.int_data; - break; - case constant_type_t::j_long: - ss << "Long: " << data.long_data; - break; - case constant_type_t::j_string_data: - ss << "StrData: " << str_data; - break; - case constant_type_t::j_string: - ss << "Str: " << data.index; - break; - case constant_type_t::j_fieldref: - ss << "FieldRef: " << data.ref_type.class_idx << " " << data.ref_type.name_and_type_idx; - break; - case constant_type_t::j_methodref: - ss << "MethodRef: " << data.ref_type.class_idx << " " << data.ref_type.name_and_type_idx; - break; - case constant_type_t::j_interface_methodref: - ss << "IfMethodRef: " << data.ref_type.class_idx << " " << data.ref_type.name_and_type_idx; - break; - case constant_type_t::j_class: - ss << "Class: " << data.ref_type.class_idx; - break; - case constant_type_t::j_nameandtype: - ss << "NameAndType: " << data.name_and_type.name_index << " " - << data.name_and_type.descriptor_index; - break; - default: - ss << "Invalid entry (" << int(type) << ")"; - break; - } - return ss.str(); - } - - std::string str_data; /** String data in 'modified utf-8'.*/ - - // store everything here. - union - { - int32_t int_data; - int64_t long_data; - float float_data; - double double_data; - uint16_t index; - ref_type_t ref_type; - name_and_type_t name_and_type; - } data = {0}; -}; - -/** - * A helper class that represents the custom container used in Java class file for storage of - * constants - */ -class constant_pool -{ -public: - /** - * Create a pool of constants - */ - constant_pool() - { - } - /** - * Load a java constant pool - */ - void load(util::membuffer &buf) - { - // FIXME: @SANITY this should check for the end of buffer. - uint16_t length = 0; - buf.read_be(length); - length--; - const constant *last_constant = nullptr; - while (length) - { - const constant &cnst = constant(buf); - constants.push_back(cnst); - last_constant = &constants[constants.size() - 1]; - if (last_constant->type == constant_type_t::j_double || - last_constant->type == constant_type_t::j_long) - { - // push in a fake constant to preserve indexing - constants.push_back(constant(0)); - length -= 2; - } - else - { - length--; - } - } - } - typedef std::vector container_type; - /** - * Access constants based on jar file index numbers (index of the first element is 1) - */ - java::constant &operator[](std::size_t constant_index) - { - if (constant_index == 0 || constant_index > constants.size()) - { - throw classfile_exception(); - } - return constants[constant_index - 1]; - } - ; - container_type::const_iterator begin() const - { - return constants.begin(); - } - ; - container_type::const_iterator end() const - { - return constants.end(); - } - -private: - container_type constants; -}; -} diff --git a/libraries/classparser/src/errors.h b/libraries/classparser/src/errors.h deleted file mode 100644 index ddbbd828..00000000 --- a/libraries/classparser/src/errors.h +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once -#include -namespace java -{ -class classfile_exception : public std::exception -{ -}; -} diff --git a/libraries/classparser/src/javaendian.h b/libraries/classparser/src/javaendian.h deleted file mode 100644 index 5a6e107b..00000000 --- a/libraries/classparser/src/javaendian.h +++ /dev/null @@ -1,59 +0,0 @@ -#pragma once -#include - -/** - * Swap bytes between big endian and local number representation - */ -namespace util -{ -#ifdef MULTIMC_BIG_ENDIAN -inline uint64_t bigswap(uint64_t x) -{ - return x; -} - -inline uint32_t bigswap(uint32_t x) -{ - return x; -} - -inline uint16_t bigswap(uint16_t x) -{ - return x; -} - -#else -inline uint64_t bigswap(uint64_t x) -{ - return (x >> 56) | ((x << 40) & 0x00FF000000000000) | ((x << 24) & 0x0000FF0000000000) | - ((x << 8) & 0x000000FF00000000) | ((x >> 8) & 0x00000000FF000000) | - ((x >> 24) & 0x0000000000FF0000) | ((x >> 40) & 0x000000000000FF00) | (x << 56); -} - -inline uint32_t bigswap(uint32_t x) -{ - return (x >> 24) | ((x << 8) & 0x00FF0000) | ((x >> 8) & 0x0000FF00) | (x << 24); -} - -inline uint16_t bigswap(uint16_t x) -{ - return (x >> 8) | (x << 8); -} - -#endif - -inline int64_t bigswap(int64_t x) -{ - return static_cast(bigswap(static_cast(x))); -} - -inline int32_t bigswap(int32_t x) -{ - return static_cast(bigswap(static_cast(x))); -} - -inline int16_t bigswap(int16_t x) -{ - return static_cast(bigswap(static_cast(x))); -} -} diff --git a/libraries/classparser/src/membuffer.h b/libraries/classparser/src/membuffer.h deleted file mode 100644 index f81c9705..00000000 --- a/libraries/classparser/src/membuffer.h +++ /dev/null @@ -1,63 +0,0 @@ -#pragma once -#include -#include -#include -#include -#include "javaendian.h" - -namespace util -{ -class membuffer -{ -public: - membuffer(char *buffer, std::size_t size) - { - current = start = buffer; - end = start + size; - } - ~membuffer() - { - // maybe? possibly? left out to avoid confusion. for now. - // delete start; - } - /** - * Read some value. That's all ;) - */ - template void read(T &val) - { - val = *(T *)current; - current += sizeof(T); - } - /** - * Read a big-endian number - * valid for 2-byte, 4-byte and 8-byte variables - */ - template void read_be(T &val) - { - val = util::bigswap(*(T *)current); - current += sizeof(T); - } - /** - * Read a string in the format: - * 2B length (big endian, unsigned) - * length bytes data - */ - void read_jstr(std::string &str) - { - uint16_t length = 0; - read_be(length); - str.append(current, length); - current += length; - } - /** - * Skip N bytes - */ - void skip(std::size_t N) - { - current += N; - } - -private: - char *start, *end, *current; -}; -} diff --git a/libraries/xz-embedded/CMakeLists.txt b/libraries/xz-embedded/CMakeLists.txt deleted file mode 100644 index 4ce46102..00000000 --- a/libraries/xz-embedded/CMakeLists.txt +++ /dev/null @@ -1,26 +0,0 @@ -cmake_minimum_required(VERSION 3.9.4) -project(xz-embedded LANGUAGES C) - -option(XZ_BUILD_BCJ "Build xz-embedded with BCJ support (native binary optimization)" OFF) -option(XZ_BUILD_CRC64 "Build xz-embedded with CRC64 checksum support" ON) -option(XZ_BUILD_MINIDEC "Build a tiny utility that decompresses xz streams" OFF) - -# See include/xz.h for manual feature configuration -# tweak this list and xz.h to fit your needs - -set(XZ_SOURCES - src/xz_crc32.c - src/xz_crc64.c - src/xz_dec_lzma2.c - src/xz_dec_stream.c -# src/xz_dec_bcj.c -) -add_library(xz-embedded STATIC ${XZ_SOURCES}) -target_include_directories(xz-embedded PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include") -set_property(TARGET xz-embedded PROPERTY C_STANDARD 99) - -if(${XZ_BUILD_MINIDEC}) - add_executable(xzminidec xzminidec.c) - target_link_libraries(xzminidec xz-embedded) - set_property(TARGET xzminidec PROPERTY C_STANDARD 99) -endif() diff --git a/libraries/xz-embedded/include/xz.h b/libraries/xz-embedded/include/xz.h deleted file mode 100644 index 3779124c..00000000 --- a/libraries/xz-embedded/include/xz.h +++ /dev/null @@ -1,321 +0,0 @@ -/* - * XZ decompressor - * - * Authors: Lasse Collin - * Igor Pavlov - * - * This file has been put into the public domain. - * You can do whatever you want with this file. - */ - -#ifndef XZ_H -#define XZ_H - -#ifdef __KERNEL__ -#include -#include -#else -#include -#include -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -/* Definitions that determine available features */ -#define XZ_DEC_ANY_CHECK 1 -#define XZ_USE_CRC64 1 - -// native machine code compression stuff -/* -#define XZ_DEC_X86 -#define XZ_DEC_POWERPC -#define XZ_DEC_IA64 -#define XZ_DEC_ARM -#define XZ_DEC_ARMTHUMB -#define XZ_DEC_SPARC -*/ - -/* In Linux, this is used to make extern functions static when needed. */ -#ifndef XZ_EXTERN -#define XZ_EXTERN extern -#endif - -/** - * enum xz_mode - Operation mode - * - * @XZ_SINGLE: Single-call mode. This uses less RAM than - * than multi-call modes, because the LZMA2 - * dictionary doesn't need to be allocated as - * part of the decoder state. All required data - * structures are allocated at initialization, - * so xz_dec_run() cannot return XZ_MEM_ERROR. - * @XZ_PREALLOC: Multi-call mode with preallocated LZMA2 - * dictionary buffer. All data structures are - * allocated at initialization, so xz_dec_run() - * cannot return XZ_MEM_ERROR. - * @XZ_DYNALLOC: Multi-call mode. The LZMA2 dictionary is - * allocated once the required size has been - * parsed from the stream headers. If the - * allocation fails, xz_dec_run() will return - * XZ_MEM_ERROR. - * - * It is possible to enable support only for a subset of the above - * modes at compile time by defining XZ_DEC_SINGLE, XZ_DEC_PREALLOC, - * or XZ_DEC_DYNALLOC. The xz_dec kernel module is always compiled - * with support for all operation modes, but the preboot code may - * be built with fewer features to minimize code size. - */ -enum xz_mode -{ - XZ_SINGLE, - XZ_PREALLOC, - XZ_DYNALLOC -}; - -/** - * enum xz_ret - Return codes - * @XZ_OK: Everything is OK so far. More input or more - * output space is required to continue. This - * return code is possible only in multi-call mode - * (XZ_PREALLOC or XZ_DYNALLOC). - * @XZ_STREAM_END: Operation finished successfully. - * @XZ_UNSUPPORTED_CHECK: Integrity check type is not supported. Decoding - * is still possible in multi-call mode by simply - * calling xz_dec_run() again. - * Note that this return value is used only if - * XZ_DEC_ANY_CHECK was defined at build time, - * which is not used in the kernel. Unsupported - * check types return XZ_OPTIONS_ERROR if - * XZ_DEC_ANY_CHECK was not defined at build time. - * @XZ_MEM_ERROR: Allocating memory failed. This return code is - * possible only if the decoder was initialized - * with XZ_DYNALLOC. The amount of memory that was - * tried to be allocated was no more than the - * dict_max argument given to xz_dec_init(). - * @XZ_MEMLIMIT_ERROR: A bigger LZMA2 dictionary would be needed than - * allowed by the dict_max argument given to - * xz_dec_init(). This return value is possible - * only in multi-call mode (XZ_PREALLOC or - * XZ_DYNALLOC); the single-call mode (XZ_SINGLE) - * ignores the dict_max argument. - * @XZ_FORMAT_ERROR: File format was not recognized (wrong magic - * bytes). - * @XZ_OPTIONS_ERROR: This implementation doesn't support the requested - * compression options. In the decoder this means - * that the header CRC32 matches, but the header - * itself specifies something that we don't support. - * @XZ_DATA_ERROR: Compressed data is corrupt. - * @XZ_BUF_ERROR: Cannot make any progress. Details are slightly - * different between multi-call and single-call - * mode; more information below. - * - * In multi-call mode, XZ_BUF_ERROR is returned when two consecutive calls - * to XZ code cannot consume any input and cannot produce any new output. - * This happens when there is no new input available, or the output buffer - * is full while at least one output byte is still pending. Assuming your - * code is not buggy, you can get this error only when decoding a compressed - * stream that is truncated or otherwise corrupt. - * - * In single-call mode, XZ_BUF_ERROR is returned only when the output buffer - * is too small or the compressed input is corrupt in a way that makes the - * decoder produce more output than the caller expected. When it is - * (relatively) clear that the compressed input is truncated, XZ_DATA_ERROR - * is used instead of XZ_BUF_ERROR. - */ -enum xz_ret -{ - XZ_OK, - XZ_STREAM_END, - XZ_UNSUPPORTED_CHECK, - XZ_MEM_ERROR, - XZ_MEMLIMIT_ERROR, - XZ_FORMAT_ERROR, - XZ_OPTIONS_ERROR, - XZ_DATA_ERROR, - XZ_BUF_ERROR -}; - -/** - * struct xz_buf - Passing input and output buffers to XZ code - * @in: Beginning of the input buffer. This may be NULL if and only - * if in_pos is equal to in_size. - * @in_pos: Current position in the input buffer. This must not exceed - * in_size. - * @in_size: Size of the input buffer - * @out: Beginning of the output buffer. This may be NULL if and only - * if out_pos is equal to out_size. - * @out_pos: Current position in the output buffer. This must not exceed - * out_size. - * @out_size: Size of the output buffer - * - * Only the contents of the output buffer from out[out_pos] onward, and - * the variables in_pos and out_pos are modified by the XZ code. - */ -struct xz_buf -{ - const uint8_t *in; - size_t in_pos; - size_t in_size; - - uint8_t *out; - size_t out_pos; - size_t out_size; -}; - -/** - * struct xz_dec - Opaque type to hold the XZ decoder state - */ -struct xz_dec; - -/** - * xz_dec_init() - Allocate and initialize a XZ decoder state - * @mode: Operation mode - * @dict_max: Maximum size of the LZMA2 dictionary (history buffer) for - * multi-call decoding. This is ignored in single-call mode - * (mode == XZ_SINGLE). LZMA2 dictionary is always 2^n bytes - * or 2^n + 2^(n-1) bytes (the latter sizes are less common - * in practice), so other values for dict_max don't make sense. - * In the kernel, dictionary sizes of 64 KiB, 128 KiB, 256 KiB, - * 512 KiB, and 1 MiB are probably the only reasonable values, - * except for kernel and initramfs images where a bigger - * dictionary can be fine and useful. - * - * Single-call mode (XZ_SINGLE): xz_dec_run() decodes the whole stream at - * once. The caller must provide enough output space or the decoding will - * fail. The output space is used as the dictionary buffer, which is why - * there is no need to allocate the dictionary as part of the decoder's - * internal state. - * - * Because the output buffer is used as the workspace, streams encoded using - * a big dictionary are not a problem in single-call mode. It is enough that - * the output buffer is big enough to hold the actual uncompressed data; it - * can be smaller than the dictionary size stored in the stream headers. - * - * Multi-call mode with preallocated dictionary (XZ_PREALLOC): dict_max bytes - * of memory is preallocated for the LZMA2 dictionary. This way there is no - * risk that xz_dec_run() could run out of memory, since xz_dec_run() will - * never allocate any memory. Instead, if the preallocated dictionary is too - * small for decoding the given input stream, xz_dec_run() will return - * XZ_MEMLIMIT_ERROR. Thus, it is important to know what kind of data will be - * decoded to avoid allocating excessive amount of memory for the dictionary. - * - * Multi-call mode with dynamically allocated dictionary (XZ_DYNALLOC): - * dict_max specifies the maximum allowed dictionary size that xz_dec_run() - * may allocate once it has parsed the dictionary size from the stream - * headers. This way excessive allocations can be avoided while still - * limiting the maximum memory usage to a sane value to prevent running the - * system out of memory when decompressing streams from untrusted sources. - * - * On success, xz_dec_init() returns a pointer to struct xz_dec, which is - * ready to be used with xz_dec_run(). If memory allocation fails, - * xz_dec_init() returns NULL. - */ -XZ_EXTERN struct xz_dec *xz_dec_init(enum xz_mode mode, uint32_t dict_max); - -/** - * xz_dec_run() - Run the XZ decoder - * @s: Decoder state allocated using xz_dec_init() - * @b: Input and output buffers - * - * The possible return values depend on build options and operation mode. - * See enum xz_ret for details. - * - * Note that if an error occurs in single-call mode (return value is not - * XZ_STREAM_END), b->in_pos and b->out_pos are not modified and the - * contents of the output buffer from b->out[b->out_pos] onward are - * undefined. This is true even after XZ_BUF_ERROR, because with some filter - * chains, there may be a second pass over the output buffer, and this pass - * cannot be properly done if the output buffer is truncated. Thus, you - * cannot give the single-call decoder a too small buffer and then expect to - * get that amount valid data from the beginning of the stream. You must use - * the multi-call decoder if you don't want to uncompress the whole stream. - */ -XZ_EXTERN enum xz_ret xz_dec_run(struct xz_dec *s, struct xz_buf *b); - -/** - * xz_dec_reset() - Reset an already allocated decoder state - * @s: Decoder state allocated using xz_dec_init() - * - * This function can be used to reset the multi-call decoder state without - * freeing and reallocating memory with xz_dec_end() and xz_dec_init(). - * - * In single-call mode, xz_dec_reset() is always called in the beginning of - * xz_dec_run(). Thus, explicit call to xz_dec_reset() is useful only in - * multi-call mode. - */ -XZ_EXTERN void xz_dec_reset(struct xz_dec *s); - -/** - * xz_dec_end() - Free the memory allocated for the decoder state - * @s: Decoder state allocated using xz_dec_init(). If s is NULL, - * this function does nothing. - */ -XZ_EXTERN void xz_dec_end(struct xz_dec *s); - -/* - * Standalone build (userspace build or in-kernel build for boot time use) - * needs a CRC32 implementation. For normal in-kernel use, kernel's own - * CRC32 module is used instead, and users of this module don't need to - * care about the functions below. - */ -#ifndef XZ_INTERNAL_CRC32 -#ifdef __KERNEL__ -#define XZ_INTERNAL_CRC32 0 -#else -#define XZ_INTERNAL_CRC32 1 -#endif -#endif - -/* - * If CRC64 support has been enabled with XZ_USE_CRC64, a CRC64 - * implementation is needed too. - */ -#ifndef XZ_USE_CRC64 -#undef XZ_INTERNAL_CRC64 -#define XZ_INTERNAL_CRC64 0 -#endif -#ifndef XZ_INTERNAL_CRC64 -#ifdef __KERNEL__ -#error Using CRC64 in the kernel has not been implemented. -#else -#define XZ_INTERNAL_CRC64 1 -#endif -#endif - -#if XZ_INTERNAL_CRC32 -/* - * This must be called before any other xz_* function to initialize - * the CRC32 lookup table. - */ -XZ_EXTERN void xz_crc32_init(void); - -/* - * Update CRC32 value using the polynomial from IEEE-802.3. To start a new - * calculation, the third argument must be zero. To continue the calculation, - * the previously returned value is passed as the third argument. - */ -XZ_EXTERN uint32_t xz_crc32(const uint8_t *buf, size_t size, uint32_t crc); -#endif - -#if XZ_INTERNAL_CRC64 -/* - * This must be called before any other xz_* function (except xz_crc32_init()) - * to initialize the CRC64 lookup table. - */ -XZ_EXTERN void xz_crc64_init(void); - -/* - * Update CRC64 value using the polynomial from ECMA-182. To start a new - * calculation, the third argument must be zero. To continue the calculation, - * the previously returned value is passed as the third argument. - */ -XZ_EXTERN uint64_t xz_crc64(const uint8_t *buf, size_t size, uint64_t crc); -#endif - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/libraries/xz-embedded/src/xz_config.h b/libraries/xz-embedded/src/xz_config.h deleted file mode 100644 index effdb1bd..00000000 --- a/libraries/xz-embedded/src/xz_config.h +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Private includes and definitions for userspace use of XZ Embedded - * - * Author: Lasse Collin - * - * This file has been put into the public domain. - * You can do whatever you want with this file. - */ - -#ifndef XZ_CONFIG_H -#define XZ_CONFIG_H - -/* Uncomment to enable CRC64 support. */ -/* #define XZ_USE_CRC64 */ - -/* Uncomment as needed to enable BCJ filter decoders. */ -/* #define XZ_DEC_X86 */ -/* #define XZ_DEC_POWERPC */ -/* #define XZ_DEC_IA64 */ -/* #define XZ_DEC_ARM */ -/* #define XZ_DEC_ARMTHUMB */ -/* #define XZ_DEC_SPARC */ - -/* - * MSVC doesn't support modern C but XZ Embedded is mostly C89 - * so these are enough. - */ -#ifdef _MSC_VER -typedef unsigned char bool; -#define true 1 -#define false 0 -#define inline __inline -#else -#include -#endif - -#include -#include - -#include "xz.h" - -#define kmalloc(size, flags) malloc(size) -#define kfree(ptr) free(ptr) -#define vmalloc(size) malloc(size) -#define vfree(ptr) free(ptr) - -#define memeq(a, b, size) (memcmp(a, b, size) == 0) -#define memzero(buf, size) memset(buf, 0, size) - -#ifndef min -#define min(x, y) ((x) < (y) ? (x) : (y)) -#endif -#define min_t(type, x, y) min(x, y) - -/* - * Some functions have been marked with __always_inline to keep the - * performance reasonable even when the compiler is optimizing for - * small code size. You may be able to save a few bytes by #defining - * __always_inline to plain inline, but don't complain if the code - * becomes slow. - * - * NOTE: System headers on GNU/Linux may #define this macro already, - * so if you want to change it, you need to #undef it first. - */ -#ifndef __always_inline -#ifdef __GNUC__ -#define __always_inline inline __attribute__((__always_inline__)) -#else -#define __always_inline inline -#endif -#endif - -/* Inline functions to access unaligned unsigned 32-bit integers */ -#ifndef get_unaligned_le32 -static inline uint32_t get_unaligned_le32(const uint8_t *buf) -{ - return (uint32_t)buf[0] | ((uint32_t)buf[1] << 8) | ((uint32_t)buf[2] << 16) | - ((uint32_t)buf[3] << 24); -} -#endif - -#ifndef get_unaligned_be32 -static inline uint32_t get_unaligned_be32(const uint8_t *buf) -{ - return (uint32_t)(buf[0] << 24) | ((uint32_t)buf[1] << 16) | ((uint32_t)buf[2] << 8) | - (uint32_t)buf[3]; -} -#endif - -#ifndef put_unaligned_le32 -static inline void put_unaligned_le32(uint32_t val, uint8_t *buf) -{ - buf[0] = (uint8_t)val; - buf[1] = (uint8_t)(val >> 8); - buf[2] = (uint8_t)(val >> 16); - buf[3] = (uint8_t)(val >> 24); -} -#endif - -#ifndef put_unaligned_be32 -static inline void put_unaligned_be32(uint32_t val, uint8_t *buf) -{ - buf[0] = (uint8_t)(val >> 24); - buf[1] = (uint8_t)(val >> 16); - buf[2] = (uint8_t)(val >> 8); - buf[3] = (uint8_t)val; -} -#endif - -/* - * Use get_unaligned_le32() also for aligned access for simplicity. On - * little endian systems, #define get_le32(ptr) (*(const uint32_t *)(ptr)) - * could save a few bytes in code size. - */ -#ifndef get_le32 -#define get_le32 get_unaligned_le32 -#endif - -#endif diff --git a/libraries/xz-embedded/src/xz_crc32.c b/libraries/xz-embedded/src/xz_crc32.c deleted file mode 100644 index 65d9d5b8..00000000 --- a/libraries/xz-embedded/src/xz_crc32.c +++ /dev/null @@ -1,61 +0,0 @@ -/* - * CRC32 using the polynomial from IEEE-802.3 - * - * Authors: Lasse Collin - * Igor Pavlov - * - * This file has been put into the public domain. - * You can do whatever you want with this file. - */ - -/* - * This is not the fastest implementation, but it is pretty compact. - * The fastest versions of xz_crc32() on modern CPUs without hardware - * accelerated CRC instruction are 3-5 times as fast as this version, - * but they are bigger and use more memory for the lookup table. - */ - -#include "xz_private.h" - -/* - * STATIC_RW_DATA is used in the pre-boot environment on some architectures. - * See for details. - */ -#ifndef STATIC_RW_DATA -#define STATIC_RW_DATA static -#endif - -STATIC_RW_DATA uint32_t xz_crc32_table[256]; - -XZ_EXTERN void xz_crc32_init(void) -{ - const uint32_t poly = 0xEDB88320; - - uint32_t i; - uint32_t j; - uint32_t r; - - for (i = 0; i < 256; ++i) - { - r = i; - for (j = 0; j < 8; ++j) - r = (r >> 1) ^ (poly & ~((r & 1) - 1)); - - xz_crc32_table[i] = r; - } - - return; -} - -XZ_EXTERN uint32_t xz_crc32(const uint8_t *buf, size_t size, uint32_t crc) -{ - crc = ~crc; - - while (size != 0) - { - crc = xz_crc32_table[*buf++ ^ (crc & 0xFF)] ^ (crc >> 8); - --size; - } - - return ~crc; -} diff --git a/libraries/xz-embedded/src/xz_crc64.c b/libraries/xz-embedded/src/xz_crc64.c deleted file mode 100644 index 0f711d8d..00000000 --- a/libraries/xz-embedded/src/xz_crc64.c +++ /dev/null @@ -1,52 +0,0 @@ -/* - * CRC64 using the polynomial from ECMA-182 - * - * This file is similar to xz_crc32.c. See the comments there. - * - * Authors: Lasse Collin - * Igor Pavlov - * - * This file has been put into the public domain. - * You can do whatever you want with this file. - */ - -#include "xz_private.h" - -#ifndef STATIC_RW_DATA -#define STATIC_RW_DATA static -#endif - -STATIC_RW_DATA uint64_t xz_crc64_table[256]; - -XZ_EXTERN void xz_crc64_init(void) -{ - const uint64_t poly = 0xC96C5795D7870F42; - - uint32_t i; - uint32_t j; - uint64_t r; - - for (i = 0; i < 256; ++i) - { - r = i; - for (j = 0; j < 8; ++j) - r = (r >> 1) ^ (poly & ~((r & 1) - 1)); - - xz_crc64_table[i] = r; - } - - return; -} - -XZ_EXTERN uint64_t xz_crc64(const uint8_t *buf, size_t size, uint64_t crc) -{ - crc = ~crc; - - while (size != 0) - { - crc = xz_crc64_table[*buf++ ^ (crc & 0xFF)] ^ (crc >> 8); - --size; - } - - return ~crc; -} diff --git a/libraries/xz-embedded/src/xz_dec_bcj.c b/libraries/xz-embedded/src/xz_dec_bcj.c deleted file mode 100644 index a79fa76d..00000000 --- a/libraries/xz-embedded/src/xz_dec_bcj.c +++ /dev/null @@ -1,588 +0,0 @@ -/* - * Branch/Call/Jump (BCJ) filter decoders - * - * Authors: Lasse Collin - * Igor Pavlov - * - * This file has been put into the public domain. - * You can do whatever you want with this file. - */ - -#include "xz_private.h" - -/* - * The rest of the file is inside this ifdef. It makes things a little more - * convenient when building without support for any BCJ filters. - */ -#ifdef XZ_DEC_BCJ - -struct xz_dec_bcj -{ - /* Type of the BCJ filter being used */ - enum - { - BCJ_X86 = 4, /* x86 or x86-64 */ - BCJ_POWERPC = 5, /* Big endian only */ - BCJ_IA64 = 6, /* Big or little endian */ - BCJ_ARM = 7, /* Little endian only */ - BCJ_ARMTHUMB = 8, /* Little endian only */ - BCJ_SPARC = 9 /* Big or little endian */ - } type; - - /* - * Return value of the next filter in the chain. We need to preserve - * this information across calls, because we must not call the next - * filter anymore once it has returned XZ_STREAM_END. - */ - enum xz_ret ret; - - /* True if we are operating in single-call mode. */ - bool single_call; - - /* - * Absolute position relative to the beginning of the uncompressed - * data (in a single .xz Block). We care only about the lowest 32 - * bits so this doesn't need to be uint64_t even with big files. - */ - uint32_t pos; - - /* x86 filter state */ - uint32_t x86_prev_mask; - - /* Temporary space to hold the variables from struct xz_buf */ - uint8_t *out; - size_t out_pos; - size_t out_size; - - struct - { - /* Amount of already filtered data in the beginning of buf */ - size_t filtered; - - /* Total amount of data currently stored in buf */ - size_t size; - - /* - * Buffer to hold a mix of filtered and unfiltered data. This - * needs to be big enough to hold Alignment + 2 * Look-ahead: - * - * Type Alignment Look-ahead - * x86 1 4 - * PowerPC 4 0 - * IA-64 16 0 - * ARM 4 0 - * ARM-Thumb 2 2 - * SPARC 4 0 - */ - uint8_t buf[16]; - } temp; -}; - -#ifdef XZ_DEC_X86 -/* - * This is used to test the most significant byte of a memory address - * in an x86 instruction. - */ -static inline int bcj_x86_test_msbyte(uint8_t b) -{ - return b == 0x00 || b == 0xFF; -} - -static size_t bcj_x86(struct xz_dec_bcj *s, uint8_t *buf, size_t size) -{ - static const bool mask_to_allowed_status[8] = {true, true, true, false, - true, false, false, false}; - - static const uint8_t mask_to_bit_num[8] = {0, 1, 2, 2, 3, 3, 3, 3}; - - size_t i; - size_t prev_pos = (size_t) - 1; - uint32_t prev_mask = s->x86_prev_mask; - uint32_t src; - uint32_t dest; - uint32_t j; - uint8_t b; - - if (size <= 4) - return 0; - - size -= 4; - for (i = 0; i < size; ++i) - { - if ((buf[i] & 0xFE) != 0xE8) - continue; - - prev_pos = i - prev_pos; - if (prev_pos > 3) - { - prev_mask = 0; - } - else - { - prev_mask = (prev_mask << (prev_pos - 1)) & 7; - if (prev_mask != 0) - { - b = buf[i + 4 - mask_to_bit_num[prev_mask]]; - if (!mask_to_allowed_status[prev_mask] || bcj_x86_test_msbyte(b)) - { - prev_pos = i; - prev_mask = (prev_mask << 1) | 1; - continue; - } - } - } - - prev_pos = i; - - if (bcj_x86_test_msbyte(buf[i + 4])) - { - src = get_unaligned_le32(buf + i + 1); - while (true) - { - dest = src - (s->pos + (uint32_t)i + 5); - if (prev_mask == 0) - break; - - j = mask_to_bit_num[prev_mask] * 8; - b = (uint8_t)(dest >> (24 - j)); - if (!bcj_x86_test_msbyte(b)) - break; - - src = dest ^ (((uint32_t)1 << (32 - j)) - 1); - } - - dest &= 0x01FFFFFF; - dest |= (uint32_t)0 - (dest & 0x01000000); - put_unaligned_le32(dest, buf + i + 1); - i += 4; - } - else - { - prev_mask = (prev_mask << 1) | 1; - } - } - - prev_pos = i - prev_pos; - s->x86_prev_mask = prev_pos > 3 ? 0 : prev_mask << (prev_pos - 1); - return i; -} -#endif - -#ifdef XZ_DEC_POWERPC -static size_t bcj_powerpc(struct xz_dec_bcj *s, uint8_t *buf, size_t size) -{ - size_t i; - uint32_t instr; - - for (i = 0; i + 4 <= size; i += 4) - { - instr = get_unaligned_be32(buf + i); - if ((instr & 0xFC000003) == 0x48000001) - { - instr &= 0x03FFFFFC; - instr -= s->pos + (uint32_t)i; - instr &= 0x03FFFFFC; - instr |= 0x48000001; - put_unaligned_be32(instr, buf + i); - } - } - - return i; -} -#endif - -#ifdef XZ_DEC_IA64 -static size_t bcj_ia64(struct xz_dec_bcj *s, uint8_t *buf, size_t size) -{ - static const uint8_t branch_table[32] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 4, 4, 6, 6, 0, 0, 7, 7, 4, 4, 0, 0, 4, 4, 0, 0}; - - /* - * The local variables take a little bit stack space, but it's less - * than what LZMA2 decoder takes, so it doesn't make sense to reduce - * stack usage here without doing that for the LZMA2 decoder too. - */ - - /* Loop counters */ - size_t i; - size_t j; - - /* Instruction slot (0, 1, or 2) in the 128-bit instruction word */ - uint32_t slot; - - /* Bitwise offset of the instruction indicated by slot */ - uint32_t bit_pos; - - /* bit_pos split into byte and bit parts */ - uint32_t byte_pos; - uint32_t bit_res; - - /* Address part of an instruction */ - uint32_t addr; - - /* Mask used to detect which instructions to convert */ - uint32_t mask; - - /* 41-bit instruction stored somewhere in the lowest 48 bits */ - uint64_t instr; - - /* Instruction normalized with bit_res for easier manipulation */ - uint64_t norm; - - for (i = 0; i + 16 <= size; i += 16) - { - mask = branch_table[buf[i] & 0x1F]; - for (slot = 0, bit_pos = 5; slot < 3; ++slot, bit_pos += 41) - { - if (((mask >> slot) & 1) == 0) - continue; - - byte_pos = bit_pos >> 3; - bit_res = bit_pos & 7; - instr = 0; - for (j = 0; j < 6; ++j) - instr |= (uint64_t)(buf[i + j + byte_pos]) << (8 * j); - - norm = instr >> bit_res; - - if (((norm >> 37) & 0x0F) == 0x05 && ((norm >> 9) & 0x07) == 0) - { - addr = (norm >> 13) & 0x0FFFFF; - addr |= ((uint32_t)(norm >> 36) & 1) << 20; - addr <<= 4; - addr -= s->pos + (uint32_t)i; - addr >>= 4; - - norm &= ~((uint64_t)0x8FFFFF << 13); - norm |= (uint64_t)(addr & 0x0FFFFF) << 13; - norm |= (uint64_t)(addr & 0x100000) << (36 - 20); - - instr &= (1 << bit_res) - 1; - instr |= norm << bit_res; - - for (j = 0; j < 6; j++) - buf[i + j + byte_pos] = (uint8_t)(instr >> (8 * j)); - } - } - } - - return i; -} -#endif - -#ifdef XZ_DEC_ARM -static size_t bcj_arm(struct xz_dec_bcj *s, uint8_t *buf, size_t size) -{ - size_t i; - uint32_t addr; - - for (i = 0; i + 4 <= size; i += 4) - { - if (buf[i + 3] == 0xEB) - { - addr = - (uint32_t)buf[i] | ((uint32_t)buf[i + 1] << 8) | ((uint32_t)buf[i + 2] << 16); - addr <<= 2; - addr -= s->pos + (uint32_t)i + 8; - addr >>= 2; - buf[i] = (uint8_t)addr; - buf[i + 1] = (uint8_t)(addr >> 8); - buf[i + 2] = (uint8_t)(addr >> 16); - } - } - - return i; -} -#endif - -#ifdef XZ_DEC_ARMTHUMB -static size_t bcj_armthumb(struct xz_dec_bcj *s, uint8_t *buf, size_t size) -{ - size_t i; - uint32_t addr; - - for (i = 0; i + 4 <= size; i += 2) - { - if ((buf[i + 1] & 0xF8) == 0xF0 && (buf[i + 3] & 0xF8) == 0xF8) - { - addr = (((uint32_t)buf[i + 1] & 0x07) << 19) | ((uint32_t)buf[i] << 11) | - (((uint32_t)buf[i + 3] & 0x07) << 8) | (uint32_t)buf[i + 2]; - addr <<= 1; - addr -= s->pos + (uint32_t)i + 4; - addr >>= 1; - buf[i + 1] = (uint8_t)(0xF0 | ((addr >> 19) & 0x07)); - buf[i] = (uint8_t)(addr >> 11); - buf[i + 3] = (uint8_t)(0xF8 | ((addr >> 8) & 0x07)); - buf[i + 2] = (uint8_t)addr; - i += 2; - } - } - - return i; -} -#endif - -#ifdef XZ_DEC_SPARC -static size_t bcj_sparc(struct xz_dec_bcj *s, uint8_t *buf, size_t size) -{ - size_t i; - uint32_t instr; - - for (i = 0; i + 4 <= size; i += 4) - { - instr = get_unaligned_be32(buf + i); - if ((instr >> 22) == 0x100 || (instr >> 22) == 0x1FF) - { - instr <<= 2; - instr -= s->pos + (uint32_t)i; - instr >>= 2; - instr = - ((uint32_t)0x40000000 - (instr & 0x400000)) | 0x40000000 | (instr & 0x3FFFFF); - put_unaligned_be32(instr, buf + i); - } - } - - return i; -} -#endif - -/* - * Apply the selected BCJ filter. Update *pos and s->pos to match the amount - * of data that got filtered. - * - * NOTE: This is implemented as a switch statement to avoid using function - * pointers, which could be problematic in the kernel boot code, which must - * avoid pointers to static data (at least on x86). - */ -static void bcj_apply(struct xz_dec_bcj *s, uint8_t *buf, size_t *pos, size_t size) -{ - size_t filtered; - - buf += *pos; - size -= *pos; - - switch (s->type) - { -#ifdef XZ_DEC_X86 - case BCJ_X86: - filtered = bcj_x86(s, buf, size); - break; -#endif -#ifdef XZ_DEC_POWERPC - case BCJ_POWERPC: - filtered = bcj_powerpc(s, buf, size); - break; -#endif -#ifdef XZ_DEC_IA64 - case BCJ_IA64: - filtered = bcj_ia64(s, buf, size); - break; -#endif -#ifdef XZ_DEC_ARM - case BCJ_ARM: - filtered = bcj_arm(s, buf, size); - break; -#endif -#ifdef XZ_DEC_ARMTHUMB - case BCJ_ARMTHUMB: - filtered = bcj_armthumb(s, buf, size); - break; -#endif -#ifdef XZ_DEC_SPARC - case BCJ_SPARC: - filtered = bcj_sparc(s, buf, size); - break; -#endif - default: - /* Never reached but silence compiler warnings. */ - filtered = 0; - break; - } - - *pos += filtered; - s->pos += filtered; -} - -/* - * Flush pending filtered data from temp to the output buffer. - * Move the remaining mixture of possibly filtered and unfiltered - * data to the beginning of temp. - */ -static void bcj_flush(struct xz_dec_bcj *s, struct xz_buf *b) -{ - size_t copy_size; - - copy_size = min_t(size_t, s->temp.filtered, b->out_size - b->out_pos); - memcpy(b->out + b->out_pos, s->temp.buf, copy_size); - b->out_pos += copy_size; - - s->temp.filtered -= copy_size; - s->temp.size -= copy_size; - memmove(s->temp.buf, s->temp.buf + copy_size, s->temp.size); -} - -/* - * The BCJ filter functions are primitive in sense that they process the - * data in chunks of 1-16 bytes. To hide this issue, this function does - * some buffering. - */ -XZ_EXTERN enum xz_ret xz_dec_bcj_run(struct xz_dec_bcj *s, struct xz_dec_lzma2 *lzma2, - struct xz_buf *b) -{ - size_t out_start; - - /* - * Flush pending already filtered data to the output buffer. Return - * immediatelly if we couldn't flush everything, or if the next - * filter in the chain had already returned XZ_STREAM_END. - */ - if (s->temp.filtered > 0) - { - bcj_flush(s, b); - if (s->temp.filtered > 0) - return XZ_OK; - - if (s->ret == XZ_STREAM_END) - return XZ_STREAM_END; - } - - /* - * If we have more output space than what is currently pending in - * temp, copy the unfiltered data from temp to the output buffer - * and try to fill the output buffer by decoding more data from the - * next filter in the chain. Apply the BCJ filter on the new data - * in the output buffer. If everything cannot be filtered, copy it - * to temp and rewind the output buffer position accordingly. - * - * This needs to be always run when temp.size == 0 to handle a special - * case where the output buffer is full and the next filter has no - * more output coming but hasn't returned XZ_STREAM_END yet. - */ - if (s->temp.size < b->out_size - b->out_pos || s->temp.size == 0) - { - out_start = b->out_pos; - memcpy(b->out + b->out_pos, s->temp.buf, s->temp.size); - b->out_pos += s->temp.size; - - s->ret = xz_dec_lzma2_run(lzma2, b); - if (s->ret != XZ_STREAM_END && (s->ret != XZ_OK || s->single_call)) - return s->ret; - - bcj_apply(s, b->out, &out_start, b->out_pos); - - /* - * As an exception, if the next filter returned XZ_STREAM_END, - * we can do that too, since the last few bytes that remain - * unfiltered are meant to remain unfiltered. - */ - if (s->ret == XZ_STREAM_END) - return XZ_STREAM_END; - - s->temp.size = b->out_pos - out_start; - b->out_pos -= s->temp.size; - memcpy(s->temp.buf, b->out + b->out_pos, s->temp.size); - - /* - * If there wasn't enough input to the next filter to fill - * the output buffer with unfiltered data, there's no point - * to try decoding more data to temp. - */ - if (b->out_pos + s->temp.size < b->out_size) - return XZ_OK; - } - - /* - * We have unfiltered data in temp. If the output buffer isn't full - * yet, try to fill the temp buffer by decoding more data from the - * next filter. Apply the BCJ filter on temp. Then we hopefully can - * fill the actual output buffer by copying filtered data from temp. - * A mix of filtered and unfiltered data may be left in temp; it will - * be taken care on the next call to this function. - */ - if (b->out_pos < b->out_size) - { - /* Make b->out{,_pos,_size} temporarily point to s->temp. */ - s->out = b->out; - s->out_pos = b->out_pos; - s->out_size = b->out_size; - b->out = s->temp.buf; - b->out_pos = s->temp.size; - b->out_size = sizeof(s->temp.buf); - - s->ret = xz_dec_lzma2_run(lzma2, b); - - s->temp.size = b->out_pos; - b->out = s->out; - b->out_pos = s->out_pos; - b->out_size = s->out_size; - - if (s->ret != XZ_OK && s->ret != XZ_STREAM_END) - return s->ret; - - bcj_apply(s, s->temp.buf, &s->temp.filtered, s->temp.size); - - /* - * If the next filter returned XZ_STREAM_END, we mark that - * everything is filtered, since the last unfiltered bytes - * of the stream are meant to be left as is. - */ - if (s->ret == XZ_STREAM_END) - s->temp.filtered = s->temp.size; - - bcj_flush(s, b); - if (s->temp.filtered > 0) - return XZ_OK; - } - - return s->ret; -} - -XZ_EXTERN struct xz_dec_bcj *xz_dec_bcj_create(bool single_call) -{ - struct xz_dec_bcj *s = kmalloc(sizeof(*s), GFP_KERNEL); - if (s != NULL) - s->single_call = single_call; - - return s; -} - -XZ_EXTERN enum xz_ret xz_dec_bcj_reset(struct xz_dec_bcj *s, uint8_t id) -{ - switch (id) - { -#ifdef XZ_DEC_X86 - case BCJ_X86: -#endif -#ifdef XZ_DEC_POWERPC - case BCJ_POWERPC: -#endif -#ifdef XZ_DEC_IA64 - case BCJ_IA64: -#endif -#ifdef XZ_DEC_ARM - case BCJ_ARM: -#endif -#ifdef XZ_DEC_ARMTHUMB - case BCJ_ARMTHUMB: -#endif -#ifdef XZ_DEC_SPARC - case BCJ_SPARC: -#endif - break; - - default: - /* Unsupported Filter ID */ - return XZ_OPTIONS_ERROR; - } - - s->type = id; - s->ret = XZ_OK; - s->pos = 0; - s->x86_prev_mask = 0; - s->temp.filtered = 0; - s->temp.size = 0; - - return XZ_OK; -} - -#endif diff --git a/libraries/xz-embedded/src/xz_dec_lzma2.c b/libraries/xz-embedded/src/xz_dec_lzma2.c deleted file mode 100644 index 365ace2b..00000000 --- a/libraries/xz-embedded/src/xz_dec_lzma2.c +++ /dev/null @@ -1,1231 +0,0 @@ -/* - * LZMA2 decoder - * - * Authors: Lasse Collin - * Igor Pavlov - * - * This file has been put into the public domain. - * You can do whatever you want with this file. - */ - -#include "xz_private.h" -#include "xz_lzma2.h" - -/* - * Range decoder initialization eats the first five bytes of each LZMA chunk. - */ -#define RC_INIT_BYTES 5 - -/* - * Minimum number of usable input buffer to safely decode one LZMA symbol. - * The worst case is that we decode 22 bits using probabilities and 26 - * direct bits. This may decode at maximum of 20 bytes of input. However, - * lzma_main() does an extra normalization before returning, thus we - * need to put 21 here. - */ -#define LZMA_IN_REQUIRED 21 - -/* - * Dictionary (history buffer) - * - * These are always true: - * start <= pos <= full <= end - * pos <= limit <= end - * - * In multi-call mode, also these are true: - * end == size - * size <= size_max - * allocated <= size - * - * Most of these variables are size_t to support single-call mode, - * in which the dictionary variables address the actual output - * buffer directly. - */ -struct dictionary -{ - /* Beginning of the history buffer */ - uint8_t *buf; - - /* Old position in buf (before decoding more data) */ - size_t start; - - /* Position in buf */ - size_t pos; - - /* - * How full dictionary is. This is used to detect corrupt input that - * would read beyond the beginning of the uncompressed stream. - */ - size_t full; - - /* Write limit; we don't write to buf[limit] or later bytes. */ - size_t limit; - - /* - * End of the dictionary buffer. In multi-call mode, this is - * the same as the dictionary size. In single-call mode, this - * indicates the size of the output buffer. - */ - size_t end; - - /* - * Size of the dictionary as specified in Block Header. This is used - * together with "full" to detect corrupt input that would make us - * read beyond the beginning of the uncompressed stream. - */ - uint32_t size; - - /* - * Maximum allowed dictionary size in multi-call mode. - * This is ignored in single-call mode. - */ - uint32_t size_max; - - /* - * Amount of memory currently allocated for the dictionary. - * This is used only with XZ_DYNALLOC. (With XZ_PREALLOC, - * size_max is always the same as the allocated size.) - */ - uint32_t allocated; - - /* Operation mode */ - enum xz_mode mode; -}; - -/* Range decoder */ -struct rc_dec -{ - uint32_t range; - uint32_t code; - - /* - * Number of initializing bytes remaining to be read - * by rc_read_init(). - */ - uint32_t init_bytes_left; - - /* - * Buffer from which we read our input. It can be either - * temp.buf or the caller-provided input buffer. - */ - const uint8_t *in; - size_t in_pos; - size_t in_limit; -}; - -/* Probabilities for a length decoder. */ -struct lzma_len_dec -{ - /* Probability of match length being at least 10 */ - uint16_t choice; - - /* Probability of match length being at least 18 */ - uint16_t choice2; - - /* Probabilities for match lengths 2-9 */ - uint16_t low[POS_STATES_MAX][LEN_LOW_SYMBOLS]; - - /* Probabilities for match lengths 10-17 */ - uint16_t mid[POS_STATES_MAX][LEN_MID_SYMBOLS]; - - /* Probabilities for match lengths 18-273 */ - uint16_t high[LEN_HIGH_SYMBOLS]; -}; - -struct lzma_dec -{ - /* Distances of latest four matches */ - uint32_t rep0; - uint32_t rep1; - uint32_t rep2; - uint32_t rep3; - - /* Types of the most recently seen LZMA symbols */ - enum lzma_state state; - - /* - * Length of a match. This is updated so that dict_repeat can - * be called again to finish repeating the whole match. - */ - uint32_t len; - - /* - * LZMA properties or related bit masks (number of literal - * context bits, a mask dervied from the number of literal - * position bits, and a mask dervied from the number - * position bits) - */ - uint32_t lc; - uint32_t literal_pos_mask; /* (1 << lp) - 1 */ - uint32_t pos_mask; /* (1 << pb) - 1 */ - - /* If 1, it's a match. Otherwise it's a single 8-bit literal. */ - uint16_t is_match[STATES][POS_STATES_MAX]; - - /* If 1, it's a repeated match. The distance is one of rep0 .. rep3. */ - uint16_t is_rep[STATES]; - - /* - * If 0, distance of a repeated match is rep0. - * Otherwise check is_rep1. - */ - uint16_t is_rep0[STATES]; - - /* - * If 0, distance of a repeated match is rep1. - * Otherwise check is_rep2. - */ - uint16_t is_rep1[STATES]; - - /* If 0, distance of a repeated match is rep2. Otherwise it is rep3. */ - uint16_t is_rep2[STATES]; - - /* - * If 1, the repeated match has length of one byte. Otherwise - * the length is decoded from rep_len_decoder. - */ - uint16_t is_rep0_long[STATES][POS_STATES_MAX]; - - /* - * Probability tree for the highest two bits of the match - * distance. There is a separate probability tree for match - * lengths of 2 (i.e. MATCH_LEN_MIN), 3, 4, and [5, 273]. - */ - uint16_t dist_slot[DIST_STATES][DIST_SLOTS]; - - /* - * Probility trees for additional bits for match distance - * when the distance is in the range [4, 127]. - */ - uint16_t dist_special[FULL_DISTANCES - DIST_MODEL_END]; - - /* - * Probability tree for the lowest four bits of a match - * distance that is equal to or greater than 128. - */ - uint16_t dist_align[ALIGN_SIZE]; - - /* Length of a normal match */ - struct lzma_len_dec match_len_dec; - - /* Length of a repeated match */ - struct lzma_len_dec rep_len_dec; - - /* Probabilities of literals */ - uint16_t literal[LITERAL_CODERS_MAX][LITERAL_CODER_SIZE]; -}; - -struct lzma2_dec -{ - /* Position in xz_dec_lzma2_run(). */ - enum lzma2_seq - { - SEQ_CONTROL, - SEQ_UNCOMPRESSED_1, - SEQ_UNCOMPRESSED_2, - SEQ_COMPRESSED_0, - SEQ_COMPRESSED_1, - SEQ_PROPERTIES, - SEQ_LZMA_PREPARE, - SEQ_LZMA_RUN, - SEQ_COPY - } sequence; - - /* Next position after decoding the compressed size of the chunk. */ - enum lzma2_seq next_sequence; - - /* Uncompressed size of LZMA chunk (2 MiB at maximum) */ - uint32_t uncompressed; - - /* - * Compressed size of LZMA chunk or compressed/uncompressed - * size of uncompressed chunk (64 KiB at maximum) - */ - uint32_t compressed; - - /* - * True if dictionary reset is needed. This is false before - * the first chunk (LZMA or uncompressed). - */ - bool need_dict_reset; - - /* - * True if new LZMA properties are needed. This is false - * before the first LZMA chunk. - */ - bool need_props; -}; - -struct xz_dec_lzma2 -{ - /* - * The order below is important on x86 to reduce code size and - * it shouldn't hurt on other platforms. Everything up to and - * including lzma.pos_mask are in the first 128 bytes on x86-32, - * which allows using smaller instructions to access those - * variables. On x86-64, fewer variables fit into the first 128 - * bytes, but this is still the best order without sacrificing - * the readability by splitting the structures. - */ - struct rc_dec rc; - struct dictionary dict; - struct lzma2_dec lzma2; - struct lzma_dec lzma; - - /* - * Temporary buffer which holds small number of input bytes between - * decoder calls. See lzma2_lzma() for details. - */ - struct - { - uint32_t size; - uint8_t buf[3 * LZMA_IN_REQUIRED]; - } temp; -}; - -/************** - * Dictionary * - **************/ - -/* - * Reset the dictionary state. When in single-call mode, set up the beginning - * of the dictionary to point to the actual output buffer. - */ -static void dict_reset(struct dictionary *dict, struct xz_buf *b) -{ - if (DEC_IS_SINGLE(dict->mode)) - { - dict->buf = b->out + b->out_pos; - dict->end = b->out_size - b->out_pos; - } - - dict->start = 0; - dict->pos = 0; - dict->limit = 0; - dict->full = 0; -} - -/* Set dictionary write limit */ -static void dict_limit(struct dictionary *dict, size_t out_max) -{ - if (dict->end - dict->pos <= out_max) - dict->limit = dict->end; - else - dict->limit = dict->pos + out_max; -} - -/* Return true if at least one byte can be written into the dictionary. */ -static inline bool dict_has_space(const struct dictionary *dict) -{ - return dict->pos < dict->limit; -} - -/* - * Get a byte from the dictionary at the given distance. The distance is - * assumed to valid, or as a special case, zero when the dictionary is - * still empty. This special case is needed for single-call decoding to - * avoid writing a '\0' to the end of the destination buffer. - */ -static inline uint32_t dict_get(const struct dictionary *dict, uint32_t dist) -{ - size_t offset = dict->pos - dist - 1; - - if (dist >= dict->pos) - offset += dict->end; - - return dict->full > 0 ? dict->buf[offset] : 0; -} - -/* - * Put one byte into the dictionary. It is assumed that there is space for it. - */ -static inline void dict_put(struct dictionary *dict, uint8_t byte) -{ - dict->buf[dict->pos++] = byte; - - if (dict->full < dict->pos) - dict->full = dict->pos; -} - -/* - * Repeat given number of bytes from the given distance. If the distance is - * invalid, false is returned. On success, true is returned and *len is - * updated to indicate how many bytes were left to be repeated. - */ -static bool dict_repeat(struct dictionary *dict, uint32_t *len, uint32_t dist) -{ - size_t back; - uint32_t left; - - if (dist >= dict->full || dist >= dict->size) - return false; - - left = min_t(size_t, dict->limit - dict->pos, *len); - *len -= left; - - back = dict->pos - dist - 1; - if (dist >= dict->pos) - back += dict->end; - - do - { - dict->buf[dict->pos++] = dict->buf[back++]; - if (back == dict->end) - back = 0; - } while (--left > 0); - - if (dict->full < dict->pos) - dict->full = dict->pos; - - return true; -} - -/* Copy uncompressed data as is from input to dictionary and output buffers. */ -static void dict_uncompressed(struct dictionary *dict, struct xz_buf *b, uint32_t *left) -{ - size_t copy_size; - - while (*left > 0 && b->in_pos < b->in_size && b->out_pos < b->out_size) - { - copy_size = min(b->in_size - b->in_pos, b->out_size - b->out_pos); - if (copy_size > dict->end - dict->pos) - copy_size = dict->end - dict->pos; - if (copy_size > *left) - copy_size = *left; - - *left -= copy_size; - - memcpy(dict->buf + dict->pos, b->in + b->in_pos, copy_size); - dict->pos += copy_size; - - if (dict->full < dict->pos) - dict->full = dict->pos; - - if (DEC_IS_MULTI(dict->mode)) - { - if (dict->pos == dict->end) - dict->pos = 0; - - memcpy(b->out + b->out_pos, b->in + b->in_pos, copy_size); - } - - dict->start = dict->pos; - - b->out_pos += copy_size; - b->in_pos += copy_size; - } -} - -/* - * Flush pending data from dictionary to b->out. It is assumed that there is - * enough space in b->out. This is guaranteed because caller uses dict_limit() - * before decoding data into the dictionary. - */ -static uint32_t dict_flush(struct dictionary *dict, struct xz_buf *b) -{ - size_t copy_size = dict->pos - dict->start; - - if (DEC_IS_MULTI(dict->mode)) - { - if (dict->pos == dict->end) - dict->pos = 0; - - memcpy(b->out + b->out_pos, dict->buf + dict->start, copy_size); - } - - dict->start = dict->pos; - b->out_pos += copy_size; - return copy_size; -} - -/***************** - * Range decoder * - *****************/ - -/* Reset the range decoder. */ -static void rc_reset(struct rc_dec *rc) -{ - rc->range = (uint32_t) - 1; - rc->code = 0; - rc->init_bytes_left = RC_INIT_BYTES; -} - -/* - * Read the first five initial bytes into rc->code if they haven't been - * read already. (Yes, the first byte gets completely ignored.) - */ -static bool rc_read_init(struct rc_dec *rc, struct xz_buf *b) -{ - while (rc->init_bytes_left > 0) - { - if (b->in_pos == b->in_size) - return false; - - rc->code = (rc->code << 8) + b->in[b->in_pos++]; - --rc->init_bytes_left; - } - - return true; -} - -/* Return true if there may not be enough input for the next decoding loop. */ -static inline bool rc_limit_exceeded(const struct rc_dec *rc) -{ - return rc->in_pos > rc->in_limit; -} - -/* - * Return true if it is possible (from point of view of range decoder) that - * we have reached the end of the LZMA chunk. - */ -static inline bool rc_is_finished(const struct rc_dec *rc) -{ - return rc->code == 0; -} - -/* Read the next input byte if needed. */ -static __always_inline void rc_normalize(struct rc_dec *rc) -{ - if (rc->range < RC_TOP_VALUE) - { - rc->range <<= RC_SHIFT_BITS; - rc->code = (rc->code << RC_SHIFT_BITS) + rc->in[rc->in_pos++]; - } -} - -/* - * Decode one bit. In some versions, this function has been splitted in three - * functions so that the compiler is supposed to be able to more easily avoid - * an extra branch. In this particular version of the LZMA decoder, this - * doesn't seem to be a good idea (tested with GCC 3.3.6, 3.4.6, and 4.3.3 - * on x86). Using a non-splitted version results in nicer looking code too. - * - * NOTE: This must return an int. Do not make it return a bool or the speed - * of the code generated by GCC 3.x decreases 10-15 %. (GCC 4.3 doesn't care, - * and it generates 10-20 % faster code than GCC 3.x from this file anyway.) - */ -static __always_inline int rc_bit(struct rc_dec *rc, uint16_t *prob) -{ - uint32_t bound; - int bit; - - rc_normalize(rc); - bound = (rc->range >> RC_BIT_MODEL_TOTAL_BITS) * *prob; - if (rc->code < bound) - { - rc->range = bound; - *prob += (RC_BIT_MODEL_TOTAL - *prob) >> RC_MOVE_BITS; - bit = 0; - } - else - { - rc->range -= bound; - rc->code -= bound; - *prob -= *prob >> RC_MOVE_BITS; - bit = 1; - } - - return bit; -} - -/* Decode a bittree starting from the most significant bit. */ -static __always_inline uint32_t rc_bittree(struct rc_dec *rc, uint16_t *probs, uint32_t limit) -{ - uint32_t symbol = 1; - - do - { - if (rc_bit(rc, &probs[symbol])) - symbol = (symbol << 1) + 1; - else - symbol <<= 1; - } while (symbol < limit); - - return symbol; -} - -/* Decode a bittree starting from the least significant bit. */ -static __always_inline void rc_bittree_reverse(struct rc_dec *rc, uint16_t *probs, - uint32_t *dest, uint32_t limit) -{ - uint32_t symbol = 1; - uint32_t i = 0; - - do - { - if (rc_bit(rc, &probs[symbol])) - { - symbol = (symbol << 1) + 1; - *dest += 1 << i; - } - else - { - symbol <<= 1; - } - } while (++i < limit); -} - -/* Decode direct bits (fixed fifty-fifty probability) */ -static inline void rc_direct(struct rc_dec *rc, uint32_t *dest, uint32_t limit) -{ - uint32_t mask; - - do - { - rc_normalize(rc); - rc->range >>= 1; - rc->code -= rc->range; - mask = (uint32_t)0 - (rc->code >> 31); - rc->code += rc->range & mask; - *dest = (*dest << 1) + (mask + 1); - } while (--limit > 0); -} - -/******** - * LZMA * - ********/ - -/* Get pointer to literal coder probability array. */ -static uint16_t *lzma_literal_probs(struct xz_dec_lzma2 *s) -{ - uint32_t prev_byte = dict_get(&s->dict, 0); - uint32_t low = prev_byte >> (8 - s->lzma.lc); - uint32_t high = (s->dict.pos & s->lzma.literal_pos_mask) << s->lzma.lc; - return s->lzma.literal[low + high]; -} - -/* Decode a literal (one 8-bit byte) */ -static void lzma_literal(struct xz_dec_lzma2 *s) -{ - uint16_t *probs; - uint32_t symbol; - uint32_t match_byte; - uint32_t match_bit; - uint32_t offset; - uint32_t i; - - probs = lzma_literal_probs(s); - - if (lzma_state_is_literal(s->lzma.state)) - { - symbol = rc_bittree(&s->rc, probs, 0x100); - } - else - { - symbol = 1; - match_byte = dict_get(&s->dict, s->lzma.rep0) << 1; - offset = 0x100; - - do - { - match_bit = match_byte & offset; - match_byte <<= 1; - i = offset + match_bit + symbol; - - if (rc_bit(&s->rc, &probs[i])) - { - symbol = (symbol << 1) + 1; - offset &= match_bit; - } - else - { - symbol <<= 1; - offset &= ~match_bit; - } - } while (symbol < 0x100); - } - - dict_put(&s->dict, (uint8_t)symbol); - lzma_state_literal(&s->lzma.state); -} - -/* Decode the length of the match into s->lzma.len. */ -static void lzma_len(struct xz_dec_lzma2 *s, struct lzma_len_dec *l, uint32_t pos_state) -{ - uint16_t *probs; - uint32_t limit; - - if (!rc_bit(&s->rc, &l->choice)) - { - probs = l->low[pos_state]; - limit = LEN_LOW_SYMBOLS; - s->lzma.len = MATCH_LEN_MIN; - } - else - { - if (!rc_bit(&s->rc, &l->choice2)) - { - probs = l->mid[pos_state]; - limit = LEN_MID_SYMBOLS; - s->lzma.len = MATCH_LEN_MIN + LEN_LOW_SYMBOLS; - } - else - { - probs = l->high; - limit = LEN_HIGH_SYMBOLS; - s->lzma.len = MATCH_LEN_MIN + LEN_LOW_SYMBOLS + LEN_MID_SYMBOLS; - } - } - - s->lzma.len += rc_bittree(&s->rc, probs, limit) - limit; -} - -/* Decode a match. The distance will be stored in s->lzma.rep0. */ -static void lzma_match(struct xz_dec_lzma2 *s, uint32_t pos_state) -{ - uint16_t *probs; - uint32_t dist_slot; - uint32_t limit; - - lzma_state_match(&s->lzma.state); - - s->lzma.rep3 = s->lzma.rep2; - s->lzma.rep2 = s->lzma.rep1; - s->lzma.rep1 = s->lzma.rep0; - - lzma_len(s, &s->lzma.match_len_dec, pos_state); - - probs = s->lzma.dist_slot[lzma_get_dist_state(s->lzma.len)]; - dist_slot = rc_bittree(&s->rc, probs, DIST_SLOTS) - DIST_SLOTS; - - if (dist_slot < DIST_MODEL_START) - { - s->lzma.rep0 = dist_slot; - } - else - { - limit = (dist_slot >> 1) - 1; - s->lzma.rep0 = 2 + (dist_slot & 1); - - if (dist_slot < DIST_MODEL_END) - { - s->lzma.rep0 <<= limit; - probs = s->lzma.dist_special + s->lzma.rep0 - dist_slot - 1; - rc_bittree_reverse(&s->rc, probs, &s->lzma.rep0, limit); - } - else - { - rc_direct(&s->rc, &s->lzma.rep0, limit - ALIGN_BITS); - s->lzma.rep0 <<= ALIGN_BITS; - rc_bittree_reverse(&s->rc, s->lzma.dist_align, &s->lzma.rep0, ALIGN_BITS); - } - } -} - -/* - * Decode a repeated match. The distance is one of the four most recently - * seen matches. The distance will be stored in s->lzma.rep0. - */ -static void lzma_rep_match(struct xz_dec_lzma2 *s, uint32_t pos_state) -{ - uint32_t tmp; - - if (!rc_bit(&s->rc, &s->lzma.is_rep0[s->lzma.state])) - { - if (!rc_bit(&s->rc, &s->lzma.is_rep0_long[s->lzma.state][pos_state])) - { - lzma_state_short_rep(&s->lzma.state); - s->lzma.len = 1; - return; - } - } - else - { - if (!rc_bit(&s->rc, &s->lzma.is_rep1[s->lzma.state])) - { - tmp = s->lzma.rep1; - } - else - { - if (!rc_bit(&s->rc, &s->lzma.is_rep2[s->lzma.state])) - { - tmp = s->lzma.rep2; - } - else - { - tmp = s->lzma.rep3; - s->lzma.rep3 = s->lzma.rep2; - } - - s->lzma.rep2 = s->lzma.rep1; - } - - s->lzma.rep1 = s->lzma.rep0; - s->lzma.rep0 = tmp; - } - - lzma_state_long_rep(&s->lzma.state); - lzma_len(s, &s->lzma.rep_len_dec, pos_state); -} - -/* LZMA decoder core */ -static bool lzma_main(struct xz_dec_lzma2 *s) -{ - uint32_t pos_state; - - /* - * If the dictionary was reached during the previous call, try to - * finish the possibly pending repeat in the dictionary. - */ - if (dict_has_space(&s->dict) && s->lzma.len > 0) - dict_repeat(&s->dict, &s->lzma.len, s->lzma.rep0); - - /* - * Decode more LZMA symbols. One iteration may consume up to - * LZMA_IN_REQUIRED - 1 bytes. - */ - while (dict_has_space(&s->dict) && !rc_limit_exceeded(&s->rc)) - { - pos_state = s->dict.pos & s->lzma.pos_mask; - - if (!rc_bit(&s->rc, &s->lzma.is_match[s->lzma.state][pos_state])) - { - lzma_literal(s); - } - else - { - if (rc_bit(&s->rc, &s->lzma.is_rep[s->lzma.state])) - lzma_rep_match(s, pos_state); - else - lzma_match(s, pos_state); - - if (!dict_repeat(&s->dict, &s->lzma.len, s->lzma.rep0)) - return false; - } - } - - /* - * Having the range decoder always normalized when we are outside - * this function makes it easier to correctly handle end of the chunk. - */ - rc_normalize(&s->rc); - - return true; -} - -/* - * Reset the LZMA decoder and range decoder state. Dictionary is nore reset - * here, because LZMA state may be reset without resetting the dictionary. - */ -static void lzma_reset(struct xz_dec_lzma2 *s) -{ - uint16_t *probs; - size_t i; - - s->lzma.state = STATE_LIT_LIT; - s->lzma.rep0 = 0; - s->lzma.rep1 = 0; - s->lzma.rep2 = 0; - s->lzma.rep3 = 0; - - /* - * All probabilities are initialized to the same value. This hack - * makes the code smaller by avoiding a separate loop for each - * probability array. - * - * This could be optimized so that only that part of literal - * probabilities that are actually required. In the common case - * we would write 12 KiB less. - */ - probs = s->lzma.is_match[0]; - for (i = 0; i < PROBS_TOTAL; ++i) - probs[i] = RC_BIT_MODEL_TOTAL / 2; - - rc_reset(&s->rc); -} - -/* - * Decode and validate LZMA properties (lc/lp/pb) and calculate the bit masks - * from the decoded lp and pb values. On success, the LZMA decoder state is - * reset and true is returned. - */ -static bool lzma_props(struct xz_dec_lzma2 *s, uint8_t props) -{ - if (props > (4 * 5 + 4) * 9 + 8) - return false; - - s->lzma.pos_mask = 0; - while (props >= 9 * 5) - { - props -= 9 * 5; - ++s->lzma.pos_mask; - } - - s->lzma.pos_mask = (1 << s->lzma.pos_mask) - 1; - - s->lzma.literal_pos_mask = 0; - while (props >= 9) - { - props -= 9; - ++s->lzma.literal_pos_mask; - } - - s->lzma.lc = props; - - if (s->lzma.lc + s->lzma.literal_pos_mask > 4) - return false; - - s->lzma.literal_pos_mask = (1 << s->lzma.literal_pos_mask) - 1; - - lzma_reset(s); - - return true; -} - -/********* - * LZMA2 * - *********/ - -/* - * The LZMA decoder assumes that if the input limit (s->rc.in_limit) hasn't - * been exceeded, it is safe to read up to LZMA_IN_REQUIRED bytes. This - * wrapper function takes care of making the LZMA decoder's assumption safe. - * - * As long as there is plenty of input left to be decoded in the current LZMA - * chunk, we decode directly from the caller-supplied input buffer until - * there's LZMA_IN_REQUIRED bytes left. Those remaining bytes are copied into - * s->temp.buf, which (hopefully) gets filled on the next call to this - * function. We decode a few bytes from the temporary buffer so that we can - * continue decoding from the caller-supplied input buffer again. - */ -static bool lzma2_lzma(struct xz_dec_lzma2 *s, struct xz_buf *b) -{ - size_t in_avail; - uint32_t tmp; - - in_avail = b->in_size - b->in_pos; - if (s->temp.size > 0 || s->lzma2.compressed == 0) - { - tmp = 2 * LZMA_IN_REQUIRED - s->temp.size; - if (tmp > s->lzma2.compressed - s->temp.size) - tmp = s->lzma2.compressed - s->temp.size; - if (tmp > in_avail) - tmp = in_avail; - - memcpy(s->temp.buf + s->temp.size, b->in + b->in_pos, tmp); - - if (s->temp.size + tmp == s->lzma2.compressed) - { - memzero(s->temp.buf + s->temp.size + tmp, sizeof(s->temp.buf) - s->temp.size - tmp); - s->rc.in_limit = s->temp.size + tmp; - } - else if (s->temp.size + tmp < LZMA_IN_REQUIRED) - { - s->temp.size += tmp; - b->in_pos += tmp; - return true; - } - else - { - s->rc.in_limit = s->temp.size + tmp - LZMA_IN_REQUIRED; - } - - s->rc.in = s->temp.buf; - s->rc.in_pos = 0; - - if (!lzma_main(s) || s->rc.in_pos > s->temp.size + tmp) - return false; - - s->lzma2.compressed -= s->rc.in_pos; - - if (s->rc.in_pos < s->temp.size) - { - s->temp.size -= s->rc.in_pos; - memmove(s->temp.buf, s->temp.buf + s->rc.in_pos, s->temp.size); - return true; - } - - b->in_pos += s->rc.in_pos - s->temp.size; - s->temp.size = 0; - } - - in_avail = b->in_size - b->in_pos; - if (in_avail >= LZMA_IN_REQUIRED) - { - s->rc.in = b->in; - s->rc.in_pos = b->in_pos; - - if (in_avail >= s->lzma2.compressed + LZMA_IN_REQUIRED) - s->rc.in_limit = b->in_pos + s->lzma2.compressed; - else - s->rc.in_limit = b->in_size - LZMA_IN_REQUIRED; - - if (!lzma_main(s)) - return false; - - in_avail = s->rc.in_pos - b->in_pos; - if (in_avail > s->lzma2.compressed) - return false; - - s->lzma2.compressed -= in_avail; - b->in_pos = s->rc.in_pos; - } - - in_avail = b->in_size - b->in_pos; - if (in_avail < LZMA_IN_REQUIRED) - { - if (in_avail > s->lzma2.compressed) - in_avail = s->lzma2.compressed; - - memcpy(s->temp.buf, b->in + b->in_pos, in_avail); - s->temp.size = in_avail; - b->in_pos += in_avail; - } - - return true; -} - -/* - * Take care of the LZMA2 control layer, and forward the job of actual LZMA - * decoding or copying of uncompressed chunks to other functions. - */ -XZ_EXTERN enum xz_ret xz_dec_lzma2_run(struct xz_dec_lzma2 *s, struct xz_buf *b) -{ - uint32_t tmp; - - while (b->in_pos < b->in_size || s->lzma2.sequence == SEQ_LZMA_RUN) - { - switch (s->lzma2.sequence) - { - case SEQ_CONTROL: - /* - * LZMA2 control byte - * - * Exact values: - * 0x00 End marker - * 0x01 Dictionary reset followed by - * an uncompressed chunk - * 0x02 Uncompressed chunk (no dictionary reset) - * - * Highest three bits (s->control & 0xE0): - * 0xE0 Dictionary reset, new properties and state - * reset, followed by LZMA compressed chunk - * 0xC0 New properties and state reset, followed - * by LZMA compressed chunk (no dictionary - * reset) - * 0xA0 State reset using old properties, - * followed by LZMA compressed chunk (no - * dictionary reset) - * 0x80 LZMA chunk (no dictionary or state reset) - * - * For LZMA compressed chunks, the lowest five bits - * (s->control & 1F) are the highest bits of the - * uncompressed size (bits 16-20). - * - * A new LZMA2 stream must begin with a dictionary - * reset. The first LZMA chunk must set new - * properties and reset the LZMA state. - * - * Values that don't match anything described above - * are invalid and we return XZ_DATA_ERROR. - */ - tmp = b->in[b->in_pos++]; - - if (tmp == 0x00) - return XZ_STREAM_END; - - if (tmp >= 0xE0 || tmp == 0x01) - { - s->lzma2.need_props = true; - s->lzma2.need_dict_reset = false; - dict_reset(&s->dict, b); - } - else if (s->lzma2.need_dict_reset) - { - return XZ_DATA_ERROR; - } - - if (tmp >= 0x80) - { - s->lzma2.uncompressed = (tmp & 0x1F) << 16; - s->lzma2.sequence = SEQ_UNCOMPRESSED_1; - - if (tmp >= 0xC0) - { - /* - * When there are new properties, - * state reset is done at - * SEQ_PROPERTIES. - */ - s->lzma2.need_props = false; - s->lzma2.next_sequence = SEQ_PROPERTIES; - } - else if (s->lzma2.need_props) - { - return XZ_DATA_ERROR; - } - else - { - s->lzma2.next_sequence = SEQ_LZMA_PREPARE; - if (tmp >= 0xA0) - lzma_reset(s); - } - } - else - { - if (tmp > 0x02) - return XZ_DATA_ERROR; - - s->lzma2.sequence = SEQ_COMPRESSED_0; - s->lzma2.next_sequence = SEQ_COPY; - } - - break; - - case SEQ_UNCOMPRESSED_1: - s->lzma2.uncompressed += (uint32_t)b->in[b->in_pos++] << 8; - s->lzma2.sequence = SEQ_UNCOMPRESSED_2; - break; - - case SEQ_UNCOMPRESSED_2: - s->lzma2.uncompressed += (uint32_t)b->in[b->in_pos++] + 1; - s->lzma2.sequence = SEQ_COMPRESSED_0; - break; - - case SEQ_COMPRESSED_0: - s->lzma2.compressed = (uint32_t)b->in[b->in_pos++] << 8; - s->lzma2.sequence = SEQ_COMPRESSED_1; - break; - - case SEQ_COMPRESSED_1: - s->lzma2.compressed += (uint32_t)b->in[b->in_pos++] + 1; - s->lzma2.sequence = s->lzma2.next_sequence; - break; - - case SEQ_PROPERTIES: - if (!lzma_props(s, b->in[b->in_pos++])) - return XZ_DATA_ERROR; - - s->lzma2.sequence = SEQ_LZMA_PREPARE; - - case SEQ_LZMA_PREPARE: - if (s->lzma2.compressed < RC_INIT_BYTES) - return XZ_DATA_ERROR; - - if (!rc_read_init(&s->rc, b)) - return XZ_OK; - - s->lzma2.compressed -= RC_INIT_BYTES; - s->lzma2.sequence = SEQ_LZMA_RUN; - - case SEQ_LZMA_RUN: - /* - * Set dictionary limit to indicate how much we want - * to be encoded at maximum. Decode new data into the - * dictionary. Flush the new data from dictionary to - * b->out. Check if we finished decoding this chunk. - * In case the dictionary got full but we didn't fill - * the output buffer yet, we may run this loop - * multiple times without changing s->lzma2.sequence. - */ - dict_limit(&s->dict, - min_t(size_t, b->out_size - b->out_pos, s->lzma2.uncompressed)); - if (!lzma2_lzma(s, b)) - return XZ_DATA_ERROR; - - s->lzma2.uncompressed -= dict_flush(&s->dict, b); - - if (s->lzma2.uncompressed == 0) - { - if (s->lzma2.compressed > 0 || s->lzma.len > 0 || !rc_is_finished(&s->rc)) - return XZ_DATA_ERROR; - - rc_reset(&s->rc); - s->lzma2.sequence = SEQ_CONTROL; - } - else if (b->out_pos == b->out_size || - (b->in_pos == b->in_size && s->temp.size < s->lzma2.compressed)) - { - return XZ_OK; - } - - break; - - case SEQ_COPY: - dict_uncompressed(&s->dict, b, &s->lzma2.compressed); - if (s->lzma2.compressed > 0) - return XZ_OK; - - s->lzma2.sequence = SEQ_CONTROL; - break; - } - } - - return XZ_OK; -} - -XZ_EXTERN struct xz_dec_lzma2 *xz_dec_lzma2_create(enum xz_mode mode, uint32_t dict_max) -{ - struct xz_dec_lzma2 *s = kmalloc(sizeof(*s), GFP_KERNEL); - if (s == NULL) - return NULL; - - s->dict.mode = mode; - s->dict.size_max = dict_max; - - if (DEC_IS_PREALLOC(mode)) - { - s->dict.buf = vmalloc(dict_max); - if (s->dict.buf == NULL) - { - kfree(s); - return NULL; - } - } - else if (DEC_IS_DYNALLOC(mode)) - { - s->dict.buf = NULL; - s->dict.allocated = 0; - } - - return s; -} - -XZ_EXTERN enum xz_ret xz_dec_lzma2_reset(struct xz_dec_lzma2 *s, uint8_t props) -{ - /* This limits dictionary size to 3 GiB to keep parsing simpler. */ - if (props > 39) - return XZ_OPTIONS_ERROR; - - s->dict.size = 2 + (props & 1); - s->dict.size <<= (props >> 1) + 11; - - if (DEC_IS_MULTI(s->dict.mode)) - { - if (s->dict.size > s->dict.size_max) - return XZ_MEMLIMIT_ERROR; - - s->dict.end = s->dict.size; - - if (DEC_IS_DYNALLOC(s->dict.mode)) - { - if (s->dict.allocated < s->dict.size) - { - vfree(s->dict.buf); - s->dict.buf = vmalloc(s->dict.size); - if (s->dict.buf == NULL) - { - s->dict.allocated = 0; - return XZ_MEM_ERROR; - } - } - } - } - - s->lzma.len = 0; - - s->lzma2.sequence = SEQ_CONTROL; - s->lzma2.need_dict_reset = true; - - s->temp.size = 0; - - return XZ_OK; -} - -XZ_EXTERN void xz_dec_lzma2_end(struct xz_dec_lzma2 *s) -{ - if (DEC_IS_MULTI(s->dict.mode)) - vfree(s->dict.buf); - - kfree(s); -} diff --git a/libraries/xz-embedded/src/xz_dec_stream.c b/libraries/xz-embedded/src/xz_dec_stream.c deleted file mode 100644 index f8d7be05..00000000 --- a/libraries/xz-embedded/src/xz_dec_stream.c +++ /dev/null @@ -1,860 +0,0 @@ -/* - * .xz Stream decoder - * - * Author: Lasse Collin - * - * This file has been put into the public domain. - * You can do whatever you want with this file. - */ - -#include "xz_private.h" -#include "xz_stream.h" - -#ifdef XZ_USE_CRC64 -#define IS_CRC64(check_type) ((check_type) == XZ_CHECK_CRC64) -#else -#define IS_CRC64(check_type) false -#endif - -/* Hash used to validate the Index field */ -struct xz_dec_hash -{ - vli_type unpadded; - vli_type uncompressed; - uint32_t crc32; -}; - -struct xz_dec -{ - /* Position in dec_main() */ - enum - { - SEQ_STREAM_HEADER, - SEQ_BLOCK_START, - SEQ_BLOCK_HEADER, - SEQ_BLOCK_UNCOMPRESS, - SEQ_BLOCK_PADDING, - SEQ_BLOCK_CHECK, - SEQ_INDEX, - SEQ_INDEX_PADDING, - SEQ_INDEX_CRC32, - SEQ_STREAM_FOOTER - } sequence; - - /* Position in variable-length integers and Check fields */ - uint32_t pos; - - /* Variable-length integer decoded by dec_vli() */ - vli_type vli; - - /* Saved in_pos and out_pos */ - size_t in_start; - size_t out_start; - -#ifdef XZ_USE_CRC64 - /* CRC32 or CRC64 value in Block or CRC32 value in Index */ - uint64_t crc; -#else - /* CRC32 value in Block or Index */ - uint32_t crc; -#endif - - /* Type of the integrity check calculated from uncompressed data */ - enum xz_check check_type; - - /* Operation mode */ - enum xz_mode mode; - - /* - * True if the next call to xz_dec_run() is allowed to return - * XZ_BUF_ERROR. - */ - bool allow_buf_error; - - /* Information stored in Block Header */ - struct - { - /* - * Value stored in the Compressed Size field, or - * VLI_UNKNOWN if Compressed Size is not present. - */ - vli_type compressed; - - /* - * Value stored in the Uncompressed Size field, or - * VLI_UNKNOWN if Uncompressed Size is not present. - */ - vli_type uncompressed; - - /* Size of the Block Header field */ - uint32_t size; - } block_header; - - /* Information collected when decoding Blocks */ - struct - { - /* Observed compressed size of the current Block */ - vli_type compressed; - - /* Observed uncompressed size of the current Block */ - vli_type uncompressed; - - /* Number of Blocks decoded so far */ - vli_type count; - - /* - * Hash calculated from the Block sizes. This is used to - * validate the Index field. - */ - struct xz_dec_hash hash; - } block; - - /* Variables needed when verifying the Index field */ - struct - { - /* Position in dec_index() */ - enum - { - SEQ_INDEX_COUNT, - SEQ_INDEX_UNPADDED, - SEQ_INDEX_UNCOMPRESSED - } sequence; - - /* Size of the Index in bytes */ - vli_type size; - - /* Number of Records (matches block.count in valid files) */ - vli_type count; - - /* - * Hash calculated from the Records (matches block.hash in - * valid files). - */ - struct xz_dec_hash hash; - } index; - - /* - * Temporary buffer needed to hold Stream Header, Block Header, - * and Stream Footer. The Block Header is the biggest (1 KiB) - * so we reserve space according to that. buf[] has to be aligned - * to a multiple of four bytes; the size_t variables before it - * should guarantee this. - */ - struct - { - size_t pos; - size_t size; - uint8_t buf[1024]; - } temp; - - struct xz_dec_lzma2 *lzma2; - -#ifdef XZ_DEC_BCJ - struct xz_dec_bcj *bcj; - bool bcj_active; -#endif -}; - -#ifdef XZ_DEC_ANY_CHECK -/* Sizes of the Check field with different Check IDs */ -static const uint8_t check_sizes[16] = {0, 4, 4, 4, 8, 8, 8, 16, - 16, 16, 32, 32, 32, 64, 64, 64}; -#endif - -/* - * Fill s->temp by copying data starting from b->in[b->in_pos]. Caller - * must have set s->temp.pos to indicate how much data we are supposed - * to copy into s->temp.buf. Return true once s->temp.pos has reached - * s->temp.size. - */ -static bool fill_temp(struct xz_dec *s, struct xz_buf *b) -{ - size_t copy_size = min_t(size_t, b->in_size - b->in_pos, s->temp.size - s->temp.pos); - - memcpy(s->temp.buf + s->temp.pos, b->in + b->in_pos, copy_size); - b->in_pos += copy_size; - s->temp.pos += copy_size; - - if (s->temp.pos == s->temp.size) - { - s->temp.pos = 0; - return true; - } - - return false; -} - -/* Decode a variable-length integer (little-endian base-128 encoding) */ -static enum xz_ret dec_vli(struct xz_dec *s, const uint8_t *in, size_t *in_pos, size_t in_size) -{ - uint8_t byte; - - if (s->pos == 0) - s->vli = 0; - - while (*in_pos < in_size) - { - byte = in[*in_pos]; - ++*in_pos; - - s->vli |= (vli_type)(byte & 0x7F) << s->pos; - - if ((byte & 0x80) == 0) - { - /* Don't allow non-minimal encodings. */ - if (byte == 0 && s->pos != 0) - return XZ_DATA_ERROR; - - s->pos = 0; - return XZ_STREAM_END; - } - - s->pos += 7; - if (s->pos == 7 * VLI_BYTES_MAX) - return XZ_DATA_ERROR; - } - - return XZ_OK; -} - -/* - * Decode the Compressed Data field from a Block. Update and validate - * the observed compressed and uncompressed sizes of the Block so that - * they don't exceed the values possibly stored in the Block Header - * (validation assumes that no integer overflow occurs, since vli_type - * is normally uint64_t). Update the CRC32 or CRC64 value if presence of - * the CRC32 or CRC64 field was indicated in Stream Header. - * - * Once the decoding is finished, validate that the observed sizes match - * the sizes possibly stored in the Block Header. Update the hash and - * Block count, which are later used to validate the Index field. - */ -static enum xz_ret dec_block(struct xz_dec *s, struct xz_buf *b) -{ - enum xz_ret ret; - - s->in_start = b->in_pos; - s->out_start = b->out_pos; - -#ifdef XZ_DEC_BCJ - if (s->bcj_active) - ret = xz_dec_bcj_run(s->bcj, s->lzma2, b); - else -#endif - ret = xz_dec_lzma2_run(s->lzma2, b); - - s->block.compressed += b->in_pos - s->in_start; - s->block.uncompressed += b->out_pos - s->out_start; - - /* - * There is no need to separately check for VLI_UNKNOWN, since - * the observed sizes are always smaller than VLI_UNKNOWN. - */ - if (s->block.compressed > s->block_header.compressed || - s->block.uncompressed > s->block_header.uncompressed) - return XZ_DATA_ERROR; - - if (s->check_type == XZ_CHECK_CRC32) - s->crc = xz_crc32(b->out + s->out_start, b->out_pos - s->out_start, s->crc); -#ifdef XZ_USE_CRC64 - else if (s->check_type == XZ_CHECK_CRC64) - s->crc = xz_crc64(b->out + s->out_start, b->out_pos - s->out_start, s->crc); -#endif - - if (ret == XZ_STREAM_END) - { - if (s->block_header.compressed != VLI_UNKNOWN && - s->block_header.compressed != s->block.compressed) - return XZ_DATA_ERROR; - - if (s->block_header.uncompressed != VLI_UNKNOWN && - s->block_header.uncompressed != s->block.uncompressed) - return XZ_DATA_ERROR; - - s->block.hash.unpadded += s->block_header.size + s->block.compressed; - -#ifdef XZ_DEC_ANY_CHECK - s->block.hash.unpadded += check_sizes[s->check_type]; -#else - if (s->check_type == XZ_CHECK_CRC32) - s->block.hash.unpadded += 4; - else if (IS_CRC64(s->check_type)) - s->block.hash.unpadded += 8; -#endif - - s->block.hash.uncompressed += s->block.uncompressed; - s->block.hash.crc32 = xz_crc32((const uint8_t *)&s->block.hash, sizeof(s->block.hash), - s->block.hash.crc32); - - ++s->block.count; - } - - return ret; -} - -/* Update the Index size and the CRC32 value. */ -static void index_update(struct xz_dec *s, const struct xz_buf *b) -{ - size_t in_used = b->in_pos - s->in_start; - s->index.size += in_used; - s->crc = xz_crc32(b->in + s->in_start, in_used, s->crc); -} - -/* - * Decode the Number of Records, Unpadded Size, and Uncompressed Size - * fields from the Index field. That is, Index Padding and CRC32 are not - * decoded by this function. - * - * This can return XZ_OK (more input needed), XZ_STREAM_END (everything - * successfully decoded), or XZ_DATA_ERROR (input is corrupt). - */ -static enum xz_ret dec_index(struct xz_dec *s, struct xz_buf *b) -{ - enum xz_ret ret; - - do - { - ret = dec_vli(s, b->in, &b->in_pos, b->in_size); - if (ret != XZ_STREAM_END) - { - index_update(s, b); - return ret; - } - - switch (s->index.sequence) - { - case SEQ_INDEX_COUNT: - s->index.count = s->vli; - - /* - * Validate that the Number of Records field - * indicates the same number of Records as - * there were Blocks in the Stream. - */ - if (s->index.count != s->block.count) - return XZ_DATA_ERROR; - - s->index.sequence = SEQ_INDEX_UNPADDED; - break; - - case SEQ_INDEX_UNPADDED: - s->index.hash.unpadded += s->vli; - s->index.sequence = SEQ_INDEX_UNCOMPRESSED; - break; - - case SEQ_INDEX_UNCOMPRESSED: - s->index.hash.uncompressed += s->vli; - s->index.hash.crc32 = xz_crc32((const uint8_t *)&s->index.hash, - sizeof(s->index.hash), s->index.hash.crc32); - --s->index.count; - s->index.sequence = SEQ_INDEX_UNPADDED; - break; - } - } while (s->index.count > 0); - - return XZ_STREAM_END; -} - -/* - * Validate that the next four or eight input bytes match the value - * of s->crc. s->pos must be zero when starting to validate the first byte. - * The "bits" argument allows using the same code for both CRC32 and CRC64. - */ -static enum xz_ret crc_validate(struct xz_dec *s, struct xz_buf *b, uint32_t bits) -{ - do - { - if (b->in_pos == b->in_size) - return XZ_OK; - - if (((s->crc >> s->pos) & 0xFF) != b->in[b->in_pos++]) - return XZ_DATA_ERROR; - - s->pos += 8; - - } while (s->pos < bits); - - s->crc = 0; - s->pos = 0; - - return XZ_STREAM_END; -} - -#ifdef XZ_DEC_ANY_CHECK -/* - * Skip over the Check field when the Check ID is not supported. - * Returns true once the whole Check field has been skipped over. - */ -static bool check_skip(struct xz_dec *s, struct xz_buf *b) -{ - while (s->pos < check_sizes[s->check_type]) - { - if (b->in_pos == b->in_size) - return false; - - ++b->in_pos; - ++s->pos; - } - - s->pos = 0; - - return true; -} -#endif - -/* Decode the Stream Header field (the first 12 bytes of the .xz Stream). */ -static enum xz_ret dec_stream_header(struct xz_dec *s) -{ - if (!memeq(s->temp.buf, HEADER_MAGIC, HEADER_MAGIC_SIZE)) - return XZ_FORMAT_ERROR; - - if (xz_crc32(s->temp.buf + HEADER_MAGIC_SIZE, 2, 0) != - get_le32(s->temp.buf + HEADER_MAGIC_SIZE + 2)) - return XZ_DATA_ERROR; - - if (s->temp.buf[HEADER_MAGIC_SIZE] != 0) - return XZ_OPTIONS_ERROR; - - /* - * Of integrity checks, we support none (Check ID = 0), - * CRC32 (Check ID = 1), and optionally CRC64 (Check ID = 4). - * However, if XZ_DEC_ANY_CHECK is defined, we will accept other - * check types too, but then the check won't be verified and - * a warning (XZ_UNSUPPORTED_CHECK) will be given. - */ - s->check_type = s->temp.buf[HEADER_MAGIC_SIZE + 1]; - -#ifdef XZ_DEC_ANY_CHECK - if (s->check_type > XZ_CHECK_MAX) - return XZ_OPTIONS_ERROR; - - if (s->check_type > XZ_CHECK_CRC32 && !IS_CRC64(s->check_type)) - return XZ_UNSUPPORTED_CHECK; -#else - if (s->check_type > XZ_CHECK_CRC32 && !IS_CRC64(s->check_type)) - return XZ_OPTIONS_ERROR; -#endif - - return XZ_OK; -} - -/* Decode the Stream Footer field (the last 12 bytes of the .xz Stream) */ -static enum xz_ret dec_stream_footer(struct xz_dec *s) -{ - if (!memeq(s->temp.buf + 10, FOOTER_MAGIC, FOOTER_MAGIC_SIZE)) - return XZ_DATA_ERROR; - - if (xz_crc32(s->temp.buf + 4, 6, 0) != get_le32(s->temp.buf)) - return XZ_DATA_ERROR; - - /* - * Validate Backward Size. Note that we never added the size of the - * Index CRC32 field to s->index.size, thus we use s->index.size / 4 - * instead of s->index.size / 4 - 1. - */ - if ((s->index.size >> 2) != get_le32(s->temp.buf + 4)) - return XZ_DATA_ERROR; - - if (s->temp.buf[8] != 0 || s->temp.buf[9] != s->check_type) - return XZ_DATA_ERROR; - - /* - * Use XZ_STREAM_END instead of XZ_OK to be more convenient - * for the caller. - */ - return XZ_STREAM_END; -} - -/* Decode the Block Header and initialize the filter chain. */ -static enum xz_ret dec_block_header(struct xz_dec *s) -{ - enum xz_ret ret; - - /* - * Validate the CRC32. We know that the temp buffer is at least - * eight bytes so this is safe. - */ - s->temp.size -= 4; - if (xz_crc32(s->temp.buf, s->temp.size, 0) != get_le32(s->temp.buf + s->temp.size)) - return XZ_DATA_ERROR; - - s->temp.pos = 2; - -/* - * Catch unsupported Block Flags. We support only one or two filters - * in the chain, so we catch that with the same test. - */ -#ifdef XZ_DEC_BCJ - if (s->temp.buf[1] & 0x3E) -#else - if (s->temp.buf[1] & 0x3F) -#endif - return XZ_OPTIONS_ERROR; - - /* Compressed Size */ - if (s->temp.buf[1] & 0x40) - { - if (dec_vli(s, s->temp.buf, &s->temp.pos, s->temp.size) != XZ_STREAM_END) - return XZ_DATA_ERROR; - - s->block_header.compressed = s->vli; - } - else - { - s->block_header.compressed = VLI_UNKNOWN; - } - - /* Uncompressed Size */ - if (s->temp.buf[1] & 0x80) - { - if (dec_vli(s, s->temp.buf, &s->temp.pos, s->temp.size) != XZ_STREAM_END) - return XZ_DATA_ERROR; - - s->block_header.uncompressed = s->vli; - } - else - { - s->block_header.uncompressed = VLI_UNKNOWN; - } - -#ifdef XZ_DEC_BCJ - /* If there are two filters, the first one must be a BCJ filter. */ - s->bcj_active = s->temp.buf[1] & 0x01; - if (s->bcj_active) - { - if (s->temp.size - s->temp.pos < 2) - return XZ_OPTIONS_ERROR; - - ret = xz_dec_bcj_reset(s->bcj, s->temp.buf[s->temp.pos++]); - if (ret != XZ_OK) - return ret; - - /* - * We don't support custom start offset, - * so Size of Properties must be zero. - */ - if (s->temp.buf[s->temp.pos++] != 0x00) - return XZ_OPTIONS_ERROR; - } -#endif - - /* Valid Filter Flags always take at least two bytes. */ - if (s->temp.size - s->temp.pos < 2) - return XZ_DATA_ERROR; - - /* Filter ID = LZMA2 */ - if (s->temp.buf[s->temp.pos++] != 0x21) - return XZ_OPTIONS_ERROR; - - /* Size of Properties = 1-byte Filter Properties */ - if (s->temp.buf[s->temp.pos++] != 0x01) - return XZ_OPTIONS_ERROR; - - /* Filter Properties contains LZMA2 dictionary size. */ - if (s->temp.size - s->temp.pos < 1) - return XZ_DATA_ERROR; - - ret = xz_dec_lzma2_reset(s->lzma2, s->temp.buf[s->temp.pos++]); - if (ret != XZ_OK) - return ret; - - /* The rest must be Header Padding. */ - while (s->temp.pos < s->temp.size) - if (s->temp.buf[s->temp.pos++] != 0x00) - return XZ_OPTIONS_ERROR; - - s->temp.pos = 0; - s->block.compressed = 0; - s->block.uncompressed = 0; - - return XZ_OK; -} - -static enum xz_ret dec_main(struct xz_dec *s, struct xz_buf *b) -{ - enum xz_ret ret; - - /* - * Store the start position for the case when we are in the middle - * of the Index field. - */ - s->in_start = b->in_pos; - - while (true) - { - switch (s->sequence) - { - case SEQ_STREAM_HEADER: - /* - * Stream Header is copied to s->temp, and then - * decoded from there. This way if the caller - * gives us only little input at a time, we can - * still keep the Stream Header decoding code - * simple. Similar approach is used in many places - * in this file. - */ - if (!fill_temp(s, b)) - return XZ_OK; - - /* - * If dec_stream_header() returns - * XZ_UNSUPPORTED_CHECK, it is still possible - * to continue decoding if working in multi-call - * mode. Thus, update s->sequence before calling - * dec_stream_header(). - */ - s->sequence = SEQ_BLOCK_START; - - ret = dec_stream_header(s); - if (ret != XZ_OK) - return ret; - - case SEQ_BLOCK_START: - /* We need one byte of input to continue. */ - if (b->in_pos == b->in_size) - return XZ_OK; - - /* See if this is the beginning of the Index field. */ - if (b->in[b->in_pos] == 0) - { - s->in_start = b->in_pos++; - s->sequence = SEQ_INDEX; - break; - } - - /* - * Calculate the size of the Block Header and - * prepare to decode it. - */ - s->block_header.size = ((uint32_t)b->in[b->in_pos] + 1) * 4; - - s->temp.size = s->block_header.size; - s->temp.pos = 0; - s->sequence = SEQ_BLOCK_HEADER; - - case SEQ_BLOCK_HEADER: - if (!fill_temp(s, b)) - return XZ_OK; - - ret = dec_block_header(s); - if (ret != XZ_OK) - return ret; - - s->sequence = SEQ_BLOCK_UNCOMPRESS; - - case SEQ_BLOCK_UNCOMPRESS: - ret = dec_block(s, b); - if (ret != XZ_STREAM_END) - return ret; - - s->sequence = SEQ_BLOCK_PADDING; - - case SEQ_BLOCK_PADDING: - /* - * Size of Compressed Data + Block Padding - * must be a multiple of four. We don't need - * s->block.compressed for anything else - * anymore, so we use it here to test the size - * of the Block Padding field. - */ - while (s->block.compressed & 3) - { - if (b->in_pos == b->in_size) - return XZ_OK; - - if (b->in[b->in_pos++] != 0) - return XZ_DATA_ERROR; - - ++s->block.compressed; - } - - s->sequence = SEQ_BLOCK_CHECK; - - case SEQ_BLOCK_CHECK: - if (s->check_type == XZ_CHECK_CRC32) - { - ret = crc_validate(s, b, 32); - if (ret != XZ_STREAM_END) - return ret; - } - else if (IS_CRC64(s->check_type)) - { - ret = crc_validate(s, b, 64); - if (ret != XZ_STREAM_END) - return ret; - } -#ifdef XZ_DEC_ANY_CHECK - else if (!check_skip(s, b)) - { - return XZ_OK; - } -#endif - - s->sequence = SEQ_BLOCK_START; - break; - - case SEQ_INDEX: - ret = dec_index(s, b); - if (ret != XZ_STREAM_END) - return ret; - - s->sequence = SEQ_INDEX_PADDING; - - case SEQ_INDEX_PADDING: - while ((s->index.size + (b->in_pos - s->in_start)) & 3) - { - if (b->in_pos == b->in_size) - { - index_update(s, b); - return XZ_OK; - } - - if (b->in[b->in_pos++] != 0) - return XZ_DATA_ERROR; - } - - /* Finish the CRC32 value and Index size. */ - index_update(s, b); - - /* Compare the hashes to validate the Index field. */ - if (!memeq(&s->block.hash, &s->index.hash, sizeof(s->block.hash))) - return XZ_DATA_ERROR; - - s->sequence = SEQ_INDEX_CRC32; - - case SEQ_INDEX_CRC32: - ret = crc_validate(s, b, 32); - if (ret != XZ_STREAM_END) - return ret; - - s->temp.size = STREAM_HEADER_SIZE; - s->sequence = SEQ_STREAM_FOOTER; - - case SEQ_STREAM_FOOTER: - if (!fill_temp(s, b)) - return XZ_OK; - - return dec_stream_footer(s); - } - } - - /* Never reached */ -} - -/* - * xz_dec_run() is a wrapper for dec_main() to handle some special cases in - * multi-call and single-call decoding. - * - * In multi-call mode, we must return XZ_BUF_ERROR when it seems clear that we - * are not going to make any progress anymore. This is to prevent the caller - * from calling us infinitely when the input file is truncated or otherwise - * corrupt. Since zlib-style API allows that the caller fills the input buffer - * only when the decoder doesn't produce any new output, we have to be careful - * to avoid returning XZ_BUF_ERROR too easily: XZ_BUF_ERROR is returned only - * after the second consecutive call to xz_dec_run() that makes no progress. - * - * In single-call mode, if we couldn't decode everything and no error - * occurred, either the input is truncated or the output buffer is too small. - * Since we know that the last input byte never produces any output, we know - * that if all the input was consumed and decoding wasn't finished, the file - * must be corrupt. Otherwise the output buffer has to be too small or the - * file is corrupt in a way that decoding it produces too big output. - * - * If single-call decoding fails, we reset b->in_pos and b->out_pos back to - * their original values. This is because with some filter chains there won't - * be any valid uncompressed data in the output buffer unless the decoding - * actually succeeds (that's the price to pay of using the output buffer as - * the workspace). - */ -XZ_EXTERN enum xz_ret xz_dec_run(struct xz_dec *s, struct xz_buf *b) -{ - size_t in_start; - size_t out_start; - enum xz_ret ret; - - if (DEC_IS_SINGLE(s->mode)) - xz_dec_reset(s); - - in_start = b->in_pos; - out_start = b->out_pos; - ret = dec_main(s, b); - - if (DEC_IS_SINGLE(s->mode)) - { - if (ret == XZ_OK) - ret = b->in_pos == b->in_size ? XZ_DATA_ERROR : XZ_BUF_ERROR; - - if (ret != XZ_STREAM_END) - { - b->in_pos = in_start; - b->out_pos = out_start; - } - } - else if (ret == XZ_OK && in_start == b->in_pos && out_start == b->out_pos) - { - if (s->allow_buf_error) - ret = XZ_BUF_ERROR; - - s->allow_buf_error = true; - } - else - { - s->allow_buf_error = false; - } - - return ret; -} - -XZ_EXTERN struct xz_dec *xz_dec_init(enum xz_mode mode, uint32_t dict_max) -{ - struct xz_dec *s = kmalloc(sizeof(*s), GFP_KERNEL); - if (s == NULL) - return NULL; - - s->mode = mode; - -#ifdef XZ_DEC_BCJ - s->bcj = xz_dec_bcj_create(DEC_IS_SINGLE(mode)); - if (s->bcj == NULL) - goto error_bcj; -#endif - - s->lzma2 = xz_dec_lzma2_create(mode, dict_max); - if (s->lzma2 == NULL) - goto error_lzma2; - - xz_dec_reset(s); - return s; - -error_lzma2: -#ifdef XZ_DEC_BCJ - xz_dec_bcj_end(s->bcj); -error_bcj: -#endif - kfree(s); - return NULL; -} - -XZ_EXTERN void xz_dec_reset(struct xz_dec *s) -{ - s->sequence = SEQ_STREAM_HEADER; - s->allow_buf_error = false; - s->pos = 0; - s->crc = 0; - memzero(&s->block, sizeof(s->block)); - memzero(&s->index, sizeof(s->index)); - s->temp.pos = 0; - s->temp.size = STREAM_HEADER_SIZE; -} - -XZ_EXTERN void xz_dec_end(struct xz_dec *s) -{ - if (s != NULL) - { - xz_dec_lzma2_end(s->lzma2); -#ifdef XZ_DEC_BCJ - xz_dec_bcj_end(s->bcj); -#endif - kfree(s); - } -} diff --git a/libraries/xz-embedded/src/xz_lzma2.h b/libraries/xz-embedded/src/xz_lzma2.h deleted file mode 100644 index 82a425f2..00000000 --- a/libraries/xz-embedded/src/xz_lzma2.h +++ /dev/null @@ -1,204 +0,0 @@ -/* - * LZMA2 definitions - * - * Authors: Lasse Collin - * Igor Pavlov - * - * This file has been put into the public domain. - * You can do whatever you want with this file. - */ - -#ifndef XZ_LZMA2_H -#define XZ_LZMA2_H - -/* Range coder constants */ -#define RC_SHIFT_BITS 8 -#define RC_TOP_BITS 24 -#define RC_TOP_VALUE (1 << RC_TOP_BITS) -#define RC_BIT_MODEL_TOTAL_BITS 11 -#define RC_BIT_MODEL_TOTAL (1 << RC_BIT_MODEL_TOTAL_BITS) -#define RC_MOVE_BITS 5 - -/* - * Maximum number of position states. A position state is the lowest pb - * number of bits of the current uncompressed offset. In some places there - * are different sets of probabilities for different position states. - */ -#define POS_STATES_MAX (1 << 4) - -/* - * This enum is used to track which LZMA symbols have occurred most recently - * and in which order. This information is used to predict the next symbol. - * - * Symbols: - * - Literal: One 8-bit byte - * - Match: Repeat a chunk of data at some distance - * - Long repeat: Multi-byte match at a recently seen distance - * - Short repeat: One-byte repeat at a recently seen distance - * - * The symbol names are in from STATE_oldest_older_previous. REP means - * either short or long repeated match, and NONLIT means any non-literal. - */ -enum lzma_state -{ - STATE_LIT_LIT, - STATE_MATCH_LIT_LIT, - STATE_REP_LIT_LIT, - STATE_SHORTREP_LIT_LIT, - STATE_MATCH_LIT, - STATE_REP_LIT, - STATE_SHORTREP_LIT, - STATE_LIT_MATCH, - STATE_LIT_LONGREP, - STATE_LIT_SHORTREP, - STATE_NONLIT_MATCH, - STATE_NONLIT_REP -}; - -/* Total number of states */ -#define STATES 12 - -/* The lowest 7 states indicate that the previous state was a literal. */ -#define LIT_STATES 7 - -/* Indicate that the latest symbol was a literal. */ -static inline void lzma_state_literal(enum lzma_state *state) -{ - if (*state <= STATE_SHORTREP_LIT_LIT) - *state = STATE_LIT_LIT; - else if (*state <= STATE_LIT_SHORTREP) - *state -= 3; - else - *state -= 6; -} - -/* Indicate that the latest symbol was a match. */ -static inline void lzma_state_match(enum lzma_state *state) -{ - *state = *state < LIT_STATES ? STATE_LIT_MATCH : STATE_NONLIT_MATCH; -} - -/* Indicate that the latest state was a long repeated match. */ -static inline void lzma_state_long_rep(enum lzma_state *state) -{ - *state = *state < LIT_STATES ? STATE_LIT_LONGREP : STATE_NONLIT_REP; -} - -/* Indicate that the latest symbol was a short match. */ -static inline void lzma_state_short_rep(enum lzma_state *state) -{ - *state = *state < LIT_STATES ? STATE_LIT_SHORTREP : STATE_NONLIT_REP; -} - -/* Test if the previous symbol was a literal. */ -static inline bool lzma_state_is_literal(enum lzma_state state) -{ - return state < LIT_STATES; -} - -/* Each literal coder is divided in three sections: - * - 0x001-0x0FF: Without match byte - * - 0x101-0x1FF: With match byte; match bit is 0 - * - 0x201-0x2FF: With match byte; match bit is 1 - * - * Match byte is used when the previous LZMA symbol was something else than - * a literal (that is, it was some kind of match). - */ -#define LITERAL_CODER_SIZE 0x300 - -/* Maximum number of literal coders */ -#define LITERAL_CODERS_MAX (1 << 4) - -/* Minimum length of a match is two bytes. */ -#define MATCH_LEN_MIN 2 - -/* Match length is encoded with 4, 5, or 10 bits. - * - * Length Bits - * 2-9 4 = Choice=0 + 3 bits - * 10-17 5 = Choice=1 + Choice2=0 + 3 bits - * 18-273 10 = Choice=1 + Choice2=1 + 8 bits - */ -#define LEN_LOW_BITS 3 -#define LEN_LOW_SYMBOLS (1 << LEN_LOW_BITS) -#define LEN_MID_BITS 3 -#define LEN_MID_SYMBOLS (1 << LEN_MID_BITS) -#define LEN_HIGH_BITS 8 -#define LEN_HIGH_SYMBOLS (1 << LEN_HIGH_BITS) -#define LEN_SYMBOLS (LEN_LOW_SYMBOLS + LEN_MID_SYMBOLS + LEN_HIGH_SYMBOLS) - -/* - * Maximum length of a match is 273 which is a result of the encoding - * described above. - */ -#define MATCH_LEN_MAX (MATCH_LEN_MIN + LEN_SYMBOLS - 1) - -/* - * Different sets of probabilities are used for match distances that have - * very short match length: Lengths of 2, 3, and 4 bytes have a separate - * set of probabilities for each length. The matches with longer length - * use a shared set of probabilities. - */ -#define DIST_STATES 4 - -/* - * Get the index of the appropriate probability array for decoding - * the distance slot. - */ -static inline uint32_t lzma_get_dist_state(uint32_t len) -{ - return len < DIST_STATES + MATCH_LEN_MIN ? len - MATCH_LEN_MIN : DIST_STATES - 1; -} - -/* - * The highest two bits of a 32-bit match distance are encoded using six bits. - * This six-bit value is called a distance slot. This way encoding a 32-bit - * value takes 6-36 bits, larger values taking more bits. - */ -#define DIST_SLOT_BITS 6 -#define DIST_SLOTS (1 << DIST_SLOT_BITS) - -/* Match distances up to 127 are fully encoded using probabilities. Since - * the highest two bits (distance slot) are always encoded using six bits, - * the distances 0-3 don't need any additional bits to encode, since the - * distance slot itself is the same as the actual distance. DIST_MODEL_START - * indicates the first distance slot where at least one additional bit is - * needed. - */ -#define DIST_MODEL_START 4 - -/* - * Match distances greater than 127 are encoded in three pieces: - * - distance slot: the highest two bits - * - direct bits: 2-26 bits below the highest two bits - * - alignment bits: four lowest bits - * - * Direct bits don't use any probabilities. - * - * The distance slot value of 14 is for distances 128-191. - */ -#define DIST_MODEL_END 14 - -/* Distance slots that indicate a distance <= 127. */ -#define FULL_DISTANCES_BITS (DIST_MODEL_END / 2) -#define FULL_DISTANCES (1 << FULL_DISTANCES_BITS) - -/* - * For match distances greater than 127, only the highest two bits and the - * lowest four bits (alignment) is encoded using probabilities. - */ -#define ALIGN_BITS 4 -#define ALIGN_SIZE (1 << ALIGN_BITS) -#define ALIGN_MASK (ALIGN_SIZE - 1) - -/* Total number of all probability variables */ -#define PROBS_TOTAL (1846 + LITERAL_CODERS_MAX *LITERAL_CODER_SIZE) - -/* - * LZMA remembers the four most recent match distances. Reusing these - * distances tends to take less space than re-encoding the actual - * distance value. - */ -#define REPS 4 - -#endif diff --git a/libraries/xz-embedded/src/xz_private.h b/libraries/xz-embedded/src/xz_private.h deleted file mode 100644 index 1b616430..00000000 --- a/libraries/xz-embedded/src/xz_private.h +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Private includes and definitions - * - * Author: Lasse Collin - * - * This file has been put into the public domain. - * You can do whatever you want with this file. - */ - -#ifndef XZ_PRIVATE_H -#define XZ_PRIVATE_H - -#ifdef __KERNEL__ -#include -#include -#include -/* XZ_PREBOOT may be defined only via decompress_unxz.c. */ -#ifndef XZ_PREBOOT -#include -#include -#include -#ifdef CONFIG_XZ_DEC_X86 -#define XZ_DEC_X86 -#endif -#ifdef CONFIG_XZ_DEC_POWERPC -#define XZ_DEC_POWERPC -#endif -#ifdef CONFIG_XZ_DEC_IA64 -#define XZ_DEC_IA64 -#endif -#ifdef CONFIG_XZ_DEC_ARM -#define XZ_DEC_ARM -#endif -#ifdef CONFIG_XZ_DEC_ARMTHUMB -#define XZ_DEC_ARMTHUMB -#endif -#ifdef CONFIG_XZ_DEC_SPARC -#define XZ_DEC_SPARC -#endif -#define memeq(a, b, size) (memcmp(a, b, size) == 0) -#define memzero(buf, size) memset(buf, 0, size) -#endif -#define get_le32(p) le32_to_cpup((const uint32_t *)(p)) -#else -/* - * For userspace builds, use a separate header to define the required - * macros and functions. This makes it easier to adapt the code into - * different environments and avoids clutter in the Linux kernel tree. - */ -#include "xz_config.h" -#endif - -/* If no specific decoding mode is requested, enable support for all modes. */ -#if !defined(XZ_DEC_SINGLE) && !defined(XZ_DEC_PREALLOC) && !defined(XZ_DEC_DYNALLOC) -#define XZ_DEC_SINGLE -#define XZ_DEC_PREALLOC -#define XZ_DEC_DYNALLOC -#endif - -/* - * The DEC_IS_foo(mode) macros are used in "if" statements. If only some - * of the supported modes are enabled, these macros will evaluate to true or - * false at compile time and thus allow the compiler to omit unneeded code. - */ -#ifdef XZ_DEC_SINGLE -#define DEC_IS_SINGLE(mode) ((mode) == XZ_SINGLE) -#else -#define DEC_IS_SINGLE(mode) (false) -#endif - -#ifdef XZ_DEC_PREALLOC -#define DEC_IS_PREALLOC(mode) ((mode) == XZ_PREALLOC) -#else -#define DEC_IS_PREALLOC(mode) (false) -#endif - -#ifdef XZ_DEC_DYNALLOC -#define DEC_IS_DYNALLOC(mode) ((mode) == XZ_DYNALLOC) -#else -#define DEC_IS_DYNALLOC(mode) (false) -#endif - -#if !defined(XZ_DEC_SINGLE) -#define DEC_IS_MULTI(mode) (true) -#elif defined(XZ_DEC_PREALLOC) || defined(XZ_DEC_DYNALLOC) -#define DEC_IS_MULTI(mode) ((mode) != XZ_SINGLE) -#else -#define DEC_IS_MULTI(mode) (false) -#endif - -/* - * If any of the BCJ filter decoders are wanted, define XZ_DEC_BCJ. - * XZ_DEC_BCJ is used to enable generic support for BCJ decoders. - */ -#ifndef XZ_DEC_BCJ -#if defined(XZ_DEC_X86) || defined(XZ_DEC_POWERPC) || defined(XZ_DEC_IA64) || \ - defined(XZ_DEC_ARM) || defined(XZ_DEC_ARM) || defined(XZ_DEC_ARMTHUMB) || \ - defined(XZ_DEC_SPARC) -#define XZ_DEC_BCJ -#endif -#endif - -/* - * Allocate memory for LZMA2 decoder. xz_dec_lzma2_reset() must be used - * before calling xz_dec_lzma2_run(). - */ -XZ_EXTERN struct xz_dec_lzma2 *xz_dec_lzma2_create(enum xz_mode mode, uint32_t dict_max); - -/* - * Decode the LZMA2 properties (one byte) and reset the decoder. Return - * XZ_OK on success, XZ_MEMLIMIT_ERROR if the preallocated dictionary is not - * big enough, and XZ_OPTIONS_ERROR if props indicates something that this - * decoder doesn't support. - */ -XZ_EXTERN enum xz_ret xz_dec_lzma2_reset(struct xz_dec_lzma2 *s, uint8_t props); - -/* Decode raw LZMA2 stream from b->in to b->out. */ -XZ_EXTERN enum xz_ret xz_dec_lzma2_run(struct xz_dec_lzma2 *s, struct xz_buf *b); - -/* Free the memory allocated for the LZMA2 decoder. */ -XZ_EXTERN void xz_dec_lzma2_end(struct xz_dec_lzma2 *s); - -#ifdef XZ_DEC_BCJ -/* - * Allocate memory for BCJ decoders. xz_dec_bcj_reset() must be used before - * calling xz_dec_bcj_run(). - */ -XZ_EXTERN struct xz_dec_bcj *xz_dec_bcj_create(bool single_call); - -/* - * Decode the Filter ID of a BCJ filter. This implementation doesn't - * support custom start offsets, so no decoding of Filter Properties - * is needed. Returns XZ_OK if the given Filter ID is supported. - * Otherwise XZ_OPTIONS_ERROR is returned. - */ -XZ_EXTERN enum xz_ret xz_dec_bcj_reset(struct xz_dec_bcj *s, uint8_t id); - -/* - * Decode raw BCJ + LZMA2 stream. This must be used only if there actually is - * a BCJ filter in the chain. If the chain has only LZMA2, xz_dec_lzma2_run() - * must be called directly. - */ -XZ_EXTERN enum xz_ret xz_dec_bcj_run(struct xz_dec_bcj *s, struct xz_dec_lzma2 *lzma2, - struct xz_buf *b); - -/* Free the memory allocated for the BCJ filters. */ -#define xz_dec_bcj_end(s) kfree(s) -#endif - -#endif diff --git a/libraries/xz-embedded/src/xz_stream.h b/libraries/xz-embedded/src/xz_stream.h deleted file mode 100644 index b3d2c9fd..00000000 --- a/libraries/xz-embedded/src/xz_stream.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Definitions for handling the .xz file format - * - * Author: Lasse Collin - * - * This file has been put into the public domain. - * You can do whatever you want with this file. - */ - -#ifndef XZ_STREAM_H -#define XZ_STREAM_H - -#if defined(__KERNEL__) && !XZ_INTERNAL_CRC32 -#include -#undef crc32 -#define xz_crc32(buf, size, crc) (~crc32_le(~(uint32_t)(crc), buf, size)) -#endif - -/* - * See the .xz file format specification at - * http://tukaani.org/xz/xz-file-format.txt - * to understand the container format. - */ - -#define STREAM_HEADER_SIZE 12 - -#define HEADER_MAGIC "\3757zXZ" -#define HEADER_MAGIC_SIZE 6 - -#define FOOTER_MAGIC "YZ" -#define FOOTER_MAGIC_SIZE 2 - -/* - * Variable-length integer can hold a 63-bit unsigned integer or a special - * value indicating that the value is unknown. - * - * Experimental: vli_type can be defined to uint32_t to save a few bytes - * in code size (no effect on speed). Doing so limits the uncompressed and - * compressed size of the file to less than 256 MiB and may also weaken - * error detection slightly. - */ -typedef uint64_t vli_type; - -#define VLI_MAX ((vli_type) - 1 / 2) -#define VLI_UNKNOWN ((vli_type) - 1) - -/* Maximum encoded size of a VLI */ -#define VLI_BYTES_MAX (sizeof(vli_type) * 8 / 7) - -/* Integrity Check types */ -enum xz_check -{ - XZ_CHECK_NONE = 0, - XZ_CHECK_CRC32 = 1, - XZ_CHECK_CRC64 = 4, - XZ_CHECK_SHA256 = 10 -}; - -/* Maximum possible Check ID */ -#define XZ_CHECK_MAX 15 - -#endif diff --git a/libraries/xz-embedded/xzminidec.c b/libraries/xz-embedded/xzminidec.c deleted file mode 100644 index 44f60602..00000000 --- a/libraries/xz-embedded/xzminidec.c +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Simple XZ decoder command line tool - * - * Author: Lasse Collin - * - * This file has been put into the public domain. - * You can do whatever you want with this file. - */ - -/* - * This is really limited: Not all filters from .xz format are supported, - * only CRC32 is supported as the integrity check, and decoding of - * concatenated .xz streams is not supported. Thus, you may want to look - * at xzdec from XZ Utils if a few KiB bigger tool is not a problem. - */ - -#include -#include -#include -#include "xz.h" - -static uint8_t in[BUFSIZ]; -static uint8_t out[BUFSIZ]; - -int main(int argc, char **argv) -{ - struct xz_buf b; - struct xz_dec *s; - enum xz_ret ret; - const char *msg; - - if (argc >= 2 && strcmp(argv[1], "--help") == 0) - { - fputs("Uncompress a .xz file from stdin to stdout.\n" - "Arguments other than `--help' are ignored.\n", - stdout); - return 0; - } - - xz_crc32_init(); -#ifdef XZ_USE_CRC64 - xz_crc64_init(); -#endif - - /* - * Support up to 64 MiB dictionary. The actually needed memory - * is allocated once the headers have been parsed. - */ - s = xz_dec_init(XZ_DYNALLOC, 1 << 26); - if (s == NULL) - { - msg = "Memory allocation failed\n"; - goto error; - } - - b.in = in; - b.in_pos = 0; - b.in_size = 0; - b.out = out; - b.out_pos = 0; - b.out_size = BUFSIZ; - - while (true) - { - if (b.in_pos == b.in_size) - { - b.in_size = fread(in, 1, sizeof(in), stdin); - b.in_pos = 0; - } - - ret = xz_dec_run(s, &b); - - if (b.out_pos == sizeof(out)) - { - if (fwrite(out, 1, b.out_pos, stdout) != b.out_pos) - { - msg = "Write error\n"; - goto error; - } - - b.out_pos = 0; - } - - if (ret == XZ_OK) - continue; - -#ifdef XZ_DEC_ANY_CHECK - if (ret == XZ_UNSUPPORTED_CHECK) - { - fputs(argv[0], stderr); - fputs(": ", stderr); - fputs("Unsupported check; not verifying " - "file integrity\n", - stderr); - continue; - } -#endif - - if (fwrite(out, 1, b.out_pos, stdout) != b.out_pos || fclose(stdout)) - { - msg = "Write error\n"; - goto error; - } - - switch (ret) - { - case XZ_STREAM_END: - xz_dec_end(s); - return 0; - - case XZ_MEM_ERROR: - msg = "Memory allocation failed\n"; - goto error; - - case XZ_MEMLIMIT_ERROR: - msg = "Memory usage limit reached\n"; - goto error; - - case XZ_FORMAT_ERROR: - msg = "Not a .xz file\n"; - goto error; - - case XZ_OPTIONS_ERROR: - msg = "Unsupported options in the .xz headers\n"; - goto error; - - case XZ_DATA_ERROR: - case XZ_BUF_ERROR: - msg = "File is corrupt\n"; - goto error; - - default: - msg = "Bug!\n"; - goto error; - } - } - -error: - xz_dec_end(s); - fputs(argv[0], stderr); - fputs(": ", stderr); - fputs(msg, stderr); - return 1; -} From 1c7799e292bb1ca318627cea69395ff601e6f9e0 Mon Sep 17 00:00:00 2001 From: Adrien <66513643+AshtakaOOf@users.noreply.github.com> Date: Mon, 17 Oct 2022 22:53:02 +0200 Subject: [PATCH 061/101] Update README.md Change some stuff temporarily Signed-off-by: Adrien <66513643+AshtakaOOf@users.noreply.github.com> --- README.md | 94 +++++-------------------------------------------------- 1 file changed, 7 insertions(+), 87 deletions(-) diff --git a/README.md b/README.md index 6ff868e0..c9a2da44 100644 --- a/README.md +++ b/README.md @@ -1,100 +1,20 @@ -

-PolyMC logo -PolyMC logo -

- -PolyMC is a custom launcher for Minecraft that focuses on predictability, long term stability and simplicity. - -This is a **fork** of the MultiMC Launcher and not endorsed by MultiMC. -If you want to read about why this fork was created, check out [our FAQ page](https://polymc.org/wiki/overview/faq/). -
+PlaceholderMC is a custom launcher that will be the continuation of the now dead PolyMC. +Here is the [Discord Server](https://discord.gg/hX4g537UNE) # Installation -- All downloads and instructions for PolyMC can be found [here](https://polymc.org/download/) -- Last build status: +- All downloads and instructions for PlaceholderMC will soon be available +- Last build status: ## Development Builds -There are per-commit development builds available [here](https://github.com/PolyMC/PolyMC/actions). These have debug information in the binaries, so their file sizes are relatively larger. +There are per-commit development builds available [here](https://github.com/PlaceholderMC/PlaceholderMC/actions). These have debug information in the binaries, so their file sizes are relatively larger. Portable builds are provided for AppImage on Linux, Windows, and macOS. -For Debian and Arch, you can use these packages for the latest development versions: -[![polymc-git](https://img.shields.io/badge/aur-polymc--git-blue)](https://aur.archlinux.org/packages/polymc-git/) -[![polymc-git](https://img.shields.io/badge/mpr-polymc--git-orange)](https://mpr.makedeb.org/packages/polymc-git) -For flatpak, you can use [flathub-beta](https://discourse.flathub.org/t/how-to-use-flathub-beta/2111) - # Help & Support -Feel free to create an issue if you need help. However, you might find it easier to ask in the Discord server. +Join the Discord server for now. -[![PolyMC Discord](https://img.shields.io/discord/923671181020766230?label=PolyMC%20Discord)](https://discord.gg/xq7fxrgtMP) - -For people who don't want to use Discord, we have a Matrix Space which is bridged to the Discord server: - -[![PolyMC Space](https://img.shields.io/matrix/polymc:matrix.org?label=PolyMC%20space)](https://matrix.to/#/#polymc:matrix.org) - -If there are any issues with the space or you are using a client that does not support the feature here are the individual rooms: - -[![Development](https://img.shields.io/matrix/polymc-development:matrix.org?label=PolyMC%20Development)](https://matrix.to/#/#polymc-development:matrix.org) -[![Discussion](https://img.shields.io/matrix/polymc-discussion:matrix.org?label=PolyMC%20Discussion)](https://matrix.to/#/#polymc-discussion:matrix.org) -[![Github](https://img.shields.io/matrix/polymc-github:matrix.org?label=PolyMC%20Github)](https://matrix.to/#/#polymc-github:matrix.org) -[![Maintainers](https://img.shields.io/matrix/polymc-maintainers:matrix.org?label=PolyMC%20Maintainers)](https://matrix.to/#/#polymc-maintainers:matrix.org) -[![News](https://img.shields.io/matrix/polymc-news:matrix.org?label=PolyMC%20News)](https://matrix.to/#/#polymc-news:matrix.org) -[![Offtopic](https://img.shields.io/matrix/polymc-offtopic:matrix.org?label=PolyMC%20Offtopic)](https://matrix.to/#/#polymc-offtopic:matrix.org) -[![Support](https://img.shields.io/matrix/polymc-support:matrix.org?label=PolyMC%20Support)](https://matrix.to/#/#polymc-support:matrix.org) -[![Voice](https://img.shields.io/matrix/polymc-voice:matrix.org?label=PolyMC%20Voice)](https://matrix.to/#/#polymc-voice:matrix.org) - -We also have a subreddit you can post your issues and suggestions on: - -[r/PolyMCLauncher](https://www.reddit.com/r/PolyMCLauncher/) - -# Development - -If you want to contribute to PolyMC you might find it useful to join our Discord Server or Matrix Space. - -## Building - -If you want to build PolyMC yourself, check [Build Instructions](https://polymc.org/wiki/development/build-instructions/) for build instructions. - -## Translations - -The translation effort for PolyMC is hosted on [Weblate](https://hosted.weblate.org/projects/polymc/polymc/) and information about translating PolyMC is available at - -## Download information - -To modify download information or change packaging information send a pull request or issue to the website [here](https://github.com/PolyMC/polymc.github.io/tree/master/src/download). - -## Forking/Redistributing/Custom builds policy - -We don't care what you do with your fork/custom build as long as you follow the terms of the [license](LICENSE) (this is a legal responsibility), and if you made code changes rather than just packaging a custom build, please do the following as a basic courtesy: - -- Make it clear that your fork is not PolyMC and is not endorsed by or affiliated with the PolyMC project (). -- Go through [CMakeLists.txt](CMakeLists.txt) and change PolyMC's API keys to your own or set them to empty strings (`""`) to disable them (this way the program will still compile but the functionality requiring those keys will be disabled). - -If you have any questions or want any clarification on the above conditions please make an issue and ask us. - -Be aware that if you build this software without removing the provided API keys in [CMakeLists.txt](CMakeLists.txt) you are accepting the following terms and conditions: - -- [Microsoft Identity Platform Terms of Use](https://docs.microsoft.com/en-us/legal/microsoft-identity-platform/terms-of-use) -- [CurseForge 3rd Party API Terms and Conditions](https://support.curseforge.com/en/support/solutions/articles/9000207405-curse-forge-3rd-party-api-terms-and-conditions) - -If you do not agree with these terms and conditions, then remove the associated API keys from the [CMakeLists.txt](CMakeLists.txt) file by setting them to an empty string (`""`). +[Discord Server](https://discord.gg/hX4g537UNE) All launcher code is available under the GPL-3.0-only license. - -The logo and related assets are under the CC BY-SA 4.0 license. - -## Sponsors - -Thank you to all our generous backers over at Open Collective! Support PolyMC by [becoming a backer](https://opencollective.com/polymc). - -[![OpenCollective Backers](https://opencollective.com/polymc/backers.svg?width=890&limit=1000)](https://opencollective.com/polymc#backers) - -Also, thanks to JetBrains for providing us a few licenses for all their products, as part of their [Open Source program](https://www.jetbrains.com/opensource/). - -[![JetBrains](https://resources.jetbrains.com/storage/products/company/brand/logos/jb_beam.svg)](https://www.jetbrains.com/opensource/) - -Additionally, thanks to the awesome people over at [MacStadium](https://www.macstadium.com/), for providing M1-Macs for development purposes! - -Powered by MacStadium From 27873f7ed4d4b663ecdf66868161a2d268f80155 Mon Sep 17 00:00:00 2001 From: Adrien <66513643+AshtakaOOf@users.noreply.github.com> Date: Tue, 18 Oct 2022 01:27:51 +0200 Subject: [PATCH 062/101] Update README.md Signed-off-by: Adrien <66513643+AshtakaOOf@users.noreply.github.com> --- README.md | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index c9a2da44..0c71d5d2 100644 --- a/README.md +++ b/README.md @@ -1,20 +1,19 @@ -PlaceholderMC is a custom launcher that will be the continuation of the now dead PolyMC. -Here is the [Discord Server](https://discord.gg/hX4g537UNE) +# PlaceholderMC is a custom launcher that will be the continuation of the now dead PolyMC. -# Installation +##### Here is the [Discord Server](https://discord.gg/hX4g537UNE) + +### Installation - All downloads and instructions for PlaceholderMC will soon be available - Last build status: -## Development Builds +### Development Builds There are per-commit development builds available [here](https://github.com/PlaceholderMC/PlaceholderMC/actions). These have debug information in the binaries, so their file sizes are relatively larger. Portable builds are provided for AppImage on Linux, Windows, and macOS. -# Help & Support +### Help & Support -Join the Discord server for now. - -[Discord Server](https://discord.gg/hX4g537UNE) +Join the [Discord Server](https://discord.gg/hX4g537UNE) for now. All launcher code is available under the GPL-3.0-only license. From f8642548c8cb93e9620df780308320c4a9234a66 Mon Sep 17 00:00:00 2001 From: Adrien <66513643+AshtakaOOf@users.noreply.github.com> Date: Tue, 18 Oct 2022 01:35:30 +0200 Subject: [PATCH 063/101] Update README.md Signed-off-by: Adrien <66513643+AshtakaOOf@users.noreply.github.com> --- README.md | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 0c71d5d2..1fdbf7ad 100644 --- a/README.md +++ b/README.md @@ -1,19 +1,22 @@ # PlaceholderMC is a custom launcher that will be the continuation of the now dead PolyMC. +#### We are working on a website and other media, for more info we have a discord server. +#### Logo and branding also coming soon... -##### Here is the [Discord Server](https://discord.gg/hX4g537UNE) +### Here is the [Discord Server](https://discord.gg/hX4g537UNE) -### Installation +## Installation - All downloads and instructions for PlaceholderMC will soon be available - Last build status: ### Development Builds -There are per-commit development builds available [here](https://github.com/PlaceholderMC/PlaceholderMC/actions). These have debug information in the binaries, so their file sizes are relatively larger. +There are development builds available [here](https://github.com/PlaceholderMC/PlaceholderMC/actions). These have debug information in the binaries, so their file sizes are relatively larger. Portable builds are provided for AppImage on Linux, Windows, and macOS. -### Help & Support +## Help & Support -Join the [Discord Server](https://discord.gg/hX4g537UNE) for now. +- Join the [Discord Server](https://discord.gg/hX4g537UNE) for now. +We have a vanity url https://discord.gg/placeholdermc All launcher code is available under the GPL-3.0-only license. From a86b9c82ce4cb34cf65892753a3cad6d6ca81ed1 Mon Sep 17 00:00:00 2001 From: Adrien <66513643+AshtakaOOf@users.noreply.github.com> Date: Tue, 18 Oct 2022 01:38:49 +0200 Subject: [PATCH 064/101] Update README.md Signed-off-by: Adrien <66513643+AshtakaOOf@users.noreply.github.com> --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 1fdbf7ad..b3bb467c 100644 --- a/README.md +++ b/README.md @@ -19,4 +19,6 @@ Portable builds are provided for AppImage on Linux, Windows, and macOS. - Join the [Discord Server](https://discord.gg/hX4g537UNE) for now. We have a vanity url https://discord.gg/placeholdermc +### License + All launcher code is available under the GPL-3.0-only license. From 722194405a8333a70b44cc204dabc8a590a6b3fd Mon Sep 17 00:00:00 2001 From: Sefa Eyeoglu Date: Tue, 18 Oct 2022 09:01:48 +0200 Subject: [PATCH 065/101] refactor: initial rebrand Signed-off-by: Sefa Eyeoglu --- .gitmodules | 6 +-- BUILD.md | 4 +- CMakeLists.txt | 30 +++++------ CODE_OF_CONDUCT.md | 2 +- buildconfig/BuildConfig.h | 4 +- flake.lock | 16 +++--- flake.nix | 8 +-- launcher/Application.cpp | 2 +- launcher/java/JavaUtils.cpp | 2 +- launcher/main.cpp | 2 +- launcher/ui/pages/global/LauncherPage.cpp | 2 +- launcher/ui/pages/modplatform/ImportPage.ui | 2 +- .../ui/pages/modplatform/flame/FlamePage.ui | 2 +- nix/default.nix | 14 ++--- program_info/CMakeLists.txt | 44 ++++++++-------- program_info/README.md | 4 +- program_info/genicons.sh | 48 +++++++++--------- ...rg.prismlauncher.PrismLauncher.Source.svg} | 0 ...rg.prismlauncher.PrismLauncher.bigsur.svg} | 0 ...rg.prismlauncher.PrismLauncher.desktop.in} | 6 +-- ...ismlauncher.PrismLauncher.metainfo.xml.in} | 30 +++++------ ...vg => org.prismlauncher.PrismLauncher.svg} | 0 ...ack.svg => prismlauncher-header-black.svg} | 0 ...ce.svg => prismlauncher-header.Source.svg} | 0 ...mc-header.svg => prismlauncher-header.svg} | 0 .../{polymc.6.scd => prismlauncher.6.scd} | 0 .../{polymc.icns => prismlauncher.icns} | Bin .../{polymc.ico => prismlauncher.ico} | Bin ....manifest.in => prismlauncher.manifest.in} | 2 +- .../{polymc.qrc => prismlauncher.qrc} | 2 +- .../{polymc.rc.in => prismlauncher.rc.in} | 10 ++-- 31 files changed, 121 insertions(+), 121 deletions(-) rename program_info/{org.polymc.PolyMC.Source.svg => org.prismlauncher.PrismLauncher.Source.svg} (100%) rename program_info/{org.polymc.PolyMC.bigsur.svg => org.prismlauncher.PrismLauncher.bigsur.svg} (100%) rename program_info/{org.polymc.PolyMC.desktop.in => org.prismlauncher.PrismLauncher.desktop.in} (76%) rename program_info/{org.polymc.PolyMC.metainfo.xml.in => org.prismlauncher.PrismLauncher.metainfo.xml.in} (55%) rename program_info/{org.polymc.PolyMC.svg => org.prismlauncher.PrismLauncher.svg} (100%) rename program_info/{polymc-header-black.svg => prismlauncher-header-black.svg} (100%) rename program_info/{polymc-header.Source.svg => prismlauncher-header.Source.svg} (100%) rename program_info/{polymc-header.svg => prismlauncher-header.svg} (100%) rename program_info/{polymc.6.scd => prismlauncher.6.scd} (100%) rename program_info/{polymc.icns => prismlauncher.icns} (100%) rename program_info/{polymc.ico => prismlauncher.ico} (100%) rename program_info/{polymc.manifest.in => prismlauncher.manifest.in} (92%) rename program_info/{polymc.qrc => prismlauncher.qrc} (60%) rename program_info/{polymc.rc.in => prismlauncher.rc.in} (66%) diff --git a/.gitmodules b/.gitmodules index efd5de29..d620faab 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,6 +1,3 @@ -[submodule "depends/libnbtplusplus"] - path = libraries/libnbtplusplus - url = https://github.com/PolyMC/libnbtplusplus.git [submodule "libraries/quazip"] path = libraries/quazip url = https://github.com/stachenov/quazip.git @@ -10,3 +7,6 @@ [submodule "libraries/filesystem"] path = libraries/filesystem url = https://github.com/gulrak/filesystem +[submodule "libraries/libnbtplusplus"] + path = libraries/libnbtplusplus + url = https://github.com/PlaceholderMC/libnbtplusplus.git diff --git a/BUILD.md b/BUILD.md index 8a76b68b..4d9fb76f 100644 --- a/BUILD.md +++ b/BUILD.md @@ -1,5 +1,5 @@ # Build Instructions -Build instructions are available on [the website](https://polymc.org/wiki/development/build-instructions/). +Build instructions are available on [the website](https://prismlauncher.org/wiki/development/build-instructions/). -If you would like to contribute or fix an issue with the Build instructions you can do so [here](https://github.com/PolyMC/polymc.github.io/blob/master/src/wiki/development/build-instructions.md). +If you would like to contribute or fix an issue with the Build instructions you can do so [here](https://github.com/PlaceholderMC/website/blob/master/src/wiki/development/build-instructions.md). diff --git a/CMakeLists.txt b/CMakeLists.txt index caecddbd..8b3f0251 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -71,9 +71,9 @@ endif() ##################################### Set Application options ##################################### ######## Set URLs ######## -set(Launcher_NEWS_RSS_URL "https://polymc.org/feed/feed.xml" CACHE STRING "URL to fetch PolyMC's news RSS feed from.") -set(Launcher_NEWS_OPEN_URL "https://polymc.org/news" CACHE STRING "URL that gets opened when the user clicks 'More News'") -set(Launcher_HELP_URL "https://polymc.org/wiki/help-pages/%1" CACHE STRING "URL (with arg %1 to be substituted with page-id) that gets opened when the user requests help") +set(Launcher_NEWS_RSS_URL "https://prismlauncher.org/feed/feed.xml" CACHE STRING "URL to fetch PrismLauncher's news RSS feed from.") +set(Launcher_NEWS_OPEN_URL "https://prismlauncher.org/news" CACHE STRING "URL that gets opened when the user clicks 'More News'") +set(Launcher_HELP_URL "https://prismlauncher.org/wiki/help-pages/%1" CACHE STRING "URL (with arg %1 to be substituted with page-id) that gets opened when the user requests help") ######## Set version numbers ######## set(Launcher_VERSION_MAJOR 5) @@ -90,25 +90,25 @@ set(Launcher_BUILD_PLATFORM "" CACHE STRING "A short string identifying the plat set(Launcher_UPDATER_BASE "" CACHE STRING "Base URL for the updater.") # The metadata server -set(Launcher_META_URL "https://meta.polymc.org/v1/" CACHE STRING "URL to fetch Launcher's meta files from.") +set(Launcher_META_URL "https://meta.prismlauncher.org/v1/" CACHE STRING "URL to fetch Launcher's meta files from.") # Imgur API Client ID set(Launcher_IMGUR_CLIENT_ID "5b97b0713fba4a3" CACHE STRING "Client ID you can get from Imgur when you register an application") # Bug tracker URL -set(Launcher_BUG_TRACKER_URL "https://github.com/PolyMC/PolyMC/issues" CACHE STRING "URL for the bug tracker.") +set(Launcher_BUG_TRACKER_URL "https://github.com/PrismLauncher/PrismLauncher/issues" CACHE STRING "URL for the bug tracker.") # Translations Platform URL -set(Launcher_TRANSLATIONS_URL "https://hosted.weblate.org/projects/polymc/polymc/" CACHE STRING "URL for the translations platform.") +set(Launcher_TRANSLATIONS_URL "https://hosted.weblate.org/projects/prismlauncher/prismlauncher/" CACHE STRING "URL for the translations platform.") # Matrix Space -set(Launcher_MATRIX_URL "https://matrix.to/#/#polymc:matrix.org" CACHE STRING "URL to the Matrix Space") +set(Launcher_MATRIX_URL "https://matrix.to/#/#prismlauncher:matrix.org" CACHE STRING "URL to the Matrix Space") # Discord URL -set(Launcher_DISCORD_URL "https://discord.gg/Z52pwxWCHP" CACHE STRING "URL for the Discord guild.") +set(Launcher_DISCORD_URL "https://discord.gg/prismlauncher" CACHE STRING "URL for the Discord guild.") # Subreddit URL -set(Launcher_SUBREDDIT_URL "https://www.reddit.com/r/PolyMCLauncher/" CACHE STRING "URL for the subreddit.") +set(Launcher_SUBREDDIT_URL "https://www.reddit.com/r/PrismLauncher/" CACHE STRING "URL for the subreddit.") # Builds set(Launcher_FORCE_BUNDLED_LIBS OFF CACHE BOOL "Prevent using system libraries, if they are available as submodules") @@ -123,12 +123,12 @@ set(Launcher_QT_VERSION_MAJOR "5" CACHE STRING "Major Qt version to build agains # By using this key in your builds you accept the terms of use laid down in # https://docs.microsoft.com/en-us/legal/microsoft-identity-platform/terms-of-use -set(Launcher_MSA_CLIENT_ID "549033b2-1532-4d4e-ae77-1bbaa46f9d74" CACHE STRING "Client ID you can get from Microsoft Identity Platform when you register an application") +set(Launcher_MSA_CLIENT_ID "" CACHE STRING "Client ID you can get from Microsoft Identity Platform when you register an application") # By using this key in your builds you accept the terms and conditions laid down in # https://support.curseforge.com/en/support/solutions/articles/9000207405-curse-forge-3rd-party-api-terms-and-conditions # NOTE: CurseForge requires you to change this if you make any kind of derivative work. -set(Launcher_CURSEFORGE_API_KEY "$2a$10$1Oqr2MX3O4n/ilhFGc597u8tfI3L2Hyr9/rtWDAMRjghSQV2QUuxq" CACHE STRING "API key for the CurseForge platform") +set(Launcher_CURSEFORGE_API_KEY "" CACHE STRING "API key for the CurseForge platform") #### Check the current Git commit and branch @@ -199,7 +199,7 @@ endif() ####################################### Program Info ####################################### -set(Launcher_APP_BINARY_NAME "polymc" CACHE STRING "Name of the Launcher binary") +set(Launcher_APP_BINARY_NAME "prismlauncher" CACHE STRING "Name of the Launcher binary") add_subdirectory(program_info) ####################################### Install layout ####################################### @@ -223,14 +223,14 @@ if(UNIX AND APPLE) # Mac bundle settings set(MACOSX_BUNDLE_BUNDLE_NAME "${Launcher_Name}") set(MACOSX_BUNDLE_INFO_STRING "${Launcher_Name}: A custom launcher for Minecraft that allows you to easily manage multiple installations of Minecraft at once.") - set(MACOSX_BUNDLE_GUI_IDENTIFIER "org.polymc.${Launcher_Name}") + set(MACOSX_BUNDLE_GUI_IDENTIFIER "org.prismlauncher.${Launcher_Name}") set(MACOSX_BUNDLE_BUNDLE_VERSION "${Launcher_VERSION_NAME}") set(MACOSX_BUNDLE_SHORT_VERSION_STRING "${Launcher_VERSION_NAME}") set(MACOSX_BUNDLE_LONG_VERSION_STRING "${Launcher_VERSION_NAME}") set(MACOSX_BUNDLE_ICON_FILE ${Launcher_Name}.icns) set(MACOSX_BUNDLE_COPYRIGHT "Copyright 2021-2022 ${Launcher_Copyright}") - set(MACOSX_SPARKLE_UPDATE_PUBLIC_KEY "idALcUIazingvKSSsEa9U7coDVxZVx/ORpOEE/QtJfg=") - set(MACOSX_SPARKLE_UPDATE_FEED_URL "https://polymc.org/feed/appcast.xml") + set(MACOSX_SPARKLE_UPDATE_PUBLIC_KEY "") + set(MACOSX_SPARKLE_UPDATE_FEED_URL "https://prismlauncher.org/feed/appcast.xml") set(MACOSX_SPARKLE_DOWNLOAD_URL "https://github.com/sparkle-project/Sparkle/releases/download/2.1.0/Sparkle-2.1.0.tar.xz" CACHE STRING "URL to Sparkle release archive") set(MACOSX_SPARKLE_SHA256 "bf6ac1caa9f8d321d5784859c88da874f28412f37fb327bc21b7b14c5d61ef94" CACHE STRING "SHA256 checksum for Sparkle release archive") diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 7bbd01da..defa2170 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -63,7 +63,7 @@ representative at an online or offline event. Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement via email at -[polymc-enforcement@scrumplex.net](mailto:polymc-enforcement@scrumplex.net) (Email +[coc@scrumplex.net](mailto:coc@scrumplex.net) (Email address subject to change). All complaints will be reviewed and investigated promptly and fairly. diff --git a/buildconfig/BuildConfig.h b/buildconfig/BuildConfig.h index de66cec4..ef384ed2 100644 --- a/buildconfig/BuildConfig.h +++ b/buildconfig/BuildConfig.h @@ -140,8 +140,8 @@ class Config { QString LIBRARY_BASE = "https://libraries.minecraft.net/"; QString AUTH_BASE = "https://authserver.mojang.com/"; QString IMGUR_BASE_URL = "https://api.imgur.com/3/"; - QString FMLLIBS_BASE_URL = "https://files.polymc.org/fmllibs/"; - QString TRANSLATIONS_BASE_URL = "https://i18n.polymc.org/"; + QString FMLLIBS_BASE_URL = "https://files.prismlauncher.org/fmllibs/"; // FIXME: move into CMakeLists + QString TRANSLATIONS_BASE_URL = "https://i18n.prismlauncher.org/"; // FIXME: move into CMakeLists QString MODPACKSCH_API_BASE_URL = "https://api.modpacks.ch/"; diff --git a/flake.lock b/flake.lock index a72286bb..8d04df4b 100644 --- a/flake.lock +++ b/flake.lock @@ -21,24 +21,24 @@ "locked": { "lastModified": 1650031308, "narHash": "sha256-TvVOjkUobYJD9itQYueELJX3wmecvEdCbJ0FinW2mL4=", - "owner": "PolyMC", + "owner": "PlaceholderMC", "repo": "libnbtplusplus", "rev": "2203af7eeb48c45398139b583615134efd8d407f", "type": "github" }, "original": { - "owner": "PolyMC", + "owner": "PlaceholderMC", "repo": "libnbtplusplus", "type": "github" } }, "nixpkgs": { "locked": { - "lastModified": 1658119717, - "narHash": "sha256-4upOZIQQ7Bc4CprqnHsKnqYfw+arJeAuU+QcpjYBXW0=", + "lastModified": 1666057921, + "narHash": "sha256-VpQqtXdj6G7cH//SvoprjR7XT3KS7p+tCVebGK1N6tE=", "owner": "nixos", "repo": "nixpkgs", - "rev": "9eb60f25aff0d2218c848dd4574a0ab5e296cabe", + "rev": "88eab1e431cabd0ed621428d8b40d425a07af39f", "type": "github" }, "original": { @@ -59,11 +59,11 @@ "tomlplusplus": { "flake": false, "locked": { - "lastModified": 1664034574, - "narHash": "sha256-EFMAl6tsTvkgK0DWC/pZfOIq06b2e5SnxJa1ngGRIQA=", + "lastModified": 1666026506, + "narHash": "sha256-YE0u5M9mfGPNTakFrNTBt4BSvJUr2gkJN41COnPMvh8=", "owner": "marzer", "repo": "tomlplusplus", - "rev": "8aa5c8b2a4ff2c440d4630addf64fa4f62146170", + "rev": "c8780a5b8e8d2f8ff1fd747a3a89b7becebfdee9", "type": "github" }, "original": { diff --git a/flake.nix b/flake.nix index 93192725..c6207999 100644 --- a/flake.nix +++ b/flake.nix @@ -4,7 +4,7 @@ inputs = { nixpkgs.url = "github:nixos/nixpkgs/nixpkgs-unstable"; flake-compat = { url = "github:edolstra/flake-compat"; flake = false; }; - libnbtplusplus = { url = "github:PolyMC/libnbtplusplus"; flake = false; }; + libnbtplusplus = { url = "github:PlaceholderMC/libnbtplusplus"; flake = false; }; tomlplusplus = { url = "github:marzer/tomlplusplus"; flake = false; }; }; @@ -23,14 +23,14 @@ pkgs = forAllSystems (system: nixpkgs.legacyPackages.${system}); packagesFn = pkgs: rec { - polymc = pkgs.libsForQt5.callPackage ./nix { inherit version self libnbtplusplus tomlplusplus; }; - polymc-qt6 = pkgs.qt6Packages.callPackage ./nix { inherit version self libnbtplusplus tomlplusplus; }; + prismlauncher = pkgs.libsForQt5.callPackage ./nix { inherit version self libnbtplusplus tomlplusplus; }; + prismlauncher-qt6 = pkgs.qt6Packages.callPackage ./nix { inherit version self libnbtplusplus tomlplusplus; }; }; in { packages = forAllSystems (system: let packages = packagesFn pkgs.${system}; in - packages // { default = packages.polymc; } + packages // { default = packages.prismlauncher; } ); overlay = final: packagesFn; diff --git a/launcher/Application.cpp b/launcher/Application.cpp index 968dd08e..4841ca53 100644 --- a/launcher/Application.cpp +++ b/launcher/Application.cpp @@ -1157,7 +1157,7 @@ void Application::setIconTheme(const QString& name) QIcon Application::getThemedIcon(const QString& name) { if(name == "logo") { - return QIcon(":/org.polymc.PolyMC.svg"); + return QIcon(":/org.prismlauncher.PrismLauncher.svg"); // FIXME: Make this a BuildConfig variable } return QIcon::fromTheme(name); } diff --git a/launcher/java/JavaUtils.cpp b/launcher/java/JavaUtils.cpp index 2f91605b..6096e812 100644 --- a/launcher/java/JavaUtils.cpp +++ b/launcher/java/JavaUtils.cpp @@ -174,7 +174,7 @@ JavaInstallPtr JavaUtils::GetDefaultJava() QStringList addJavasFromEnv(QList javas) { - auto env = qEnvironmentVariable("POLYMC_JAVA_PATHS"); + auto env = qEnvironmentVariable("PRISMLAUNCHER_JAVA_PATHS"); // FIXME: use launcher name from buildconfig #if defined(Q_OS_WIN32) QList javaPaths = env.replace("\\", "/").split(QLatin1String(";")); diff --git a/launcher/main.cpp b/launcher/main.cpp index 85fe1260..c6a7614c 100644 --- a/launcher/main.cpp +++ b/launcher/main.cpp @@ -75,7 +75,7 @@ int main(int argc, char *argv[]) Q_INIT_RESOURCE(multimc); Q_INIT_RESOURCE(backgrounds); Q_INIT_RESOURCE(documents); - Q_INIT_RESOURCE(polymc); + Q_INIT_RESOURCE(prismlauncher); Q_INIT_RESOURCE(pe_dark); Q_INIT_RESOURCE(pe_light); diff --git a/launcher/ui/pages/global/LauncherPage.cpp b/launcher/ui/pages/global/LauncherPage.cpp index 73ef0024..1e5df5b2 100644 --- a/launcher/ui/pages/global/LauncherPage.cpp +++ b/launcher/ui/pages/global/LauncherPage.cpp @@ -151,7 +151,7 @@ void LauncherPage::on_instDirBrowseBtn_clicked() "This is known to cause problems. " "After a restart the launcher might break, " "because it will no longer have access to that directory.\n\n" - "Granting PolyMC access to it via Flatseal is recommended.")); + "Granting %1 access to it via Flatseal is recommended.").arg(BuildConfig.LAUNCHER_DISPLAYNAME)); warning.setInformativeText( tr("Do you want to proceed anyway?")); warning.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel); diff --git a/launcher/ui/pages/modplatform/ImportPage.ui b/launcher/ui/pages/modplatform/ImportPage.ui index 0a50e871..3583cf90 100644 --- a/launcher/ui/pages/modplatform/ImportPage.ui +++ b/launcher/ui/pages/modplatform/ImportPage.ui @@ -60,7 +60,7 @@ - - PolyMC / MultiMC exported instances (ZIP) + - Prism Launcher, PolyMC or MultiMC exported instances (ZIP) Qt::AlignCenter diff --git a/launcher/ui/pages/modplatform/flame/FlamePage.ui b/launcher/ui/pages/modplatform/flame/FlamePage.ui index aab16421..1a3d0225 100644 --- a/launcher/ui/pages/modplatform/flame/FlamePage.ui +++ b/launcher/ui/pages/modplatform/flame/FlamePage.ui @@ -19,7 +19,7 @@ - Note: CurseForge allows creators to block access to third-party tools like PolyMC. As such, you may need to manually download some mods to be able to install a modpack. + Note: CurseForge allows creators to block access to third-party tools like Prism Launcher. As such, you may need to manually download some mods to be able to install a modpack. Qt::AlignCenter diff --git a/nix/default.nix b/nix/default.nix index 19136cad..c8b4f7cc 100644 --- a/nix/default.nix +++ b/nix/default.nix @@ -38,14 +38,14 @@ let libGL ]; - # This variable will be passed to Minecraft by PolyMC + # This variable will be passed to Minecraft by Prism Launcher gameLibraryPath = libpath + ":/run/opengl-driver/lib"; javaPaths = lib.makeSearchPath "bin/java" ([ jdk jdk8 ] ++ extraJDKs); in stdenv.mkDerivation rec { - pname = "polymc"; + pname = "prismlauncher"; inherit version; src = lib.cleanSource self; @@ -77,17 +77,17 @@ stdenv.mkDerivation rec { # we have to check if the system is NixOS before adding stdenv.cc.cc.lib (#923) postInstall = '' # xorg.xrandr needed for LWJGL [2.9.2, 3) https://github.com/LWJGL/lwjgl/issues/128 - wrapQtApp $out/bin/polymc \ + wrapQtApp $out/bin/prismlauncher \ --run '[ -f /etc/NIXOS ] && export LD_LIBRARY_PATH="${stdenv.cc.cc.lib}/lib:$LD_LIBRARY_PATH"' \ --prefix LD_LIBRARY_PATH : ${gameLibraryPath} \ - --prefix POLYMC_JAVA_PATHS : ${javaPaths} \ + --prefix PRISMLAUNCHER_JAVA_PATHS : ${javaPaths} \ --prefix PATH : ${lib.makeBinPath [ xorg.xrandr ]} ''; meta = with lib; { - homepage = "https://polymc.org/"; - downloadPage = "https://polymc.org/download/"; - changelog = "https://github.com/PolyMC/PolyMC/releases"; + homepage = "https://prismlauncher.org/"; + downloadPage = "https://prismlauncher.org/download/"; + changelog = "https://github.com/PrismLauncher/PrismLauncher/releases"; description = "A free, open source launcher for Minecraft"; longDescription = '' Allows you to have multiple, separate instances of Minecraft (each with diff --git a/program_info/CMakeLists.txt b/program_info/CMakeLists.txt index ac8ea6ce..4d7c224d 100644 --- a/program_info/CMakeLists.txt +++ b/program_info/CMakeLists.txt @@ -8,44 +8,44 @@ if(UNIX) endif() endif() -set(Launcher_CommonName "PolyMC") +set(Launcher_CommonName "PrismLauncher") -set(Launcher_Copyright "PolyMC Contributors\\n© 2012-2021 MultiMC Contributors") +set(Launcher_Copyright "Prism Launcher Contributors\\n© 2012-2021 MultiMC Contributors") set(Launcher_Copyright "${Launcher_Copyright}" PARENT_SCOPE) -set(Launcher_Domain "polymc.org" PARENT_SCOPE) +set(Launcher_Domain "prismlauncher.org" PARENT_SCOPE) set(Launcher_Name "${Launcher_CommonName}" PARENT_SCOPE) -set(Launcher_DisplayName "${Launcher_CommonName}" PARENT_SCOPE) +set(Launcher_DisplayName "Prism Launcher" PARENT_SCOPE) set(Launcher_UserAgent "${Launcher_CommonName}/${Launcher_VERSION_NAME}" PARENT_SCOPE) -set(Launcher_ConfigFile "polymc.cfg" PARENT_SCOPE) -set(Launcher_Git "https://github.com/PolyMC/PolyMC" PARENT_SCOPE) -set(Launcher_DesktopFileName "org.polymc.PolyMC.desktop" PARENT_SCOPE) +set(Launcher_ConfigFile "prismlauncher.cfg" PARENT_SCOPE) +set(Launcher_Git "https://github.com/PlaceholderMC/PrismLauncher" PARENT_SCOPE) +set(Launcher_DesktopFileName "org.prismlauncher.PrismLauncher.desktop" PARENT_SCOPE) -set(Launcher_Desktop "program_info/org.polymc.PolyMC.desktop" PARENT_SCOPE) -set(Launcher_MetaInfo "program_info/org.polymc.PolyMC.metainfo.xml" PARENT_SCOPE) -set(Launcher_SVG "program_info/org.polymc.PolyMC.svg" PARENT_SCOPE) -set(Launcher_Branding_ICNS "program_info/polymc.icns" PARENT_SCOPE) -set(Launcher_Branding_ICO "program_info/polymc.ico") +set(Launcher_Desktop "program_info/org.prismlauncher.PrismLauncher.desktop" PARENT_SCOPE) +set(Launcher_MetaInfo "program_info/org.prismlauncher.PrismLauncher.metainfo.xml" PARENT_SCOPE) +set(Launcher_SVG "program_info/org.prismlauncher.PrismLauncher.svg" PARENT_SCOPE) +set(Launcher_Branding_ICNS "program_info/prismlauncher.icns" PARENT_SCOPE) +set(Launcher_Branding_ICO "program_info/prismlauncher.ico") set(Launcher_Branding_ICO "${Launcher_Branding_ICO}" PARENT_SCOPE) -set(Launcher_Branding_WindowsRC "program_info/polymc.rc" PARENT_SCOPE) -set(Launcher_Branding_LogoQRC "program_info/polymc.qrc" PARENT_SCOPE) +set(Launcher_Branding_WindowsRC "program_info/prismlauncher.rc" PARENT_SCOPE) +set(Launcher_Branding_LogoQRC "program_info/prismlauncher.qrc" PARENT_SCOPE) set(Launcher_Portable_File "program_info/portable.txt" PARENT_SCOPE) -configure_file(org.polymc.PolyMC.desktop.in org.polymc.PolyMC.desktop) -configure_file(org.polymc.PolyMC.metainfo.xml.in org.polymc.PolyMC.metainfo.xml) -configure_file(polymc.rc.in polymc.rc @ONLY) -configure_file(polymc.manifest.in polymc.manifest @ONLY) -configure_file(polymc.ico polymc.ico COPYONLY) +configure_file(org.prismlauncher.PrismLauncher.desktop.in org.prismlauncher.PrismLauncher.desktop) +configure_file(org.prismlauncher.PrismLauncher.metainfo.xml.in org.prismlauncher.PrismLauncher.metainfo.xml) +configure_file(prismlauncher.rc.in prismlauncher.rc @ONLY) +configure_file(prismlauncher.manifest.in prismlauncher.manifest @ONLY) +configure_file(prismlauncher.ico prismlauncher.ico COPYONLY) configure_file(win_install.nsi.in win_install.nsi @ONLY) if(SCDOC_FOUND) - set(in_scd "${CMAKE_CURRENT_SOURCE_DIR}/polymc.6.scd") - set(out_man "${CMAKE_CURRENT_BINARY_DIR}/polymc.6") + set(in_scd "${CMAKE_CURRENT_SOURCE_DIR}/prismlauncher.6.scd") + set(out_man "${CMAKE_CURRENT_BINARY_DIR}/prismlauncher.6") add_custom_command( DEPENDS "${in_scd}" OUTPUT "${out_man}" COMMAND ${SCDOC_SCDOC} < "${in_scd}" > "${out_man}" ) add_custom_target(man ALL DEPENDS ${out_man}) - set(Launcher_ManPage "program_info/polymc.6" PARENT_SCOPE) + set(Launcher_ManPage "program_info/prismlauncher.6" PARENT_SCOPE) endif() diff --git a/program_info/README.md b/program_info/README.md index 421ef1f9..8fc81a19 100644 --- a/program_info/README.md +++ b/program_info/README.md @@ -1,6 +1,6 @@ -# PolyMC Program Info +# PrismLauncher Program Info -This is PolyMC's program info which contains information about: +This is PrismLauncher's program info which contains information about: - Application name and logo (and branding in general) - Various URLs and API endpoints diff --git a/program_info/genicons.sh b/program_info/genicons.sh index 313bdb53..bfe756d8 100755 --- a/program_info/genicons.sh +++ b/program_info/genicons.sh @@ -2,38 +2,38 @@ # ICO -inkscape -w 16 -h 16 -o polymc_16.png org.polymc.PolyMC.svg -inkscape -w 24 -h 24 -o polymc_24.png org.polymc.PolyMC.svg -inkscape -w 32 -h 32 -o polymc_32.png org.polymc.PolyMC.svg -inkscape -w 48 -h 48 -o polymc_48.png org.polymc.PolyMC.svg -inkscape -w 64 -h 64 -o polymc_64.png org.polymc.PolyMC.svg -inkscape -w 128 -h 128 -o polymc_128.png org.polymc.PolyMC.svg +inkscape -w 16 -h 16 -o prismlauncher_16.png org.prismlauncher.PrismLauncher.svg +inkscape -w 24 -h 24 -o prismlauncher_24.png org.prismlauncher.PrismLauncher.svg +inkscape -w 32 -h 32 -o prismlauncher_32.png org.prismlauncher.PrismLauncher.svg +inkscape -w 48 -h 48 -o prismlauncher_48.png org.prismlauncher.PrismLauncher.svg +inkscape -w 64 -h 64 -o prismlauncher_64.png org.prismlauncher.PrismLauncher.svg +inkscape -w 128 -h 128 -o prismlauncher_128.png org.prismlauncher.PrismLauncher.svg -convert polymc_128.png polymc_64.png polymc_48.png polymc_32.png polymc_24.png polymc_16.png polymc.ico +convert prismlauncher_128.png prismlauncher_64.png prismlauncher_48.png prismlauncher_32.png prismlauncher_24.png prismlauncher_16.png prismlauncher.ico -rm -f polymc_*.png +rm -f prismlauncher_*.png -inkscape -w 1024 -h 1024 -o polymc_1024.png org.polymc.PolyMC.bigsur.svg +inkscape -w 1024 -h 1024 -o prismlauncher_1024.png org.prismlauncher.PrismLauncher.bigsur.svg -mkdir polymc.iconset +mkdir prismlauncher.iconset -sips -z 16 16 polymc_1024.png --out polymc.iconset/icon_16x16.png -sips -z 32 32 polymc_1024.png --out polymc.iconset/icon_16x16@2x.png -sips -z 32 32 polymc_1024.png --out polymc.iconset/icon_32x32.png -sips -z 64 64 polymc_1024.png --out polymc.iconset/icon_32x32@2x.png -sips -z 128 128 polymc_1024.png --out polymc.iconset/icon_128x128.png -sips -z 256 256 polymc_1024.png --out polymc.iconset/icon_128x128@2x.png -sips -z 256 256 polymc_1024.png --out polymc.iconset/icon_256x256.png -sips -z 512 512 polymc_1024.png --out polymc.iconset/icon_256x256@2x.png -sips -z 512 512 polymc_1024.png --out polymc.iconset/icon_512x512.png -cp polymc_1024.png polymc.iconset/icon_512x512@2x.png +sips -z 16 16 prismlauncher_1024.png --out prismlauncher.iconset/icon_16x16.png +sips -z 32 32 prismlauncher_1024.png --out prismlauncher.iconset/icon_16x16@2x.png +sips -z 32 32 prismlauncher_1024.png --out prismlauncher.iconset/icon_32x32.png +sips -z 64 64 prismlauncher_1024.png --out prismlauncher.iconset/icon_32x32@2x.png +sips -z 128 128 prismlauncher_1024.png --out prismlauncher.iconset/icon_128x128.png +sips -z 256 256 prismlauncher_1024.png --out prismlauncher.iconset/icon_128x128@2x.png +sips -z 256 256 prismlauncher_1024.png --out prismlauncher.iconset/icon_256x256.png +sips -z 512 512 prismlauncher_1024.png --out prismlauncher.iconset/icon_256x256@2x.png +sips -z 512 512 prismlauncher_1024.png --out prismlauncher.iconset/icon_512x512.png +cp prismlauncher_1024.png prismlauncher.iconset/icon_512x512@2x.png -iconutil -c icns polymc.iconset +iconutil -c icns prismlauncher.iconset -rm -f polymc_*.png -rm -rf polymc.iconset +rm -f prismlauncher_*.png +rm -rf prismlauncher.iconset for dir in ../launcher/resources/*/scalable do - cp -v org.polymc.PolyMC.svg $dir/launcher.svg + cp -v org.prismlauncher.PrismLauncher.svg $dir/launcher.svg done diff --git a/program_info/org.polymc.PolyMC.Source.svg b/program_info/org.prismlauncher.PrismLauncher.Source.svg similarity index 100% rename from program_info/org.polymc.PolyMC.Source.svg rename to program_info/org.prismlauncher.PrismLauncher.Source.svg diff --git a/program_info/org.polymc.PolyMC.bigsur.svg b/program_info/org.prismlauncher.PrismLauncher.bigsur.svg similarity index 100% rename from program_info/org.polymc.PolyMC.bigsur.svg rename to program_info/org.prismlauncher.PrismLauncher.bigsur.svg diff --git a/program_info/org.polymc.PolyMC.desktop.in b/program_info/org.prismlauncher.PrismLauncher.desktop.in similarity index 76% rename from program_info/org.polymc.PolyMC.desktop.in rename to program_info/org.prismlauncher.PrismLauncher.desktop.in index e6d88909..63a6b586 100644 --- a/program_info/org.polymc.PolyMC.desktop.in +++ b/program_info/org.prismlauncher.PrismLauncher.desktop.in @@ -1,12 +1,12 @@ [Desktop Entry] Version=1.0 -Name=PolyMC +Name=Prism Launcher Comment=A custom launcher for Minecraft that allows you to easily manage multiple installations of Minecraft at once. Type=Application Terminal=false Exec=@Launcher_APP_BINARY_NAME@ StartupNotify=true -Icon=org.polymc.PolyMC +Icon=org.prismlauncher.PrismLauncher Categories=Game; Keywords=game;minecraft;launcher;mc; -StartupWMClass=PolyMC +StartupWMClass=PrismLauncher diff --git a/program_info/org.polymc.PolyMC.metainfo.xml.in b/program_info/org.prismlauncher.PrismLauncher.metainfo.xml.in similarity index 55% rename from program_info/org.polymc.PolyMC.metainfo.xml.in rename to program_info/org.prismlauncher.PrismLauncher.metainfo.xml.in index ef5a7d93..2e10f7be 100644 --- a/program_info/org.polymc.PolyMC.metainfo.xml.in +++ b/program_info/org.prismlauncher.PrismLauncher.metainfo.xml.in @@ -1,19 +1,19 @@ - org.polymc.PolyMC + org.prismlauncher.PrismLauncher - org.polymc.PolyMC + org.prismlauncher.PrismLauncher - org.polymc.PolyMC.desktop - PolyMC - PolyMC + org.prismlauncher.PrismLauncher.desktop + PrismLauncher + PrismLauncher A custom launcher for Minecraft that allows you to easily manage multiple installations of Minecraft at once CC0-1.0 GPL-3.0-only - https://polymc.org/ - https://polymc.org/wiki/ + https://prismlauncher.org/ + https://prismlauncher.org/wiki/ -

PolyMC is a custom launcher for Minecraft that focuses on predictability, long term stability and simplicity.

+

PrismLauncher is a custom launcher for Minecraft that focuses on predictability, long term stability and simplicity.

Features: