diff --git a/.clang-tidy b/.clang-tidy new file mode 100644 index 000000000..11ddc9cfc --- /dev/null +++ b/.clang-tidy @@ -0,0 +1,4 @@ +Checks: + - modernize-use-using + +SystemHeaders: false diff --git a/.github/workflows/backport.yml b/.github/workflows/backport.yml index c705ff7b0..e5443439d 100644 --- a/.github/workflows/backport.yml +++ b/.github/workflows/backport.yml @@ -24,7 +24,7 @@ jobs: with: ref: ${{ github.event.pull_request.head.sha }} - name: Create backport PRs - uses: korthout/backport-action@v1.4.0 + uses: korthout/backport-action@v2.1.1 with: # Config README: https://github.com/korthout/backport-action#backport-action pull_description: |- diff --git a/CMakeLists.txt b/CMakeLists.txt index be443fe31..faeb1c44e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -347,6 +347,11 @@ add_subdirectory(program_info) ####################################### Install layout ####################################### set(Launcher_ENABLE_UPDATER NO) +set(Launcher_BUILD_UPDATER NO) + +if (NOT APPLE AND (NOT Launcher_UPDATER_GITHUB_REPO STREQUAL "" AND NOT Launcher_BUILD_ARTIFACT STREQUAL "")) + set(Launcher_BUILD_UPDATER YES) +endif() if(NOT (UNIX AND APPLE)) # Install "portable.txt" if selected component is "portable" diff --git a/README.md b/README.md index 093bc94da..b32132d49 100644 --- a/README.md +++ b/README.md @@ -18,11 +18,18 @@ - All downloads and instructions for Prism Launcher can be found on our [Website](https://prismlauncher.org/download). -- Last build status can be found in the [GitHub Actions](https://github.com/PrismLauncher/PrismLauncher/actions). +- Last build status can be found in the [GitHub Actions](https://github.com/PrismLauncher/PrismLauncher/actions) tab (this also includes the pull requests status). ### Development Builds -There are development builds available [here](https://github.com/PrismLauncher/PrismLauncher/actions). These have debug information in the binaries, so their file sizes are relatively larger. +Please understand that these builds are not intended for most users. There may be bugs, and other instabilities. You have been warned. + +There are development builds available through: + +- [GitHub Actions](https://github.com/PrismLauncher/PrismLauncher/actions) (includes builds from pull requests opened by contribuitors) +- [nightly.link](https://nightly.link/PrismLauncher/PrismLauncher/workflows/trigger_builds/develop) (this will always point only to the latest version of develop) + +These have debug information in the binaries, so their file sizes are relatively larger. Prebuilt Development builds are provided for **Linux**, **Windows** and **macOS**. @@ -30,7 +37,7 @@ For **Arch**, **Debian**, **Fedora**, **OpenSUSE (Tumbleweed)** and **Gentoo**, [![prismlauncher-git](https://img.shields.io/badge/aur-prismlauncher--git-1793D1?label=AUR&logo=archlinux&logoColor=white)](https://aur.archlinux.org/packages/prismlauncher-git) [![prismlauncher-git](https://img.shields.io/badge/aur-prismlauncher--qt5--git-1793D1?label=AUR&logo=archlinux&logoColor=white)](https://aur.archlinux.org/packages/prismlauncher-qt5-git) [![prismlauncher-git](https://img.shields.io/badge/mpr-prismlauncher--git-A80030?label=MPR&logo=debian&logoColor=white)](https://mpr.makedeb.org/packages/prismlauncher-git)
[![prismlauncher-nightly](https://img.shields.io/badge/copr-prismlauncher--nightly-51A2DA?label=COPR&logo=fedora&logoColor=white)](https://copr.fedorainfracloud.org/coprs/g3tchoo/prismlauncher/) [![prismlauncher-nightly](https://img.shields.io/badge/OBS-prismlauncher--nightly-3AB6A9?logo=opensuse&logoColor=white)](https://build.opensuse.org/project/show/home:getchoo) [![prismlauncher-9999](https://img.shields.io/badge/gentoo-prismlauncher--9999-4D4270?label=Gentoo&logo=gentoo&logoColor=white)](https://packages.gentoo.org/packages/games-action/prismlauncher) -These packages are also availiable to all the distributions based on the ones mentioned above. +These packages are also available to all the distributions based on the ones mentioned above. ## Community & Support diff --git a/flake.lock b/flake.lock index ad18ff615..70c8cba4f 100644 --- a/flake.lock +++ b/flake.lock @@ -21,11 +21,11 @@ "nixpkgs-lib": "nixpkgs-lib" }, "locked": { - "lastModified": 1696343447, - "narHash": "sha256-B2xAZKLkkeRFG5XcHHSXXcP7To9Xzr59KXeZiRf4vdQ=", + "lastModified": 1698882062, + "narHash": "sha256-HkhafUayIqxXyHH1X8d9RDl1M2CkFgZLjKD3MzabiEo=", "owner": "hercules-ci", "repo": "flake-parts", - "rev": "c9afaba3dfa4085dbd2ccb38dfade5141e33d9d4", + "rev": "8c9fa2545007b49a5db5f650ae91f227672c3877", "type": "github" }, "original": { @@ -76,11 +76,11 @@ "libnbtplusplus": { "flake": false, "locked": { - "lastModified": 1690036783, - "narHash": "sha256-A5kTgICnx+Qdq3Fir/bKTfdTt/T1NQP2SC+nhN1ENug=", + "lastModified": 1699286814, + "narHash": "sha256-yy0q+bky80LtK1GWzz7qpM+aAGrOqLuewbid8WT1ilk=", "owner": "PrismLauncher", "repo": "libnbtplusplus", - "rev": "a5e8fd52b8bf4ab5d5bcc042b2a247867589985f", + "rev": "23b955121b8217c1c348a9ed2483167a6f3ff4ad", "type": "github" }, "original": { @@ -106,11 +106,11 @@ }, "nixpkgs": { "locked": { - "lastModified": 1697009197, - "narHash": "sha256-viVRhBTFT8fPJTb1N3brQIpFZnttmwo3JVKNuWRVc3s=", + "lastModified": 1699343069, + "narHash": "sha256-s7BBhyLA6MI6FuJgs4F/SgpntHBzz40/qV0xLPW6A1Q=", "owner": "nixos", "repo": "nixpkgs", - "rev": "01441e14af5e29c9d27ace398e6dd0b293e25a54", + "rev": "ec750fd01963ab6b20ee1f0cb488754e8036d89d", "type": "github" }, "original": { @@ -123,11 +123,11 @@ "nixpkgs-lib": { "locked": { "dir": "lib", - "lastModified": 1696019113, - "narHash": "sha256-X3+DKYWJm93DRSdC5M6K5hLqzSya9BjibtBsuARoPco=", + "lastModified": 1698611440, + "narHash": "sha256-jPjHjrerhYDy3q9+s5EAsuhyhuknNfowY6yt6pjn9pc=", "owner": "NixOS", "repo": "nixpkgs", - "rev": "f5892ddac112a1e9b3612c39af1b72987ee5783a", + "rev": "0cbe9f69c234a7700596e943bfae7ef27a31b735", "type": "github" }, "original": { @@ -153,11 +153,11 @@ ] }, "locked": { - "lastModified": 1696846637, - "narHash": "sha256-0hv4kbXxci2+pxhuXlVgftj/Jq79VSmtAyvfabCCtYk=", + "lastModified": 1699271226, + "narHash": "sha256-8Jt1KW3xTjolD6c6OjJm9USx/jmL+VVmbooADCkdDfU=", "owner": "cachix", "repo": "pre-commit-hooks.nix", - "rev": "42e1b6095ef80a51f79595d9951eb38e91c4e6ca", + "rev": "ea758da1a6dcde6dc36db348ed690d09b9864128", "type": "github" }, "original": { diff --git a/launcher/Application.cpp b/launcher/Application.cpp index 3b553f4b1..be252f1c5 100644 --- a/launcher/Application.cpp +++ b/launcher/Application.cpp @@ -58,6 +58,7 @@ #include "ui/pages/global/APIPage.h" #include "ui/pages/global/AccountListPage.h" #include "ui/pages/global/CustomCommandsPage.h" +#include "ui/pages/global/EnvironmentVariablesPage.h" #include "ui/pages/global/ExternalToolsPage.h" #include "ui/pages/global/JavaPage.h" #include "ui/pages/global/LanguagePage.h" @@ -643,6 +644,7 @@ Application::Application(int& argc, char** argv) : QApplication(argc, argv) // Minecraft mods m_settings->registerSetting("ModMetadataDisabled", false); + m_settings->registerSetting("ModDependenciesDisabled", false); // Minecraft offline player name m_settings->registerSetting("LastOfflinePlayerName", ""); @@ -719,6 +721,8 @@ Application::Application(int& argc, char** argv) : QApplication(argc, argv) m_settings->registerSetting("CloseAfterLaunch", false); m_settings->registerSetting("QuitAfterGameStop", false); + m_settings->registerSetting("Env", QVariant(QMap())); + // Custom Microsoft Authentication Client ID m_settings->registerSetting("MSAClientIDOverride", ""); @@ -744,6 +748,7 @@ Application::Application(int& argc, char** argv) : QApplication(argc, argv) m_globalSettingsProvider->addPage(); m_globalSettingsProvider->addPage(); m_globalSettingsProvider->addPage(); + m_globalSettingsProvider->addPage(); m_globalSettingsProvider->addPage(); m_globalSettingsProvider->addPage(); m_globalSettingsProvider->addPage(); diff --git a/launcher/BaseInstance.cpp b/launcher/BaseInstance.cpp index 725036395..33dc3f741 100644 --- a/launcher/BaseInstance.cpp +++ b/launcher/BaseInstance.cpp @@ -388,7 +388,7 @@ QString BaseInstance::name() const QString BaseInstance::windowTitle() const { - return BuildConfig.LAUNCHER_DISPLAYNAME + ": " + name().replace(QRegularExpression("\\s+"), " "); + return BuildConfig.LAUNCHER_DISPLAYNAME + ": " + name(); } // FIXME: why is this here? move it to MinecraftInstance!!! diff --git a/launcher/BaseInstance.h b/launcher/BaseInstance.h index 47fff5957..f4ed9113c 100644 --- a/launcher/BaseInstance.h +++ b/launcher/BaseInstance.h @@ -64,7 +64,7 @@ class LaunchTask; class BaseInstance; // pointer for lazy people -typedef std::shared_ptr InstancePtr; +using InstancePtr = std::shared_ptr; /*! * \brief Base class for instances. diff --git a/launcher/BaseVersionList.h b/launcher/BaseVersionList.h index fe1550c21..231887c4e 100644 --- a/launcher/BaseVersionList.h +++ b/launcher/BaseVersionList.h @@ -51,7 +51,7 @@ class BaseVersionList : public QAbstractListModel { ArchitectureRole, SortRole }; - typedef QList RoleList; + using RoleList = QList; explicit BaseVersionList(QObject* parent = 0); diff --git a/launcher/CMakeLists.txt b/launcher/CMakeLists.txt index a6c3a3e08..db84b4333 100644 --- a/launcher/CMakeLists.txt +++ b/launcher/CMakeLists.txt @@ -139,6 +139,7 @@ set(NET_SOURCES net/HeaderProxy.h net/RawHeaderProxy.h net/ApiHeaderProxy.h + net/StaticHeaderProxy.h net/ApiDownload.h net/ApiDownload.cpp net/ApiUpload.cpp @@ -888,6 +889,8 @@ SET(LAUNCHER_SOURCES ui/pages/global/AccountListPage.h ui/pages/global/CustomCommandsPage.cpp ui/pages/global/CustomCommandsPage.h + ui/pages/global/EnvironmentVariablesPage.cpp + ui/pages/global/EnvironmentVariablesPage.h ui/pages/global/ExternalToolsPage.cpp ui/pages/global/ExternalToolsPage.h ui/pages/global/JavaPage.cpp @@ -1041,6 +1044,8 @@ SET(LAUNCHER_SOURCES ui/widgets/Common.h ui/widgets/CustomCommands.cpp ui/widgets/CustomCommands.h + ui/widgets/EnvironmentVariables.cpp + ui/widgets/EnvironmentVariables.h ui/widgets/DropLabel.cpp ui/widgets/DropLabel.h ui/widgets/FocusLineEdit.cpp @@ -1151,6 +1156,7 @@ qt_wrap_ui(LAUNCHER_UI ui/pages/modplatform/technic/TechnicPage.ui ui/widgets/InstanceCardWidget.ui ui/widgets/CustomCommands.ui + ui/widgets/EnvironmentVariables.ui ui/widgets/InfoFrame.ui ui/widgets/ModFilterWidget.ui ui/widgets/SubTaskProgressBar.ui @@ -1308,7 +1314,7 @@ install(TARGETS ${Launcher_Name} FRAMEWORK DESTINATION ${FRAMEWORK_DEST_DIR} COMPONENT Runtime ) -if(NOT APPLE OR (DEFINED Launcher_BUILD_UPDATER AND Launcher_BUILD_UPDATER)) +if(Launcher_BUILD_UPDATER) # Updater add_library(prism_updater_logic STATIC ${PRISMUPDATER_SOURCES} ${TASKS_SOURCES} ${PRISMUPDATER_UI}) target_include_directories(prism_updater_logic PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) diff --git a/launcher/FileSystem.cpp b/launcher/FileSystem.cpp index 652ba2995..a30d0ae0b 100644 --- a/launcher/FileSystem.cpp +++ b/launcher/FileSystem.cpp @@ -123,26 +123,35 @@ namespace fs = ghc::filesystem; #if defined(__MINGW32__) -typedef struct _DUPLICATE_EXTENTS_DATA { +struct _DUPLICATE_EXTENTS_DATA { HANDLE FileHandle; LARGE_INTEGER SourceFileOffset; LARGE_INTEGER TargetFileOffset; LARGE_INTEGER ByteCount; -} DUPLICATE_EXTENTS_DATA, *PDUPLICATE_EXTENTS_DATA; +}; -typedef struct _FSCTL_GET_INTEGRITY_INFORMATION_BUFFER { +using DUPLICATE_EXTENTS_DATA = _DUPLICATE_EXTENTS_DATA; +using PDUPLICATE_EXTENTS_DATA = _DUPLICATE_EXTENTS_DATA*; + +struct _FSCTL_GET_INTEGRITY_INFORMATION_BUFFER { WORD ChecksumAlgorithm; // Checksum algorithm. e.g. CHECKSUM_TYPE_UNCHANGED, CHECKSUM_TYPE_NONE, CHECKSUM_TYPE_CRC32 WORD Reserved; // Must be 0 DWORD Flags; // FSCTL_INTEGRITY_FLAG_xxx DWORD ChecksumChunkSizeInBytes; DWORD ClusterSizeInBytes; -} FSCTL_GET_INTEGRITY_INFORMATION_BUFFER, *PFSCTL_GET_INTEGRITY_INFORMATION_BUFFER; +}; -typedef struct _FSCTL_SET_INTEGRITY_INFORMATION_BUFFER { +using FSCTL_GET_INTEGRITY_INFORMATION_BUFFER = _FSCTL_GET_INTEGRITY_INFORMATION_BUFFER; +using PFSCTL_GET_INTEGRITY_INFORMATION_BUFFER = _FSCTL_GET_INTEGRITY_INFORMATION_BUFFER*; + +struct _FSCTL_SET_INTEGRITY_INFORMATION_BUFFER { WORD ChecksumAlgorithm; // Checksum algorithm. e.g. CHECKSUM_TYPE_UNCHANGED, CHECKSUM_TYPE_NONE, CHECKSUM_TYPE_CRC32 WORD Reserved; // Must be 0 DWORD Flags; // FSCTL_INTEGRITY_FLAG_xxx -} FSCTL_SET_INTEGRITY_INFORMATION_BUFFER, *PFSCTL_SET_INTEGRITY_INFORMATION_BUFFER; +}; + +using FSCTL_SET_INTEGRITY_INFORMATION_BUFFER = _FSCTL_SET_INTEGRITY_INFORMATION_BUFFER; +using PFSCTL_SET_INTEGRITY_INFORMATION_BUFFER = _FSCTL_SET_INTEGRITY_INFORMATION_BUFFER*; #endif @@ -934,6 +943,8 @@ bool createShortcut(QString destination, QString target, QStringList args, QStri << "\n"; stream << "Type=Application" << "\n"; + stream << "Categories=Game;ActionGame;AdventureGame;Simulation" + << "\n"; stream << "Exec=\"" << target.toLocal8Bit() << "\"" << argstring.toLocal8Bit() << "\n"; stream << "Name=" << name.toLocal8Bit() << "\n"; if (!icon.isEmpty()) { diff --git a/launcher/InstanceList.cpp b/launcher/InstanceList.cpp index 756ff93dd..2b8f34293 100644 --- a/launcher/InstanceList.cpp +++ b/launcher/InstanceList.cpp @@ -290,7 +290,7 @@ void InstanceList::deleteGroup(const GroupId& name) qDebug() << "Remove" << instID << "from group" << name; removed = true; auto idx = getInstIndex(instance.get()); - if (idx > 0) + if (idx >= 0) emit dataChanged(index(idx), index(idx), { GroupRole }); } } @@ -315,7 +315,7 @@ void InstanceList::renameGroup(const QString& src, const QString& dst) qDebug() << "Set" << instID << "group to" << dst; modified = true; auto idx = getInstIndex(instance.get()); - if (idx > 0) + if (idx >= 0) emit dataChanged(index(idx), index(idx), { GroupRole }); } } @@ -947,9 +947,12 @@ QString InstanceList::getStagedInstancePath() bool InstanceList::commitStagedInstance(const QString& path, InstanceName const& instanceName, - const QString& groupName, + QString groupName, InstanceTask const& commiting) { + if (groupName.isEmpty() && !groupName.isNull()) + groupName = QString(); + QDir dir; QString instID; InstancePtr inst; diff --git a/launcher/InstanceList.h b/launcher/InstanceList.h index 6b0bcd810..5ddddee95 100644 --- a/launcher/InstanceList.h +++ b/launcher/InstanceList.h @@ -130,7 +130,7 @@ class InstanceList : public QAbstractListModel { * should_override is used when another similar instance already exists, and we want to override it * - for instance, when updating it. */ - bool commitStagedInstance(const QString& keyPath, const InstanceName& instanceName, const QString& groupName, const InstanceTask&); + bool commitStagedInstance(const QString& keyPath, const InstanceName& instanceName, QString groupName, const InstanceTask&); /** * Destroy a previously created staging area given by @keyPath - used when creation fails. diff --git a/launcher/LaunchController.cpp b/launcher/LaunchController.cpp index 21a146062..f59cdeda8 100644 --- a/launcher/LaunchController.cpp +++ b/launcher/LaunchController.cpp @@ -89,7 +89,7 @@ void LaunchController::decideAccount() // Tell the user they need to log in at least one account in order to play. auto reply = CustomMessageBox::selectable(m_parentWidget, tr("No Accounts"), tr("In order to play Minecraft, you must have at least one Microsoft " - "account which owns Minecraft logged in." + "account which owns Minecraft logged in. " "Would you like to open the account manager to add an account now?"), QMessageBox::Information, QMessageBox::Yes | QMessageBox::No) ->exec(); @@ -106,7 +106,7 @@ void LaunchController::decideAccount() // Select the account to use. If the instance has a specific account set, that will be used. Otherwise, the default account will be used auto instanceAccountId = m_instance->settings()->get("InstanceAccountId").toString(); auto instanceAccountIndex = accounts->findAccountByProfileId(instanceAccountId); - if (instanceAccountIndex == -1) { + if (instanceAccountIndex == -1 || instanceAccountId.isEmpty()) { m_accountToUse = accounts->defaultAccount(); } else { m_accountToUse = accounts->at(instanceAccountIndex); diff --git a/launcher/MMCZip.h b/launcher/MMCZip.h index 1c6ebe34a..45b1df0b3 100644 --- a/launcher/MMCZip.h +++ b/launcher/MMCZip.h @@ -172,7 +172,7 @@ class ExportToZipTask : public Task { void setExcludeFiles(QStringList excludeFiles) { m_exclude_files = excludeFiles; } void addExtraFile(QString fileName, QByteArray data) { m_extra_files.insert(fileName, data); } - typedef std::optional ZipResult; + using ZipResult = std::optional; protected: virtual void executeTask() override; diff --git a/launcher/MTPixmapCache.h b/launcher/MTPixmapCache.h index 1a3e52160..b6bd13045 100644 --- a/launcher/MTPixmapCache.h +++ b/launcher/MTPixmapCache.h @@ -5,6 +5,7 @@ #include #include #include +#include #define GET_TYPE() \ Qt::ConnectionType type; \ @@ -100,10 +101,14 @@ class PixmapCache final : public QObject { */ bool _markCacheMissByEviciton() { + static constexpr uint maxInt = static_cast(std::numeric_limits::max()); + static constexpr uint step = 10240; + static constexpr int oneSecond = 1000; + auto now = QTime::currentTime(); if (!m_last_cache_miss_by_eviciton.isNull()) { auto diff = m_last_cache_miss_by_eviciton.msecsTo(now); - if (diff < 1000) { // less than a second ago + if (diff < oneSecond) { // less than a second ago ++m_consecutive_fast_evicitons; } else { m_consecutive_fast_evicitons = 0; @@ -111,11 +116,17 @@ class PixmapCache final : public QObject { } m_last_cache_miss_by_eviciton = now; if (m_consecutive_fast_evicitons >= m_consecutive_fast_evicitons_threshold) { - // double the cache size - auto newSize = _cacheLimit() * 2; - qDebug() << m_consecutive_fast_evicitons << "pixmap cache misses by eviction happened too fast, doubling cache size to" - << newSize; - _setCacheLimit(newSize); + // increase the cache size + uint newSize = _cacheLimit() + step; + if (newSize >= maxInt) { // increase it until you overflow :D + newSize = maxInt; + qDebug() << m_consecutive_fast_evicitons + << tr("pixmap cache misses by eviction happened too fast, doing nothing as the cache size reached it's limit"); + } else { + qDebug() << m_consecutive_fast_evicitons + << tr("pixmap cache misses by eviction happened too fast, increasing cache size to") << static_cast(newSize); + } + _setCacheLimit(static_cast(newSize)); m_consecutive_fast_evicitons = 0; return true; } diff --git a/launcher/VersionProxyModel.h b/launcher/VersionProxyModel.h index c7d5fd94e..57c711d58 100644 --- a/launcher/VersionProxyModel.h +++ b/launcher/VersionProxyModel.h @@ -10,7 +10,7 @@ class VersionProxyModel : public QAbstractProxyModel { Q_OBJECT public: enum Column { Name, ParentVersion, Branch, Type, Architecture, Path, Time }; - typedef QHash> FilterMap; + using FilterMap = QHash>; public: VersionProxyModel(QObject* parent = 0); diff --git a/launcher/java/JavaChecker.h b/launcher/java/JavaChecker.h index 743f49417..7111f8522 100644 --- a/launcher/java/JavaChecker.h +++ b/launcher/java/JavaChecker.h @@ -22,8 +22,8 @@ struct JavaCheckResult { enum class Validity { Errored, ReturnedInvalidData, Valid } validity = Validity::Errored; }; -typedef shared_qobject_ptr QProcessPtr; -typedef shared_qobject_ptr JavaCheckerPtr; +using QProcessPtr = shared_qobject_ptr; +using JavaCheckerPtr = shared_qobject_ptr; class JavaChecker : public QObject { Q_OBJECT public: diff --git a/launcher/java/JavaCheckerJob.h b/launcher/java/JavaCheckerJob.h index 009687917..ddf827968 100644 --- a/launcher/java/JavaCheckerJob.h +++ b/launcher/java/JavaCheckerJob.h @@ -20,7 +20,7 @@ #include "tasks/Task.h" class JavaCheckerJob; -typedef shared_qobject_ptr JavaCheckerJobPtr; +using JavaCheckerJobPtr = shared_qobject_ptr; // FIXME: this just seems horribly redundant class JavaCheckerJob : public Task { diff --git a/launcher/java/JavaInstall.h b/launcher/java/JavaInstall.h index 49e9ed06e..8c2743a00 100644 --- a/launcher/java/JavaInstall.h +++ b/launcher/java/JavaInstall.h @@ -42,4 +42,4 @@ struct JavaInstall : public BaseVersion { bool recommended = false; }; -typedef std::shared_ptr JavaInstallPtr; +using JavaInstallPtr = std::shared_ptr; diff --git a/launcher/java/JavaUtils.cpp b/launcher/java/JavaUtils.cpp index cca1ed6d4..074bf54df 100644 --- a/launcher/java/JavaUtils.cpp +++ b/launcher/java/JavaUtils.cpp @@ -34,6 +34,7 @@ */ #include +#include #include #include @@ -335,6 +336,7 @@ QList JavaUtils::FindJavaPaths() } } + candidates.append(getMinecraftJavaBundle()); candidates = addJavasFromEnv(candidates); candidates.removeDuplicates(); return candidates; @@ -360,6 +362,7 @@ QList JavaUtils::FindJavaPaths() javas.append(systemLibraryJVMDir.absolutePath() + "/" + java + "/Contents/Home/bin/java"); javas.append(systemLibraryJVMDir.absolutePath() + "/" + java + "/Contents/Commands/java"); } + javas.append(getMinecraftJavaBundle()); javas = addJavasFromEnv(javas); javas.removeDuplicates(); return javas; @@ -411,6 +414,7 @@ QList JavaUtils::FindJavaPaths() // javas downloaded by sdkman scanJavaDirs(FS::PathCombine(home, ".sdkman/candidates/java")); + javas.append(getMinecraftJavaBundle()); javas = addJavasFromEnv(javas); javas.removeDuplicates(); return javas; @@ -423,6 +427,7 @@ QList JavaUtils::FindJavaPaths() QList javas; javas.append(this->GetDefaultJava()->path); + javas.append(getMinecraftJavaBundle()); return addJavasFromEnv(javas); } #endif @@ -431,3 +436,50 @@ QString JavaUtils::getJavaCheckPath() { return APPLICATION->getJarPath("JavaCheck.jar"); } + +QStringList getMinecraftJavaBundle() +{ + QString partialPath; + QString executable = "java"; + QStringList processpaths; +#if defined(Q_OS_OSX) + partialPath = FS::PathCombine(QDir::homePath(), "Library/Application Support"); +#elif defined(Q_OS_WIN32) + partialPath = QProcessEnvironment::systemEnvironment().value("LOCALAPPDATA", ""); + executable += "w.exe"; + + // add the microsoft store version of the launcher to the search. the current path is: + // C:\Users\USERNAME\AppData\Local\Packages\Microsoft.4297127D64EC6_8wekyb3d8bbwe\LocalCache\Local\runtime + auto minecraftMSStorePath = + FS::PathCombine(QFileInfo(partialPath).absolutePath(), "Local", "Packages", "Microsoft.4297127D64EC6_8wekyb3d8bbwe"); + minecraftMSStorePath = FS::PathCombine(minecraftMSStorePath, "LocalCache", "Local", "runtime"); + processpaths << minecraftMSStorePath; +#else + partialPath = QDir::homePath(); +#endif + auto minecraftDataPath = FS::PathCombine(partialPath, ".minecraft", "runtime"); + processpaths << minecraftDataPath; + + QStringList javas; + while (!processpaths.isEmpty()) { + auto dirPath = processpaths.takeFirst(); + QDir dir(dirPath); + if (!dir.exists()) + continue; + auto entries = dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot); + auto binFound = false; + for (auto& entry : entries) { + if (entry.baseName() == "bin") { + javas.append(FS::PathCombine(entry.canonicalFilePath(), executable)); + binFound = true; + break; + } + } + if (!binFound) { + for (auto& entry : entries) { + processpaths << entry.canonicalFilePath(); + } + } + } + return javas; +} diff --git a/launcher/java/JavaUtils.h b/launcher/java/JavaUtils.h index 616179706..2fb03af7a 100644 --- a/launcher/java/JavaUtils.h +++ b/launcher/java/JavaUtils.h @@ -26,6 +26,7 @@ QString stripVariableEntries(QString name, QString target, QString remove); QProcessEnvironment CleanEnviroment(); +QStringList getMinecraftJavaBundle(); class JavaUtils : public QObject { Q_OBJECT diff --git a/launcher/minecraft/Agent.h b/launcher/minecraft/Agent.h index 8958521e5..bc385a74e 100644 --- a/launcher/minecraft/Agent.h +++ b/launcher/minecraft/Agent.h @@ -6,7 +6,7 @@ class Agent; -typedef std::shared_ptr AgentPtr; +using AgentPtr = std::shared_ptr; class Agent { public: diff --git a/launcher/minecraft/AssetsUtils.cpp b/launcher/minecraft/AssetsUtils.cpp index 4ef007075..48e150d16 100644 --- a/launcher/minecraft/AssetsUtils.cpp +++ b/launcher/minecraft/AssetsUtils.cpp @@ -48,6 +48,7 @@ #include "FileSystem.h" #include "net/ApiDownload.h" #include "net/ChecksumValidator.h" +#include "net/Download.h" #include "Application.h" diff --git a/launcher/minecraft/Component.h b/launcher/minecraft/Component.h index 3474a22e0..fdb61c45e 100644 --- a/launcher/minecraft/Component.h +++ b/launcher/minecraft/Component.h @@ -105,4 +105,4 @@ class Component : public QObject, public ProblemProvider { bool m_loaded = false; }; -typedef shared_qobject_ptr ComponentPtr; +using ComponentPtr = shared_qobject_ptr; diff --git a/launcher/minecraft/Library.h b/launcher/minecraft/Library.h index f8816a97b..adb89c4c6 100644 --- a/launcher/minecraft/Library.h +++ b/launcher/minecraft/Library.h @@ -52,7 +52,7 @@ class Library; class MinecraftInstance; -typedef std::shared_ptr LibraryPtr; +using LibraryPtr = std::shared_ptr; class Library { friend class OneSixVersionFormat; diff --git a/launcher/minecraft/MinecraftInstance.cpp b/launcher/minecraft/MinecraftInstance.cpp index 55fd864bb..7cb4100ea 100644 --- a/launcher/minecraft/MinecraftInstance.cpp +++ b/launcher/minecraft/MinecraftInstance.cpp @@ -188,6 +188,9 @@ void MinecraftInstance::loadSpecificSettings() auto legacySettings = m_settings->registerSetting("OverrideLegacySettings", false); m_settings->registerOverride(global_settings->getSetting("OnlineFixes"), legacySettings); + auto envSetting = m_settings->registerSetting("OverrideEnv", false); + m_settings->registerOverride(global_settings->getSetting("Env"), envSetting); + m_settings->set("InstanceType", "OneSix"); } @@ -548,6 +551,7 @@ QMap MinecraftInstance::getVariables() out.insert("INST_MC_DIR", QDir::toNativeSeparators(QDir(gameRoot()).absolutePath())); out.insert("INST_JAVA", settings()->get("JavaPath").toString()); out.insert("INST_JAVA_ARGS", javaArguments().join(' ')); + out.insert("NO_COLOR", "1"); return out; } @@ -571,15 +575,20 @@ QProcessEnvironment MinecraftInstance::createLaunchEnvironment() #ifdef Q_OS_LINUX if (settings()->get("EnableMangoHud").toBool() && APPLICATION->capabilities() & Application::SupportsMangoHud) { - auto preloadList = env.value("LD_PRELOAD").split(QLatin1String(":")); - auto libPaths = env.value("LD_LIBRARY_PATH").split(QLatin1String(":")); + QStringList preloadList; + if (auto value = env.value("LD_PRELOAD"); !value.isEmpty()) + preloadList = value.split(QLatin1String(":")); + QStringList libPaths; + if (auto value = env.value("LD_LIBRARY_PATH"); !value.isEmpty()) + libPaths = value.split(QLatin1String(":")); auto mangoHudLibString = MangoHud::getLibraryString(); if (!mangoHudLibString.isEmpty()) { QFileInfo mangoHudLib(mangoHudLibString); // dlsym variant is only needed for OpenGL and not included in the vulkan layer - preloadList << "libMangoHud_dlsym.so" << mangoHudLib.fileName(); + preloadList << "libMangoHud_dlsym.so" + << "libMangoHud_opengl.so" << mangoHudLib.fileName(); libPaths << mangoHudLib.absolutePath(); } @@ -598,6 +607,23 @@ QProcessEnvironment MinecraftInstance::createLaunchEnvironment() } #endif + // custom env + + auto insertEnv = [&env](QMap envMap) { + if (envMap.isEmpty()) + return; + + for (auto iter = envMap.begin(); iter != envMap.end(); iter++) + env.insert(iter.key(), iter.value().toString()); + }; + + bool overrideEnv = settings()->get("OverrideEnv").toBool(); + + if (!overrideEnv) + insertEnv(APPLICATION->settings()->get("Env").toMap()); + else + insertEnv(settings()->get("Env").toMap()); + return env; } @@ -710,7 +736,7 @@ QString MinecraftInstance::createLaunchScript(AuthSessionPtr session, MinecraftS { QString windowParams; if (settings()->get("LaunchMaximized").toBool()) - windowParams = "max"; + windowParams = "maximized"; else windowParams = QString("%1x%2").arg(settings()->get("MinecraftWinWidth").toInt()).arg(settings()->get("MinecraftWinHeight").toInt()); @@ -718,6 +744,19 @@ QString MinecraftInstance::createLaunchScript(AuthSessionPtr session, MinecraftS launchScript += "windowParams " + windowParams + "\n"; } + // launcher info + { + launchScript += "launcherBrand " + BuildConfig.LAUNCHER_NAME + "\n"; + launchScript += "launcherVersion " + BuildConfig.printableVersionString() + "\n"; + } + + // instance info + { + launchScript += "instanceName " + name() + "\n"; + launchScript += "instanceIconKey " + name() + "\n"; + launchScript += "instanceIconPath icon.png\n"; // we already save a copy here + } + // legacy auth if (session) { launchScript += "userName " + session->player_name + "\n"; diff --git a/launcher/minecraft/MinecraftInstance.h b/launcher/minecraft/MinecraftInstance.h index a816a3e60..b1f305201 100644 --- a/launcher/minecraft/MinecraftInstance.h +++ b/launcher/minecraft/MinecraftInstance.h @@ -174,4 +174,4 @@ class MinecraftInstance : public BaseInstance { mutable std::shared_ptr m_game_options; }; -typedef std::shared_ptr MinecraftInstancePtr; +using MinecraftInstancePtr = std::shared_ptr; diff --git a/launcher/minecraft/MojangDownloadInfo.h b/launcher/minecraft/MojangDownloadInfo.h index 855dbe005..eb64f95b7 100644 --- a/launcher/minecraft/MojangDownloadInfo.h +++ b/launcher/minecraft/MojangDownloadInfo.h @@ -5,7 +5,7 @@ struct MojangDownloadInfo { // types - typedef std::shared_ptr Ptr; + using Ptr = std::shared_ptr; // data /// Local filesystem path. WARNING: not used, only here so we can pass through mojang files unmolested! @@ -23,7 +23,7 @@ struct MojangLibraryDownloadInfo { MojangLibraryDownloadInfo() {} // types - typedef std::shared_ptr Ptr; + using Ptr = std::shared_ptr; // methods MojangDownloadInfo* getDownloadInfo(QString classifier) @@ -42,7 +42,7 @@ struct MojangLibraryDownloadInfo { struct MojangAssetIndexInfo : public MojangDownloadInfo { // types - typedef std::shared_ptr Ptr; + using Ptr = std::shared_ptr; // methods MojangAssetIndexInfo() {} diff --git a/launcher/minecraft/ProfileUtils.h b/launcher/minecraft/ProfileUtils.h index 98a7ff739..edabe0bf0 100644 --- a/launcher/minecraft/ProfileUtils.h +++ b/launcher/minecraft/ProfileUtils.h @@ -38,7 +38,7 @@ #include "VersionFile.h" namespace ProfileUtils { -typedef QStringList PatchOrder; +using PatchOrder = QStringList; /// Read and parse a OneSix format order file bool readOverrideOrders(QString path, PatchOrder& order); diff --git a/launcher/minecraft/auth/AuthSession.h b/launcher/minecraft/auth/AuthSession.h index 074b2d6e3..cec238033 100644 --- a/launcher/minecraft/auth/AuthSession.h +++ b/launcher/minecraft/auth/AuthSession.h @@ -43,4 +43,4 @@ struct AuthSession { bool demo = false; }; -typedef std::shared_ptr AuthSessionPtr; +using AuthSessionPtr = std::shared_ptr; diff --git a/launcher/minecraft/auth/MinecraftAccount.h b/launcher/minecraft/auth/MinecraftAccount.h index 910f4a28a..c4e9756a9 100644 --- a/launcher/minecraft/auth/MinecraftAccount.h +++ b/launcher/minecraft/auth/MinecraftAccount.h @@ -54,7 +54,7 @@ class Task; class AccountTask; class MinecraftAccount; -typedef shared_qobject_ptr MinecraftAccountPtr; +using MinecraftAccountPtr = shared_qobject_ptr; Q_DECLARE_METATYPE(MinecraftAccountPtr) /** diff --git a/launcher/minecraft/launch/MinecraftServerTarget.h b/launcher/minecraft/launch/MinecraftServerTarget.h index af8d6550b..2edd8a30d 100644 --- a/launcher/minecraft/launch/MinecraftServerTarget.h +++ b/launcher/minecraft/launch/MinecraftServerTarget.h @@ -26,4 +26,4 @@ struct MinecraftServerTarget { static MinecraftServerTarget parse(const QString& fullAddress); }; -typedef std::shared_ptr MinecraftServerTargetPtr; +using MinecraftServerTargetPtr = std::shared_ptr; diff --git a/launcher/minecraft/mod/ModFolderModel.cpp b/launcher/minecraft/mod/ModFolderModel.cpp index 8e31fa34b..98e21b9f0 100644 --- a/launcher/minecraft/mod/ModFolderModel.cpp +++ b/launcher/minecraft/mod/ModFolderModel.cpp @@ -38,9 +38,9 @@ #include "ModFolderModel.h" #include -#include #include #include +#include #include #include #include @@ -71,10 +71,9 @@ ModFolderModel::ModFolderModel(const QString& dir, BaseInstance* instance, bool tr("Side"), tr("Loaders"), tr("Miecraft Versions"), tr("Release Type") }); m_column_sort_keys = { SortType::ENABLED, SortType::NAME, SortType::NAME, SortType::VERSION, SortType::DATE, SortType::PROVIDER, SortType::SIDE, SortType::LOADERS, SortType::MC_VERSIONS, SortType::RELEASE_TYPE }; - m_column_resize_modes = { QHeaderView::ResizeToContents, QHeaderView::Interactive, QHeaderView::Stretch, - QHeaderView::ResizeToContents, QHeaderView::ResizeToContents, QHeaderView::ResizeToContents, - QHeaderView::ResizeToContents, QHeaderView::ResizeToContents, QHeaderView::ResizeToContents, - QHeaderView::ResizeToContents }; + m_column_resize_modes = { QHeaderView::Interactive, QHeaderView::Interactive, QHeaderView::Stretch, QHeaderView::Interactive, + QHeaderView::Interactive, QHeaderView::Interactive, QHeaderView::Interactive, QHeaderView::Interactive, + QHeaderView::Interactive, QHeaderView::Interactive }; m_columnsHideable = { false, true, false, true, true, true, true, true, true, true }; } @@ -159,6 +158,11 @@ QVariant ModFolderModel::data(const QModelIndex& index, int role) const } return {}; } + case Qt::SizeHintRole: + if (column == ImageColumn) { + return QSize(32, 32); + } + return {}; case Qt::CheckStateRole: switch (column) { case ActiveColumn: diff --git a/launcher/minecraft/mod/ResourceFolderModel.cpp b/launcher/minecraft/mod/ResourceFolderModel.cpp index 0503b660b..4a3ee9922 100644 --- a/launcher/minecraft/mod/ResourceFolderModel.cpp +++ b/launcher/minecraft/mod/ResourceFolderModel.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -516,36 +517,22 @@ void ResourceFolderModel::setupHeaderAction(QAction* act, int column) act->setText(columnNames().at(column)); } -void ResourceFolderModel::saveHiddenColumn(int column, bool hidden) +void ResourceFolderModel::saveColumns(QTreeView* tree) { - auto const setting_name = QString("UI/%1_Page/HiddenColumns").arg(id()); + auto const setting_name = QString("UI/%1_Page/Columns").arg(id()); auto setting = (m_instance->settings()->contains(setting_name)) ? m_instance->settings()->getSetting(setting_name) : m_instance->settings()->registerSetting(setting_name); - auto hiddenColumns = setting->get().toStringList(); - auto name = columnNames(false).at(column); - auto index = hiddenColumns.indexOf(name); - if (index >= 0 && !hidden) { - hiddenColumns.removeAt(index); - } else if (index < 0 && hidden) { - hiddenColumns.append(name); - } - setting->set(hiddenColumns); + setting->set(tree->header()->saveState()); } -void ResourceFolderModel::loadHiddenColumns(QTreeView* tree) +void ResourceFolderModel::loadColumns(QTreeView* tree) { - auto const setting_name = QString("UI/%1_Page/HiddenColumns").arg(id()); + auto const setting_name = QString("UI/%1_Page/Columns").arg(id()); auto setting = (m_instance->settings()->contains(setting_name)) ? m_instance->settings()->getSetting(setting_name) : m_instance->settings()->registerSetting(setting_name); - auto hiddenColumns = setting->get().toStringList(); - auto col_names = columnNames(false); - for (auto col_name : hiddenColumns) { - auto index = col_names.indexOf(col_name); - if (index >= 0) - tree->setColumnHidden(index, true); - } + tree->header()->restoreState(setting->get().toByteArray()); } QMenu* ResourceFolderModel::createHeaderContextMenu(QTreeView* tree) @@ -570,7 +557,7 @@ QMenu* ResourceFolderModel::createHeaderContextMenu(QTreeView* tree) if (m_column_resize_modes.at(c) == QHeaderView::ResizeToContents) tree->resizeColumnToContents(c); } - saveHiddenColumn(col, !toggled); + saveColumns(tree); }); menu->addAction(act); diff --git a/launcher/minecraft/mod/ResourceFolderModel.h b/launcher/minecraft/mod/ResourceFolderModel.h index 60b8879c0..b3f6d9a58 100644 --- a/launcher/minecraft/mod/ResourceFolderModel.h +++ b/launcher/minecraft/mod/ResourceFolderModel.h @@ -117,8 +117,8 @@ class ResourceFolderModel : public QAbstractListModel { [[nodiscard]] QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; void setupHeaderAction(QAction* act, int column); - void saveHiddenColumn(int column, bool hidden); - void loadHiddenColumns(QTreeView* tree); + void saveColumns(QTreeView* tree); + void loadColumns(QTreeView* tree); QMenu* createHeaderContextMenu(QTreeView* tree); /** This creates a proxy model to filter / sort the model for a UI. @@ -201,8 +201,7 @@ class ResourceFolderModel : public QAbstractListModel { QList m_column_sort_keys = { SortType::ENABLED, SortType::NAME, SortType::DATE }; QStringList m_column_names = { "Enable", "Name", "Last Modified" }; QStringList m_column_names_translated = { tr("Enable"), tr("Name"), tr("Last Modified") }; - QList m_column_resize_modes = { QHeaderView::ResizeToContents, QHeaderView::Stretch, - QHeaderView::ResizeToContents }; + QList m_column_resize_modes = { QHeaderView::Interactive, QHeaderView::Stretch, QHeaderView::Interactive }; QList m_columnsHideable = { false, false, true }; QDir m_dir; diff --git a/launcher/minecraft/mod/ResourcePackFolderModel.cpp b/launcher/minecraft/mod/ResourcePackFolderModel.cpp index f27431576..693b8af05 100644 --- a/launcher/minecraft/mod/ResourcePackFolderModel.cpp +++ b/launcher/minecraft/mod/ResourcePackFolderModel.cpp @@ -52,8 +52,8 @@ ResourcePackFolderModel::ResourcePackFolderModel(const QString& dir, BaseInstanc m_column_names = QStringList({ "Enable", "Image", "Name", "Pack Format", "Last Modified" }); m_column_names_translated = QStringList({ tr("Enable"), tr("Image"), tr("Name"), tr("Pack Format"), tr("Last Modified") }); m_column_sort_keys = { SortType::ENABLED, SortType::NAME, SortType::NAME, SortType::PACK_FORMAT, SortType::DATE }; - m_column_resize_modes = { QHeaderView::ResizeToContents, QHeaderView::Interactive, QHeaderView::Stretch, QHeaderView::ResizeToContents, - QHeaderView::ResizeToContents }; + m_column_resize_modes = { QHeaderView::Interactive, QHeaderView::Interactive, QHeaderView::Stretch, QHeaderView::Interactive, + QHeaderView::Interactive }; m_columnsHideable = { false, true, false, true, true }; } @@ -117,6 +117,11 @@ QVariant ResourcePackFolderModel::data(const QModelIndex& index, int role) const } return m_resources[row]->internal_id(); } + case Qt::SizeHintRole: + if (column == ImageColumn) { + return QSize(32, 32); + } + return {}; case Qt::CheckStateRole: switch (column) { case ActiveColumn: diff --git a/launcher/minecraft/mod/TexturePackFolderModel.cpp b/launcher/minecraft/mod/TexturePackFolderModel.cpp index 5c5f2b7c1..f210501c7 100644 --- a/launcher/minecraft/mod/TexturePackFolderModel.cpp +++ b/launcher/minecraft/mod/TexturePackFolderModel.cpp @@ -47,8 +47,7 @@ TexturePackFolderModel::TexturePackFolderModel(const QString& dir, BaseInstance* m_column_names = QStringList({ "Enable", "Image", "Name", "Last Modified" }); m_column_names_translated = QStringList({ tr("Enable"), tr("Image"), tr("Name"), tr("Last Modified") }); m_column_sort_keys = { SortType::ENABLED, SortType::NAME, SortType::NAME, SortType::DATE }; - m_column_resize_modes = { QHeaderView::ResizeToContents, QHeaderView::Interactive, QHeaderView::Stretch, - QHeaderView::ResizeToContents }; + m_column_resize_modes = { QHeaderView::Interactive, QHeaderView::Interactive, QHeaderView::Stretch, QHeaderView::Interactive }; m_columnsHideable = { false, true, false, true }; } @@ -104,6 +103,11 @@ QVariant TexturePackFolderModel::data(const QModelIndex& index, int role) const } return {}; } + case Qt::SizeHintRole: + if (column == ImageColumn) { + return QSize(32, 32); + } + return {}; case Qt::CheckStateRole: if (column == ActiveColumn) { return m_resources[row]->enabled() ? Qt::Checked : Qt::Unchecked; diff --git a/launcher/minecraft/mod/tasks/LocalModParseTask.cpp b/launcher/minecraft/mod/tasks/LocalModParseTask.cpp index 7ec00c0c6..e9e12d86a 100644 --- a/launcher/minecraft/mod/tasks/LocalModParseTask.cpp +++ b/launcher/minecraft/mod/tasks/LocalModParseTask.cpp @@ -688,6 +688,7 @@ bool loadIconFile(const Mod& mod) return png_invalid(); // icon invalid } } + return false; } case ResourceType::ZIPFILE: { QuaZip zip(mod.fileinfo().filePath()); @@ -714,6 +715,7 @@ bool loadIconFile(const Mod& mod) } else { return png_invalid(); // could not set icon as current file. } + return false; } case ResourceType::LITEMOD: { return false; // can lightmods even have icons? diff --git a/launcher/minecraft/mod/tasks/LocalResourcePackParseTask.cpp b/launcher/minecraft/mod/tasks/LocalResourcePackParseTask.cpp index 7b9f4f594..26bc07637 100644 --- a/launcher/minecraft/mod/tasks/LocalResourcePackParseTask.cpp +++ b/launcher/minecraft/mod/tasks/LocalResourcePackParseTask.cpp @@ -232,10 +232,9 @@ bool processPackPNG(const ResourcePack& pack) } else { return png_invalid(); // pack.png does not exists or is not a valid file. } + return false; // not processed correctly; https://github.com/PrismLauncher/PrismLauncher/issues/1740 } case ResourceType::ZIPFILE: { - Q_ASSERT(pack.type() == ResourceType::ZIPFILE); - QuaZip zip(pack.fileinfo().filePath()); if (!zip.open(QuaZip::mdUnzip)) return false; // can't open zip file @@ -259,6 +258,7 @@ bool processPackPNG(const ResourcePack& pack) } else { return png_invalid(); // could not set pack.mcmeta as current file. } + return false; // not processed correctly; https://github.com/PrismLauncher/PrismLauncher/issues/1740 } default: qWarning() << "Invalid type for resource pack parse task!"; diff --git a/launcher/minecraft/mod/tasks/LocalTexturePackParseTask.cpp b/launcher/minecraft/mod/tasks/LocalTexturePackParseTask.cpp index 887a1062e..d7e61ca90 100644 --- a/launcher/minecraft/mod/tasks/LocalTexturePackParseTask.cpp +++ b/launcher/minecraft/mod/tasks/LocalTexturePackParseTask.cpp @@ -186,10 +186,9 @@ bool processPackPNG(const TexturePack& pack) } else { return png_invalid(); // pack.png does not exists or is not a valid file. } + return false; } case ResourceType::ZIPFILE: { - Q_ASSERT(pack.type() == ResourceType::ZIPFILE); - QuaZip zip(pack.fileinfo().filePath()); if (!zip.open(QuaZip::mdUnzip)) return false; // can't open zip file @@ -215,6 +214,7 @@ bool processPackPNG(const TexturePack& pack) zip.close(); return png_invalid(); // could not set pack.mcmeta as current file. } + return false; } default: qWarning() << "Invalid type for resource pack parse task!"; diff --git a/launcher/minecraft/services/SkinDelete.h b/launcher/minecraft/services/SkinDelete.h index d5b2e63db..44e30453f 100644 --- a/launcher/minecraft/services/SkinDelete.h +++ b/launcher/minecraft/services/SkinDelete.h @@ -4,7 +4,7 @@ #include #include "tasks/Task.h" -typedef shared_qobject_ptr SkinDeletePtr; +using SkinDeletePtr = shared_qobject_ptr; class SkinDelete : public Task { Q_OBJECT diff --git a/launcher/minecraft/services/SkinUpload.h b/launcher/minecraft/services/SkinUpload.h index 5716aa996..016367ff8 100644 --- a/launcher/minecraft/services/SkinUpload.h +++ b/launcher/minecraft/services/SkinUpload.h @@ -5,7 +5,7 @@ #include #include "tasks/Task.h" -typedef shared_qobject_ptr SkinUploadPtr; +using SkinUploadPtr = shared_qobject_ptr; class SkinUpload : public Task { Q_OBJECT diff --git a/launcher/modplatform/flame/FlameAPI.cpp b/launcher/modplatform/flame/FlameAPI.cpp index cc3f31e32..a1cfe1a60 100644 --- a/launcher/modplatform/flame/FlameAPI.cpp +++ b/launcher/modplatform/flame/FlameAPI.cpp @@ -210,19 +210,17 @@ Task::Ptr FlameAPI::getFile(const QString& addonId, const QString& fileId, std:: return netJob; } -// https://docs.curseforge.com/?python#tocS_ModsSearchSortField -static QList s_sorts = { { 1, "Featured", QObject::tr("Sort by Featured") }, - { 2, "Popularity", QObject::tr("Sort by Popularity") }, - { 3, "LastUpdated", QObject::tr("Sort by Last Updated") }, - { 4, "Name", QObject::tr("Sort by Name") }, - { 5, "Author", QObject::tr("Sort by Author") }, - { 6, "TotalDownloads", QObject::tr("Sort by Downloads") }, - { 7, "Category", QObject::tr("Sort by Category") }, - { 8, "GameVersion", QObject::tr("Sort by Game Version") } }; - QList FlameAPI::getSortingMethods() const { - return s_sorts; + // https://docs.curseforge.com/?python#tocS_ModsSearchSortField + return { { 1, "Featured", QObject::tr("Sort by Featured") }, + { 2, "Popularity", QObject::tr("Sort by Popularity") }, + { 3, "LastUpdated", QObject::tr("Sort by Last Updated") }, + { 4, "Name", QObject::tr("Sort by Name") }, + { 5, "Author", QObject::tr("Sort by Author") }, + { 6, "TotalDownloads", QObject::tr("Sort by Downloads") }, + { 7, "Category", QObject::tr("Sort by Category") }, + { 8, "GameVersion", QObject::tr("Sort by Game Version") } }; } Task::Ptr FlameAPI::getModCategories(std::shared_ptr response) diff --git a/launcher/modplatform/import_ftb/PackHelpers.h b/launcher/modplatform/import_ftb/PackHelpers.h index 5400252b6..221eb5bf6 100644 --- a/launcher/modplatform/import_ftb/PackHelpers.h +++ b/launcher/modplatform/import_ftb/PackHelpers.h @@ -45,7 +45,7 @@ struct Modpack { QIcon icon; }; -typedef QList ModpackList; +using ModpackList = QList; Modpack parseDirectory(QString path); diff --git a/launcher/modplatform/legacy_ftb/PackHelpers.h b/launcher/modplatform/legacy_ftb/PackHelpers.h index 4fb535530..f2d18f802 100644 --- a/launcher/modplatform/legacy_ftb/PackHelpers.h +++ b/launcher/modplatform/legacy_ftb/PackHelpers.h @@ -31,7 +31,7 @@ struct Modpack { QString packCode; }; -typedef QList ModpackList; +using ModpackList = QList; } // namespace LegacyFTB diff --git a/launcher/modplatform/modrinth/ModrinthAPI.cpp b/launcher/modplatform/modrinth/ModrinthAPI.cpp index d3f006e6f..4798ace84 100644 --- a/launcher/modplatform/modrinth/ModrinthAPI.cpp +++ b/launcher/modplatform/modrinth/ModrinthAPI.cpp @@ -111,16 +111,14 @@ Task::Ptr ModrinthAPI::getProjects(QStringList addonIds, std::shared_ptr s_sorts = { { 1, "relevance", QObject::tr("Sort by Relevance") }, - { 2, "downloads", QObject::tr("Sort by Downloads") }, - { 3, "follows", QObject::tr("Sort by Follows") }, - { 4, "newest", QObject::tr("Sort by Last Updated") }, - { 5, "updated", QObject::tr("Sort by Newest") } }; - QList ModrinthAPI::getSortingMethods() const { - return s_sorts; + // https://docs.modrinth.com/api-spec/#tag/projects/operation/searchProjects + return { { 1, "relevance", QObject::tr("Sort by Relevance") }, + { 2, "downloads", QObject::tr("Sort by Downloads") }, + { 3, "follows", QObject::tr("Sort by Follows") }, + { 4, "newest", QObject::tr("Sort by Newest") }, + { 5, "updated", QObject::tr("Sort by Last Updated") } }; } Task::Ptr ModrinthAPI::getModCategories(std::shared_ptr response) diff --git a/launcher/net/NetRequest.cpp b/launcher/net/NetRequest.cpp index cb675be1b..728c0e077 100644 --- a/launcher/net/NetRequest.cpp +++ b/launcher/net/NetRequest.cpp @@ -112,6 +112,8 @@ void NetRequest::executeTask() m_last_progress_bytes = 0; QNetworkReply* rep = getReply(request); + if (rep == nullptr) // it failed + return; m_reply.reset(rep); connect(rep, &QNetworkReply::downloadProgress, this, &NetRequest::downloadProgress); connect(rep, &QNetworkReply::finished, this, &NetRequest::downloadFinished); diff --git a/launcher/net/NetRequest.h b/launcher/net/NetRequest.h index ee47ab2a6..0b307b4f6 100644 --- a/launcher/net/NetRequest.h +++ b/launcher/net/NetRequest.h @@ -87,7 +87,7 @@ class NetRequest : public NetAction { std::unique_ptr m_sink; Options m_options; - typedef const QLoggingCategory& (*logCatFunc)(); + using logCatFunc = const QLoggingCategory& (*)(); logCatFunc logCat = taskUploadLogC; std::chrono::steady_clock m_clock; diff --git a/launcher/net/StaticHeaderProxy.h b/launcher/net/StaticHeaderProxy.h new file mode 100644 index 000000000..8af7d203d --- /dev/null +++ b/launcher/net/StaticHeaderProxy.h @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: GPL-3.0-only +/* + * Prism Launcher - Minecraft Launcher + * Copyright (C) 2023 Rachel Powers <508861+Ryex@users.noreply.github.com> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#pragma once + +#include "net/HeaderProxy.h" + +namespace Net { + +class StaticHeaderProxy : public HeaderProxy { + public: + StaticHeaderProxy(QList hdrs = {}) : HeaderProxy(), m_hdrs(hdrs){}; + virtual ~StaticHeaderProxy() = default; + + public: + virtual QList headers(const QNetworkRequest&) const override { return m_hdrs; }; + void setHeaders(QList hdrs) { m_hdrs = hdrs; }; + + private: + QList m_hdrs; +}; + +} // namespace Net diff --git a/launcher/news/NewsEntry.h b/launcher/news/NewsEntry.h index 2d409a9fb..ab717ec89 100644 --- a/launcher/news/NewsEntry.h +++ b/launcher/news/NewsEntry.h @@ -51,4 +51,4 @@ class NewsEntry : public QObject { QString link; }; -typedef std::shared_ptr NewsEntryPtr; +using NewsEntryPtr = std::shared_ptr; diff --git a/launcher/pathmatcher/IPathMatcher.h b/launcher/pathmatcher/IPathMatcher.h index cd6121979..f3b01e8cf 100644 --- a/launcher/pathmatcher/IPathMatcher.h +++ b/launcher/pathmatcher/IPathMatcher.h @@ -4,7 +4,7 @@ class IPathMatcher { public: - typedef std::shared_ptr Ptr; + using Ptr = std::shared_ptr; public: virtual ~IPathMatcher() {} diff --git a/launcher/resources/breeze_dark/breeze_dark.qrc b/launcher/resources/breeze_dark/breeze_dark.qrc index 320ca8171..61d82ec30 100644 --- a/launcher/resources/breeze_dark/breeze_dark.qrc +++ b/launcher/resources/breeze_dark/breeze_dark.qrc @@ -9,6 +9,7 @@ scalable/copy.svg scalable/coremods.svg scalable/custom-commands.svg + scalable/environment-variables.svg scalable/discord.svg scalable/externaltools.svg scalable/help.svg diff --git a/launcher/resources/breeze_dark/scalable/environment-variables.svg b/launcher/resources/breeze_dark/scalable/environment-variables.svg new file mode 100644 index 000000000..308c4a239 --- /dev/null +++ b/launcher/resources/breeze_dark/scalable/environment-variables.svg @@ -0,0 +1,13 @@ + + + + + + diff --git a/launcher/resources/breeze_light/breeze_light.qrc b/launcher/resources/breeze_light/breeze_light.qrc index e88cd9a00..2211c7188 100644 --- a/launcher/resources/breeze_light/breeze_light.qrc +++ b/launcher/resources/breeze_light/breeze_light.qrc @@ -9,6 +9,7 @@ scalable/copy.svg scalable/coremods.svg scalable/custom-commands.svg + scalable/environment-variables.svg scalable/discord.svg scalable/externaltools.svg scalable/help.svg diff --git a/launcher/resources/breeze_light/scalable/environment-variables.svg b/launcher/resources/breeze_light/scalable/environment-variables.svg new file mode 100644 index 000000000..f5d4acc3b --- /dev/null +++ b/launcher/resources/breeze_light/scalable/environment-variables.svg @@ -0,0 +1,13 @@ + + + + + + diff --git a/launcher/resources/flat/flat.qrc b/launcher/resources/flat/flat.qrc index 2fd5daefe..8876027da 100644 --- a/launcher/resources/flat/flat.qrc +++ b/launcher/resources/flat/flat.qrc @@ -11,6 +11,7 @@ scalable/copy.svg scalable/coremods.svg scalable/custom-commands.svg + scalable/environment-variables.svg scalable/discord.svg scalable/externaltools.svg scalable/help.svg diff --git a/launcher/resources/flat/scalable/custom-commands.svg b/launcher/resources/flat/scalable/custom-commands.svg index a35634b16..f2e587843 100644 --- a/launcher/resources/flat/scalable/custom-commands.svg +++ b/launcher/resources/flat/scalable/custom-commands.svg @@ -1,86 +1 @@ - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - + diff --git a/launcher/resources/flat/scalable/environment-variables.svg b/launcher/resources/flat/scalable/environment-variables.svg new file mode 100644 index 000000000..a35634b16 --- /dev/null +++ b/launcher/resources/flat/scalable/environment-variables.svg @@ -0,0 +1,86 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + diff --git a/launcher/resources/flat_white/flat_white.qrc b/launcher/resources/flat_white/flat_white.qrc index a1c940da0..83b178cbf 100644 --- a/launcher/resources/flat_white/flat_white.qrc +++ b/launcher/resources/flat_white/flat_white.qrc @@ -11,6 +11,7 @@ scalable/copy.svg scalable/coremods.svg scalable/custom-commands.svg + scalable/environment-variables.svg scalable/discord.svg scalable/externaltools.svg scalable/help.svg diff --git a/launcher/resources/flat_white/scalable/custom-commands.svg b/launcher/resources/flat_white/scalable/custom-commands.svg index fe1cf9987..0ba459cff 100644 --- a/launcher/resources/flat_white/scalable/custom-commands.svg +++ b/launcher/resources/flat_white/scalable/custom-commands.svg @@ -1,86 +1 @@ - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - + diff --git a/launcher/resources/flat_white/scalable/environment-variables.svg b/launcher/resources/flat_white/scalable/environment-variables.svg new file mode 100644 index 000000000..fe1cf9987 --- /dev/null +++ b/launcher/resources/flat_white/scalable/environment-variables.svg @@ -0,0 +1,86 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + diff --git a/launcher/resources/multimc/multimc.qrc b/launcher/resources/multimc/multimc.qrc index 80981559b..eeba32186 100644 --- a/launcher/resources/multimc/multimc.qrc +++ b/launcher/resources/multimc/multimc.qrc @@ -73,8 +73,8 @@ 64x64/screenshots.png scalable/screenshots.svg - scalable/custom-commands.svg + scalable/environment-variables.svg 16x16/cat.png diff --git a/launcher/resources/multimc/scalable/custom-commands.svg b/launcher/resources/multimc/scalable/custom-commands.svg index b7f1a149b..0d502bb1d 100644 --- a/launcher/resources/multimc/scalable/custom-commands.svg +++ b/launcher/resources/multimc/scalable/custom-commands.svg @@ -1,338 +1,4339 @@ + + width="128" + height="128" + id="svg2756" + sodipodi:version="0.32" + inkscape:version="0.45.1" + version="1.0" + sodipodi:docname="konsole.svg" + inkscape:output_extension="org.inkscape.output.svg.inkscape" + sodipodi:docbase="/home/david/sandbox"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + inkscape:zoom="4" + inkscape:cx="64" + inkscape:cy="73.608336" + inkscape:document-units="px" + inkscape:current-layer="layer1" + height="128px" + width="128px" + showgrid="true" + gridspacingy="4px" + gridspacingx="4px" + gridempspacing="0" + inkscape:window-width="971" + inkscape:window-height="648" + inkscape:window-x="46" + inkscape:window-y="45" /> + id="metadata2761"> image/svg+xml - + inkscape:label="Livello 1" + inkscape:groupmode="layer" + id="layer1"> + + + + + + + + + + + - - + x="12" + y="16" + width="104" + height="80" + id="rect30" /> - - - - - - - - - - - - - - - - - - - - - + id="g32" + transform="matrix(1.0851064,0,0,1.1142857,3.2340422,6.9714286)"> + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - + id="g2644"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/launcher/resources/multimc/scalable/environment-variables.svg b/launcher/resources/multimc/scalable/environment-variables.svg new file mode 100644 index 000000000..5e136b202 --- /dev/null +++ b/launcher/resources/multimc/scalable/environment-variables.svg @@ -0,0 +1,346 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + diff --git a/launcher/resources/pe_blue/pe_blue.qrc b/launcher/resources/pe_blue/pe_blue.qrc index da45ef9a1..717d3972e 100644 --- a/launcher/resources/pe_blue/pe_blue.qrc +++ b/launcher/resources/pe_blue/pe_blue.qrc @@ -10,6 +10,7 @@ scalable/copy.svg scalable/coremods.svg scalable/custom-commands.svg + scalable/environment-variables.svg scalable/externaltools.svg scalable/help.svg scalable/instance-settings.svg diff --git a/launcher/resources/pe_blue/scalable/environment-variables.svg b/launcher/resources/pe_blue/scalable/environment-variables.svg new file mode 100644 index 000000000..61c63a4c5 --- /dev/null +++ b/launcher/resources/pe_blue/scalable/environment-variables.svg @@ -0,0 +1,345 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/launcher/resources/pe_colored/pe_colored.qrc b/launcher/resources/pe_colored/pe_colored.qrc index ba5bd44f9..023c81e74 100644 --- a/launcher/resources/pe_colored/pe_colored.qrc +++ b/launcher/resources/pe_colored/pe_colored.qrc @@ -10,6 +10,7 @@ scalable/copy.svg scalable/coremods.svg scalable/custom-commands.svg + scalable/environment-variables.svg scalable/externaltools.svg scalable/help.svg scalable/instance-settings.svg diff --git a/launcher/resources/pe_colored/scalable/environment-variables.svg b/launcher/resources/pe_colored/scalable/environment-variables.svg new file mode 100644 index 000000000..c1aab6bca --- /dev/null +++ b/launcher/resources/pe_colored/scalable/environment-variables.svg @@ -0,0 +1,347 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/launcher/resources/pe_dark/pe_dark.qrc b/launcher/resources/pe_dark/pe_dark.qrc index 2bfec42cb..c97fb469c 100644 --- a/launcher/resources/pe_dark/pe_dark.qrc +++ b/launcher/resources/pe_dark/pe_dark.qrc @@ -10,6 +10,7 @@ scalable/copy.svg scalable/coremods.svg scalable/custom-commands.svg + scalable/environment-variables.svg scalable/externaltools.svg scalable/help.svg scalable/instance-settings.svg diff --git a/launcher/resources/pe_dark/scalable/environment-variables.svg b/launcher/resources/pe_dark/scalable/environment-variables.svg new file mode 100644 index 000000000..46a3445f4 --- /dev/null +++ b/launcher/resources/pe_dark/scalable/environment-variables.svg @@ -0,0 +1,345 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/launcher/resources/pe_light/pe_light.qrc b/launcher/resources/pe_light/pe_light.qrc index 25d5da73b..b590dd2c6 100644 --- a/launcher/resources/pe_light/pe_light.qrc +++ b/launcher/resources/pe_light/pe_light.qrc @@ -10,6 +10,7 @@ scalable/copy.svg scalable/coremods.svg scalable/custom-commands.svg + scalable/environment-variables.svg scalable/externaltools.svg scalable/help.svg scalable/instance-settings.svg diff --git a/launcher/resources/pe_light/scalable/environment-variables.svg b/launcher/resources/pe_light/scalable/environment-variables.svg new file mode 100644 index 000000000..b8d562ffe --- /dev/null +++ b/launcher/resources/pe_light/scalable/environment-variables.svg @@ -0,0 +1,345 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/launcher/screenshots/ImgurAlbumCreation.cpp b/launcher/screenshots/ImgurAlbumCreation.cpp index d548c89ae..7e42ff40c 100644 --- a/launcher/screenshots/ImgurAlbumCreation.cpp +++ b/launcher/screenshots/ImgurAlbumCreation.cpp @@ -39,87 +39,76 @@ #include #include #include +#include #include #include #include +#include -#include "Application.h" #include "BuildConfig.h" +#include "net/StaticHeaderProxy.h" -ImgurAlbumCreation::ImgurAlbumCreation(QList screenshots) : NetAction(), m_screenshots(screenshots) +Net::NetRequest::Ptr ImgurAlbumCreation::make(std::shared_ptr output, QList screenshots) { - m_url = BuildConfig.IMGUR_BASE_URL + "album.json"; - m_state = State::Inactive; + auto up = makeShared(); + up->m_url = BuildConfig.IMGUR_BASE_URL + "album.json"; + up->m_sink.reset(new Sink(output)); + up->m_screenshots = screenshots; + return up; } -void ImgurAlbumCreation::executeTask() +QNetworkReply* ImgurAlbumCreation::getReply(QNetworkRequest& request) { - m_state = State::Running; - QNetworkRequest request(m_url); - request.setHeader(QNetworkRequest::UserAgentHeader, APPLICATION->getUserAgentUncached().toUtf8()); - request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); - request.setRawHeader("Authorization", QString("Client-ID %1").arg(BuildConfig.IMGUR_CLIENT_ID).toStdString().c_str()); - request.setRawHeader("Accept", "application/json"); - QStringList hashes; for (auto shot : m_screenshots) { hashes.append(shot->m_imgurDeleteHash); } - const QByteArray data = "deletehashes=" + hashes.join(',').toUtf8() + "&title=Minecraft%20Screenshots&privacy=hidden"; + return m_network->post(request, data); +}; - QNetworkReply* rep = APPLICATION->network()->post(request, data); - - m_reply.reset(rep); - connect(rep, &QNetworkReply::uploadProgress, this, &ImgurAlbumCreation::downloadProgress); - connect(rep, &QNetworkReply::finished, this, &ImgurAlbumCreation::downloadFinished); -#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) // QNetworkReply::errorOccurred added in 5.15 - connect(rep, &QNetworkReply::errorOccurred, this, &ImgurAlbumCreation::downloadError); -#else - connect(rep, QOverload::of(&QNetworkReply::error), this, &ImgurAlbumCreation::downloadError); -#endif - connect(rep, &QNetworkReply::sslErrors, this, &ImgurAlbumCreation::sslErrors); +void ImgurAlbumCreation::init() +{ + qDebug() << "Setting up imgur upload"; + auto api_headers = new Net::StaticHeaderProxy( + QList{ { "Content-Type", "application/x-www-form-urlencoded" }, + { "Authorization", QString("Client-ID %1").arg(BuildConfig.IMGUR_CLIENT_ID).toStdString().c_str() }, + { "Accept", "application/json" } }); + addHeaderProxy(api_headers); } -void ImgurAlbumCreation::downloadError([[maybe_unused]] QNetworkReply::NetworkError error) +auto ImgurAlbumCreation::Sink::init(QNetworkRequest& request) -> Task::State { - qDebug() << m_reply->errorString(); - m_state = State::Failed; + m_output.clear(); + return Task::State::Running; +}; + +auto ImgurAlbumCreation::Sink::write(QByteArray& data) -> Task::State +{ + m_output.append(data); + return Task::State::Running; } -void ImgurAlbumCreation::downloadFinished() +auto ImgurAlbumCreation::Sink::abort() -> Task::State { - if (m_state != State::Failed) { - QByteArray data = m_reply->readAll(); - m_reply.reset(); - QJsonParseError jsonError; - QJsonDocument doc = QJsonDocument::fromJson(data, &jsonError); - if (jsonError.error != QJsonParseError::NoError) { - qDebug() << jsonError.errorString(); - emitFailed(); - return; - } - auto object = doc.object(); - if (!object.value("success").toBool()) { - qDebug() << doc.toJson(); - emitFailed(); - return; - } - m_deleteHash = object.value("data").toObject().value("deletehash").toString(); - m_id = object.value("data").toObject().value("id").toString(); - m_state = State::Succeeded; - emit succeeded(); - return; - } else { - qDebug() << m_reply->readAll(); - m_reply.reset(); - emitFailed(); - return; + m_output.clear(); + return Task::State::Failed; +} + +auto ImgurAlbumCreation::Sink::finalize(QNetworkReply&) -> Task::State +{ + QJsonParseError jsonError; + QJsonDocument doc = QJsonDocument::fromJson(m_output, &jsonError); + if (jsonError.error != QJsonParseError::NoError) { + qDebug() << jsonError.errorString(); + return Task::State::Failed; } -} - -void ImgurAlbumCreation::downloadProgress(qint64 bytesReceived, qint64 bytesTotal) -{ - setProgress(bytesReceived, bytesTotal); - emit progress(bytesReceived, bytesTotal); -} + auto object = doc.object(); + if (!object.value("success").toBool()) { + qDebug() << doc.toJson(); + return Task::State::Failed; + } + m_result->deleteHash = object.value("data").toObject().value("deletehash").toString(); + m_result->id = object.value("data").toObject().value("id").toString(); + return Task::State::Succeeded; +} \ No newline at end of file diff --git a/launcher/screenshots/ImgurAlbumCreation.h b/launcher/screenshots/ImgurAlbumCreation.h index bb71bec2b..7c292db73 100644 --- a/launcher/screenshots/ImgurAlbumCreation.h +++ b/launcher/screenshots/ImgurAlbumCreation.h @@ -36,34 +36,39 @@ #pragma once #include "Screenshot.h" -#include "net/NetAction.h" +#include "net/NetRequest.h" -typedef shared_qobject_ptr ImgurAlbumCreationPtr; -class ImgurAlbumCreation : public NetAction { +class ImgurAlbumCreation : public Net::NetRequest { public: - explicit ImgurAlbumCreation(QList screenshots); - static ImgurAlbumCreationPtr make(QList screenshots) - { - return ImgurAlbumCreationPtr(new ImgurAlbumCreation(screenshots)); - } + virtual ~ImgurAlbumCreation() = default; - QString deleteHash() const { return m_deleteHash; } - QString id() const { return m_id; } + struct Result { + QString deleteHash; + QString id; + }; - void init() override{}; + class Sink : public Net::Sink { + public: + Sink(std::shared_ptr res) : m_result(res){}; + virtual ~Sink() = default; - protected slots: - void downloadProgress(qint64 bytesReceived, qint64 bytesTotal) override; - void downloadError(QNetworkReply::NetworkError error) override; - void downloadFinished() override; - void downloadReadyRead() override {} + public: + auto init(QNetworkRequest& request) -> Task::State override; + auto write(QByteArray& data) -> Task::State override; + auto abort() -> Task::State override; + auto finalize(QNetworkReply& reply) -> Task::State override; + auto hasLocalData() -> bool override { return false; } - public slots: - void executeTask() override; + private: + std::shared_ptr m_result; + QByteArray m_output; + }; + + static NetRequest::Ptr make(std::shared_ptr output, QList screenshots); + QNetworkReply* getReply(QNetworkRequest& request) override; + + void init() override; private: QList m_screenshots; - - QString m_deleteHash; - QString m_id; }; diff --git a/launcher/screenshots/ImgurUpload.cpp b/launcher/screenshots/ImgurUpload.cpp index 29499a20d..7ed672eb7 100644 --- a/launcher/screenshots/ImgurUpload.cpp +++ b/launcher/screenshots/ImgurUpload.cpp @@ -35,8 +35,8 @@ */ #include "ImgurUpload.h" -#include "Application.h" #include "BuildConfig.h" +#include "net/StaticHeaderProxy.h" #include #include @@ -47,104 +47,84 @@ #include #include -ImgurUpload::ImgurUpload(ScreenShot::Ptr shot) : NetAction(), m_shot(shot) +void ImgurUpload::init() { - m_url = BuildConfig.IMGUR_BASE_URL + "upload.json"; - m_state = State::Inactive; + qDebug() << "Setting up imgur upload"; + auto api_headers = new Net::StaticHeaderProxy( + QList{ { "Authorization", QString("Client-ID %1").arg(BuildConfig.IMGUR_CLIENT_ID).toStdString().c_str() }, + { "Accept", "application/json" } }); + addHeaderProxy(api_headers); } -void ImgurUpload::executeTask() +QNetworkReply* ImgurUpload::getReply(QNetworkRequest& request) { - finished = false; - m_state = Task::State::Running; - QNetworkRequest request(m_url); - request.setHeader(QNetworkRequest::UserAgentHeader, APPLICATION->getUserAgentUncached().toUtf8()); - request.setRawHeader("Authorization", QString("Client-ID %1").arg(BuildConfig.IMGUR_CLIENT_ID).toStdString().c_str()); - request.setRawHeader("Accept", "application/json"); + auto file = new QFile(m_fileInfo.absoluteFilePath()); - QFile f(m_shot->m_file.absoluteFilePath()); - if (!f.open(QFile::ReadOnly)) { + if (!file->open(QFile::ReadOnly)) { emitFailed(); - return; + return nullptr; } QHttpMultiPart* multipart = new QHttpMultiPart(QHttpMultiPart::FormDataType); + file->setParent(multipart); QHttpPart filePart; - filePart.setBody(f.readAll().toBase64()); + filePart.setBodyDevice(file); filePart.setHeader(QNetworkRequest::ContentTypeHeader, "image/png"); filePart.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data; name=\"image\""); multipart->append(filePart); QHttpPart typePart; typePart.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data; name=\"type\""); - typePart.setBody("base64"); + typePart.setBody("file"); multipart->append(typePart); QHttpPart namePart; namePart.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data; name=\"name\""); - namePart.setBody(m_shot->m_file.baseName().toUtf8()); + namePart.setBody(m_fileInfo.baseName().toUtf8()); multipart->append(namePart); - QNetworkReply* rep = m_network->post(request, multipart); + return m_network->post(request, multipart); +}; - m_reply.reset(rep); - connect(rep, &QNetworkReply::uploadProgress, this, &ImgurUpload::downloadProgress); - connect(rep, &QNetworkReply::finished, this, &ImgurUpload::downloadFinished); -#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) // QNetworkReply::errorOccurred added in 5.15 - connect(rep, &QNetworkReply::errorOccurred, this, &ImgurUpload::downloadError); -#else - connect(rep, QOverload::of(&QNetworkReply::error), this, &ImgurUpload::downloadError); -#endif - connect(rep, &QNetworkReply::sslErrors, this, &ImgurUpload::sslErrors); +auto ImgurUpload::Sink::init(QNetworkRequest& request) -> Task::State +{ + m_output.clear(); + return Task::State::Running; +}; + +auto ImgurUpload::Sink::write(QByteArray& data) -> Task::State +{ + m_output.append(data); + return Task::State::Running; } -void ImgurUpload::downloadError([[maybe_unused]] QNetworkReply::NetworkError error) +auto ImgurUpload::Sink::abort() -> Task::State { - qCritical() << "ImgurUpload failed with error" << m_reply->errorString() << "Server reply:\n" << m_reply->readAll(); - if (finished) { - qCritical() << "Double finished ImgurUpload!"; - return; - } - m_state = Task::State::Failed; - finished = true; - m_reply.reset(); - emitFailed(); + m_output.clear(); + return Task::State::Failed; } -void ImgurUpload::downloadFinished() +auto ImgurUpload::Sink::finalize(QNetworkReply&) -> Task::State { - if (finished) { - qCritical() << "Double finished ImgurUpload!"; - return; - } - QByteArray data = m_reply->readAll(); - m_reply.reset(); QJsonParseError jsonError; - QJsonDocument doc = QJsonDocument::fromJson(data, &jsonError); + QJsonDocument doc = QJsonDocument::fromJson(m_output, &jsonError); if (jsonError.error != QJsonParseError::NoError) { qDebug() << "imgur server did not reply with JSON" << jsonError.errorString(); - finished = true; - m_reply.reset(); - emitFailed(); - return; + return Task::State::Failed; } auto object = doc.object(); if (!object.value("success").toBool()) { qDebug() << "Screenshot upload not successful:" << doc.toJson(); - finished = true; - m_reply.reset(); - emitFailed(); - return; + return Task::State::Failed; } m_shot->m_imgurId = object.value("data").toObject().value("id").toString(); m_shot->m_url = object.value("data").toObject().value("link").toString(); m_shot->m_imgurDeleteHash = object.value("data").toObject().value("deletehash").toString(); - m_state = Task::State::Succeeded; - finished = true; - emit succeeded(); - return; + return Task::State::Succeeded; } -void ImgurUpload::downloadProgress(qint64 bytesReceived, qint64 bytesTotal) +Net::NetRequest::Ptr ImgurUpload::make(ScreenShot::Ptr m_shot) { - setProgress(bytesReceived, bytesTotal); - emit progress(bytesReceived, bytesTotal); + auto up = makeShared(m_shot->m_file); + up->m_url = std::move(BuildConfig.IMGUR_BASE_URL + "upload.json"); + up->m_sink.reset(new Sink(m_shot)); + return up; } diff --git a/launcher/screenshots/ImgurUpload.h b/launcher/screenshots/ImgurUpload.h index 542255b2d..5867ad306 100644 --- a/launcher/screenshots/ImgurUpload.h +++ b/launcher/screenshots/ImgurUpload.h @@ -35,27 +35,36 @@ #pragma once +#include #include "Screenshot.h" -#include "net/NetAction.h" +#include "net/NetRequest.h" -class ImgurUpload : public NetAction { +class ImgurUpload : public Net::NetRequest { public: - using Ptr = shared_qobject_ptr; + class Sink : public Net::Sink { + public: + Sink(ScreenShot::Ptr shot) : m_shot(shot){}; + virtual ~Sink() = default; - explicit ImgurUpload(ScreenShot::Ptr shot); - static Ptr make(ScreenShot::Ptr shot) { return Ptr(new ImgurUpload(shot)); } - void init() override{}; + public: + auto init(QNetworkRequest& request) -> Task::State override; + auto write(QByteArray& data) -> Task::State override; + auto abort() -> Task::State override; + auto finalize(QNetworkReply& reply) -> Task::State override; + auto hasLocalData() -> bool override { return false; } - protected slots: - void downloadProgress(qint64 bytesReceived, qint64 bytesTotal) override; - void downloadError(QNetworkReply::NetworkError error) override; - void downloadFinished() override; - void downloadReadyRead() override {} + private: + ScreenShot::Ptr m_shot; + QByteArray m_output; + }; + ImgurUpload(QFileInfo info) : m_fileInfo(info) {} + virtual ~ImgurUpload() = default; - public slots: - void executeTask() override; + static NetRequest::Ptr make(ScreenShot::Ptr m_shot); + + void init() override; private: - ScreenShot::Ptr m_shot; - bool finished = true; + virtual QNetworkReply* getReply(QNetworkRequest&) override; + const QFileInfo m_fileInfo; }; diff --git a/launcher/settings/SettingsObject.h b/launcher/settings/SettingsObject.h index 75631f247..f133f2f7f 100644 --- a/launcher/settings/SettingsObject.h +++ b/launcher/settings/SettingsObject.h @@ -26,8 +26,8 @@ class Setting; class SettingsObject; -typedef std::shared_ptr SettingsObjectPtr; -typedef std::weak_ptr SettingsObjectWeakPtr; +using SettingsObjectPtr = std::shared_ptr; +using SettingsObjectWeakPtr = std::weak_ptr; /*! * \brief The SettingsObject handles communicating settings between the application and a diff --git a/launcher/tasks/Task.h b/launcher/tasks/Task.h index 94b4089f3..883408c97 100644 --- a/launcher/tasks/Task.h +++ b/launcher/tasks/Task.h @@ -77,7 +77,7 @@ struct TaskStepProgress { Q_DECLARE_METATYPE(TaskStepProgress) -typedef QList> TaskStepProgressList; +using TaskStepProgressList = QList>; class Task : public QObject, public QRunnable { Q_OBJECT diff --git a/launcher/ui/dialogs/AboutDialog.cpp b/launcher/ui/dialogs/AboutDialog.cpp index 3c6f6ef16..cee01e821 100644 --- a/launcher/ui/dialogs/AboutDialog.cpp +++ b/launcher/ui/dialogs/AboutDialog.cpp @@ -85,6 +85,7 @@ QString getCreditsHtml() stream << QString("

TayouVR %1

\n").arg(getGitHub("TayouVR")); stream << QString("

TheKodeToad %1

\n").arg(getGitHub("TheKodeToad")); stream << QString("

getchoo %1

\n").arg(getGitHub("getchoo")); + stream << QString("

Alexandru Tripon (Trial97) %1

\n").arg(getGitHub("Trial97")); stream << "
\n"; // TODO: possibly retrieve from git history at build time? @@ -100,7 +101,7 @@ QString getCreditsHtml() stream << "

" << QObject::tr("With thanks to", "About Credits") << "

\n"; stream << QString("

Boba %1

\n").arg(getWebsite("https://bobaonline.neocities.org/")); stream << QString("

Davi Rafael %1

\n").arg(getWebsite("https://auti.one/")); - stream << QString("

Fulmine %1

\n").arg(getWebsite("https://www.fulmine.xyz/")); + stream << QString("

Fulmine %1

\n").arg(getWebsite("https://fulmine.xyz/")); stream << QString("

ely %1

\n").arg(getGitHub("elyrodso")); stream << QString("

gon sawa %1

\n").arg(getGitHub("gonsawa")); stream << QString("

Pankakes

\n"); diff --git a/launcher/ui/dialogs/ChooseProviderDialog.h b/launcher/ui/dialogs/ChooseProviderDialog.h index be9735b5c..51e7c98c6 100644 --- a/launcher/ui/dialogs/ChooseProviderDialog.h +++ b/launcher/ui/dialogs/ChooseProviderDialog.h @@ -13,7 +13,6 @@ enum class ResourceProvider; class Mod; class NetJob; -class ModUpdateDialog; class ChooseProviderDialog : public QDialog { Q_OBJECT diff --git a/launcher/ui/dialogs/ExportInstanceDialog.h b/launcher/ui/dialogs/ExportInstanceDialog.h index 02f38f63d..183681f57 100644 --- a/launcher/ui/dialogs/ExportInstanceDialog.h +++ b/launcher/ui/dialogs/ExportInstanceDialog.h @@ -43,7 +43,7 @@ #include "FileIgnoreProxy.h" class BaseInstance; -typedef std::shared_ptr InstancePtr; +using InstancePtr = std::shared_ptr; namespace Ui { class ExportInstanceDialog; diff --git a/launcher/ui/dialogs/ExportToModListDialog.cpp b/launcher/ui/dialogs/ExportToModListDialog.cpp index c811bfe6a..a343f555a 100644 --- a/launcher/ui/dialogs/ExportToModListDialog.cpp +++ b/launcher/ui/dialogs/ExportToModListDialog.cpp @@ -214,10 +214,11 @@ void ExportToModListDialog::addExtra(ExportToModList::OptionalData option) void ExportToModListDialog::enableCustom(bool enabled) { ui->authorsCheckBox->setHidden(enabled); - ui->versionCheckBox->setHidden(enabled); - ui->urlCheckBox->setHidden(enabled); - ui->authorsButton->setHidden(!enabled); + + ui->versionCheckBox->setHidden(enabled); ui->versionButton->setHidden(!enabled); + + ui->urlCheckBox->setHidden(enabled); ui->urlButton->setHidden(!enabled); } diff --git a/launcher/ui/dialogs/ExportToModListDialog.ui b/launcher/ui/dialogs/ExportToModListDialog.ui index 25eb43429..4f8ab52b5 100644 --- a/launcher/ui/dialogs/ExportToModListDialog.ui +++ b/launcher/ui/dialogs/ExportToModListDialog.ui @@ -7,7 +7,7 @@ 0 0 650 - 446 + 522 @@ -61,18 +61,37 @@ + + + 0 + 0 + + Template - + + + + 0 + 0 + + + + + + 0 + 0 + + Optional Info diff --git a/launcher/ui/dialogs/MSALoginDialog.cpp b/launcher/ui/dialogs/MSALoginDialog.cpp index 74fff9fd3..7df423412 100644 --- a/launcher/ui/dialogs/MSALoginDialog.cpp +++ b/launcher/ui/dialogs/MSALoginDialog.cpp @@ -105,8 +105,16 @@ void MSALoginDialog::showVerificationUriAndCode(const QUrl& uri, const QString& QString urlString = uri.toString(); QString linkString = QString("%2").arg(urlString, urlString); - ui->label->setText( - tr("

Please open up %1 in a browser and put in the code %2 to proceed with login.

").arg(linkString, code)); + if (urlString == "https://www.microsoft.com/link" && !code.isEmpty()) { + urlString += QString("?otc=%1").arg(code); + DesktopServices::openUrl(urlString); + ui->label->setText(tr("

Please login in the opened browser. If no browser was opened, please open up %1 in " + "a browser and put in the code %2 to proceed with login.

") + .arg(linkString, code)); + } else { + ui->label->setText( + tr("

Please open up %1 in a browser and put in the code %2 to proceed with login.

").arg(linkString, code)); + } ui->actionButton->setVisible(true); connect(ui->actionButton, &QPushButton::clicked, [=]() { DesktopServices::openUrl(uri); diff --git a/launcher/ui/dialogs/ModUpdateDialog.cpp b/launcher/ui/dialogs/ModUpdateDialog.cpp index 1a70ea59a..cbaaf88b9 100644 --- a/launcher/ui/dialogs/ModUpdateDialog.cpp +++ b/launcher/ui/dialogs/ModUpdateDialog.cpp @@ -39,7 +39,8 @@ static std::optional mcLoaders(BaseInstance* inst) ModUpdateDialog::ModUpdateDialog(QWidget* parent, BaseInstance* instance, const std::shared_ptr mods, - QList& search_for) + QList& search_for, + bool includeDeps) : ReviewMessageBox(parent, tr("Confirm mods to update"), "") , m_parent(parent) , m_mod_model(mods) @@ -47,6 +48,7 @@ ModUpdateDialog::ModUpdateDialog(QWidget* parent, , m_second_try_metadata( new ConcurrentTask(nullptr, "Second Metadata Search", APPLICATION->settings()->get("NumberOfConcurrentTasks").toInt())) , m_instance(instance) + , m_include_deps(includeDeps) { ReviewMessageBox::setGeometry(0, 0, 800, 600); @@ -186,7 +188,7 @@ void ModUpdateDialog::checkCandidates() } } - { // dependencies + if (m_include_deps && !APPLICATION->settings()->get("ModDependenciesDisabled").toBool()) { // dependencies auto depTask = makeShared(this, m_instance, m_mod_model.get(), selectedVers); connect(depTask.get(), &Task::failed, this, diff --git a/launcher/ui/dialogs/ModUpdateDialog.h b/launcher/ui/dialogs/ModUpdateDialog.h index b79aa4943..98f6780bf 100644 --- a/launcher/ui/dialogs/ModUpdateDialog.h +++ b/launcher/ui/dialogs/ModUpdateDialog.h @@ -19,7 +19,8 @@ class ModUpdateDialog final : public ReviewMessageBox { explicit ModUpdateDialog(QWidget* parent, BaseInstance* instance, const std::shared_ptr mod_model, - QList& search_for); + QList& search_for, + bool includeDeps); void checkCandidates(); @@ -61,4 +62,5 @@ class ModUpdateDialog final : public ReviewMessageBox { bool m_no_updates = false; bool m_aborted = false; + bool m_include_deps = false; }; diff --git a/launcher/ui/dialogs/ResourceDownloadDialog.cpp b/launcher/ui/dialogs/ResourceDownloadDialog.cpp index f21502365..e434b8184 100644 --- a/launcher/ui/dialogs/ResourceDownloadDialog.cpp +++ b/launcher/ui/dialogs/ResourceDownloadDialog.cpp @@ -271,13 +271,15 @@ QList ModDownloadDialog::getPages() GetModDependenciesTask::Ptr ModDownloadDialog::getModDependenciesTask() { - if (auto model = dynamic_cast(getBaseModel().get()); model) { - QList> selectedVers; - for (auto& selected : getTasks()) { - selectedVers.append(std::make_shared(selected->getPack(), selected->getVersion())); - } + if (!APPLICATION->settings()->get("ModDependenciesDisabled").toBool()) { // dependencies + if (auto model = dynamic_cast(getBaseModel().get()); model) { + QList> selectedVers; + for (auto& selected : getTasks()) { + selectedVers.append(std::make_shared(selected->getPack(), selected->getVersion())); + } - return makeShared(this, m_instance, model, selectedVers); + return makeShared(this, m_instance, model, selectedVers); + } } return nullptr; } diff --git a/launcher/ui/instanceview/AccessibleInstanceView_p.h b/launcher/ui/instanceview/AccessibleInstanceView_p.h index e99f85069..1a3a62d9f 100644 --- a/launcher/ui/instanceview/AccessibleInstanceView_p.h +++ b/launcher/ui/instanceview/AccessibleInstanceView_p.h @@ -59,7 +59,7 @@ class AccessibleInstanceView : public QAccessibleTableInterface, public QAccessi protected: // maybe vector - typedef QHash ChildCache; + using ChildCache = QHash; mutable ChildCache childToId; virtual ~AccessibleInstanceView(); diff --git a/launcher/ui/instanceview/InstanceView.cpp b/launcher/ui/instanceview/InstanceView.cpp index 690dc917b..e665097f4 100644 --- a/launcher/ui/instanceview/InstanceView.cpp +++ b/launcher/ui/instanceview/InstanceView.cpp @@ -39,6 +39,7 @@ #include #include #include +#include #include #include #include @@ -277,12 +278,14 @@ void InstanceView::mousePressEvent(QMouseEvent* event) m_pressedAlreadySelected = selectionModel()->isSelected(m_pressedIndex); m_pressedPosition = geometryPos; - VisualGroup::HitResults hitResult; - m_pressedCategory = categoryAt(geometryPos, hitResult); - if (m_pressedCategory && hitResult & VisualGroup::CheckboxHit) { - setState(m_pressedCategory->collapsed ? ExpandingState : CollapsingState); - event->accept(); - return; + if (event->button() == Qt::LeftButton) { + VisualGroup::HitResults hitResult; + m_pressedCategory = categoryAt(geometryPos, hitResult); + if (m_pressedCategory && hitResult & VisualGroup::CheckboxHit) { + setState(m_pressedCategory->collapsed ? ExpandingState : CollapsingState); + event->accept(); + return; + } } if (index.isValid() && (index.flags() & Qt::ItemIsEnabled)) { @@ -365,10 +368,7 @@ void InstanceView::mouseReleaseEvent(QMouseEvent* event) VisualGroup::HitResults hitResult; - bool click = - (index == m_pressedIndex && index.isValid()) || (m_pressedCategory && m_pressedCategory == categoryAt(geometryPos, hitResult)); - - if (click && m_pressedCategory) { + if (event->button() == Qt::LeftButton && m_pressedCategory != nullptr && m_pressedCategory == categoryAt(geometryPos, hitResult)) { if (state() == ExpandingState) { m_pressedCategory->collapsed = false; emit groupStateChanged(m_pressedCategory->text, false); @@ -396,7 +396,7 @@ void InstanceView::mouseReleaseEvent(QMouseEvent* event) setState(NoState); - if (click) { + if (index == m_pressedIndex && index.isValid()) { if (event->button() == Qt::LeftButton) { emit clicked(index); } @@ -478,6 +478,38 @@ void InstanceView::paintEvent([[maybe_unused]] QPaintEvent* event) #endif option.widget = this; + if (model()->rowCount() == 0) { + painter.save(); + const QString line1 = tr("Welcome!"); + const QString line2 = tr("Click \"Add Instance\" to get started."); + auto rect = this->viewport()->rect(); + auto font = option.font; + font.setPointSize(37); + painter.setFont(font); + auto fm = painter.fontMetrics(); + + if (rect.height() <= (fm.height() * 5) || rect.width() <= fm.horizontalAdvance(line2)) { + auto s = rect.height() / (5. * fm.height()); + auto sx = rect.width() * 1. / fm.horizontalAdvance(line2); + if (s >= sx) + s = sx; + auto ps = font.pointSize() * s; + if (ps <= 0) + ps = 1; + font.setPointSize(ps); + painter.setFont(font); + fm = painter.fontMetrics(); + } + + // text + rect.setTop(rect.top() + fm.height() * 1.5); + painter.drawText(rect, Qt::AlignHCenter, line1); + rect.setTop(rect.top() + fm.height()); + painter.drawText(rect, Qt::AlignHCenter, line2); + painter.restore(); + return; + } + int wpWidth = viewport()->width(); option.rect.setWidth(wpWidth); for (int i = 0; i < m_groups.size(); ++i) { diff --git a/launcher/ui/pages/BasePage.h b/launcher/ui/pages/BasePage.h index d35206a08..cb3a7633d 100644 --- a/launcher/ui/pages/BasePage.h +++ b/launcher/ui/pages/BasePage.h @@ -77,4 +77,4 @@ class BasePage { bool isOpened = false; }; -typedef std::shared_ptr BasePagePtr; +using BasePagePtr = std::shared_ptr; diff --git a/launcher/ui/pages/BasePageProvider.h b/launcher/ui/pages/BasePageProvider.h index 4c3ecd6c1..422891e6b 100644 --- a/launcher/ui/pages/BasePageProvider.h +++ b/launcher/ui/pages/BasePageProvider.h @@ -26,7 +26,7 @@ class BasePageProvider { }; class GenericPageProvider : public BasePageProvider { - typedef std::function PageCreator; + using PageCreator = std::function; public: explicit GenericPageProvider(const QString& dialogTitle) : m_dialogTitle(dialogTitle) {} diff --git a/launcher/ui/pages/global/AccountListPage.cpp b/launcher/ui/pages/global/AccountListPage.cpp index 50f3ff2b6..2fd8a0402 100644 --- a/launcher/ui/pages/global/AccountListPage.cpp +++ b/launcher/ui/pages/global/AccountListPage.cpp @@ -42,22 +42,17 @@ #include -#include "net/NetJob.h" - #include "ui/dialogs/CustomMessageBox.h" #include "ui/dialogs/MSALoginDialog.h" #include "ui/dialogs/OfflineLoginDialog.h" #include "ui/dialogs/ProgressDialog.h" #include "ui/dialogs/SkinUploadDialog.h" -#include "minecraft/auth/AccountTask.h" #include "minecraft/services/SkinDelete.h" #include "tasks/Task.h" #include "Application.h" -#include "BuildConfig.h" - AccountListPage::AccountListPage(QWidget* parent) : QMainWindow(parent), ui(new Ui::AccountListPage) { ui->setupUi(this); @@ -172,6 +167,12 @@ void AccountListPage::on_actionAddOffline_triggered() void AccountListPage::on_actionRemove_triggered() { + auto response = CustomMessageBox::selectable(this, tr("Remove account?"), tr("Do you really want to delete this account?"), + QMessageBox::Question, QMessageBox::Yes | QMessageBox::No, QMessageBox::No) + ->exec(); + if (response != QMessageBox::Yes) { + return; + } QModelIndexList selection = ui->listView->selectionModel()->selectedIndexes(); if (selection.size() > 0) { QModelIndex selected = selection.first(); @@ -230,6 +231,7 @@ void AccountListPage::updateButtonStates() ui->actionNoDefault->setEnabled(true); ui->actionNoDefault->setChecked(false); } + ui->listView->resizeColumnToContents(3); } void AccountListPage::on_actionUploadSkin_triggered() diff --git a/launcher/ui/pages/global/EnvironmentVariablesPage.cpp b/launcher/ui/pages/global/EnvironmentVariablesPage.cpp new file mode 100644 index 000000000..2d44ed624 --- /dev/null +++ b/launcher/ui/pages/global/EnvironmentVariablesPage.cpp @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: GPL-3.0-only +/* + * Prism Launcher - Minecraft Launcher + * Copyright (C) 2023 TheKodeToad + * + * 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 +#include +#include + +#include "EnvironmentVariablesPage.h" + +EnvironmentVariablesPage::EnvironmentVariablesPage(QWidget* parent) : QWidget(parent) +{ + auto verticalLayout = new QVBoxLayout(this); + verticalLayout->setObjectName(QStringLiteral("verticalLayout")); + verticalLayout->setContentsMargins(0, 0, 0, 0); + + auto tabWidget = new QTabWidget(this); + tabWidget->setObjectName(QStringLiteral("tabWidget")); + variables = new EnvironmentVariables(this); + variables->setContentsMargins(6, 6, 6, 6); + tabWidget->addTab(variables, "Foo"); + tabWidget->tabBar()->hide(); + verticalLayout->addWidget(tabWidget); + + variables->initialize(false, false, APPLICATION->settings()->get("Env").toMap()); +} + +QString EnvironmentVariablesPage::displayName() const +{ + return tr("Environment Variables"); +} + +QIcon EnvironmentVariablesPage::icon() const +{ + return APPLICATION->getThemedIcon("environment-variables"); +} + +QString EnvironmentVariablesPage::id() const +{ + return "environment-variables"; +} + +QString EnvironmentVariablesPage::helpPage() const +{ + return "Environment-variables"; +} + +bool EnvironmentVariablesPage::apply() +{ + APPLICATION->settings()->set("Env", variables->value()); + return true; +} + +void EnvironmentVariablesPage::retranslate() +{ + variables->retranslate(); +} diff --git a/launcher/ui/pages/global/EnvironmentVariablesPage.h b/launcher/ui/pages/global/EnvironmentVariablesPage.h new file mode 100644 index 000000000..6e80775ec --- /dev/null +++ b/launcher/ui/pages/global/EnvironmentVariablesPage.h @@ -0,0 +1,42 @@ +// SPDX-License-Identifier: GPL-3.0-only +/* + * Prism Launcher - Minecraft Launcher + * Copyright (C) 2023 TheKodeToad + * + * 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 "ui/pages/BasePage.h" +#include "ui/widgets/EnvironmentVariables.h" + +class EnvironmentVariablesPage : public QWidget, public BasePage { + Q_OBJECT + + public: + explicit EnvironmentVariablesPage(QWidget* parent = nullptr); + + QString displayName() const override; + QIcon icon() const override; + QString id() const override; + QString helpPage() const override; + + bool apply() override; + void retranslate() override; + + private: + EnvironmentVariables* variables; +}; diff --git a/launcher/ui/pages/global/LauncherPage.cpp b/launcher/ui/pages/global/LauncherPage.cpp index 6d8c65ec5..d15883db5 100644 --- a/launcher/ui/pages/global/LauncherPage.cpp +++ b/launcher/ui/pages/global/LauncherPage.cpp @@ -223,6 +223,7 @@ void LauncherPage::applySettings() // Mods s->set("ModMetadataDisabled", ui->metadataDisableBtn->isChecked()); + s->set("ModDependenciesDisabled", ui->dependenciesDisableBtn->isChecked()); } void LauncherPage::loadSettings() { @@ -278,6 +279,7 @@ void LauncherPage::loadSettings() // Mods ui->metadataDisableBtn->setChecked(s->get("ModMetadataDisabled").toBool()); ui->metadataWarningLabel->setHidden(!ui->metadataDisableBtn->isChecked()); + ui->dependenciesDisableBtn->setChecked(s->get("ModDependenciesDisabled").toBool()); } void LauncherPage::refreshFontPreview() diff --git a/launcher/ui/pages/global/LauncherPage.ui b/launcher/ui/pages/global/LauncherPage.ui index 250a8bc88..83897f7a7 100644 --- a/launcher/ui/pages/global/LauncherPage.ui +++ b/launcher/ui/pages/global/LauncherPage.ui @@ -186,6 +186,16 @@
+ + + + Disable the automatic detection, installation, and updating of mod dependencies. + + + Disable automatic mod dependency management + + + diff --git a/launcher/ui/pages/instance/ExternalResourcesPage.cpp b/launcher/ui/pages/instance/ExternalResourcesPage.cpp index 1a8fafa9b..b04c7250c 100644 --- a/launcher/ui/pages/instance/ExternalResourcesPage.cpp +++ b/launcher/ui/pages/instance/ExternalResourcesPage.cpp @@ -42,6 +42,7 @@ #include "minecraft/mod/ResourceFolderModel.h" #include "ui/GuiUtil.h" +#include #include #include #include @@ -95,7 +96,8 @@ ExternalResourcesPage::ExternalResourcesPage(BaseInstance* instance, std::shared connect(viewHeader, &QHeaderView::customContextMenuRequested, this, &ExternalResourcesPage::ShowHeaderContextMenu); - m_model->loadHiddenColumns(ui->treeView); + m_model->loadColumns(ui->treeView); + connect(ui->treeView->header(), &QHeaderView::sectionResized, this, [this] { m_model->saveColumns(ui->treeView); }); } ExternalResourcesPage::~ExternalResourcesPage() diff --git a/launcher/ui/pages/instance/ExternalResourcesPage.ui b/launcher/ui/pages/instance/ExternalResourcesPage.ui index ba703f77d..ff08e12d2 100644 --- a/launcher/ui/pages/instance/ExternalResourcesPage.ui +++ b/launcher/ui/pages/instance/ExternalResourcesPage.ui @@ -70,6 +70,9 @@ + + true + Actions @@ -146,17 +149,6 @@ Download a new resource - - - false - - - Check for &Updates - - - Try to check or update all selected resources (all resources if none are selected) - - false @@ -168,15 +160,15 @@ Go to mods home page - + - false + true - Remove metadata + Check for &Updates - Remove mod's metadata + Try to check or update all selected resources (all resources if none are selected) diff --git a/launcher/ui/pages/instance/InstanceSettingsPage.cpp b/launcher/ui/pages/instance/InstanceSettingsPage.cpp index c0ced2415..74785f97e 100644 --- a/launcher/ui/pages/instance/InstanceSettingsPage.cpp +++ b/launcher/ui/pages/instance/InstanceSettingsPage.cpp @@ -90,6 +90,9 @@ void InstanceSettingsPage::globalSettingsButtonClicked(bool) case 2: APPLICATION->ShowGlobalSettings(this, "custom-commands"); return; + case 3: + APPLICATION->ShowGlobalSettings(this, "environment-variables"); + return; default: APPLICATION->ShowGlobalSettings(this, "minecraft-settings"); return; @@ -199,6 +202,14 @@ void InstanceSettingsPage::applySettings() m_settings->reset("PostExitCommand"); } + // Environment Variables + auto env = ui->environmentVariables->override(); + m_settings->set("OverrideEnv", env); + if (env) + m_settings->set("Env", ui->environmentVariables->value()); + else + m_settings->reset("Env"); + // Workarounds bool workarounds = ui->nativeWorkaroundsGroupBox->isChecked(); m_settings->set("OverrideNativeWorkarounds", workarounds); @@ -318,6 +329,9 @@ void InstanceSettingsPage::loadSettings() ui->customCommands->initialize(true, m_settings->get("OverrideCommands").toBool(), m_settings->get("PreLaunchCommand").toString(), m_settings->get("WrapperCommand").toString(), m_settings->get("PostExitCommand").toString()); + // Environment variables + ui->environmentVariables->initialize(true, m_settings->get("OverrideEnv").toBool(), m_settings->get("Env").toMap()); + // Workarounds ui->nativeWorkaroundsGroupBox->setChecked(m_settings->get("OverrideNativeWorkarounds").toBool()); ui->useNativeGLFWCheck->setChecked(m_settings->get("UseNativeGLFW").toBool()); @@ -484,6 +498,7 @@ void InstanceSettingsPage::retranslate() { ui->retranslateUi(this); ui->customCommands->retranslate(); // TODO: why is this seperate from the others? + ui->environmentVariables->retranslate(); } void InstanceSettingsPage::updateThresholds() diff --git a/launcher/ui/pages/instance/InstanceSettingsPage.ui b/launcher/ui/pages/instance/InstanceSettingsPage.ui index 8defaccb3..ad348cc0b 100644 --- a/launcher/ui/pages/instance/InstanceSettingsPage.ui +++ b/launcher/ui/pages/instance/InstanceSettingsPage.ui @@ -35,13 +35,10 @@ - - QTabWidget::Rounded - 0 - + Java @@ -254,7 +251,7 @@ - + Game windows @@ -414,7 +411,7 @@ - + Custom commands @@ -424,6 +421,16 @@ + + + Environment variables + + + + + + + Workarounds @@ -736,6 +743,12 @@
ui/widgets/CustomCommands.h
1 + + EnvironmentVariables + QWidget +
ui/widgets/EnvironmentVariables.h
+ 1 +
openGlobalJavaSettingsButton diff --git a/launcher/ui/pages/instance/ModFolderPage.cpp b/launcher/ui/pages/instance/ModFolderPage.cpp index 625d37933..a38e608f2 100644 --- a/launcher/ui/pages/instance/ModFolderPage.cpp +++ b/launcher/ui/pages/instance/ModFolderPage.cpp @@ -84,50 +84,71 @@ ModFolderPage::ModFolderPage(BaseInstance* inst, std::shared_ptr connect(ui->actionDownloadItem, &QAction::triggered, this, &ModFolderPage::installMods); + // update menu + auto updateMenu = ui->actionUpdateItem->menu(); + if (updateMenu) { + updateMenu->clear(); + } else { + updateMenu = new QMenu(this); + } + + auto update = updateMenu->addAction(tr("Check for Updates")); + update->setToolTip(tr("Try to check or update all selected mods (all mods if none are selected)")); + connect(update, &QAction::triggered, this, &ModFolderPage::updateMods); + + auto updateWithDeps = updateMenu->addAction(tr("Verify Dependencies")); + updateWithDeps->setToolTip( + tr("Try to update and check for missing dependencies all selected mods (all mods if none are selected)")); + connect(updateWithDeps, &QAction::triggered, this, [this] { updateMods(true); }); + + auto depsDisabled = APPLICATION->settings()->getSetting("ModDependenciesDisabled"); + updateWithDeps->setVisible(!depsDisabled->get().toBool()); + connect(depsDisabled.get(), &Setting::SettingChanged, this, + [updateWithDeps](const Setting& setting, QVariant value) { updateWithDeps->setVisible(!value.toBool()); }); + + auto actionRemoveItemMetadata = updateMenu->addAction(tr("Reset update metadata")); + actionRemoveItemMetadata->setToolTip(tr("Remove mod's metadata")); + connect(actionRemoveItemMetadata, &QAction::triggered, this, &ModFolderPage::deleteModMetadata); + actionRemoveItemMetadata->setEnabled(false); + + ui->actionUpdateItem->setMenu(updateMenu); + ui->actionUpdateItem->setToolTip(tr("Try to check or update all selected mods (all mods if none are selected)")); - ui->actionsToolbar->insertActionAfter(ui->actionAddItem, ui->actionUpdateItem); connect(ui->actionUpdateItem, &QAction::triggered, this, &ModFolderPage::updateMods); + ui->actionsToolbar->insertActionBefore(ui->actionAddItem, ui->actionUpdateItem); ui->actionVisitItemPage->setToolTip(tr("Go to mod's home page")); ui->actionsToolbar->addAction(ui->actionVisitItemPage); connect(ui->actionVisitItemPage, &QAction::triggered, this, &ModFolderPage::visitModPages); - ui->actionRemoveItemMetadata->setToolTip(tr("Remove mod's metadata")); - ui->actionsToolbar->insertActionAfter(ui->actionRemoveItem, ui->actionRemoveItemMetadata); - connect(ui->actionRemoveItemMetadata, &QAction::triggered, this, &ModFolderPage::deleteModMetadata); - auto check_allow_update = [this] { return ui->treeView->selectionModel()->hasSelection() || !m_model->empty(); }; - connect(ui->treeView->selectionModel(), &QItemSelectionModel::selectionChanged, this, [this, check_allow_update] { - ui->actionUpdateItem->setEnabled(check_allow_update()); + connect(ui->treeView->selectionModel(), &QItemSelectionModel::selectionChanged, this, + [this, check_allow_update, actionRemoveItemMetadata] { + ui->actionUpdateItem->setEnabled(check_allow_update()); - auto selection = m_filterModel->mapSelectionToSource(ui->treeView->selectionModel()->selection()).indexes(); - auto mods_list = m_model->selectedMods(selection); - auto selected = std::count_if(mods_list.cbegin(), mods_list.cend(), - [](Mod* v) { return v->metadata() != nullptr || v->homeurl().size() != 0; }); - if (selected <= 1) { - ui->actionVisitItemPage->setText(tr("Visit mod's page")); - ui->actionVisitItemPage->setToolTip(tr("Go to mod's home page")); + auto selection = m_filterModel->mapSelectionToSource(ui->treeView->selectionModel()->selection()).indexes(); + auto mods_list = m_model->selectedMods(selection); + auto selected = std::count_if(mods_list.cbegin(), mods_list.cend(), + [](Mod* v) { return v->metadata() != nullptr || v->homeurl().size() != 0; }); + if (selected <= 1) { + ui->actionVisitItemPage->setText(tr("Visit mod's page")); + ui->actionVisitItemPage->setToolTip(tr("Go to mod's home page")); - ui->actionRemoveItemMetadata->setToolTip(tr("Remove mod's metadata")); - } else { - ui->actionVisitItemPage->setText(tr("Visit mods' pages")); - ui->actionVisitItemPage->setToolTip(tr("Go to the pages of the selected mods")); + } else { + ui->actionVisitItemPage->setText(tr("Visit mods' pages")); + ui->actionVisitItemPage->setToolTip(tr("Go to the pages of the selected mods")); + } + ui->actionVisitItemPage->setEnabled(selected != 0); + actionRemoveItemMetadata->setEnabled(selected != 0); + }); - ui->actionRemoveItemMetadata->setToolTip(tr("Remove mods' metadata")); - } - ui->actionVisitItemPage->setEnabled(selected != 0); - ui->actionRemoveItemMetadata->setEnabled(selected != 0); - }); + auto updateButtons = [this, check_allow_update] { ui->actionUpdateItem->setEnabled(check_allow_update()); }; + connect(mods.get(), &ModFolderModel::rowsInserted, this, updateButtons); - connect(mods.get(), &ModFolderModel::rowsInserted, this, - [this, check_allow_update] { ui->actionUpdateItem->setEnabled(check_allow_update()); }); + connect(mods.get(), &ModFolderModel::rowsRemoved, this, updateButtons); - connect(mods.get(), &ModFolderModel::rowsRemoved, this, - [this, check_allow_update] { ui->actionUpdateItem->setEnabled(check_allow_update()); }); - - connect(mods.get(), &ModFolderModel::updateFinished, this, - [this, check_allow_update] { ui->actionUpdateItem->setEnabled(check_allow_update()); }); + connect(mods.get(), &ModFolderModel::updateFinished, this, updateButtons); } } @@ -204,7 +225,7 @@ void ModFolderPage::installMods() } } -void ModFolderPage::updateMods() +void ModFolderPage::updateMods(bool includeDeps) { if (m_instance->typeName() != "Minecraft") return; // this is a null instance or a legacy instance @@ -214,6 +235,10 @@ void ModFolderPage::updateMods() QMessageBox::critical(this, tr("Error"), tr("Please install a mod loader first!")); return; } + if (APPLICATION->settings()->get("ModMetadataDisabled").toBool()) { + QMessageBox::critical(this, tr("Error"), tr("Mod updates are unavailable when metadata is disabled!")); + return; + } auto selection = m_filterModel->mapSelectionToSource(ui->treeView->selectionModel()->selection()).indexes(); auto mods_list = m_model->selectedMods(selection); @@ -221,7 +246,7 @@ void ModFolderPage::updateMods() if (use_all) mods_list = m_model->allMods(); - ModUpdateDialog update_dialog(this, m_instance, m_model, mods_list); + ModUpdateDialog update_dialog(this, m_instance, m_model, mods_list, includeDeps); update_dialog.checkCandidates(); if (update_dialog.aborted()) { diff --git a/launcher/ui/pages/instance/ModFolderPage.h b/launcher/ui/pages/instance/ModFolderPage.h index 0c654d0d1..4672350c6 100644 --- a/launcher/ui/pages/instance/ModFolderPage.h +++ b/launcher/ui/pages/instance/ModFolderPage.h @@ -64,7 +64,7 @@ class ModFolderPage : public ExternalResourcesPage { void deleteModMetadata(); void installMods(); - void updateMods(); + void updateMods(bool includeDeps = false); void visitModPages(); protected: diff --git a/launcher/ui/pages/instance/ScreenshotsPage.cpp b/launcher/ui/pages/instance/ScreenshotsPage.cpp index 29c835fc1..83fb0d5ff 100644 --- a/launcher/ui/pages/instance/ScreenshotsPage.cpp +++ b/launcher/ui/pages/instance/ScreenshotsPage.cpp @@ -68,8 +68,8 @@ #include #include "RWStorage.h" -typedef RWStorage SharedIconCache; -typedef std::shared_ptr SharedIconCachePtr; +using SharedIconCache = RWStorage; +using SharedIconCachePtr = std::shared_ptr; class ThumbnailingResult : public QObject { Q_OBJECT @@ -383,20 +383,31 @@ void ScreenshotsPage::on_actionUpload_triggered() QList uploaded; auto job = NetJob::Ptr(new NetJob("Screenshot Upload", APPLICATION->network())); + + ProgressDialog dialog(this); + dialog.setSkipButton(true, tr("Abort")); + if (selection.size() < 2) { auto item = selection.at(0); auto info = m_model->fileInfo(item); auto screenshot = std::make_shared(info); job->addNetAction(ImgurUpload::make(screenshot)); - m_uploadActive = true; - ProgressDialog dialog(this); + connect(job.get(), &Task::failed, [this](QString reason) { + CustomMessageBox::selectable(this, tr("Failed to upload screenshots!"), reason, QMessageBox::Critical)->show(); + }); + connect(job.get(), &Task::aborted, [this] { + CustomMessageBox::selectable(this, tr("Screenshots upload aborted"), tr("The task has been aborted by the user."), + QMessageBox::Information) + ->show(); + }); - if (dialog.execWithTask(job.get()) != QDialog::Accepted) { - CustomMessageBox::selectable(this, tr("Failed to upload screenshots!"), tr("Unknown error"), QMessageBox::Warning)->exec(); - } else { + m_uploadActive = true; + + if (dialog.execWithTask(job.get()) == QDialog::Accepted) { auto link = screenshot->m_url; QClipboard* clipboard = QApplication::clipboard(); + qDebug() << "ImgurUpload link" << link; clipboard->setText(link); CustomMessageBox::selectable( this, tr("Upload finished"), @@ -417,22 +428,36 @@ void ScreenshotsPage::on_actionUpload_triggered() } SequentialTask task; auto albumTask = NetJob::Ptr(new NetJob("Imgur Album Creation", APPLICATION->network())); - auto imgurAlbum = ImgurAlbumCreation::make(uploaded); + auto imgurResult = std::make_shared(); + auto imgurAlbum = ImgurAlbumCreation::make(imgurResult, uploaded); albumTask->addNetAction(imgurAlbum); task.addTask(job); task.addTask(albumTask); - m_uploadActive = true; - ProgressDialog prog(this); - if (prog.execWithTask(&task) != QDialog::Accepted) { - CustomMessageBox::selectable(this, tr("Failed to upload screenshots!"), tr("Unknown error"), QMessageBox::Warning)->exec(); - } else { - auto link = QString("https://imgur.com/a/%1").arg(imgurAlbum->id()); - QClipboard* clipboard = QApplication::clipboard(); - clipboard->setText(link); - CustomMessageBox::selectable(this, tr("Upload finished"), - tr("The link to the uploaded album has been placed in your clipboard.").arg(link), + + connect(&task, &Task::failed, [this](QString reason) { + CustomMessageBox::selectable(this, tr("Failed to upload screenshots!"), reason, QMessageBox::Critical)->show(); + }); + connect(&task, &Task::aborted, [this] { + CustomMessageBox::selectable(this, tr("Screenshots upload aborted"), tr("The task has been aborted by the user."), QMessageBox::Information) - ->exec(); + ->show(); + }); + + m_uploadActive = true; + if (dialog.execWithTask(&task) == QDialog::Accepted) { + if (imgurResult->id.isEmpty()) { + CustomMessageBox::selectable(this, tr("Failed to upload screenshots!"), tr("Unknown error"), QMessageBox::Warning)->exec(); + } else { + auto link = QString("https://imgur.com/a/%1").arg(imgurResult->id); + qDebug() << "ImgurUpload link" << link; + QClipboard* clipboard = QApplication::clipboard(); + clipboard->setText(link); + CustomMessageBox::selectable( + this, tr("Upload finished"), + tr("The link to the uploaded album has been placed in your clipboard.").arg(link), + QMessageBox::Information) + ->exec(); + } } m_uploadActive = false; } diff --git a/launcher/ui/pages/modplatform/atlauncher/AtlListModel.h b/launcher/ui/pages/modplatform/atlauncher/AtlListModel.h index ed1fdc9f9..bcadd7c91 100644 --- a/launcher/ui/pages/modplatform/atlauncher/AtlListModel.h +++ b/launcher/ui/pages/modplatform/atlauncher/AtlListModel.h @@ -24,8 +24,8 @@ namespace Atl { -typedef QMap LogoMap; -typedef std::function LogoCallback; +using LogoMap = QMap; +using LogoCallback = std::function; class ListModel : public QAbstractListModel { Q_OBJECT diff --git a/launcher/ui/pages/modplatform/flame/FlameModel.h b/launcher/ui/pages/modplatform/flame/FlameModel.h index fd8496dfb..5a07ef6bb 100644 --- a/launcher/ui/pages/modplatform/flame/FlameModel.h +++ b/launcher/ui/pages/modplatform/flame/FlameModel.h @@ -19,8 +19,8 @@ namespace Flame { -typedef QMap LogoMap; -typedef std::function LogoCallback; +using LogoMap = QMap; +using LogoCallback = std::function; class ListModel : public QAbstractListModel { Q_OBJECT diff --git a/launcher/ui/pages/modplatform/import_ftb/ImportFTBPage.cpp b/launcher/ui/pages/modplatform/import_ftb/ImportFTBPage.cpp index 43ff1c0fe..d46f16b4d 100644 --- a/launcher/ui/pages/modplatform/import_ftb/ImportFTBPage.cpp +++ b/launcher/ui/pages/modplatform/import_ftb/ImportFTBPage.cpp @@ -90,7 +90,7 @@ void ImportFTBPage::suggestCurrent() } dialog->setSuggestedPack(selected.name, new PackInstallTask(selected)); - QString editedLogoName = QString("ftb_%1_%2,jpg").arg(selected.name, selected.id); + QString editedLogoName = QString("ftb_%1_%2.jpg").arg(selected.name, QString::number(selected.id)); dialog->setSuggestedIconFromFile(FS::PathCombine(selected.path, "folder.jpg"), editedLogoName); } diff --git a/launcher/ui/pages/modplatform/legacy_ftb/ListModel.h b/launcher/ui/pages/modplatform/legacy_ftb/ListModel.h index c802a4b56..f35012078 100644 --- a/launcher/ui/pages/modplatform/legacy_ftb/ListModel.h +++ b/launcher/ui/pages/modplatform/legacy_ftb/ListModel.h @@ -13,8 +13,8 @@ namespace LegacyFTB { -typedef QMap FTBLogoMap; -typedef std::function LogoCallback; +using FTBLogoMap = QMap; +using LogoCallback = std::function; class FilterModel : public QSortFilterProxyModel { Q_OBJECT diff --git a/launcher/ui/pages/modplatform/technic/TechnicModel.h b/launcher/ui/pages/modplatform/technic/TechnicModel.h index aeb4f3084..09e9294bb 100644 --- a/launcher/ui/pages/modplatform/technic/TechnicModel.h +++ b/launcher/ui/pages/modplatform/technic/TechnicModel.h @@ -42,7 +42,7 @@ namespace Technic { -typedef std::function LogoCallback; +using LogoCallback = std::function; class ListModel : public QAbstractListModel { Q_OBJECT diff --git a/launcher/ui/setupwizard/JavaWizardPage.cpp b/launcher/ui/setupwizard/JavaWizardPage.cpp index e2c444373..abe4860da 100644 --- a/launcher/ui/setupwizard/JavaWizardPage.cpp +++ b/launcher/ui/setupwizard/JavaWizardPage.cpp @@ -64,8 +64,7 @@ bool JavaWizardPage::validatePage() } case JavaSettingsWidget::ValidationStatus::AllOK: { settings->set("JavaPath", m_java_widget->javaPath()); - return true; - } + } /* fallthrough */ case JavaSettingsWidget::ValidationStatus::JavaBad: { // Memory auto s = APPLICATION->settings(); diff --git a/launcher/ui/themes/CustomTheme.cpp b/launcher/ui/themes/CustomTheme.cpp index 29ecf6254..4859983c6 100644 --- a/launcher/ui/themes/CustomTheme.cpp +++ b/launcher/ui/themes/CustomTheme.cpp @@ -165,11 +165,15 @@ CustomTheme::CustomTheme(ITheme* baseTheme, QFileInfo& fileInfo, bool isManifest QString path = FS::PathCombine("themes", m_id); QString pathResources = FS::PathCombine("themes", m_id, "resources"); - if (!FS::ensureFolderPathExists(path) || !FS::ensureFolderPathExists(pathResources)) { - themeWarningLog() << "couldn't create folder for theme!"; + if (!FS::ensureFolderPathExists(path)) { + themeWarningLog() << "Theme directory for" << m_id << "could not be created. This theme might be invalid"; return; } + if (!FS::ensureFolderPathExists(pathResources)) { + themeWarningLog() << "Resources directory for" << m_id << "could not be created"; + } + auto themeFilePath = FS::PathCombine(path, themeFile); bool jsonDataIncomplete = false; @@ -230,7 +234,11 @@ CustomTheme::CustomTheme(ITheme* baseTheme, QFileInfo& fileInfo, bool isManifest QStringList CustomTheme::searchPaths() { - return { FS::PathCombine("themes", m_id, "resources") }; + QString pathResources = FS::PathCombine("themes", m_id, "resources"); + if (QFileInfo::exists(pathResources)) + return { pathResources }; + + return {}; } QString CustomTheme::id() diff --git a/launcher/ui/widgets/EnvironmentVariables.cpp b/launcher/ui/widgets/EnvironmentVariables.cpp new file mode 100644 index 000000000..633fc6122 --- /dev/null +++ b/launcher/ui/widgets/EnvironmentVariables.cpp @@ -0,0 +1,110 @@ +// SPDX-License-Identifier: GPL-3.0-only +/* + * Prism Launcher - Minecraft Launcher + * Copyright (C) 2023 TheKodeToad + * + * 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 + +#include "Application.h" +#include "EnvironmentVariables.h" +#include "ui/dialogs/CustomMessageBox.h" +#include "ui_EnvironmentVariables.h" + +EnvironmentVariables::EnvironmentVariables(QWidget* parent) : QWidget(parent), ui(new Ui::EnvironmentVariables) +{ + ui->setupUi(this); + ui->list->installEventFilter(this); + + ui->list->sortItems(0, Qt::AscendingOrder); + ui->list->setSortingEnabled(true); + ui->list->header()->resizeSections(QHeaderView::Interactive); + ui->list->header()->resizeSection(0, 200); + + connect(ui->add, &QPushButton::clicked, this, [this] { + auto item = new QTreeWidgetItem(ui->list); + item->setText(0, "ENV_VAR"); + item->setText(1, "value"); + item->setFlags(item->flags() | Qt::ItemIsEditable); + ui->list->addTopLevelItem(item); + ui->list->selectionModel()->select(ui->list->model()->index(ui->list->indexOfTopLevelItem(item), 0), + QItemSelectionModel::ClearAndSelect | QItemSelectionModel::SelectionFlag::Rows); + ui->list->editItem(item); + }); + + connect(ui->remove, &QPushButton::clicked, this, [this] { + for (QTreeWidgetItem* item : ui->list->selectedItems()) + ui->list->takeTopLevelItem(ui->list->indexOfTopLevelItem(item)); + }); + + connect(ui->clear, &QPushButton::clicked, this, [this] { ui->list->clear(); }); +} + +EnvironmentVariables::~EnvironmentVariables() +{ + delete ui; +} + +void EnvironmentVariables::initialize(bool instance, bool override, const QMap& value) +{ + // update widgets to settings + ui->groupBox->setCheckable(instance); + ui->groupBox->setChecked(override); + + // populate + ui->list->clear(); + for (auto iter = value.begin(); iter != value.end(); iter++) { + auto item = new QTreeWidgetItem(ui->list); + item->setText(0, iter.key()); + item->setText(1, iter.value().toString()); + item->setFlags(item->flags() | Qt::ItemIsEditable); + ui->list->addTopLevelItem(item); + } +} + +bool EnvironmentVariables::eventFilter(QObject* watched, QEvent* event) +{ + if (watched == ui->list && event->type() == QEvent::KeyPress) { + const QKeyEvent* keyEvent = (QKeyEvent*)event; + if (keyEvent->key() == Qt::Key_Delete) { + emit ui->remove->clicked(); + return true; + } + } + + return QObject::eventFilter(watched, event); +} + +void EnvironmentVariables::retranslate() +{ + ui->retranslateUi(this); +} + +bool EnvironmentVariables::override() const +{ + if (!ui->groupBox->isCheckable()) + return false; + return ui->groupBox->isChecked(); +} + +QMap EnvironmentVariables::value() const +{ + QMap result; + QTreeWidgetItem* item = ui->list->topLevelItem(0); + for (int i = 1; item != nullptr; item = ui->list->topLevelItem(i++)) + result[item->text(0)] = item->text(1); + + return result; +} diff --git a/launcher/ui/widgets/EnvironmentVariables.h b/launcher/ui/widgets/EnvironmentVariables.h new file mode 100644 index 000000000..092d586bd --- /dev/null +++ b/launcher/ui/widgets/EnvironmentVariables.h @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: GPL-3.0-only +/* + * Prism Launcher - Minecraft Launcher + * Copyright (C) 2023 TheKodeToad + * + * 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 + +namespace Ui { +class EnvironmentVariables; +} + +class EnvironmentVariables : public QWidget { + Q_OBJECT + + public: + explicit EnvironmentVariables(QWidget* state = nullptr); + ~EnvironmentVariables() override; + void initialize(bool instance, bool override, const QMap& value); + bool eventFilter(QObject* watched, QEvent* event) override; + + void retranslate(); + bool override() const; + QMap value() const; + + private: + Ui::EnvironmentVariables* ui; +}; diff --git a/launcher/ui/widgets/EnvironmentVariables.ui b/launcher/ui/widgets/EnvironmentVariables.ui new file mode 100644 index 000000000..ded5b2ded --- /dev/null +++ b/launcher/ui/widgets/EnvironmentVariables.ui @@ -0,0 +1,115 @@ + + + EnvironmentVariables + + + + 0 + 0 + 565 + 410 + + + + Form + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + &Environment Variables + + + true + + + + + + true + + + QAbstractItemView::ExtendedSelection + + + false + + + false + + + true + + + false + + + + Name + + + + + Value + + + + + + + + + + &Add + + + + + + + &Remove + + + + + + + &Clear + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + + + diff --git a/launcher/ui/widgets/ModListView.cpp b/launcher/ui/widgets/ModListView.cpp index c72d4c522..a38c7c86a 100644 --- a/launcher/ui/widgets/ModListView.cpp +++ b/launcher/ui/widgets/ModListView.cpp @@ -48,14 +48,14 @@ void ModListView::setModel(QAbstractItemModel* model) return; } if (!string.size()) { - head->setSectionResizeMode(0, QHeaderView::ResizeToContents); + head->setSectionResizeMode(0, QHeaderView::Interactive); head->setSectionResizeMode(1, QHeaderView::Stretch); for (int i = 2; i < head->count(); i++) - head->setSectionResizeMode(i, QHeaderView::ResizeToContents); + head->setSectionResizeMode(i, QHeaderView::Interactive); } else { head->setSectionResizeMode(0, QHeaderView::Stretch); for (int i = 1; i < head->count(); i++) - head->setSectionResizeMode(i, QHeaderView::ResizeToContents); + head->setSectionResizeMode(i, QHeaderView::Interactive); } } diff --git a/libraries/.clang-tidy b/libraries/.clang-tidy new file mode 100644 index 000000000..358b093b9 --- /dev/null +++ b/libraries/.clang-tidy @@ -0,0 +1,2 @@ +# We don't care about linting third-party code. +Checks: -* diff --git a/libraries/launcher/org/prismlauncher/EntryPoint.java b/libraries/launcher/org/prismlauncher/EntryPoint.java index 3ef161b40..699adfe30 100644 --- a/libraries/launcher/org/prismlauncher/EntryPoint.java +++ b/libraries/launcher/org/prismlauncher/EntryPoint.java @@ -105,13 +105,16 @@ public final class EntryPoint { return ExitCode.ABORT; } + setProperties(params); + + String launcherType = params.getString("launcher"); + try { LegacyProxy.applyOnlineFixes(params); Launcher launcher; - String type = params.getString("launcher"); - switch (type) { + switch (launcherType) { case "standard": launcher = new StandardLauncher(params); break; @@ -121,7 +124,7 @@ public final class EntryPoint { break; default: - throw new IllegalArgumentException("Invalid launcher type: " + type); + throw new IllegalArgumentException("Invalid launcher type: " + launcherType); } launcher.launch(); @@ -138,6 +141,39 @@ public final class EntryPoint { } } + private static void setProperties(Parameters params) { + String launcherBrand = params.getString("launcherBrand", null); + String launcherVersion = params.getString("launcherVersion", null); + String name = params.getString("instanceName", null); + String iconId = params.getString("instanceIconKey", null); + String iconPath = params.getString("instanceIconPath", null); + String windowTitle = params.getString("windowTitle", null); + String windowDimensions = params.getString("windowParams", null); + + if (launcherBrand != null) + System.setProperty("minecraft.launcher.brand", launcherBrand); + if (launcherVersion != null) + System.setProperty("minecraft.launcher.version", launcherVersion); + + // set useful properties for mods + if (name != null) + System.setProperty("org.prismlauncher.instance.name", name); + if (iconId != null) + System.setProperty("org.prismlauncher.instance.icon.id", iconId); + if (iconPath != null) + System.setProperty("org.prismlauncher.instance.icon.path", iconPath); + if (windowTitle != null) + System.setProperty("org.prismlauncher.window.title", windowTitle); + if (windowDimensions != null) + System.setProperty("org.prismlauncher.window.dimensions", windowDimensions); + + // set multimc properties for compatibility + if (name != null) + System.setProperty("multimc.instance.title", name); + if (iconId != null) + System.setProperty("multimc.instance.icon", iconId); + } + private static PreLaunchAction parseLine(String input, Parameters params) throws ParseException { switch (input) { case "": diff --git a/libraries/launcher/org/prismlauncher/launcher/impl/AbstractLauncher.java b/libraries/launcher/org/prismlauncher/launcher/impl/AbstractLauncher.java index 761837041..de28a0401 100644 --- a/libraries/launcher/org/prismlauncher/launcher/impl/AbstractLauncher.java +++ b/libraries/launcher/org/prismlauncher/launcher/impl/AbstractLauncher.java @@ -83,7 +83,7 @@ public abstract class AbstractLauncher implements Launcher { String windowParams = params.getString("windowParams", null); - if ("max".equals(windowParams) || windowParams == null) { + if ("maximized".equals(windowParams) || windowParams == null) { maximize = windowParams != null; width = DEFAULT_WINDOW_WIDTH; diff --git a/program_info/prismlauncher.manifest.in b/program_info/prismlauncher.manifest.in index 6f4467c7d..fb28afc17 100644 --- a/program_info/prismlauncher.manifest.in +++ b/program_info/prismlauncher.manifest.in @@ -16,12 +16,6 @@ Custom Minecraft launcher for managing multiple installs. - - - - - -