Merge branch 'develop' into skinfix
Signed-off-by: TheKodeToad <TheKodeToad@proton.me>
This commit is contained in:
commit
c37e1fb9f1
8
.editorconfig
Normal file
8
.editorconfig
Normal file
@ -0,0 +1,8 @@
|
||||
# EditorConfig specs and documentation: https://EditorConfig.org
|
||||
|
||||
# top-most EditorConfig file
|
||||
root = true
|
||||
|
||||
# C++ Code Style settings
|
||||
[*.{c++,cc,cpp,cppm,cxx,h,h++,hh,hpp,hxx,inl,ipp,ixx,tlh,tli}]
|
||||
cpp_generate_documentation_comments = doxygen_slash_star
|
4
.git-blame-ignore-revs
Normal file
4
.git-blame-ignore-revs
Normal file
@ -0,0 +1,4 @@
|
||||
# .git-blame-ignore-revs
|
||||
|
||||
# tabs -> spaces
|
||||
bbb3b3e6f6e3c0f95873f22e6d0a4aaf350f49d9
|
32
.github/workflows/backport.yml
vendored
Normal file
32
.github/workflows/backport.yml
vendored
Normal file
@ -0,0 +1,32 @@
|
||||
name: Backport
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [closed, labeled]
|
||||
|
||||
# WARNING:
|
||||
# When extending this action, be aware that $GITHUB_TOKEN allows write access to
|
||||
# the GitHub repository. This means that it should not evaluate user input in a
|
||||
# way that allows code injection.
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
backport:
|
||||
permissions:
|
||||
contents: write # for korthout/backport-action to create branch
|
||||
pull-requests: write # for korthout/backport-action to create PR to backport
|
||||
name: Backport Pull Request
|
||||
if: github.repository_owner == 'PrismLauncher' && github.event.pull_request.merged == true && (github.event_name != 'labeled' || startsWith('backport', github.event.label.name))
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
- name: Create backport PRs
|
||||
uses: korthout/backport-action@v1.3.1
|
||||
with:
|
||||
# Config README: https://github.com/korthout/backport-action#backport-action
|
||||
pull_description: |-
|
||||
Bot-based backport to `${target_branch}`, triggered by a label in #${pull_number}.
|
||||
|
21
.github/workflows/build.yml
vendored
21
.github/workflows/build.yml
vendored
@ -191,7 +191,7 @@ jobs:
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
sudo apt-get -y update
|
||||
sudo apt-get -y install ninja-build extra-cmake-modules scdoc
|
||||
sudo apt-get -y install ninja-build extra-cmake-modules scdoc appstream
|
||||
|
||||
- name: Install Dependencies (macOS)
|
||||
if: runner.os == 'macOS'
|
||||
@ -250,6 +250,7 @@ jobs:
|
||||
wget "https://github.com/linuxdeploy/linuxdeploy-plugin-qt/releases/download/continuous/linuxdeploy-plugin-qt-x86_64.AppImage"
|
||||
|
||||
${{ github.workspace }}/.github/scripts/prepare_JREs.sh
|
||||
sudo apt install libopengl0
|
||||
|
||||
- name: Add QT_HOST_PATH var (Windows MSVC arm64)
|
||||
if: runner.os == 'Windows' && matrix.architecture == 'arm64'
|
||||
@ -263,23 +264,23 @@ jobs:
|
||||
- name: Configure CMake (macOS)
|
||||
if: runner.os == 'macOS' && matrix.qt_ver == 6
|
||||
run: |
|
||||
cmake -S . -B ${{ env.BUILD_DIR }} -DCMAKE_INSTALL_PREFIX=${{ env.INSTALL_DIR }} -DCMAKE_BUILD_TYPE=${{ inputs.build_type }} -DENABLE_LTO=ON -DLauncher_BUILD_PLATFORM=${{ matrix.name }} -DCMAKE_C_COMPILER_LAUNCHER=${{ env.CCACHE_VAR }} -DCMAKE_CXX_COMPILER_LAUNCHER=${{ env.CCACHE_VAR }} -DLauncher_QT_VERSION_MAJOR=${{ matrix.qt_ver }} -DCMAKE_OSX_ARCHITECTURES="x86_64;arm64" -G Ninja
|
||||
cmake -S . -B ${{ env.BUILD_DIR }} -DCMAKE_INSTALL_PREFIX=${{ env.INSTALL_DIR }} -DCMAKE_BUILD_TYPE=${{ inputs.build_type }} -DENABLE_LTO=ON -DLauncher_BUILD_PLATFORM=official -DCMAKE_C_COMPILER_LAUNCHER=${{ env.CCACHE_VAR }} -DCMAKE_CXX_COMPILER_LAUNCHER=${{ env.CCACHE_VAR }} -DLauncher_QT_VERSION_MAJOR=${{ matrix.qt_ver }} -DCMAKE_OSX_ARCHITECTURES="x86_64;arm64" -G Ninja
|
||||
|
||||
- name: Configure CMake (macOS-Legacy)
|
||||
if: runner.os == 'macOS' && matrix.qt_ver == 5
|
||||
run: |
|
||||
cmake -S . -B ${{ env.BUILD_DIR }} -DCMAKE_INSTALL_PREFIX=${{ env.INSTALL_DIR }} -DCMAKE_BUILD_TYPE=${{ inputs.build_type }} -DENABLE_LTO=ON -DLauncher_BUILD_PLATFORM=${{ matrix.name }} -DCMAKE_C_COMPILER_LAUNCHER=${{ env.CCACHE_VAR }} -DCMAKE_CXX_COMPILER_LAUNCHER=${{ env.CCACHE_VAR }} -DLauncher_QT_VERSION_MAJOR=${{ matrix.qt_ver }} -DMACOSX_SPARKLE_UPDATE_PUBLIC_KEY="" -DMACOSX_SPARKLE_UPDATE_FEED_URL="" -G Ninja
|
||||
cmake -S . -B ${{ env.BUILD_DIR }} -DCMAKE_INSTALL_PREFIX=${{ env.INSTALL_DIR }} -DCMAKE_BUILD_TYPE=${{ inputs.build_type }} -DENABLE_LTO=ON -DLauncher_BUILD_PLATFORM=official -DCMAKE_C_COMPILER_LAUNCHER=${{ env.CCACHE_VAR }} -DCMAKE_CXX_COMPILER_LAUNCHER=${{ env.CCACHE_VAR }} -DLauncher_QT_VERSION_MAJOR=${{ matrix.qt_ver }} -DMACOSX_SPARKLE_UPDATE_PUBLIC_KEY="" -DMACOSX_SPARKLE_UPDATE_FEED_URL="" -G Ninja
|
||||
|
||||
- name: Configure CMake (Windows MinGW-w64)
|
||||
if: runner.os == 'Windows' && matrix.msystem != ''
|
||||
shell: msys2 {0}
|
||||
run: |
|
||||
cmake -S . -B ${{ env.BUILD_DIR }} -DCMAKE_INSTALL_PREFIX=${{ env.INSTALL_DIR }} -DCMAKE_BUILD_TYPE=${{ inputs.build_type }} -DENABLE_LTO=ON -DLauncher_BUILD_PLATFORM=${{ matrix.name }} -DCMAKE_C_COMPILER_LAUNCHER=${{ env.CCACHE_VAR }} -DCMAKE_CXX_COMPILER_LAUNCHER=${{ env.CCACHE_VAR }} -DLauncher_QT_VERSION_MAJOR=6 -DCMAKE_OBJDUMP=/mingw64/bin/objdump.exe -G Ninja
|
||||
cmake -S . -B ${{ env.BUILD_DIR }} -DCMAKE_INSTALL_PREFIX=${{ env.INSTALL_DIR }} -DCMAKE_BUILD_TYPE=${{ inputs.build_type }} -DENABLE_LTO=ON -DLauncher_BUILD_PLATFORM=official -DCMAKE_C_COMPILER_LAUNCHER=${{ env.CCACHE_VAR }} -DCMAKE_CXX_COMPILER_LAUNCHER=${{ env.CCACHE_VAR }} -DLauncher_QT_VERSION_MAJOR=6 -DCMAKE_OBJDUMP=/mingw64/bin/objdump.exe -G Ninja
|
||||
|
||||
- name: Configure CMake (Windows MSVC)
|
||||
if: runner.os == 'Windows' && matrix.msystem == ''
|
||||
run: |
|
||||
cmake -S . -B ${{ env.BUILD_DIR }} -DCMAKE_INSTALL_PREFIX=${{ env.INSTALL_DIR }} -DCMAKE_BUILD_TYPE=${{ inputs.build_type }} -DENABLE_LTO=ON -DLauncher_BUILD_PLATFORM=${{ matrix.name }} -DLauncher_QT_VERSION_MAJOR=${{ matrix.qt_ver }} -DCMAKE_MSVC_RUNTIME_LIBRARY="MultiThreadedDLL" -A${{ matrix.architecture}} -DLauncher_FORCE_BUNDLED_LIBS=ON
|
||||
cmake -S . -B ${{ env.BUILD_DIR }} -DCMAKE_INSTALL_PREFIX=${{ env.INSTALL_DIR }} -DCMAKE_BUILD_TYPE=${{ inputs.build_type }} -DENABLE_LTO=ON -DLauncher_BUILD_PLATFORM=official -DLauncher_QT_VERSION_MAJOR=${{ matrix.qt_ver }} -DCMAKE_MSVC_RUNTIME_LIBRARY="MultiThreadedDLL" -A${{ matrix.architecture}} -DLauncher_FORCE_BUNDLED_LIBS=ON
|
||||
# https://github.com/ccache/ccache/wiki/MS-Visual-Studio (I coudn't figure out the compiler prefix)
|
||||
if ("${{ env.CCACHE_VAR }}")
|
||||
{
|
||||
@ -294,7 +295,7 @@ jobs:
|
||||
- name: Configure CMake (Linux)
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
cmake -S . -B ${{ env.BUILD_DIR }} -DCMAKE_INSTALL_PREFIX=/usr -DCMAKE_BUILD_TYPE=${{ inputs.build_type }} -DENABLE_LTO=ON -DLauncher_BUILD_PLATFORM=Linux -DCMAKE_C_COMPILER_LAUNCHER=${{ env.CCACHE_VAR }} -DCMAKE_CXX_COMPILER_LAUNCHER=${{ env.CCACHE_VAR }} -DLauncher_QT_VERSION_MAJOR=${{ matrix.qt_ver }} -G Ninja
|
||||
cmake -S . -B ${{ env.BUILD_DIR }} -DCMAKE_INSTALL_PREFIX=/usr -DCMAKE_BUILD_TYPE=${{ inputs.build_type }} -DENABLE_LTO=ON -DLauncher_BUILD_PLATFORM=official -DCMAKE_C_COMPILER_LAUNCHER=${{ env.CCACHE_VAR }} -DCMAKE_CXX_COMPILER_LAUNCHER=${{ env.CCACHE_VAR }} -DLauncher_QT_VERSION_MAJOR=${{ matrix.qt_ver }} -G Ninja
|
||||
|
||||
##
|
||||
# BUILD
|
||||
@ -467,7 +468,8 @@ jobs:
|
||||
shell: bash
|
||||
run: |
|
||||
cmake --install ${{ env.BUILD_DIR }} --prefix ${{ env.INSTALL_APPIMAGE_DIR }}/usr
|
||||
|
||||
mv ${{ env.INSTALL_APPIMAGE_DIR }}/usr/share/metainfo/org.prismlauncher.PrismLauncher.metainfo.xml ${{ env.INSTALL_APPIMAGE_DIR }}/usr/share/metainfo/org.prismlauncher.PrismLauncher.appdata.xml
|
||||
export "NO_APPSTREAM=1" # we have to skip appstream checking because appstream on ubuntu 20.04 is outdated
|
||||
export OUTPUT="PrismLauncher-${{ runner.os }}-${{ env.VERSION }}-${{ inputs.build_type }}-x86_64.AppImage"
|
||||
|
||||
chmod +x linuxdeploy-*.AppImage
|
||||
@ -482,7 +484,8 @@ jobs:
|
||||
cp -r /home/runner/work/PrismLauncher/Qt/${{ matrix.qt_version }}/gcc_64/plugins/iconengines/* ${{ env.INSTALL_APPIMAGE_DIR }}/usr/plugins/iconengines
|
||||
|
||||
cp /usr/lib/x86_64-linux-gnu/libcrypto.so.1.1 ${{ env.INSTALL_APPIMAGE_DIR }}/usr/lib/
|
||||
cp /usr/lib/x86_64-linux-gnu/libssl.so.1.1 ${{ env.INSTALL_APPIMAGE_DIR }}//usr/lib/
|
||||
cp /usr/lib/x86_64-linux-gnu/libssl.so.1.1 ${{ env.INSTALL_APPIMAGE_DIR }}/usr/lib/
|
||||
cp /usr/lib/x86_64-linux-gnu/libOpenGL.so.0* ${{ env.INSTALL_APPIMAGE_DIR }}/usr/lib/
|
||||
|
||||
LD_LIBRARY_PATH="${LD_LIBRARY_PATH}:${{ env.INSTALL_APPIMAGE_DIR }}/usr/lib"
|
||||
LD_LIBRARY_PATH="${LD_LIBRARY_PATH}:${{ env.INSTALL_APPIMAGE_DIR }}/usr/lib/jvm/java-8-openjdk/lib/amd64/server"
|
||||
@ -599,7 +602,7 @@ jobs:
|
||||
submodules: 'true'
|
||||
- name: Install nix
|
||||
if: inputs.build_type == 'Debug'
|
||||
uses: cachix/install-nix-action@v21
|
||||
uses: cachix/install-nix-action@v22
|
||||
with:
|
||||
install_url: https://nixos.org/nix/install
|
||||
extra_nix_config: |
|
||||
|
2
.github/workflows/trigger_release.yml
vendored
2
.github/workflows/trigger_release.yml
vendored
@ -47,7 +47,7 @@ jobs:
|
||||
mv PrismLauncher-macOS-Legacy*/PrismLauncher.tar.gz PrismLauncher-macOS-Legacy-${{ env.VERSION }}.tar.gz
|
||||
mv PrismLauncher-macOS*/PrismLauncher.tar.gz PrismLauncher-macOS-${{ env.VERSION }}.tar.gz
|
||||
|
||||
tar -czf PrismLauncher-${{ env.VERSION }}.tar.gz PrismLauncher-${{ env.VERSION }}
|
||||
tar --exclude='.git' -czf PrismLauncher-${{ env.VERSION }}.tar.gz PrismLauncher-${{ env.VERSION }}
|
||||
|
||||
for d in PrismLauncher-Windows-MSVC*; do
|
||||
cd "${d}" || continue
|
||||
|
28
.github/workflows/update-flake.yml
vendored
Normal file
28
.github/workflows/update-flake.yml
vendored
Normal file
@ -0,0 +1,28 @@
|
||||
name: Update Flake Lockfile
|
||||
|
||||
on:
|
||||
schedule:
|
||||
# run weekly on sunday
|
||||
- cron: "0 0 * * 0"
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
update-flake:
|
||||
if: github.repository == 'PrismLauncher/PrismLauncher'
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: cachix/install-nix-action@v22
|
||||
|
||||
- uses: DeterminateSystems/update-flake-lock@v19
|
||||
with:
|
||||
commit-msg: "chore(nix): update lockfile"
|
||||
pr-title: "chore(nix): update lockfile"
|
||||
pr-labels: |
|
||||
Linux
|
||||
simple change
|
3
.gitmodules
vendored
3
.gitmodules
vendored
@ -19,3 +19,6 @@
|
||||
[submodule "libraries/cmark"]
|
||||
path = libraries/cmark
|
||||
url = https://github.com/commonmark/cmark.git
|
||||
[submodule "flatpak/shared-modules"]
|
||||
path = flatpak/shared-modules
|
||||
url = https://github.com/flathub/shared-modules.git
|
||||
|
@ -85,6 +85,38 @@ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DTOML_ENABLE_FLOAT16=0")
|
||||
# set CXXFLAGS for build targets
|
||||
set(CMAKE_CXX_FLAGS_RELEASE "-O2 -D_FORTIFY_SOURCE=2 ${CMAKE_CXX_FLAGS_RELEASE}")
|
||||
|
||||
option(DEBUG_ADDRESS_SANITIZER "Enable Address Sanitizer in Debug builds" on)
|
||||
|
||||
# If this is a Debug build turn on address sanitiser
|
||||
if (CMAKE_BUILD_TYPE STREQUAL "Debug" AND DEBUG_ADDRESS_SANITIZER)
|
||||
message(STATUS "Address Sanitizer enabled for Debug builds, Turn it off with -DDEBUG_ADDRESS_SANITIZER=off")
|
||||
if ("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang")
|
||||
if (CMAKE_CXX_COMPILER_FRONTEND_VARIANT STREQUAL "MSVC")
|
||||
# using clang with clang-cl front end
|
||||
message(STATUS "Address Sanitizer available on Clang MSVC frontend")
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /fsanitize=address /O1 /Oy-")
|
||||
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /fsanitize=address /O1 /Oy-")
|
||||
else()
|
||||
# AppleClang and Clang
|
||||
message(STATUS "Address Sanitizer available on Clang")
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=address -O1 -fno-omit-frame-pointer")
|
||||
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fsanitize=address -O1 -fno-omit-frame-pointer")
|
||||
endif()
|
||||
elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
|
||||
# GCC
|
||||
message(STATUS "Address Sanitizer available on GCC")
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=address -O1 -fno-omit-frame-pointer")
|
||||
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fsanitize=address -O1 -fno-omit-frame-pointer")
|
||||
link_libraries("asan")
|
||||
elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")
|
||||
message(STATUS "Address Sanitizer available on MSVC")
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /fsanitize=address /O1 /Oy-")
|
||||
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /fsanitize=address /O1 /Oy-")
|
||||
else()
|
||||
message(STATUS "Address Sanitizer not available on compiler ${CMAKE_CXX_COMPILER_ID}")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
option(ENABLE_LTO "Enable Link Time Optimization" off)
|
||||
|
||||
if(ENABLE_LTO)
|
||||
@ -138,7 +170,7 @@ set(Launcher_NEWS_OPEN_URL "https://prismlauncher.org/news" CACHE STRING "URL th
|
||||
set(Launcher_HELP_URL "https://prismlauncher.org/wiki/help-pages/%1" CACHE STRING "URL (with arg %1 to be substituted with page-id) that gets opened when the user requests help")
|
||||
|
||||
######## Set version numbers ########
|
||||
set(Launcher_VERSION_MAJOR 7)
|
||||
set(Launcher_VERSION_MAJOR 8)
|
||||
set(Launcher_VERSION_MINOR 0)
|
||||
|
||||
set(Launcher_VERSION_NAME "${Launcher_VERSION_MAJOR}.${Launcher_VERSION_MINOR}")
|
||||
@ -146,7 +178,7 @@ set(Launcher_VERSION_NAME4 "${Launcher_VERSION_MAJOR}.${Launcher_VERSION_MINOR}.
|
||||
set(Launcher_VERSION_NAME4_COMMA "${Launcher_VERSION_MAJOR},${Launcher_VERSION_MINOR},0,0")
|
||||
|
||||
# Build platform.
|
||||
set(Launcher_BUILD_PLATFORM "" CACHE STRING "A short string identifying the platform that this build was built for. Only used to display in the about dialog.")
|
||||
set(Launcher_BUILD_PLATFORM "unknown" CACHE STRING "A short string identifying the platform that this build was built for. Only used to display in the about dialog.")
|
||||
|
||||
# Channel list URL
|
||||
set(Launcher_UPDATER_BASE "" CACHE STRING "Base URL for the updater.")
|
||||
@ -332,7 +364,7 @@ elseif(UNIX)
|
||||
|
||||
set(BINARY_DEST_DIR "bin")
|
||||
set(LIBRARY_DEST_DIR "lib${LIB_SUFFIX}")
|
||||
set(JARS_DEST_DIR "share/${Launcher_APP_BINARY_NAME}")
|
||||
set(JARS_DEST_DIR "share/${Launcher_Name}")
|
||||
|
||||
# install as bundle with no dependencies included
|
||||
set(INSTALL_BUNDLE "nodeps")
|
||||
@ -345,7 +377,7 @@ elseif(UNIX)
|
||||
install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/${Launcher_SVG} DESTINATION "${KDE_INSTALL_ICONDIR}/hicolor/scalable/apps")
|
||||
install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/${Launcher_mrpack_MIMEInfo} DESTINATION ${KDE_INSTALL_MIMEDIR})
|
||||
|
||||
install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/launcher/qtlogging.ini" DESTINATION "${KDE_INSTALL_DATADIR}/${Launcher_Name}")
|
||||
install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/launcher/qtlogging.ini" DESTINATION "share/${Launcher_Name}")
|
||||
|
||||
if(Launcher_ManPage)
|
||||
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${Launcher_ManPage} DESTINATION "${KDE_INSTALL_MANDIR}/man6")
|
||||
|
@ -61,3 +61,10 @@ As a bonus, you can also [cryptographically sign your commits][gh-signing-commit
|
||||
|
||||
[gh-signing-commits]: https://docs.github.com/en/authentication/managing-commit-signature-verification/signing-commits
|
||||
[gh-vigilant-mode]: https://docs.github.com/en/authentication/managing-commit-signature-verification/displaying-verification-statuses-for-all-of-your-commits
|
||||
|
||||
|
||||
## Backporting to Release Branches
|
||||
|
||||
We use [automated backports](https://github.com/PrismLauncher/PrismLauncher/blob/develop/.github/workflows/backport.yml) to merge specific contributions from develop into `release` branches.
|
||||
|
||||
This is done when pull requests are merged and have labels such as `backport release-7.x` - which should be added along with the milestone for the release.
|
||||
|
@ -65,7 +65,7 @@ Config::Config()
|
||||
MAC_SPARKLE_PUB_KEY = "@MACOSX_SPARKLE_UPDATE_PUBLIC_KEY@";
|
||||
MAC_SPARKLE_APPCAST_URL = "@MACOSX_SPARKLE_UPDATE_FEED_URL@";
|
||||
|
||||
if (BUILD_PLATFORM == "macOS" && !MAC_SPARKLE_PUB_KEY.isEmpty() && !MAC_SPARKLE_APPCAST_URL.isEmpty())
|
||||
if (!MAC_SPARKLE_PUB_KEY.isEmpty() && !MAC_SPARKLE_APPCAST_URL.isEmpty())
|
||||
{
|
||||
UPDATER_ENABLED = true;
|
||||
}
|
||||
@ -82,6 +82,7 @@ Config::Config()
|
||||
{
|
||||
GIT_REFSPEC = "refs/heads/stable";
|
||||
GIT_TAG = versionString();
|
||||
GIT_COMMIT = "";
|
||||
}
|
||||
|
||||
if (GIT_REFSPEC.startsWith("refs/heads/"))
|
||||
|
@ -68,7 +68,7 @@ class Config {
|
||||
|
||||
bool UPDATER_ENABLED = false;
|
||||
|
||||
/// A short string identifying this build's platform. For example, "lin64" or "win32".
|
||||
/// A short string identifying this build's platform or distribution.
|
||||
QString BUILD_PLATFORM;
|
||||
|
||||
/// A string containing the build timestamp
|
||||
|
48
flake.lock
48
flake.lock
@ -21,11 +21,11 @@
|
||||
"nixpkgs-lib": "nixpkgs-lib"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1683560683,
|
||||
"narHash": "sha256-XAygPMN5Xnk/W2c1aW0jyEa6lfMDZWlQgiNtmHXytPc=",
|
||||
"lastModified": 1688466019,
|
||||
"narHash": "sha256-VeM2akYrBYMsb4W/MmBo1zmaMfgbL4cH3Pu8PGyIwJ0=",
|
||||
"owner": "hercules-ci",
|
||||
"repo": "flake-parts",
|
||||
"rev": "006c75898cf814ef9497252b022e91c946ba8e17",
|
||||
"rev": "8e8d955c22df93dbe24f19ea04f47a74adbdc5ec",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@ -35,12 +35,15 @@
|
||||
}
|
||||
},
|
||||
"flake-utils": {
|
||||
"inputs": {
|
||||
"systems": "systems"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1667395993,
|
||||
"narHash": "sha256-nuEHfE/LcWyuSWnS8t12N1wc105Qtau+/OdUAjtQ0rA=",
|
||||
"lastModified": 1685518550,
|
||||
"narHash": "sha256-o2d0KcvaXzTrPRIo0kOLV0/QXHhDQ5DTi+OxcjO8xqY=",
|
||||
"owner": "numtide",
|
||||
"repo": "flake-utils",
|
||||
"rev": "5aed5285a952e0b949eb3ba02c12fa4fcfef535f",
|
||||
"rev": "a1720a10a6cfe8234c0e93907ffe81be440f4cef",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@ -88,11 +91,11 @@
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1685012353,
|
||||
"narHash": "sha256-U3oOge4cHnav8OLGdRVhL45xoRj4Ppd+It6nPC9nNIU=",
|
||||
"lastModified": 1689413807,
|
||||
"narHash": "sha256-exuzOvOhGAEKWQKwDuZAL4N8a1I837hH5eocaTcIbLc=",
|
||||
"owner": "nixos",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "aeb75dba965e790de427b73315d5addf91a54955",
|
||||
"rev": "46ed466081b9cad1125b11f11a2af5cc40b942c7",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@ -105,11 +108,11 @@
|
||||
"nixpkgs-lib": {
|
||||
"locked": {
|
||||
"dir": "lib",
|
||||
"lastModified": 1682879489,
|
||||
"narHash": "sha256-sASwo8gBt7JDnOOstnps90K1wxmVfyhsTPPNTGBPjjg=",
|
||||
"lastModified": 1688049487,
|
||||
"narHash": "sha256-100g4iaKC9MalDjUW9iN6Jl/OocTDtXdeAj7pEGIRh4=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "da45bf6ec7bbcc5d1e14d3795c025199f28e0de0",
|
||||
"rev": "4bc72cae107788bf3f24f30db2e2f685c9298dc9",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@ -135,11 +138,11 @@
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1684842236,
|
||||
"narHash": "sha256-rYWsIXHvNhVQ15RQlBUv67W3YnM+Pd+DuXGMvCBq2IE=",
|
||||
"lastModified": 1689328505,
|
||||
"narHash": "sha256-9B3+OeUn1a/CvzE3GW6nWNwS5J7PDHTyHGlpL3wV5oA=",
|
||||
"owner": "cachix",
|
||||
"repo": "pre-commit-hooks.nix",
|
||||
"rev": "61e567d6497bc9556f391faebe5e410e6623217f",
|
||||
"rev": "5e28316db471d1ac234beb70031b635437421dd6",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@ -156,6 +159,21 @@
|
||||
"nixpkgs": "nixpkgs",
|
||||
"pre-commit-hooks": "pre-commit-hooks"
|
||||
}
|
||||
},
|
||||
"systems": {
|
||||
"locked": {
|
||||
"lastModified": 1681028828,
|
||||
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
|
||||
"owner": "nix-systems",
|
||||
"repo": "default",
|
||||
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "nix-systems",
|
||||
"repo": "default",
|
||||
"type": "github"
|
||||
}
|
||||
}
|
||||
},
|
||||
"root": "root",
|
||||
|
22
flatpak/libdecor.json
Normal file
22
flatpak/libdecor.json
Normal file
@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "libdecor",
|
||||
"buildsystem": "meson",
|
||||
"config-opts": [
|
||||
"-Ddemo=false"
|
||||
],
|
||||
"sources": [
|
||||
{
|
||||
"type": "git",
|
||||
"url": "https://gitlab.freedesktop.org/libdecor/libdecor.git",
|
||||
"commit": "73260393a97291c887e1074ab7f318e031be0ac6"
|
||||
},
|
||||
{
|
||||
"type": "patch",
|
||||
"path": "patches/weird_libdecor.patch"
|
||||
}
|
||||
],
|
||||
"cleanup": [
|
||||
"/include",
|
||||
"/lib/pkgconfig"
|
||||
]
|
||||
}
|
@ -5,13 +5,6 @@ sdk: org.kde.Sdk
|
||||
sdk-extensions:
|
||||
- org.freedesktop.Sdk.Extension.openjdk17
|
||||
- org.freedesktop.Sdk.Extension.openjdk8
|
||||
add-extensions:
|
||||
com.valvesoftware.Steam.Utility.gamescope:
|
||||
version: stable
|
||||
add-ld-path: lib
|
||||
no-autodownload: true
|
||||
autodelete: false
|
||||
directory: utils/gamescope
|
||||
|
||||
command: prismlauncher
|
||||
finish-args:
|
||||
@ -26,12 +19,22 @@ finish-args:
|
||||
# Mod drag&drop
|
||||
- --filesystem=xdg-download:ro
|
||||
|
||||
cleanup:
|
||||
- /lib/libGLU*
|
||||
|
||||
modules:
|
||||
# Might be needed by some Controller mods (see https://github.com/isXander/Controlify/issues/31)
|
||||
- shared-modules/libusb/libusb.json
|
||||
|
||||
# Needed for proper Wayland support
|
||||
- libdecor.json
|
||||
|
||||
- name: prismlauncher
|
||||
buildsystem: cmake-ninja
|
||||
builddir: true
|
||||
config-opts:
|
||||
- -DLauncher_BUILD_PLATFORM=flatpak
|
||||
- -DCMAKE_BUILD_TYPE=Debug
|
||||
- -DCMAKE_BUILD_TYPE=RelWithDebInfo
|
||||
- -DLauncher_QT_VERSION_MAJOR=5
|
||||
build-options:
|
||||
env:
|
||||
@ -40,7 +43,7 @@ modules:
|
||||
sources:
|
||||
- type: dir
|
||||
path: ../
|
||||
builddir: true
|
||||
|
||||
- name: openjdk
|
||||
buildsystem: simple
|
||||
build-commands:
|
||||
@ -49,14 +52,45 @@ modules:
|
||||
- mv /app/jre /app/jdk/17
|
||||
- /usr/lib/sdk/openjdk8/install.sh
|
||||
- mv /app/jre /app/jdk/8
|
||||
cleanup: [/jre]
|
||||
cleanup:
|
||||
- /jre
|
||||
|
||||
- name: glfw
|
||||
buildsystem: cmake-ninja
|
||||
config-opts:
|
||||
- -DCMAKE_BUILD_TYPE=RelWithDebInfo
|
||||
- -DBUILD_SHARED_LIBS:BOOL=ON
|
||||
- -DGLFW_USE_WAYLAND=ON
|
||||
sources:
|
||||
- type: git
|
||||
url: https://github.com/glfw/glfw.git
|
||||
commit: 3fa2360720eeba1964df3c0ecf4b5df8648a8e52
|
||||
- type: patch
|
||||
path: patches/0003-Don-t-crash-on-calls-to-focus-or-icon.patch
|
||||
- type: patch
|
||||
path: patches/0005-Add-warning-about-being-an-unofficial-patch.patch
|
||||
- type: patch
|
||||
path: patches/0007-Platform-Prefer-Wayland-over-X11.patch
|
||||
cleanup:
|
||||
- /include
|
||||
- /lib/cmake
|
||||
- /lib/pkgconfig
|
||||
|
||||
- name: xrandr
|
||||
buildsystem: autotools
|
||||
sources:
|
||||
- type: archive
|
||||
url: https://xorg.freedesktop.org/archive/individual/app/xrandr-1.5.1.tar.xz
|
||||
sha256: 7bc76daf9d72f8aff885efad04ce06b90488a1a169d118dea8a2b661832e8762
|
||||
cleanup: [/share/man, /bin/xkeystone]
|
||||
url: https://xorg.freedesktop.org/archive/individual/app/xrandr-1.5.2.tar.xz
|
||||
sha256: c8bee4790d9058bacc4b6246456c58021db58a87ddda1a9d0139bf5f18f1f240
|
||||
x-checker-data:
|
||||
type: anitya
|
||||
project-id: 14957
|
||||
stable-only: true
|
||||
url-template: https://xorg.freedesktop.org/archive/individual/app/xrandr-$version.tar.xz
|
||||
cleanup:
|
||||
- /share/man
|
||||
- /bin/xkeystone
|
||||
|
||||
- name: gamemode
|
||||
buildsystem: meson
|
||||
config-opts:
|
||||
@ -67,19 +101,56 @@ modules:
|
||||
# post-install is running inside the build dir, we need it from the source though
|
||||
- install -Dm755 ../data/gamemoderun -t /app/bin
|
||||
sources:
|
||||
- type: git
|
||||
url: https://github.com/FeralInteractive/gamemode
|
||||
tag: "1.7"
|
||||
commit: 4dc99dff76218718763a6b07fc1900fa6d1dafd9
|
||||
- type: archive
|
||||
archive-type: tar-gzip
|
||||
url: https://api.github.com/repos/FeralInteractive/gamemode/tarball/1.7
|
||||
sha256: 57ce73ba605d1cf12f8d13725006a895182308d93eba0f69f285648449641803
|
||||
x-checker-data:
|
||||
type: json
|
||||
url: https://api.github.com/repos/FeralInteractive/gamemode/releases/latest
|
||||
version-query: .tag_name
|
||||
url-query: .tarball_url
|
||||
timestamp-query: .published_at
|
||||
cleanup:
|
||||
- /include
|
||||
- /lib/pkgconfig
|
||||
- /lib/libgamemodeauto.a
|
||||
|
||||
- name: glxinfo
|
||||
buildsystem: meson
|
||||
config-opts:
|
||||
- --bindir=/app/mesa-demos
|
||||
- -Degl=disabled
|
||||
- -Dglut=disabled
|
||||
- -Dosmesa=disabled
|
||||
- -Dvulkan=disabled
|
||||
- -Dwayland=disabled
|
||||
post-install:
|
||||
- mv -v /app/mesa-demos/glxinfo /app/bin
|
||||
sources:
|
||||
- type: archive
|
||||
url: https://archive.mesa3d.org/demos/mesa-demos-9.0.0.tar.xz
|
||||
sha256: 3046a3d26a7b051af7ebdd257a5f23bfeb160cad6ed952329cdff1e9f1ed496b
|
||||
x-checker-data:
|
||||
type: anitya
|
||||
project-id: 16781
|
||||
stable-only: true
|
||||
url-template: https://archive.mesa3d.org/demos/mesa-demos-$version.tar.xz
|
||||
cleanup:
|
||||
- /include
|
||||
- /mesa-demos
|
||||
- /share
|
||||
modules:
|
||||
- shared-modules/glu/glu-9.json
|
||||
|
||||
- name: enhance
|
||||
buildsystem: simple
|
||||
build-commands:
|
||||
- mkdir -p /app/utils/gamescope
|
||||
- install -Dm755 prime-run /app/bin/prime-run
|
||||
- mv /app/bin/prismlauncher /app/bin/prismrun
|
||||
- install -Dm755 prismlauncher /app/bin/prismlauncher
|
||||
sources:
|
||||
- type: file
|
||||
path: ../flatpak/prime-run
|
||||
path: prime-run
|
||||
- type: file
|
||||
path: ../flatpak/prismlauncher
|
||||
path: prismlauncher
|
||||
|
@ -0,0 +1,24 @@
|
||||
diff --git a/src/wl_window.c b/src/wl_window.c
|
||||
index 52d3b9eb..4ac4eb5d 100644
|
||||
--- a/src/wl_window.c
|
||||
+++ b/src/wl_window.c
|
||||
@@ -2117,8 +2117,7 @@ void _glfwSetWindowTitleWayland(_GLFWwindow* window, const char* title)
|
||||
void _glfwSetWindowIconWayland(_GLFWwindow* window,
|
||||
int count, const GLFWimage* images)
|
||||
{
|
||||
- _glfwInputError(GLFW_FEATURE_UNAVAILABLE,
|
||||
- "Wayland: The platform does not support setting the window icon");
|
||||
+ fprintf(stderr, "!!! Ignoring Error: Wayland: The platform does not support setting the window icon\n");
|
||||
}
|
||||
|
||||
void _glfwGetWindowPosWayland(_GLFWwindow* window, int* xpos, int* ypos)
|
||||
@@ -2361,8 +2360,7 @@ void _glfwRequestWindowAttentionWayland(_GLFWwindow* window)
|
||||
|
||||
void _glfwFocusWindowWayland(_GLFWwindow* window)
|
||||
{
|
||||
- _glfwInputError(GLFW_FEATURE_UNAVAILABLE,
|
||||
- "Wayland: The platform does not support setting the input focus");
|
||||
+ fprintf(stderr, "!!! Ignoring Error: Wayland: The platform does not support setting the input focus\n");
|
||||
}
|
||||
|
||||
void _glfwSetWindowMonitorWayland(_GLFWwindow* window,
|
@ -0,0 +1,17 @@
|
||||
diff --git a/src/init.c b/src/init.c
|
||||
index 06dbb3f2..a7c6da86 100644
|
||||
--- a/src/init.c
|
||||
+++ b/src/init.c
|
||||
@@ -449,6 +449,12 @@ GLFWAPI int glfwInit(void)
|
||||
_glfw.initialized = GLFW_TRUE;
|
||||
|
||||
glfwDefaultWindowHints();
|
||||
+
|
||||
+ fprintf(stderr, "!!! Patched GLFW from https://github.com/Admicos/minecraft-wayland\n"
|
||||
+ "!!! If any issues with the window, or some issues with rendering, occur, "
|
||||
+ "first try with the built-in GLFW, and if that solves the issue, report there first.\n"
|
||||
+ "!!! Use outside Minecraft is untested, and things might break.\n");
|
||||
+
|
||||
return GLFW_TRUE;
|
||||
}
|
||||
|
20
flatpak/patches/0007-Platform-Prefer-Wayland-over-X11.patch
Normal file
20
flatpak/patches/0007-Platform-Prefer-Wayland-over-X11.patch
Normal file
@ -0,0 +1,20 @@
|
||||
diff --git a/src/platform.c b/src/platform.c
|
||||
index c5966ae7..3e7442f9 100644
|
||||
--- a/src/platform.c
|
||||
+++ b/src/platform.c
|
||||
@@ -49,12 +49,12 @@ static const struct
|
||||
#if defined(_GLFW_COCOA)
|
||||
{ GLFW_PLATFORM_COCOA, _glfwConnectCocoa },
|
||||
#endif
|
||||
-#if defined(_GLFW_X11)
|
||||
- { GLFW_PLATFORM_X11, _glfwConnectX11 },
|
||||
-#endif
|
||||
#if defined(_GLFW_WAYLAND)
|
||||
{ GLFW_PLATFORM_WAYLAND, _glfwConnectWayland },
|
||||
#endif
|
||||
+#if defined(_GLFW_X11)
|
||||
+ { GLFW_PLATFORM_X11, _glfwConnectX11 },
|
||||
+#endif
|
||||
};
|
||||
|
||||
GLFWbool _glfwSelectPlatform(int desiredID, _GLFWplatform* platform)
|
40
flatpak/patches/weird_libdecor.patch
Normal file
40
flatpak/patches/weird_libdecor.patch
Normal file
@ -0,0 +1,40 @@
|
||||
diff --git a/src/libdecor.c b/src/libdecor.c
|
||||
index a9c1106..1aa38b3 100644
|
||||
--- a/src/libdecor.c
|
||||
+++ b/src/libdecor.c
|
||||
@@ -1391,22 +1391,32 @@ calculate_priority(const struct libdecor_plugin_description *plugin_description)
|
||||
static bool
|
||||
check_symbol_conflicts(const struct libdecor_plugin_description *plugin_description)
|
||||
{
|
||||
+ bool ret = true;
|
||||
char * const *symbol;
|
||||
+ void* main_prog = dlopen(NULL, RTLD_LAZY);
|
||||
+ if (!main_prog) {
|
||||
+ fprintf(stderr, "Plugin \"%s\" couldn't check conflicting symbols: \"%s\".\n",
|
||||
+ plugin_description->description, dlerror());
|
||||
+ return false;
|
||||
+ }
|
||||
+
|
||||
|
||||
symbol = plugin_description->conflicting_symbols;
|
||||
while (*symbol) {
|
||||
dlerror();
|
||||
- dlsym (RTLD_DEFAULT, *symbol);
|
||||
+ dlsym (main_prog, *symbol);
|
||||
if (!dlerror()) {
|
||||
fprintf(stderr, "Plugin \"%s\" uses conflicting symbol \"%s\".\n",
|
||||
plugin_description->description, *symbol);
|
||||
- return false;
|
||||
+ ret = false;
|
||||
+ break;
|
||||
}
|
||||
|
||||
symbol++;
|
||||
}
|
||||
|
||||
- return true;
|
||||
+ dlclose(main_prog);
|
||||
+ return ret;
|
||||
}
|
||||
|
||||
static struct plugin_loader *
|
@ -5,7 +5,7 @@ for i in {0..9}; do
|
||||
test -S "$XDG_RUNTIME_DIR"/discord-ipc-"$i" || ln -sf {app/com.discordapp.Discord,"$XDG_RUNTIME_DIR"}/discord-ipc-"$i";
|
||||
done
|
||||
|
||||
export PATH="${PATH}${PATH:+:}/app/utils/gamescope/bin:/usr/lib/extensions/vulkan/MangoHud/bin"
|
||||
export LD_LIBRARY_PATH="${LD_LIBRARY_PATH}${LD_LIBRARY_PATH:+:}/usr/lib/extensions/vulkan/MangoHud/\$LIB/"
|
||||
export PATH="${PATH}${PATH:+:}/usr/lib/extensions/vulkan/gamescope/bin:/usr/lib/extensions/vulkan/MangoHud/bin"
|
||||
export VK_LAYER_PATH="/usr/lib/extensions/vulkan/share/vulkan/implicit_layer.d/"
|
||||
|
||||
exec /app/bin/prismrun "$@"
|
||||
|
1
flatpak/shared-modules
Submodule
1
flatpak/shared-modules
Submodule
@ -0,0 +1 @@
|
||||
Subproject commit 45094ca570be383d06df729b6972830ec63bd3df
|
@ -6,9 +6,10 @@
|
||||
* Prism Launcher - Minecraft Launcher
|
||||
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
|
||||
* Copyright (C) 2022 Lenny McLennington <lenny@sneed.church>
|
||||
* Copyright (C) 2022 Tayou <tayou@gmx.net>
|
||||
* Copyright (C) 2022 Tayou <git@tayou.org>
|
||||
* Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me>
|
||||
* Copyright (C) 2023 Rachel Powers <508861+Ryex@users.noreply.github.com>
|
||||
* Copyright (C) 2023 seth <getchoo at tuta dot io>
|
||||
*
|
||||
* 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
|
||||
@ -376,33 +377,33 @@ Application::Application(int &argc, char **argv) : QApplication(argc, argv)
|
||||
|
||||
// init the logger
|
||||
{
|
||||
static const QString logBase = BuildConfig.LAUNCHER_NAME + "-%0.log";
|
||||
auto moveFile = [](const QString &oldName, const QString &newName)
|
||||
{
|
||||
static const QString baseLogFile = BuildConfig.LAUNCHER_NAME + "-%0.log";
|
||||
static const QString logBase = FS::PathCombine("logs", baseLogFile);
|
||||
auto moveFile = [](const QString& oldName, const QString& newName) {
|
||||
QFile::remove(newName);
|
||||
QFile::copy(oldName, newName);
|
||||
QFile::remove(oldName);
|
||||
};
|
||||
if (FS::ensureFolderPathExists("logs")) { // if this did not fail
|
||||
for (auto i = 0; i <= 4; i++)
|
||||
if (auto oldName = baseLogFile.arg(i);
|
||||
QFile::exists(oldName)) // do not pointlessly delete new files if the old ones are not there
|
||||
moveFile(oldName, logBase.arg(i));
|
||||
}
|
||||
|
||||
moveFile(logBase.arg(3), logBase.arg(4));
|
||||
moveFile(logBase.arg(2), logBase.arg(3));
|
||||
moveFile(logBase.arg(1), logBase.arg(2));
|
||||
moveFile(logBase.arg(0), logBase.arg(1));
|
||||
for (auto i = 4; i > 0; i--)
|
||||
moveFile(logBase.arg(i - 1), logBase.arg(i));
|
||||
|
||||
logFile = std::unique_ptr<QFile>(new QFile(logBase.arg(0)));
|
||||
if(!logFile->open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate))
|
||||
{
|
||||
showFatalErrorMessage(
|
||||
"The launcher data folder is not writable!",
|
||||
QString(
|
||||
"The launcher couldn't create a log file - the data folder is not writable.\n"
|
||||
if (!logFile->open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) {
|
||||
showFatalErrorMessage("The launcher data folder is not writable!",
|
||||
QString("The launcher couldn't create a log file - the data folder is not writable.\n"
|
||||
"\n"
|
||||
"Make sure you have write permissions to the data folder.\n"
|
||||
"(%1)\n"
|
||||
"\n"
|
||||
"The launcher cannot continue until you fix this problem."
|
||||
).arg(dataPath)
|
||||
);
|
||||
"The launcher cannot continue until you fix this problem.")
|
||||
.arg(dataPath));
|
||||
return;
|
||||
}
|
||||
qInstallMessageHandler(appDebugOutput);
|
||||
@ -433,7 +434,11 @@ Application::Application(int &argc, char **argv) : QApplication(argc, argv)
|
||||
}
|
||||
// seach root path
|
||||
if(!foundLoggingRules) {
|
||||
#if defined(Q_OS_LINUX) || defined(Q_OS_FREEBSD) || defined(Q_OS_OPENBSD)
|
||||
logRulesPath = FS::PathCombine(m_rootPath, "share", BuildConfig.LAUNCHER_NAME, logRulesFile);
|
||||
#else
|
||||
logRulesPath = FS::PathCombine(m_rootPath, logRulesFile);
|
||||
#endif
|
||||
qDebug() << "Testing" << logRulesPath << "...";
|
||||
foundLoggingRules = QFile::exists(logRulesPath);
|
||||
}
|
||||
@ -471,6 +476,7 @@ Application::Application(int &argc, char **argv) : QApplication(argc, argv)
|
||||
|
||||
qDebug() << BuildConfig.LAUNCHER_DISPLAYNAME << ", (c) 2013-2021 " << BuildConfig.LAUNCHER_COPYRIGHT;
|
||||
qDebug() << "Version : " << BuildConfig.printableVersionString();
|
||||
qDebug() << "Platform : " << BuildConfig.BUILD_PLATFORM;
|
||||
qDebug() << "Git commit : " << BuildConfig.GIT_COMMIT;
|
||||
qDebug() << "Git refspec : " << BuildConfig.GIT_REFSPEC;
|
||||
if (adjustedBy.size())
|
||||
@ -568,6 +574,7 @@ Application::Application(int &argc, char **argv) : QApplication(argc, argv)
|
||||
|
||||
// Language
|
||||
m_settings->registerSetting("Language", QString());
|
||||
m_settings->registerSetting("UseSystemLocale", false);
|
||||
|
||||
// Console
|
||||
m_settings->registerSetting("ShowConsole", false);
|
||||
@ -594,7 +601,7 @@ Application::Application(int &argc, char **argv) : QApplication(argc, argv)
|
||||
|
||||
// Java Settings
|
||||
m_settings->registerSetting("JavaPath", "");
|
||||
m_settings->registerSetting("JavaTimestamp", 0);
|
||||
m_settings->registerSetting("JavaSignature", "");
|
||||
m_settings->registerSetting("JavaArchitecture", "");
|
||||
m_settings->registerSetting("JavaRealArchitecture", "");
|
||||
m_settings->registerSetting("JavaVersion", "");
|
||||
@ -604,6 +611,9 @@ Application::Application(int &argc, char **argv) : QApplication(argc, argv)
|
||||
m_settings->registerSetting("IgnoreJavaCompatibility", false);
|
||||
m_settings->registerSetting("IgnoreJavaWizard", false);
|
||||
|
||||
// Mod loader settings
|
||||
m_settings->registerSetting("DisableQuiltBeacon", false);
|
||||
|
||||
// Native library workarounds
|
||||
m_settings->registerSetting("UseNativeOpenAL", false);
|
||||
m_settings->registerSetting("UseNativeGLFW", false);
|
||||
@ -687,9 +697,17 @@ Application::Application(int &argc, char **argv) : QApplication(argc, argv)
|
||||
m_settings->reset("PastebinCustomAPIBase");
|
||||
}
|
||||
}
|
||||
// meta URL
|
||||
{
|
||||
// Meta URL
|
||||
m_settings->registerSetting("MetaURLOverride", "");
|
||||
|
||||
QUrl metaUrl(m_settings->get("MetaURLOverride").toString());
|
||||
|
||||
// get rid of invalid meta urls
|
||||
if (!metaUrl.isValid() || metaUrl.scheme() != "http" || metaUrl.scheme() != "https")
|
||||
m_settings->reset("MetaURLOverride");
|
||||
}
|
||||
|
||||
m_settings->registerSetting("CloseAfterLaunch", false);
|
||||
m_settings->registerSetting("QuitAfterGameStop", false);
|
||||
|
||||
@ -910,12 +928,7 @@ bool Application::createSetupWizard()
|
||||
}
|
||||
return false;
|
||||
}();
|
||||
bool languageRequired = [&]()
|
||||
{
|
||||
if (settings()->get("Language").toString().isEmpty())
|
||||
return true;
|
||||
return false;
|
||||
}();
|
||||
bool languageRequired = settings()->get("Language").toString().isEmpty();
|
||||
bool pasteInterventionRequired = settings()->get("PastebinURL") != "";
|
||||
bool themeInterventionRequired = settings()->get("ApplicationTheme") == "";
|
||||
bool wizardRequired = javaRequired || languageRequired || pasteInterventionRequired || themeInterventionRequired;
|
||||
@ -1559,7 +1572,7 @@ QString Application::getJarPath(QString jarFile)
|
||||
{
|
||||
QStringList potentialPaths = {
|
||||
#if defined(Q_OS_LINUX) || defined(Q_OS_FREEBSD) || defined(Q_OS_OPENBSD)
|
||||
FS::PathCombine(m_rootPath, "share/" + BuildConfig.LAUNCHER_APP_BINARY_NAME),
|
||||
FS::PathCombine(m_rootPath, "share", BuildConfig.LAUNCHER_NAME),
|
||||
#endif
|
||||
FS::PathCombine(m_rootPath, "jars"),
|
||||
FS::PathCombine(applicationDirPath(), "jars"),
|
||||
@ -1699,6 +1712,7 @@ bool Application::handleDataMigration(const QString& currentData,
|
||||
matcher->add(std::make_shared<SimplePrefixMatcher>(configFile));
|
||||
matcher->add(std::make_shared<SimplePrefixMatcher>(
|
||||
BuildConfig.LAUNCHER_CONFIGFILE)); // it's possible that we already used that directory before
|
||||
matcher->add(std::make_shared<SimplePrefixMatcher>("logs/"));
|
||||
matcher->add(std::make_shared<SimplePrefixMatcher>("accounts.json"));
|
||||
matcher->add(std::make_shared<SimplePrefixMatcher>("accounts/"));
|
||||
matcher->add(std::make_shared<SimplePrefixMatcher>("assets/"));
|
||||
|
@ -2,7 +2,7 @@
|
||||
/*
|
||||
* Prism Launcher - Minecraft Launcher
|
||||
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
|
||||
* Copyright (C) 2022 Tayou <tayou@gmx.net>
|
||||
* Copyright (C) 2022 Tayou <git@tayou.org>
|
||||
* Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
|
@ -15,15 +15,14 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <QString>
|
||||
#include <QMetaType>
|
||||
#include <QString>
|
||||
#include <memory>
|
||||
|
||||
/*!
|
||||
* An abstract base class for versions.
|
||||
*/
|
||||
class BaseVersion
|
||||
{
|
||||
class BaseVersion {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<BaseVersion>;
|
||||
virtual ~BaseVersion() {}
|
||||
@ -45,14 +44,8 @@ public:
|
||||
*/
|
||||
virtual QString typeString() const = 0;
|
||||
|
||||
virtual bool operator<(BaseVersion &a)
|
||||
{
|
||||
return name() < a.name();
|
||||
};
|
||||
virtual bool operator>(BaseVersion &a)
|
||||
{
|
||||
return name() > a.name();
|
||||
};
|
||||
virtual bool operator<(BaseVersion& a) { return name() < a.name(); };
|
||||
virtual bool operator>(BaseVersion& a) { return name() > a.name(); };
|
||||
};
|
||||
|
||||
Q_DECLARE_METATYPE(BaseVersion::Ptr)
|
||||
|
@ -362,6 +362,8 @@ set(MINECRAFT_SOURCES
|
||||
minecraft/mod/tasks/LocalWorldSaveParseTask.cpp
|
||||
minecraft/mod/tasks/LocalResourceParse.h
|
||||
minecraft/mod/tasks/LocalResourceParse.cpp
|
||||
minecraft/mod/tasks/GetModDependenciesTask.h
|
||||
minecraft/mod/tasks/GetModDependenciesTask.cpp
|
||||
|
||||
# Assets
|
||||
minecraft/AssetsUtils.h
|
||||
@ -375,8 +377,6 @@ set(MINECRAFT_SOURCES
|
||||
minecraft/services/SkinDelete.cpp
|
||||
minecraft/services/SkinDelete.h
|
||||
|
||||
mojang/PackageManifest.h
|
||||
mojang/PackageManifest.cpp
|
||||
minecraft/Agent.h)
|
||||
|
||||
# the screenshots feature
|
||||
@ -487,6 +487,9 @@ set(API_SOURCES
|
||||
modplatform/helpers/HashUtils.cpp
|
||||
modplatform/helpers/OverrideUtils.h
|
||||
modplatform/helpers/OverrideUtils.cpp
|
||||
|
||||
modplatform/helpers/ExportToModList.h
|
||||
modplatform/helpers/ExportToModList.cpp
|
||||
)
|
||||
|
||||
set(FTB_SOURCES
|
||||
@ -514,6 +517,8 @@ set(FLAME_SOURCES
|
||||
modplatform/flame/FlameCheckUpdate.h
|
||||
modplatform/flame/FlameInstanceCreationTask.h
|
||||
modplatform/flame/FlameInstanceCreationTask.cpp
|
||||
modplatform/flame/FlamePackExportTask.h
|
||||
modplatform/flame/FlamePackExportTask.cpp
|
||||
)
|
||||
|
||||
set(MODRINTH_SOURCES
|
||||
@ -682,6 +687,7 @@ SET(LAUNCHER_SOURCES
|
||||
VersionProxyModel.h
|
||||
VersionProxyModel.cpp
|
||||
Markdown.h
|
||||
Markdown.cpp
|
||||
|
||||
# Super secret!
|
||||
KonamiCode.h
|
||||
@ -825,8 +831,8 @@ SET(LAUNCHER_SOURCES
|
||||
ui/pages/global/APIPage.h
|
||||
|
||||
# GUI - platform pages
|
||||
ui/pages/modplatform/VanillaPage.cpp
|
||||
ui/pages/modplatform/VanillaPage.h
|
||||
ui/pages/modplatform/CustomPage.cpp
|
||||
ui/pages/modplatform/CustomPage.h
|
||||
|
||||
ui/pages/modplatform/ResourcePage.cpp
|
||||
ui/pages/modplatform/ResourcePage.h
|
||||
@ -906,8 +912,10 @@ SET(LAUNCHER_SOURCES
|
||||
ui/dialogs/EditAccountDialog.h
|
||||
ui/dialogs/ExportInstanceDialog.cpp
|
||||
ui/dialogs/ExportInstanceDialog.h
|
||||
ui/dialogs/ExportMrPackDialog.cpp
|
||||
ui/dialogs/ExportMrPackDialog.h
|
||||
ui/dialogs/ExportPackDialog.cpp
|
||||
ui/dialogs/ExportPackDialog.h
|
||||
ui/dialogs/ExportToModListDialog.cpp
|
||||
ui/dialogs/ExportToModListDialog.h
|
||||
ui/dialogs/IconPickerDialog.cpp
|
||||
ui/dialogs/IconPickerDialog.h
|
||||
ui/dialogs/ImportResourceDialog.cpp
|
||||
@ -1032,7 +1040,7 @@ qt_wrap_ui(LAUNCHER_UI
|
||||
ui/pages/instance/ScreenshotsPage.ui
|
||||
ui/pages/modplatform/atlauncher/AtlOptionalModDialog.ui
|
||||
ui/pages/modplatform/atlauncher/AtlPage.ui
|
||||
ui/pages/modplatform/VanillaPage.ui
|
||||
ui/pages/modplatform/CustomPage.ui
|
||||
ui/pages/modplatform/ResourcePage.ui
|
||||
ui/pages/modplatform/flame/FlamePage.ui
|
||||
ui/pages/modplatform/legacy_ftb/Page.ui
|
||||
@ -1054,7 +1062,8 @@ qt_wrap_ui(LAUNCHER_UI
|
||||
ui/dialogs/ProfileSelectDialog.ui
|
||||
ui/dialogs/SkinUploadDialog.ui
|
||||
ui/dialogs/ExportInstanceDialog.ui
|
||||
ui/dialogs/ExportMrPackDialog.ui
|
||||
ui/dialogs/ExportPackDialog.ui
|
||||
ui/dialogs/ExportToModListDialog.ui
|
||||
ui/dialogs/IconPickerDialog.ui
|
||||
ui/dialogs/ImportResourceDialog.ui
|
||||
ui/dialogs/MSALoginDialog.ui
|
||||
|
@ -40,6 +40,7 @@
|
||||
#include <QFileSystemModel>
|
||||
#include <QSortFilterProxyModel>
|
||||
#include <QStack>
|
||||
#include <algorithm>
|
||||
#include "FileSystem.h"
|
||||
#include "SeparatorPrefixTree.h"
|
||||
#include "StringUtils.h"
|
||||
@ -254,3 +255,25 @@ bool FileIgnoreProxy::filterAcceptsColumn(int source_column, const QModelIndex&
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool FileIgnoreProxy::filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const
|
||||
{
|
||||
QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
|
||||
QFileSystemModel* fsm = qobject_cast<QFileSystemModel*>(sourceModel());
|
||||
|
||||
auto fileInfo = fsm->fileInfo(index);
|
||||
return !ignoreFile(fileInfo);
|
||||
}
|
||||
|
||||
bool FileIgnoreProxy::ignoreFile(QFileInfo fileInfo) const
|
||||
{
|
||||
auto fileName = fileInfo.fileName();
|
||||
auto path = relPath(fileInfo.absoluteFilePath());
|
||||
return std::any_of(m_ignoreFiles.cbegin(), m_ignoreFiles.cend(), [fileName](auto iFileName) { return fileName == iFileName; }) ||
|
||||
m_ignoreFilePaths.covers(path);
|
||||
}
|
||||
|
||||
bool FileIgnoreProxy::filterFile(const QString& fileName) const
|
||||
{
|
||||
return blocked.covers(fileName) || ignoreFile(QFileInfo(QDir(root), fileName));
|
||||
}
|
||||
|
@ -36,6 +36,7 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <QFileInfo>
|
||||
#include <QSortFilterProxyModel>
|
||||
#include "SeparatorPrefixTree.h"
|
||||
|
||||
@ -63,10 +64,22 @@ class FileIgnoreProxy : public QSortFilterProxyModel {
|
||||
inline const SeparatorPrefixTree<'/'>& blockedPaths() const { return blocked; }
|
||||
inline SeparatorPrefixTree<'/'>& blockedPaths() { return blocked; }
|
||||
|
||||
// list of file names that need to be removed completely from model
|
||||
inline QStringList& ignoreFilesWithName() { return m_ignoreFiles; }
|
||||
// list of relative paths that need to be removed completely from model
|
||||
inline SeparatorPrefixTree<'/'>& ignoreFilesWithPath() { return m_ignoreFilePaths; }
|
||||
|
||||
bool filterFile(const QString& fileName) const;
|
||||
|
||||
protected:
|
||||
bool filterAcceptsColumn(int source_column, const QModelIndex& source_parent) const;
|
||||
bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const;
|
||||
|
||||
bool ignoreFile(QFileInfo file) const;
|
||||
|
||||
private:
|
||||
const QString root;
|
||||
SeparatorPrefixTree<'/'> blocked;
|
||||
QStringList m_ignoreFiles;
|
||||
SeparatorPrefixTree<'/'> m_ignoreFilePaths;
|
||||
};
|
||||
|
@ -36,6 +36,7 @@
|
||||
*/
|
||||
|
||||
#include "FileSystem.h"
|
||||
#include <QPair>
|
||||
|
||||
#include "BuildConfig.h"
|
||||
|
||||
@ -102,7 +103,7 @@ namespace fs = ghc::filesystem;
|
||||
#include <linux/fs.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <unistd.h>
|
||||
#elif defined(Q_OS_MACOS) || defined(Q_OS_FREEBSD) || defined(Q_OS_OPENBSD)
|
||||
#elif defined(Q_OS_MACOS)
|
||||
#include <sys/attr.h>
|
||||
#include <sys/clonefile.h>
|
||||
#elif defined(Q_OS_WIN)
|
||||
@ -246,6 +247,7 @@ bool copy::operator()(const QString& offset, bool dryRun)
|
||||
{
|
||||
using copy_opts = fs::copy_options;
|
||||
m_copied = 0; // reset counter
|
||||
m_failedPaths.clear();
|
||||
|
||||
// NOTE always deep copy on windows. the alternatives are too messy.
|
||||
#if defined Q_OS_WIN32
|
||||
@ -277,6 +279,9 @@ bool copy::operator()(const QString& offset, bool dryRun)
|
||||
qWarning() << "Failed to copy files:" << QString::fromStdString(err.message());
|
||||
qDebug() << "Source file:" << src_path;
|
||||
qDebug() << "Destination file:" << dst_path;
|
||||
m_failedPaths.append(dst_path);
|
||||
emit copyFailed(relative_dst_path);
|
||||
return;
|
||||
}
|
||||
m_copied++;
|
||||
emit fileCopied(relative_dst_path);
|
||||
@ -769,10 +774,47 @@ QString getDesktopDir()
|
||||
// Cross-platform Shortcut creation
|
||||
bool createShortcut(QString destination, QString target, QStringList args, QString name, QString icon)
|
||||
{
|
||||
if (destination.isEmpty()) {
|
||||
destination = PathCombine(getDesktopDir(), RemoveInvalidFilenameChars(name));
|
||||
}
|
||||
#if defined(Q_OS_MACOS)
|
||||
destination += ".command";
|
||||
// Create the Application
|
||||
QDir applicationDirectory = QStandardPaths::writableLocation(QStandardPaths::ApplicationsLocation) + "/" + BuildConfig.LAUNCHER_NAME + " Instances/";
|
||||
|
||||
QFile f(destination);
|
||||
if (!applicationDirectory.mkpath(".")) {
|
||||
qWarning() << "Couldn't create application directory";
|
||||
return false;
|
||||
}
|
||||
|
||||
QDir application = applicationDirectory.path() + "/" + name + ".app/";
|
||||
|
||||
if (application.exists()) {
|
||||
qWarning() << "Application already exists!";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!application.mkpath(".")) {
|
||||
qWarning() << "Couldn't create application";
|
||||
return false;
|
||||
}
|
||||
|
||||
QDir content = application.path() + "/Contents/";
|
||||
QDir resources = content.path() + "/Resources/";
|
||||
QDir binaryDir = content.path() + "/MacOS/";
|
||||
QFile info = content.path() + "/Info.plist";
|
||||
|
||||
if (!(content.mkpath(".") && resources.mkpath(".") && binaryDir.mkpath("."))) {
|
||||
qWarning() << "Couldn't create directories within application";
|
||||
return false;
|
||||
}
|
||||
info.open(QIODevice::WriteOnly | QIODevice::Text);
|
||||
|
||||
QFile(icon).rename(resources.path() + "/Icon.icns");
|
||||
|
||||
// Create the Command file
|
||||
QString exec = binaryDir.path() + "/Run.command";
|
||||
|
||||
QFile f(exec);
|
||||
f.open(QIODevice::WriteOnly | QIODevice::Text);
|
||||
QTextStream stream(&f);
|
||||
|
||||
@ -789,8 +831,32 @@ bool createShortcut(QString destination, QString target, QStringList args, QStri
|
||||
|
||||
f.setPermissions(f.permissions() | QFileDevice::ExeOwner | QFileDevice::ExeGroup | QFileDevice::ExeOther);
|
||||
|
||||
// Generate the Info.plist
|
||||
QTextStream infoStream(&info);
|
||||
infoStream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n"
|
||||
"<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" "
|
||||
"\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">"
|
||||
"<plist version=\"1.0\">\n"
|
||||
"<dict>\n"
|
||||
" <key>CFBundleExecutable</key>\n"
|
||||
" <string>Run.command</string>\n" // The path to the executable
|
||||
" <key>CFBundleIconFile</key>\n"
|
||||
" <string>Icon.icns</string>\n"
|
||||
" <key>CFBundleName</key>\n"
|
||||
" <string>" << name << "</string>\n" // Name of the application
|
||||
" <key>CFBundlePackageType</key>\n"
|
||||
" <string>APPL</string>\n"
|
||||
" <key>CFBundleShortVersionString</key>\n"
|
||||
" <string>1.0</string>\n"
|
||||
" <key>CFBundleVersion</key>\n"
|
||||
" <string>1.0</string>\n"
|
||||
"</dict>\n"
|
||||
"</plist>";
|
||||
|
||||
return true;
|
||||
#elif defined(Q_OS_LINUX) || defined(Q_OS_FREEBSD) || defined(Q_OS_OPENBSD)
|
||||
if (!destination.endsWith(".desktop")) // in case of isFlatpak destination is already populated
|
||||
destination += ".desktop";
|
||||
QFile f(destination);
|
||||
f.open(QIODevice::WriteOnly | QIODevice::Text);
|
||||
QTextStream stream(&f);
|
||||
@ -1072,6 +1138,7 @@ bool clone::operator()(const QString& offset, bool dryRun)
|
||||
}
|
||||
|
||||
m_cloned = 0; // reset counter
|
||||
m_failedClones.clear();
|
||||
|
||||
auto src = PathCombine(m_src.absolutePath(), offset);
|
||||
auto dst = PathCombine(m_dst.absolutePath(), offset);
|
||||
@ -1092,6 +1159,9 @@ bool clone::operator()(const QString& offset, bool dryRun)
|
||||
qDebug() << "Failed to clone files: error" << err.value() << "message" << QString::fromStdString(err.message());
|
||||
qDebug() << "Source file:" << src_path;
|
||||
qDebug() << "Destination file:" << dst_path;
|
||||
m_failedClones.append(qMakePair(src_path, dst_path));
|
||||
emit cloneFailed(src_path, dst_path);
|
||||
return;
|
||||
}
|
||||
m_cloned++;
|
||||
emit fileCloned(src_path, dst_path);
|
||||
@ -1151,7 +1221,7 @@ bool clone_file(const QString& src, const QString& dst, std::error_code& ec)
|
||||
return false;
|
||||
}
|
||||
|
||||
#elif defined(Q_OS_MACOS) || defined(Q_OS_FREEBSD) || defined(Q_OS_OPENBSD)
|
||||
#elif defined(Q_OS_MACOS)
|
||||
|
||||
if (!macos_bsd_clonefile(src_path, dst_path, ec)) {
|
||||
qDebug() << "failed macos_bsd_clonefile:";
|
||||
@ -1380,7 +1450,7 @@ bool linux_ficlone(const std::string& src_path, const std::string& dst_path, std
|
||||
return true;
|
||||
}
|
||||
|
||||
#elif defined(Q_OS_MACOS) || defined(Q_OS_FREEBSD) || defined(Q_OS_OPENBSD)
|
||||
#elif defined(Q_OS_MACOS)
|
||||
|
||||
bool macos_bsd_clonefile(const std::string& src_path, const std::string& dst_path, std::error_code& ec)
|
||||
{
|
||||
|
@ -43,6 +43,7 @@
|
||||
#include <system_error>
|
||||
|
||||
#include <QDir>
|
||||
#include <QPair>
|
||||
#include <QFlags>
|
||||
#include <QLocalServer>
|
||||
#include <QObject>
|
||||
@ -112,9 +113,12 @@ class copy : public QObject {
|
||||
bool operator()(bool dryRun = false) { return operator()(QString(), dryRun); }
|
||||
|
||||
int totalCopied() { return m_copied; }
|
||||
int totalFailed() { return m_failedPaths.length(); }
|
||||
QStringList failed() { return m_failedPaths; }
|
||||
|
||||
signals:
|
||||
void fileCopied(const QString& relativeName);
|
||||
void copyFailed(const QString& relativeName);
|
||||
// TODO: maybe add a "shouldCopy" signal in the future?
|
||||
|
||||
private:
|
||||
@ -127,6 +131,7 @@ class copy : public QObject {
|
||||
QDir m_src;
|
||||
QDir m_dst;
|
||||
int m_copied;
|
||||
QStringList m_failedPaths;
|
||||
};
|
||||
|
||||
struct LinkPair {
|
||||
@ -471,6 +476,9 @@ class clone : public QObject {
|
||||
bool operator()(bool dryRun = false) { return operator()(QString(), dryRun); }
|
||||
|
||||
int totalCloned() { return m_cloned; }
|
||||
int totalFailed() { return m_failedClones.length(); }
|
||||
|
||||
QList<QPair<QString, QString>> failed() { return m_failedClones; }
|
||||
|
||||
signals:
|
||||
void fileCloned(const QString& src, const QString& dst);
|
||||
@ -485,6 +493,7 @@ class clone : public QObject {
|
||||
QDir m_src;
|
||||
QDir m_dst;
|
||||
int m_cloned;
|
||||
QList<QPair<QString, QString>> m_failedClones;
|
||||
};
|
||||
|
||||
/**
|
||||
|
@ -45,7 +45,10 @@ QString InstanceName::name() const
|
||||
{
|
||||
if (!m_modified_name.isEmpty())
|
||||
return modifiedName();
|
||||
if (!m_original_version.isEmpty())
|
||||
return QString("%1 %2").arg(m_original_name, m_original_version);
|
||||
|
||||
return m_original_name;
|
||||
}
|
||||
|
||||
QString InstanceName::originalName() const
|
||||
|
@ -187,8 +187,8 @@ void LaunchController::login() {
|
||||
switch(m_accountToUse->accountState()) {
|
||||
case AccountState::Offline: {
|
||||
m_session->wants_online = false;
|
||||
// NOTE: fallthrough is intentional
|
||||
}
|
||||
/* fallthrough */
|
||||
case AccountState::Online: {
|
||||
if(!m_session->wants_online) {
|
||||
// we ask the user for a player name
|
||||
@ -267,8 +267,8 @@ void LaunchController::login() {
|
||||
// This means some sort of soft error that we can fix with a refresh ... so let's refresh.
|
||||
case AccountState::Unchecked: {
|
||||
m_accountToUse->refresh();
|
||||
// NOTE: fallthrough intentional
|
||||
}
|
||||
/* fallthrough */
|
||||
case AccountState::Working: {
|
||||
// refresh is in progress, we need to wait for it to finish to proceed.
|
||||
ProgressDialog progDialog(m_parentWidget);
|
||||
@ -390,7 +390,10 @@ void LaunchController::launchInstance()
|
||||
m_launcher->prependStep(makeShared<TextPrint>(m_launcher.get(), "Launched instance in " + online_mode + " mode\n", MessageLevel::Launcher));
|
||||
|
||||
// Prepend Version
|
||||
m_launcher->prependStep(makeShared<TextPrint>(m_launcher.get(), BuildConfig.LAUNCHER_DISPLAYNAME + " version: " + BuildConfig.printableVersionString() + "\n\n", MessageLevel::Launcher));
|
||||
{
|
||||
auto versionString = QString("%1 version: %2 (%3)").arg(BuildConfig.LAUNCHER_DISPLAYNAME, BuildConfig.printableVersionString(), BuildConfig.BUILD_PLATFORM);
|
||||
m_launcher->prependStep(makeShared<TextPrint>(m_launcher.get(), versionString + "\n\n", MessageLevel::Launcher));
|
||||
}
|
||||
m_launcher->start();
|
||||
}
|
||||
|
||||
|
@ -1,7 +1,8 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
/*
|
||||
* PolyMC - Minecraft Launcher
|
||||
* Prism Launcher - Minecraft Launcher
|
||||
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
|
||||
* Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
@ -33,56 +34,50 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include "MMCZip.h"
|
||||
#include <quazip/quazip.h>
|
||||
#include <quazip/quazipdir.h>
|
||||
#include <quazip/quazipfile.h>
|
||||
#include "MMCZip.h"
|
||||
#include "FileSystem.h"
|
||||
|
||||
#include <QCoreApplication>
|
||||
#include <QDebug>
|
||||
#include <QtConcurrentRun>
|
||||
|
||||
namespace MMCZip {
|
||||
// ours
|
||||
bool MMCZip::mergeZipFiles(QuaZip *into, QFileInfo from, QSet<QString> &contained, const FilterFunction filter)
|
||||
bool mergeZipFiles(QuaZip* into, QFileInfo from, QSet<QString>& contained, const FilterFunction filter)
|
||||
{
|
||||
QuaZip modZip(from.filePath());
|
||||
modZip.open(QuaZip::mdUnzip);
|
||||
|
||||
QuaZipFile fileInsideMod(&modZip);
|
||||
QuaZipFile zipOutFile(into);
|
||||
for (bool more = modZip.goToFirstFile(); more; more = modZip.goToNextFile())
|
||||
{
|
||||
for (bool more = modZip.goToFirstFile(); more; more = modZip.goToNextFile()) {
|
||||
QString filename = modZip.getCurrentFileName();
|
||||
if (filter && !filter(filename))
|
||||
{
|
||||
qDebug() << "Skipping file " << filename << " from "
|
||||
<< from.fileName() << " - filtered";
|
||||
if (filter && !filter(filename)) {
|
||||
qDebug() << "Skipping file " << filename << " from " << from.fileName() << " - filtered";
|
||||
continue;
|
||||
}
|
||||
if (contained.contains(filename))
|
||||
{
|
||||
qDebug() << "Skipping already contained file " << filename << " from "
|
||||
<< from.fileName();
|
||||
if (contained.contains(filename)) {
|
||||
qDebug() << "Skipping already contained file " << filename << " from " << from.fileName();
|
||||
continue;
|
||||
}
|
||||
contained.insert(filename);
|
||||
|
||||
if (!fileInsideMod.open(QIODevice::ReadOnly))
|
||||
{
|
||||
if (!fileInsideMod.open(QIODevice::ReadOnly)) {
|
||||
qCritical() << "Failed to open " << filename << " from " << from.fileName();
|
||||
return false;
|
||||
}
|
||||
|
||||
QuaZipNewInfo info_out(fileInsideMod.getActualFileName());
|
||||
|
||||
if (!zipOutFile.open(QIODevice::WriteOnly, info_out))
|
||||
{
|
||||
if (!zipOutFile.open(QIODevice::WriteOnly, info_out)) {
|
||||
qCritical() << "Failed to open " << filename << " in the jar";
|
||||
fileInsideMod.close();
|
||||
return false;
|
||||
}
|
||||
if (!JlCompress::copyData(fileInsideMod, zipOutFile))
|
||||
{
|
||||
if (!JlCompress::copyData(fileInsideMod, zipOutFile)) {
|
||||
zipOutFile.close();
|
||||
fileInsideMod.close();
|
||||
qCritical() << "Failed to copy data of " << filename << " into the jar";
|
||||
@ -94,10 +89,11 @@ bool MMCZip::mergeZipFiles(QuaZip *into, QFileInfo from, QSet<QString> &containe
|
||||
return true;
|
||||
}
|
||||
|
||||
bool MMCZip::compressDirFiles(QuaZip *zip, QString dir, QFileInfoList files, bool followSymlinks)
|
||||
bool compressDirFiles(QuaZip* zip, QString dir, QFileInfoList files, bool followSymlinks)
|
||||
{
|
||||
QDir directory(dir);
|
||||
if (!directory.exists()) return false;
|
||||
if (!directory.exists())
|
||||
return false;
|
||||
|
||||
for (auto e : files) {
|
||||
auto filePath = directory.relativeFilePath(e.absoluteFilePath());
|
||||
@ -109,13 +105,14 @@ bool MMCZip::compressDirFiles(QuaZip *zip, QString dir, QFileInfoList files, boo
|
||||
srcPath = e.canonicalFilePath();
|
||||
}
|
||||
}
|
||||
if( !JlCompress::compressFile(zip, srcPath, filePath)) return false;
|
||||
if (!JlCompress::compressFile(zip, srcPath, filePath))
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool MMCZip::compressDirFiles(QString fileCompressed, QString dir, QFileInfoList files, bool followSymlinks)
|
||||
bool compressDirFiles(QString fileCompressed, QString dir, QFileInfoList files, bool followSymlinks)
|
||||
{
|
||||
QuaZip zip(fileCompressed);
|
||||
QDir().mkpath(QFileInfo(fileCompressed).absolutePath());
|
||||
@ -136,11 +133,10 @@ bool MMCZip::compressDirFiles(QString fileCompressed, QString dir, QFileInfoList
|
||||
}
|
||||
|
||||
// ours
|
||||
bool MMCZip::createModdedJar(QString sourceJarPath, QString targetJarPath, const QList<Mod*>& mods)
|
||||
bool createModdedJar(QString sourceJarPath, QString targetJarPath, const QList<Mod*>& mods)
|
||||
{
|
||||
QuaZip zipOut(targetJarPath);
|
||||
if (!zipOut.open(QuaZip::mdCreate))
|
||||
{
|
||||
if (!zipOut.open(QuaZip::mdCreate)) {
|
||||
QFile::remove(targetJarPath);
|
||||
qCritical() << "Failed to open the minecraft.jar for modding";
|
||||
return false;
|
||||
@ -151,37 +147,29 @@ bool MMCZip::createModdedJar(QString sourceJarPath, QString targetJarPath, const
|
||||
|
||||
// Modify the jar
|
||||
// This needs to be done in reverse-order to ensure we respect the loading order of components
|
||||
for (auto i = mods.crbegin(); i != mods.crend(); i++)
|
||||
{
|
||||
for (auto i = mods.crbegin(); i != mods.crend(); i++) {
|
||||
const auto* mod = *i;
|
||||
// do not merge disabled mods.
|
||||
if (!mod->enabled())
|
||||
continue;
|
||||
if (mod->type() == ResourceType::ZIPFILE)
|
||||
{
|
||||
if (!mergeZipFiles(&zipOut, mod->fileinfo(), addedFiles))
|
||||
{
|
||||
if (mod->type() == ResourceType::ZIPFILE) {
|
||||
if (!mergeZipFiles(&zipOut, mod->fileinfo(), addedFiles)) {
|
||||
zipOut.close();
|
||||
QFile::remove(targetJarPath);
|
||||
qCritical() << "Failed to add" << mod->fileinfo().fileName() << "to the jar.";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else if (mod->type() == ResourceType::SINGLEFILE)
|
||||
{
|
||||
} else if (mod->type() == ResourceType::SINGLEFILE) {
|
||||
// FIXME: buggy - does not work with addedFiles
|
||||
auto filename = mod->fileinfo();
|
||||
if (!JlCompress::compressFile(&zipOut, filename.absoluteFilePath(), filename.fileName()))
|
||||
{
|
||||
if (!JlCompress::compressFile(&zipOut, filename.absoluteFilePath(), filename.fileName())) {
|
||||
zipOut.close();
|
||||
QFile::remove(targetJarPath);
|
||||
qCritical() << "Failed to add" << mod->fileinfo().fileName() << "to the jar.";
|
||||
return false;
|
||||
}
|
||||
addedFiles.insert(filename.fileName());
|
||||
}
|
||||
else if (mod->type() == ResourceType::FOLDER)
|
||||
{
|
||||
} else if (mod->type() == ResourceType::FOLDER) {
|
||||
// untested, but seems to be unused / not possible to reach
|
||||
// FIXME: buggy - does not work with addedFiles
|
||||
auto filename = mod->fileinfo();
|
||||
@ -190,25 +178,21 @@ bool MMCZip::createModdedJar(QString sourceJarPath, QString targetJarPath, const
|
||||
dir.cdUp();
|
||||
QString parent_dir = dir.absolutePath();
|
||||
auto files = QFileInfoList();
|
||||
MMCZip::collectFileListRecursively(what_to_zip, nullptr, &files, nullptr);
|
||||
collectFileListRecursively(what_to_zip, nullptr, &files, nullptr);
|
||||
|
||||
for (auto e : files) {
|
||||
if (addedFiles.contains(e.filePath()))
|
||||
files.removeAll(e);
|
||||
}
|
||||
|
||||
if (!MMCZip::compressDirFiles(&zipOut, parent_dir, files))
|
||||
{
|
||||
if (!compressDirFiles(&zipOut, parent_dir, files)) {
|
||||
zipOut.close();
|
||||
QFile::remove(targetJarPath);
|
||||
qCritical() << "Failed to add" << mod->fileinfo().fileName() << "to the jar.";
|
||||
return false;
|
||||
}
|
||||
qDebug() << "Adding folder " << filename.fileName() << " from "
|
||||
<< filename.absoluteFilePath();
|
||||
}
|
||||
else
|
||||
{
|
||||
qDebug() << "Adding folder " << filename.fileName() << " from " << filename.absoluteFilePath();
|
||||
} else {
|
||||
// Make sure we do not continue launching when something is missing or undefined...
|
||||
zipOut.close();
|
||||
QFile::remove(targetJarPath);
|
||||
@ -217,8 +201,7 @@ bool MMCZip::createModdedJar(QString sourceJarPath, QString targetJarPath, const
|
||||
}
|
||||
}
|
||||
|
||||
if (!mergeZipFiles(&zipOut, QFileInfo(sourceJarPath), addedFiles, [](const QString key){return !key.contains("META-INF");}))
|
||||
{
|
||||
if (!mergeZipFiles(&zipOut, QFileInfo(sourceJarPath), addedFiles, [](const QString key) { return !key.contains("META-INF"); })) {
|
||||
zipOut.close();
|
||||
QFile::remove(targetJarPath);
|
||||
qCritical() << "Failed to insert minecraft.jar contents.";
|
||||
@ -227,8 +210,7 @@ bool MMCZip::createModdedJar(QString sourceJarPath, QString targetJarPath, const
|
||||
|
||||
// Recompress the jar
|
||||
zipOut.close();
|
||||
if (zipOut.getZipError() != 0)
|
||||
{
|
||||
if (zipOut.getZipError() != 0) {
|
||||
QFile::remove(targetJarPath);
|
||||
qCritical() << "Failed to finalize minecraft.jar!";
|
||||
return false;
|
||||
@ -237,7 +219,7 @@ bool MMCZip::createModdedJar(QString sourceJarPath, QString targetJarPath, const
|
||||
}
|
||||
|
||||
// ours
|
||||
QString MMCZip::findFolderOfFileInZip(QuaZip* zip, const QString& what, const QStringList& ignore_paths, const QString& root)
|
||||
QString findFolderOfFileInZip(QuaZip* zip, const QString& what, const QStringList& ignore_paths, const QString& root)
|
||||
{
|
||||
QuaZipDir rootDir(zip, root);
|
||||
for (auto&& fileName : rootDir.entryList(QDir::Files)) {
|
||||
@ -261,27 +243,23 @@ QString MMCZip::findFolderOfFileInZip(QuaZip* zip, const QString& what, const QS
|
||||
}
|
||||
|
||||
// ours
|
||||
bool MMCZip::findFilesInZip(QuaZip * zip, const QString & what, QStringList & result, const QString &root)
|
||||
bool findFilesInZip(QuaZip* zip, const QString& what, QStringList& result, const QString& root)
|
||||
{
|
||||
QuaZipDir rootDir(zip, root);
|
||||
for(auto fileName: rootDir.entryList(QDir::Files))
|
||||
{
|
||||
if(fileName == what)
|
||||
{
|
||||
for (auto fileName : rootDir.entryList(QDir::Files)) {
|
||||
if (fileName == what) {
|
||||
result.append(root);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
for(auto fileName: rootDir.entryList(QDir::Dirs))
|
||||
{
|
||||
for (auto fileName : rootDir.entryList(QDir::Dirs)) {
|
||||
findFilesInZip(zip, what, result, root + fileName);
|
||||
}
|
||||
return !result.isEmpty();
|
||||
}
|
||||
|
||||
|
||||
// ours
|
||||
std::optional<QStringList> MMCZip::extractSubDir(QuaZip *zip, const QString & subdir, const QString &target)
|
||||
std::optional<QStringList> extractSubDir(QuaZip* zip, const QString& subdir, const QString& target)
|
||||
{
|
||||
auto target_top_dir = QUrl::fromLocalFile(target);
|
||||
|
||||
@ -292,13 +270,10 @@ std::optional<QStringList> MMCZip::extractSubDir(QuaZip *zip, const QString & su
|
||||
if (numEntries < 0) {
|
||||
qWarning() << "Failed to enumerate files in archive";
|
||||
return std::nullopt;
|
||||
}
|
||||
else if(numEntries == 0) {
|
||||
} else if (numEntries == 0) {
|
||||
qDebug() << "Extracting empty archives seems odd...";
|
||||
return extracted;
|
||||
}
|
||||
else if (!zip->goToFirstFile())
|
||||
{
|
||||
} else if (!zip->goToFirstFile()) {
|
||||
qWarning() << "Failed to seek to first file in zip";
|
||||
return std::nullopt;
|
||||
}
|
||||
@ -334,7 +309,8 @@ std::optional<QStringList> MMCZip::extractSubDir(QuaZip *zip, const QString & su
|
||||
}
|
||||
|
||||
if (!target_top_dir.isParentOf(QUrl::fromLocalFile(target_file_path))) {
|
||||
qWarning() << "Extracting" << relative_file_name << "was cancelled, because it was effectively outside of the target path" << target;
|
||||
qWarning() << "Extracting" << relative_file_name << "was cancelled, because it was effectively outside of the target path"
|
||||
<< target;
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
@ -345,7 +321,8 @@ std::optional<QStringList> MMCZip::extractSubDir(QuaZip *zip, const QString & su
|
||||
}
|
||||
|
||||
extracted.append(target_file_path);
|
||||
QFile::setPermissions(target_file_path, QFileDevice::Permission::ReadUser | QFileDevice::Permission::WriteUser | QFileDevice::Permission::ExeUser);
|
||||
QFile::setPermissions(target_file_path,
|
||||
QFileDevice::Permission::ReadUser | QFileDevice::Permission::WriteUser | QFileDevice::Permission::ExeUser);
|
||||
|
||||
qDebug() << "Extracted file" << relative_file_name << "to" << target_file_path;
|
||||
} while (zip->goToNextFile());
|
||||
@ -354,51 +331,50 @@ std::optional<QStringList> MMCZip::extractSubDir(QuaZip *zip, const QString & su
|
||||
}
|
||||
|
||||
// ours
|
||||
bool MMCZip::extractRelFile(QuaZip *zip, const QString &file, const QString &target)
|
||||
bool extractRelFile(QuaZip* zip, const QString& file, const QString& target)
|
||||
{
|
||||
return JlCompress::extractFile(zip, file, target);
|
||||
}
|
||||
|
||||
// ours
|
||||
std::optional<QStringList> MMCZip::extractDir(QString fileCompressed, QString dir)
|
||||
std::optional<QStringList> extractDir(QString fileCompressed, QString dir)
|
||||
{
|
||||
QuaZip zip(fileCompressed);
|
||||
if (!zip.open(QuaZip::mdUnzip))
|
||||
{
|
||||
if (!zip.open(QuaZip::mdUnzip)) {
|
||||
// check if this is a minimum size empty zip file...
|
||||
QFileInfo fileInfo(fileCompressed);
|
||||
if (fileInfo.size() == 22) {
|
||||
return QStringList();
|
||||
}
|
||||
qWarning() << "Could not open archive for unzipping:" << fileCompressed << "Error:" << zip.getZipError();;
|
||||
qWarning() << "Could not open archive for unzipping:" << fileCompressed << "Error:" << zip.getZipError();
|
||||
;
|
||||
return std::nullopt;
|
||||
}
|
||||
return MMCZip::extractSubDir(&zip, "", dir);
|
||||
return extractSubDir(&zip, "", dir);
|
||||
}
|
||||
|
||||
// ours
|
||||
std::optional<QStringList> MMCZip::extractDir(QString fileCompressed, QString subdir, QString dir)
|
||||
std::optional<QStringList> extractDir(QString fileCompressed, QString subdir, QString dir)
|
||||
{
|
||||
QuaZip zip(fileCompressed);
|
||||
if (!zip.open(QuaZip::mdUnzip))
|
||||
{
|
||||
if (!zip.open(QuaZip::mdUnzip)) {
|
||||
// check if this is a minimum size empty zip file...
|
||||
QFileInfo fileInfo(fileCompressed);
|
||||
if (fileInfo.size() == 22) {
|
||||
return QStringList();
|
||||
}
|
||||
qWarning() << "Could not open archive for unzipping:" << fileCompressed << "Error:" << zip.getZipError();;
|
||||
qWarning() << "Could not open archive for unzipping:" << fileCompressed << "Error:" << zip.getZipError();
|
||||
;
|
||||
return std::nullopt;
|
||||
}
|
||||
return MMCZip::extractSubDir(&zip, subdir, dir);
|
||||
return extractSubDir(&zip, subdir, dir);
|
||||
}
|
||||
|
||||
// ours
|
||||
bool MMCZip::extractFile(QString fileCompressed, QString file, QString target)
|
||||
bool extractFile(QString fileCompressed, QString file, QString target)
|
||||
{
|
||||
QuaZip zip(fileCompressed);
|
||||
if (!zip.open(QuaZip::mdUnzip))
|
||||
{
|
||||
if (!zip.open(QuaZip::mdUnzip)) {
|
||||
// check if this is a minimum size empty zip file...
|
||||
QFileInfo fileInfo(fileCompressed);
|
||||
if (fileInfo.size() == 22) {
|
||||
@ -407,13 +383,14 @@ bool MMCZip::extractFile(QString fileCompressed, QString file, QString target)
|
||||
qWarning() << "Could not open archive for unzipping:" << fileCompressed << "Error:" << zip.getZipError();
|
||||
return false;
|
||||
}
|
||||
return MMCZip::extractRelFile(&zip, file, target);
|
||||
return extractRelFile(&zip, file, target);
|
||||
}
|
||||
|
||||
bool MMCZip::collectFileListRecursively(const QString& rootDir, const QString& subDir, QFileInfoList *files,
|
||||
MMCZip::FilterFunction excludeFilter) {
|
||||
bool collectFileListRecursively(const QString& rootDir, const QString& subDir, QFileInfoList* files, FilterFunction excludeFilter)
|
||||
{
|
||||
QDir rootDirectory(rootDir);
|
||||
if (!rootDirectory.exists()) return false;
|
||||
if (!rootDirectory.exists())
|
||||
return false;
|
||||
|
||||
QDir directory;
|
||||
if (subDir == nullptr)
|
||||
@ -421,7 +398,8 @@ bool MMCZip::collectFileListRecursively(const QString& rootDir, const QString& s
|
||||
else
|
||||
directory = QDir(subDir);
|
||||
|
||||
if (!directory.exists()) return false; // shouldn't ever happen
|
||||
if (!directory.exists())
|
||||
return false; // shouldn't ever happen
|
||||
|
||||
// recurse directories
|
||||
QFileInfoList entries = directory.entryInfoList(QDir::AllDirs | QDir::NoDotAndDotDot | QDir::Hidden);
|
||||
@ -439,7 +417,88 @@ bool MMCZip::collectFileListRecursively(const QString& rootDir, const QString& s
|
||||
continue;
|
||||
}
|
||||
|
||||
files->append(e); // we want the original paths for MMCZip::compressDirFiles
|
||||
files->append(e); // we want the original paths for compressDirFiles
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void ExportToZipTask::executeTask()
|
||||
{
|
||||
setStatus("Adding files...");
|
||||
setProgress(0, m_files.length());
|
||||
m_build_zip_future = QtConcurrent::run(QThreadPool::globalInstance(), [this]() { return exportZip(); });
|
||||
connect(&m_build_zip_watcher, &QFutureWatcher<ZipResult>::finished, this, &ExportToZipTask::finish);
|
||||
m_build_zip_watcher.setFuture(m_build_zip_future);
|
||||
}
|
||||
|
||||
auto ExportToZipTask::exportZip() -> ZipResult
|
||||
{
|
||||
if (!m_dir.exists()) {
|
||||
return ZipResult(tr("Folder doesn't exist"));
|
||||
}
|
||||
if (!m_output.isOpen() && !m_output.open(QuaZip::mdCreate)) {
|
||||
return ZipResult(tr("Could not create file"));
|
||||
}
|
||||
|
||||
for (auto fileName : m_extra_files.keys()) {
|
||||
if (m_build_zip_future.isCanceled())
|
||||
return ZipResult();
|
||||
QuaZipFile indexFile(&m_output);
|
||||
if (!indexFile.open(QIODevice::WriteOnly, QuaZipNewInfo(fileName))) {
|
||||
return ZipResult(tr("Could not create:") + fileName);
|
||||
}
|
||||
indexFile.write(m_extra_files[fileName]);
|
||||
}
|
||||
|
||||
for (const QFileInfo& file : m_files) {
|
||||
if (m_build_zip_future.isCanceled())
|
||||
return ZipResult();
|
||||
|
||||
auto absolute = file.absoluteFilePath();
|
||||
auto relative = m_dir.relativeFilePath(absolute);
|
||||
setStatus("Compresing: " + relative);
|
||||
setProgress(m_progress + 1, m_progressTotal);
|
||||
if (m_follow_symlinks) {
|
||||
if (file.isSymLink())
|
||||
absolute = file.symLinkTarget();
|
||||
else
|
||||
absolute = file.canonicalFilePath();
|
||||
}
|
||||
|
||||
if (!m_exclude_files.contains(relative) && !JlCompress::compressFile(&m_output, absolute, m_destination_prefix + relative)) {
|
||||
return ZipResult(tr("Could not read and compress %1").arg(relative));
|
||||
}
|
||||
}
|
||||
|
||||
m_output.close();
|
||||
if (m_output.getZipError() != 0) {
|
||||
return ZipResult(tr("A zip error occurred"));
|
||||
}
|
||||
return ZipResult();
|
||||
}
|
||||
|
||||
void ExportToZipTask::finish()
|
||||
{
|
||||
if (m_build_zip_future.isCanceled()) {
|
||||
QFile::remove(m_output_path);
|
||||
emitAborted();
|
||||
} else if (auto result = m_build_zip_future.result(); result.has_value()) {
|
||||
QFile::remove(m_output_path);
|
||||
emitFailed(result.value());
|
||||
} else {
|
||||
emitSucceeded();
|
||||
}
|
||||
}
|
||||
|
||||
bool ExportToZipTask::abort()
|
||||
{
|
||||
if (m_build_zip_future.isRunning()) {
|
||||
m_build_zip_future.cancel();
|
||||
// NOTE: Here we don't do `emitAborted()` because it will be done when `m_build_zip_future` actually cancels, which may not occur
|
||||
// immediately.
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace MMCZip
|
@ -1,7 +1,8 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
/*
|
||||
* PolyMC - Minecraft Launcher
|
||||
* Prism Launcher - Minecraft Launcher
|
||||
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
|
||||
* Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
@ -35,24 +36,28 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <QString>
|
||||
#include <QFileInfo>
|
||||
#include <QSet>
|
||||
#include "minecraft/mod/Mod.h"
|
||||
#include <functional>
|
||||
|
||||
#include <quazip.h>
|
||||
#include <quazip/JlCompress.h>
|
||||
#include <QDir>
|
||||
#include <QFileInfo>
|
||||
#include <QFuture>
|
||||
#include <QFutureWatcher>
|
||||
#include <QHash>
|
||||
#include <QSet>
|
||||
#include <QString>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include "minecraft/mod/Mod.h"
|
||||
#include "tasks/Task.h"
|
||||
|
||||
namespace MMCZip
|
||||
{
|
||||
namespace MMCZip {
|
||||
using FilterFunction = std::function<bool(const QString&)>;
|
||||
|
||||
/**
|
||||
* Merge two zip files, using a filter function
|
||||
*/
|
||||
bool mergeZipFiles(QuaZip *into, QFileInfo from, QSet<QString> &contained,
|
||||
const FilterFunction filter = nullptr);
|
||||
bool mergeZipFiles(QuaZip* into, QFileInfo from, QSet<QString>& contained, const FilterFunction filter = nullptr);
|
||||
|
||||
/**
|
||||
* Compress directory, by providing a list of files to compress
|
||||
@ -141,4 +146,47 @@ namespace MMCZip
|
||||
* \return true for success or false for failure
|
||||
*/
|
||||
bool collectFileListRecursively(const QString& rootDir, const QString& subDir, QFileInfoList* files, FilterFunction excludeFilter);
|
||||
}
|
||||
|
||||
class ExportToZipTask : public Task {
|
||||
public:
|
||||
ExportToZipTask(QString outputPath, QDir dir, QFileInfoList files, QString destinationPrefix = "", bool followSymlinks = false)
|
||||
: m_output_path(outputPath)
|
||||
, m_output(outputPath)
|
||||
, m_dir(dir)
|
||||
, m_files(files)
|
||||
, m_destination_prefix(destinationPrefix)
|
||||
, m_follow_symlinks(followSymlinks)
|
||||
{
|
||||
setAbortable(true);
|
||||
};
|
||||
ExportToZipTask(QString outputPath, QString dir, QFileInfoList files, QString destinationPrefix = "", bool followSymlinks = false)
|
||||
: ExportToZipTask(outputPath, QDir(dir), files, destinationPrefix, followSymlinks){};
|
||||
|
||||
virtual ~ExportToZipTask() = default;
|
||||
|
||||
void setExcludeFiles(QStringList excludeFiles) { m_exclude_files = excludeFiles; }
|
||||
void addExtraFile(QString fileName, QByteArray data) { m_extra_files.insert(fileName, data); }
|
||||
|
||||
typedef std::optional<QString> ZipResult;
|
||||
|
||||
protected:
|
||||
virtual void executeTask() override;
|
||||
bool abort() override;
|
||||
|
||||
ZipResult exportZip();
|
||||
void finish();
|
||||
|
||||
private:
|
||||
QString m_output_path;
|
||||
QuaZip m_output;
|
||||
QDir m_dir;
|
||||
QFileInfoList m_files;
|
||||
QString m_destination_prefix;
|
||||
bool m_follow_symlinks;
|
||||
QStringList m_exclude_files;
|
||||
QHash<QString, QByteArray> m_extra_files;
|
||||
|
||||
QFuture<ZipResult> m_build_zip_future;
|
||||
QFutureWatcher<ZipResult> m_build_zip_watcher;
|
||||
};
|
||||
} // namespace MMCZip
|
||||
|
@ -3,6 +3,8 @@
|
||||
#include <QCoreApplication>
|
||||
#include <QPixmapCache>
|
||||
#include <QThread>
|
||||
#include <QTime>
|
||||
#include <QDebug>
|
||||
|
||||
#define GET_TYPE() \
|
||||
Qt::ConnectionType type; \
|
||||
@ -60,6 +62,8 @@ class PixmapCache final : public QObject {
|
||||
DEFINE_FUNC_ONE_PARAM(remove, bool, const QPixmapCache::Key&)
|
||||
DEFINE_FUNC_TWO_PARAM(replace, bool, const QPixmapCache::Key&, const QPixmap&)
|
||||
DEFINE_FUNC_ONE_PARAM(setCacheLimit, bool, int)
|
||||
DEFINE_FUNC_NO_PARAM(markCacheMissByEviciton, bool)
|
||||
DEFINE_FUNC_ONE_PARAM(setFastEvictionThreshold, bool, int)
|
||||
|
||||
// NOTE: Every function returns something non-void to simplify the macros.
|
||||
private slots:
|
||||
@ -90,6 +94,43 @@ class PixmapCache final : public QObject {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark that a cache miss occurred because of a eviction if too many of these occur too fast the cache size is increased
|
||||
* @return if the cache size was increased
|
||||
*/
|
||||
bool _markCacheMissByEviciton()
|
||||
{
|
||||
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
|
||||
++m_consecutive_fast_evicitons;
|
||||
} else {
|
||||
m_consecutive_fast_evicitons = 0;
|
||||
}
|
||||
}
|
||||
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);
|
||||
m_consecutive_fast_evicitons = 0;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool _setFastEvictionThreshold(int threshold)
|
||||
{
|
||||
m_consecutive_fast_evicitons_threshold = threshold;
|
||||
return true;
|
||||
}
|
||||
|
||||
private:
|
||||
static PixmapCache* s_instance;
|
||||
QTime m_last_cache_miss_by_eviciton;
|
||||
int m_consecutive_fast_evicitons = 0;
|
||||
int m_consecutive_fast_evicitons_threshold = 15;
|
||||
};
|
||||
|
31
launcher/Markdown.cpp
Normal file
31
launcher/Markdown.cpp
Normal file
@ -0,0 +1,31 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
/*
|
||||
* Prism Launcher - Minecraft Launcher
|
||||
* Copyright (C) 2023 Joshua Goins <josh@redstrate.com>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "Markdown.h"
|
||||
|
||||
QString markdownToHTML(const QString& markdown)
|
||||
{
|
||||
const QByteArray markdownData = markdown.toUtf8();
|
||||
char* buffer = cmark_markdown_to_html(markdownData.constData(), markdownData.length(), CMARK_OPT_NOBREAKS | CMARK_OPT_UNSAFE);
|
||||
|
||||
QString htmlStr(buffer);
|
||||
|
||||
free(buffer);
|
||||
|
||||
return htmlStr;
|
||||
}
|
@ -21,14 +21,4 @@
|
||||
#include <QString>
|
||||
#include <cmark.h>
|
||||
|
||||
static QString markdownToHTML(const QString& markdown)
|
||||
{
|
||||
const QByteArray markdownData = markdown.toUtf8();
|
||||
char* buffer = cmark_markdown_to_html(markdownData.constData(), markdownData.length(), CMARK_OPT_NOBREAKS | CMARK_OPT_UNSAFE);
|
||||
|
||||
QString htmlStr(buffer);
|
||||
|
||||
free(buffer);
|
||||
|
||||
return htmlStr;
|
||||
}
|
||||
QString markdownToHTML(const QString& markdown);
|
@ -38,6 +38,8 @@ class ResourceDownloadTask : public SequentialTask {
|
||||
const QString& getFilename() const { return m_pack_version.fileName; }
|
||||
const QString& getCustomPath() const { return m_custom_target_folder; }
|
||||
const QVariant& getVersionID() const { return m_pack_version.fileId; }
|
||||
const ModPlatform::IndexedVersion& getVersion() const { return m_pack_version; }
|
||||
const ModPlatform::ResourceProvider& getProvider() const { return m_pack->provider; }
|
||||
const QString& getName() const { return m_pack->name; }
|
||||
ModPlatform::IndexedPack::Ptr getPack() { return m_pack; }
|
||||
|
||||
|
@ -1,7 +1,8 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
/*
|
||||
* PolyMC - Minecraft Launcher
|
||||
* Prism Launcher - Minecraft Launcher
|
||||
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
|
||||
* Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
@ -54,9 +55,14 @@ public:
|
||||
bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const
|
||||
{
|
||||
const auto &filters = m_parent->filters();
|
||||
const QString &search = m_parent->search();
|
||||
const QModelIndex idx = sourceModel()->index(source_row, 0, source_parent);
|
||||
|
||||
if (!search.isEmpty() && !sourceModel()->data(idx, BaseVersionList::VersionRole).toString().contains(search, Qt::CaseInsensitive))
|
||||
return false;
|
||||
|
||||
for (auto it = filters.begin(); it != filters.end(); ++it)
|
||||
{
|
||||
auto idx = sourceModel()->index(source_row, 0, source_parent);
|
||||
auto data = sourceModel()->data(idx, it.key());
|
||||
auto match = data.toString();
|
||||
if(!it.value()->accepts(match))
|
||||
@ -187,37 +193,23 @@ QVariant VersionProxyModel::data(const QModelIndex &index, int role) const
|
||||
}
|
||||
case Qt::ToolTipRole:
|
||||
{
|
||||
switch(column)
|
||||
{
|
||||
case Name:
|
||||
{
|
||||
if(hasRecommended)
|
||||
if(column == Name && hasRecommended)
|
||||
{
|
||||
auto value = sourceModel()->data(parentIndex, BaseVersionList::RecommendedRole);
|
||||
if(value.toBool())
|
||||
{
|
||||
return tr("Recommended");
|
||||
}
|
||||
else if(hasLatest)
|
||||
{
|
||||
} else if(hasLatest) {
|
||||
auto value = sourceModel()->data(parentIndex, BaseVersionList::LatestRole);
|
||||
if(value.toBool())
|
||||
{
|
||||
return tr("Latest");
|
||||
}
|
||||
}
|
||||
else if(index.row() == 0)
|
||||
{
|
||||
return tr("Latest");
|
||||
}
|
||||
}
|
||||
}
|
||||
default:
|
||||
{
|
||||
} else {
|
||||
return sourceModel()->data(parentIndex, BaseVersionList::VersionIdRole);
|
||||
}
|
||||
}
|
||||
}
|
||||
case Qt::DecorationRole:
|
||||
{
|
||||
switch(column)
|
||||
@ -239,10 +231,6 @@ QVariant VersionProxyModel::data(const QModelIndex &index, int role) const
|
||||
return APPLICATION->getThemedIcon("bug");
|
||||
}
|
||||
}
|
||||
else if(index.row() == 0)
|
||||
{
|
||||
return APPLICATION->getThemedIcon("bug");
|
||||
}
|
||||
QPixmap pixmap;
|
||||
QPixmapCache::find("placeholder", &pixmap);
|
||||
if(!pixmap)
|
||||
@ -431,6 +419,7 @@ QModelIndex VersionProxyModel::getVersion(const QString& version) const
|
||||
void VersionProxyModel::clearFilters()
|
||||
{
|
||||
m_filters.clear();
|
||||
m_search.clear();
|
||||
filterModel->filterChanged();
|
||||
}
|
||||
|
||||
@ -440,11 +429,21 @@ void VersionProxyModel::setFilter(const BaseVersionList::ModelRoles column, Filt
|
||||
filterModel->filterChanged();
|
||||
}
|
||||
|
||||
void VersionProxyModel::setSearch(const QString &search) {
|
||||
m_search = search;
|
||||
filterModel->filterChanged();
|
||||
}
|
||||
|
||||
const VersionProxyModel::FilterMap &VersionProxyModel::filters() const
|
||||
{
|
||||
return m_filters;
|
||||
}
|
||||
|
||||
const QString &VersionProxyModel::search() const
|
||||
{
|
||||
return m_search;
|
||||
}
|
||||
|
||||
void VersionProxyModel::sourceAboutToBeReset()
|
||||
{
|
||||
beginResetModel();
|
||||
|
@ -38,7 +38,9 @@ public:
|
||||
virtual void setSourceModel(QAbstractItemModel *sourceModel) override;
|
||||
|
||||
const FilterMap &filters() const;
|
||||
const QString &search() const;
|
||||
void setFilter(const BaseVersionList::ModelRoles column, Filter * filter);
|
||||
void setSearch(const QString &search);
|
||||
void clearFilters();
|
||||
QModelIndex getRecommended() const;
|
||||
QModelIndex getVersion(const QString & version) const;
|
||||
@ -59,6 +61,7 @@ private slots:
|
||||
private:
|
||||
QList<Column> m_columns;
|
||||
FilterMap m_filters;
|
||||
QString m_search;
|
||||
BaseVersionList::RoleList roles;
|
||||
VersionFilterModel * filterModel;
|
||||
bool hasRecommended = false;
|
||||
|
@ -85,7 +85,7 @@ void JavaChecker::performCheck()
|
||||
process->setProgram(m_path);
|
||||
process->setProcessChannelMode(QProcess::SeparateChannels);
|
||||
process->setProcessEnvironment(CleanEnviroment());
|
||||
qDebug() << "Running java checker: " + m_path + args.join(" ");;
|
||||
qDebug() << "Running java checker:" << m_path << args.join(" ");
|
||||
|
||||
connect(process.get(), QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this, &JavaChecker::finished);
|
||||
connect(process.get(), &QProcess::errorOccurred, this, &JavaChecker::error);
|
||||
|
@ -1,5 +1,24 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
/*
|
||||
* Prism Launcher - Minecraft Launcher
|
||||
* Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "JavaInstall.h"
|
||||
|
||||
#include "BaseVersion.h"
|
||||
#include "StringUtils.h"
|
||||
|
||||
bool JavaInstall::operator<(const JavaInstall& rhs)
|
||||
@ -7,12 +26,10 @@ bool JavaInstall::operator<(const JavaInstall &rhs)
|
||||
auto archCompare = StringUtils::naturalCompare(arch, rhs.arch, Qt::CaseInsensitive);
|
||||
if (archCompare != 0)
|
||||
return archCompare < 0;
|
||||
if(id < rhs.id)
|
||||
{
|
||||
if (id < rhs.id) {
|
||||
return true;
|
||||
}
|
||||
if(id > rhs.id)
|
||||
{
|
||||
if (id > rhs.id) {
|
||||
return false;
|
||||
}
|
||||
return StringUtils::naturalCompare(path, rhs.path, Qt::CaseInsensitive) < 0;
|
||||
@ -27,3 +44,21 @@ bool JavaInstall::operator>(const JavaInstall &rhs)
|
||||
{
|
||||
return (!operator<(rhs)) && (!operator==(rhs));
|
||||
}
|
||||
|
||||
bool JavaInstall::operator<(BaseVersion& a)
|
||||
{
|
||||
try {
|
||||
return operator<(dynamic_cast<JavaInstall&>(a));
|
||||
} catch (const std::bad_cast& e) {
|
||||
return BaseVersion::operator<(a);
|
||||
}
|
||||
}
|
||||
|
||||
bool JavaInstall::operator>(BaseVersion& a)
|
||||
{
|
||||
try {
|
||||
return operator>(dynamic_cast<JavaInstall&>(a));
|
||||
} catch (const std::bad_cast& e) {
|
||||
return BaseVersion::operator>(a);
|
||||
}
|
||||
}
|
||||
|
@ -1,30 +1,37 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
/*
|
||||
* Prism Launcher - Minecraft Launcher
|
||||
* Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "BaseVersion.h"
|
||||
#include "JavaVersion.h"
|
||||
|
||||
struct JavaInstall : public BaseVersion
|
||||
{
|
||||
struct JavaInstall : public BaseVersion {
|
||||
JavaInstall() {}
|
||||
JavaInstall(QString id, QString arch, QString path)
|
||||
: id(id), arch(arch), path(path)
|
||||
{
|
||||
}
|
||||
virtual QString descriptor()
|
||||
{
|
||||
return id.toString();
|
||||
}
|
||||
JavaInstall(QString id, QString arch, QString path) : id(id), arch(arch), path(path) {}
|
||||
virtual QString descriptor() { return id.toString(); }
|
||||
|
||||
virtual QString name()
|
||||
{
|
||||
return id.toString();
|
||||
}
|
||||
virtual QString name() { return id.toString(); }
|
||||
|
||||
virtual QString typeString() const
|
||||
{
|
||||
return arch;
|
||||
}
|
||||
virtual QString typeString() const { return arch; }
|
||||
|
||||
virtual bool operator<(BaseVersion& a) override;
|
||||
virtual bool operator>(BaseVersion& a) override;
|
||||
bool operator<(const JavaInstall& rhs);
|
||||
bool operator==(const JavaInstall& rhs);
|
||||
bool operator>(const JavaInstall& rhs);
|
||||
|
@ -1,7 +1,8 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
/*
|
||||
* PolyMC - Minecraft Launcher
|
||||
* Prism Launcher - Minecraft Launcher
|
||||
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
|
||||
* Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
@ -98,6 +99,8 @@ QVariant JavaInstallList::data(const QModelIndex &index, int role) const
|
||||
auto version = std::dynamic_pointer_cast<JavaInstall>(m_vlist[index.row()]);
|
||||
switch (role)
|
||||
{
|
||||
case SortRole:
|
||||
return -index.row();
|
||||
case VersionPointerRole:
|
||||
return QVariant::fromValue(m_vlist[index.row()]);
|
||||
case VersionIdRole:
|
||||
|
@ -81,15 +81,20 @@ void CheckJava::executeTask()
|
||||
}
|
||||
|
||||
QFileInfo javaInfo(realJavaPath);
|
||||
qlonglong javaUnixTime = javaInfo.lastModified().toMSecsSinceEpoch();
|
||||
auto storedUnixTime = settings->get("JavaTimestamp").toLongLong();
|
||||
qint64 javaUnixTime = javaInfo.lastModified().toMSecsSinceEpoch();
|
||||
auto storedSignature = settings->get("JavaSignature").toString();
|
||||
auto storedArchitecture = settings->get("JavaArchitecture").toString();
|
||||
auto storedRealArchitecture = settings->get("JavaRealArchitecture").toString();
|
||||
auto storedVersion = settings->get("JavaVersion").toString();
|
||||
auto storedVendor = settings->get("JavaVendor").toString();
|
||||
m_javaUnixTime = javaUnixTime;
|
||||
|
||||
QCryptographicHash hash(QCryptographicHash::Sha1);
|
||||
hash.addData(QByteArray::number(javaUnixTime));
|
||||
hash.addData(m_javaPath.toUtf8());
|
||||
m_javaSignature = hash.result().toHex();
|
||||
|
||||
// if timestamps are not the same, or something is missing, check!
|
||||
if (javaUnixTime != storedUnixTime || storedVersion.size() == 0
|
||||
if (m_javaSignature != storedSignature || storedVersion.size() == 0
|
||||
|| storedArchitecture.size() == 0 || storedRealArchitecture.size() == 0
|
||||
|| storedVendor.size() == 0)
|
||||
{
|
||||
@ -140,7 +145,7 @@ void CheckJava::checkJavaFinished(JavaCheckResult result)
|
||||
instance->settings()->set("JavaArchitecture", result.mojangPlatform);
|
||||
instance->settings()->set("JavaRealArchitecture", result.realPlatform);
|
||||
instance->settings()->set("JavaVendor", result.javaVendor);
|
||||
instance->settings()->set("JavaTimestamp", m_javaUnixTime);
|
||||
instance->settings()->set("JavaSignature", m_javaSignature);
|
||||
emitSucceeded();
|
||||
return;
|
||||
}
|
||||
|
@ -40,6 +40,6 @@ private:
|
||||
|
||||
private:
|
||||
QString m_javaPath;
|
||||
qlonglong m_javaUnixTime;
|
||||
QString m_javaSignature;
|
||||
JavaCheckerPtr m_JavaChecker;
|
||||
};
|
||||
|
@ -45,10 +45,10 @@ QVariant Index::data(const QModelIndex &index, int role) const
|
||||
switch (role)
|
||||
{
|
||||
case Qt::DisplayRole:
|
||||
switch (index.column())
|
||||
{
|
||||
case 0: return list->humanReadable();
|
||||
default: break;
|
||||
if (index.column() == 0) {
|
||||
return list->humanReadable();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
case UidRole: return list->uid();
|
||||
case NameRole: return list->name();
|
||||
|
@ -4,6 +4,7 @@
|
||||
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
|
||||
* Copyright (C) 2022 Jamie Mansfield <jmansfield@cadixdev.org>
|
||||
* Copyright (C) 2022 TheKodeToad <TheKodeToad@proton.me>
|
||||
* Copyright (c) 2023 seth <getchoo at tuta dot io>
|
||||
*
|
||||
* 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
|
||||
@ -148,10 +149,11 @@ void MinecraftInstance::loadSpecificSettings()
|
||||
m_settings->registerOverride(global_settings->getSetting("IgnoreJavaCompatibility"), javaOrLocation);
|
||||
|
||||
// special!
|
||||
m_settings->registerPassthrough(global_settings->getSetting("JavaTimestamp"), javaOrLocation);
|
||||
m_settings->registerPassthrough(global_settings->getSetting("JavaVersion"), javaOrLocation);
|
||||
m_settings->registerPassthrough(global_settings->getSetting("JavaSignature"), javaOrLocation);
|
||||
m_settings->registerPassthrough(global_settings->getSetting("JavaArchitecture"), javaOrLocation);
|
||||
m_settings->registerPassthrough(global_settings->getSetting("JavaRealArchitecture"), javaOrLocation);
|
||||
m_settings->registerPassthrough(global_settings->getSetting("JavaVersion"), javaOrLocation);
|
||||
m_settings->registerPassthrough(global_settings->getSetting("JavaVendor"), javaOrLocation);
|
||||
|
||||
// Window Size
|
||||
auto windowSetting = m_settings->registerSetting("OverrideWindow", false);
|
||||
@ -185,6 +187,10 @@ void MinecraftInstance::loadSpecificSettings()
|
||||
m_settings->registerOverride(global_settings->getSetting("CloseAfterLaunch"), miscellaneousOverride);
|
||||
m_settings->registerOverride(global_settings->getSetting("QuitAfterGameStop"), miscellaneousOverride);
|
||||
|
||||
// Mod loader specific options
|
||||
auto modLoaderSettings = m_settings->registerSetting("OverrideModLoaderSettings", false);
|
||||
m_settings->registerOverride(global_settings->getSetting("DisableQuiltBeacon"), modLoaderSettings);
|
||||
|
||||
m_settings->set("InstanceType", "OneSix");
|
||||
}
|
||||
|
||||
@ -392,6 +398,12 @@ QStringList MinecraftInstance::extraArguments()
|
||||
agent->library()->getApplicableFiles(runtimeContext(), jar, temp1, temp2, temp3, getLocalLibraryPath());
|
||||
list.append("-javaagent:"+jar[0]+(agent->argument().isEmpty() ? "" : "="+agent->argument()));
|
||||
}
|
||||
|
||||
{
|
||||
const auto loaders = version->getModLoaders();
|
||||
if (loaders.has_value() && loaders.value() & ResourceAPI::Quilt && settings()->get("DisableQuiltBeacon").toBool())
|
||||
list.append("-Dloader.disable_beacon=true");
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
@ -1124,36 +1136,27 @@ JavaVersion MinecraftInstance::getJavaVersion()
|
||||
|
||||
std::shared_ptr<ModFolderModel> MinecraftInstance::loaderModList()
|
||||
{
|
||||
if (!m_loader_mod_list)
|
||||
{
|
||||
if (!m_loader_mod_list) {
|
||||
bool is_indexed = !APPLICATION->settings()->get("ModMetadataDisabled").toBool();
|
||||
m_loader_mod_list.reset(new ModFolderModel(modsRoot(), this, is_indexed));
|
||||
m_loader_mod_list->disableInteraction(isRunning());
|
||||
connect(this, &BaseInstance::runningStatusChanged, m_loader_mod_list.get(), &ModFolderModel::disableInteraction);
|
||||
}
|
||||
return m_loader_mod_list;
|
||||
}
|
||||
|
||||
std::shared_ptr<ModFolderModel> MinecraftInstance::coreModList()
|
||||
{
|
||||
if (!m_core_mod_list)
|
||||
{
|
||||
if (!m_core_mod_list) {
|
||||
bool is_indexed = !APPLICATION->settings()->get("ModMetadataDisabled").toBool();
|
||||
m_core_mod_list.reset(new ModFolderModel(coreModsDir(), this, is_indexed));
|
||||
m_core_mod_list->disableInteraction(isRunning());
|
||||
connect(this, &BaseInstance::runningStatusChanged, m_core_mod_list.get(), &ModFolderModel::disableInteraction);
|
||||
}
|
||||
return m_core_mod_list;
|
||||
}
|
||||
|
||||
std::shared_ptr<ModFolderModel> MinecraftInstance::nilModList()
|
||||
{
|
||||
if (!m_nil_mod_list)
|
||||
{
|
||||
if (!m_nil_mod_list) {
|
||||
bool is_indexed = !APPLICATION->settings()->get("ModMetadataDisabled").toBool();
|
||||
m_nil_mod_list.reset(new ModFolderModel(nilModsDir(), this, is_indexed, false));
|
||||
m_nil_mod_list->disableInteraction(isRunning());
|
||||
connect(this, &BaseInstance::runningStatusChanged, m_nil_mod_list.get(), &ModFolderModel::disableInteraction);
|
||||
}
|
||||
return m_nil_mod_list;
|
||||
}
|
||||
|
@ -65,7 +65,8 @@
|
||||
static const QMap<QString, ResourceAPI::ModLoaderType> modloaderMapping{
|
||||
{"net.minecraftforge", ResourceAPI::Forge},
|
||||
{"net.fabricmc.fabric-loader", ResourceAPI::Fabric},
|
||||
{"org.quiltmc.quilt-loader", ResourceAPI::Quilt}
|
||||
{"org.quiltmc.quilt-loader", ResourceAPI::Quilt},
|
||||
{"com.mumfrey.liteloader", ResourceAPI::LiteLoader}
|
||||
};
|
||||
|
||||
PackProfile::PackProfile(MinecraftInstance * instance)
|
||||
|
@ -328,18 +328,21 @@ QVariant AccountList::data(const QModelIndex &index, int role) const
|
||||
case AccountState::Gone: {
|
||||
return tr("Gone", "Account status");
|
||||
}
|
||||
default: {
|
||||
return tr("Unknown", "Account status");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
case MigrationColumn: {
|
||||
if(account->isMSA() || account->isOffline()) {
|
||||
return tr("N/A", "Can Migrate?");
|
||||
return tr("N/A", "Can Migrate");
|
||||
}
|
||||
if (account->canMigrate()) {
|
||||
return tr("Yes", "Can Migrate?");
|
||||
return tr("Yes", "Can Migrate");
|
||||
}
|
||||
else {
|
||||
return tr("No", "Can Migrate?");
|
||||
return tr("No", "Can Migrate");
|
||||
}
|
||||
}
|
||||
|
||||
@ -354,12 +357,13 @@ QVariant AccountList::data(const QModelIndex &index, int role) const
|
||||
return QVariant::fromValue(account);
|
||||
|
||||
case Qt::CheckStateRole:
|
||||
switch (index.column())
|
||||
{
|
||||
case ProfileNameColumn:
|
||||
if (index.column() == ProfileNameColumn) {
|
||||
return account == m_defaultAccount ? Qt::Checked : Qt::Unchecked;
|
||||
} else {
|
||||
return QVariant();
|
||||
}
|
||||
|
||||
|
||||
default:
|
||||
return QVariant();
|
||||
}
|
||||
|
@ -26,6 +26,7 @@ bool AuthSession::MakeOffline(QString offline_playername)
|
||||
return false;
|
||||
}
|
||||
session = "-";
|
||||
access_token = "0";
|
||||
player_name = offline_playername;
|
||||
status = PlayableOffline;
|
||||
return true;
|
||||
|
@ -37,6 +37,7 @@
|
||||
|
||||
#include "MinecraftAccount.h"
|
||||
|
||||
#include <QCryptographicHash>
|
||||
#include <QUuid>
|
||||
#include <QJsonObject>
|
||||
#include <QJsonArray>
|
||||
@ -100,7 +101,7 @@ MinecraftAccountPtr MinecraftAccount::createOffline(const QString &username)
|
||||
account->data.yggdrasilToken.extra["clientToken"] = QUuid::createUuid().toString().remove(QRegularExpression("[{}-]"));
|
||||
account->data.minecraftEntitlement.ownsMinecraft = true;
|
||||
account->data.minecraftEntitlement.canPlayMinecraft = true;
|
||||
account->data.minecraftProfile.id = QUuid::createUuid().toString().remove(QRegularExpression("[{}-]"));
|
||||
account->data.minecraftProfile.id = uuidFromUsername(username).toString().remove(QRegularExpression("[{}-]"));
|
||||
account->data.minecraftProfile.name = username;
|
||||
account->data.minecraftProfile.validity = Katabasis::Validity::Certain;
|
||||
return account;
|
||||
@ -334,3 +335,32 @@ void MinecraftAccount::incrementUses()
|
||||
qWarning() << "Profile" << data.profileId() << "is now in use.";
|
||||
}
|
||||
}
|
||||
|
||||
QUuid MinecraftAccount::uuidFromUsername(QString username) {
|
||||
auto input = QString("OfflinePlayer:%1").arg(username).toUtf8();
|
||||
|
||||
// basically a reimplementation of Java's UUID#nameUUIDFromBytes
|
||||
QByteArray digest = QCryptographicHash::hash(input, QCryptographicHash::Md5);
|
||||
|
||||
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
|
||||
auto bOr = [](QByteArray& array, int index, char value) {
|
||||
array[index] = array.at(index) | value;
|
||||
};
|
||||
auto bAnd = [](QByteArray& array, int index, char value) {
|
||||
array[index] = array.at(index) & value;
|
||||
};
|
||||
#else
|
||||
auto bOr = [](QByteArray& array, qsizetype index, char value) {
|
||||
array[index] |= value;
|
||||
};
|
||||
auto bAnd = [](QByteArray& array, qsizetype index, char value) {
|
||||
array[index] &= value;
|
||||
};
|
||||
#endif
|
||||
bAnd(digest, 6, (char) 0x0f); // clear version
|
||||
bOr(digest, 6, (char) 0x30); // set to version 3
|
||||
bAnd(digest, 8, (char) 0x3f); // clear variant
|
||||
bOr(digest, 8, (char) 0x80); // set to IETF variant
|
||||
|
||||
return QUuid::fromRfc4122(digest);
|
||||
}
|
||||
|
@ -98,6 +98,8 @@ public: /* construction */
|
||||
static MinecraftAccountPtr loadFromJsonV2(const QJsonObject &json);
|
||||
static MinecraftAccountPtr loadFromJsonV3(const QJsonObject &json);
|
||||
|
||||
static QUuid uuidFromUsername(QString username);
|
||||
|
||||
//! Saves a MinecraftAccount to a JSON object and returns it.
|
||||
QJsonObject saveToJson() const;
|
||||
|
||||
|
@ -273,6 +273,7 @@ void Yggdrasil::processReply() {
|
||||
AccountTaskState::STATE_FAILED_GONE,
|
||||
tr("The Mojang account no longer exists. It may have been migrated to a Microsoft account.")
|
||||
);
|
||||
return;
|
||||
}
|
||||
default:
|
||||
changeState(
|
||||
|
@ -74,6 +74,7 @@ std::pair<int, bool> DataPack::compare(const Resource& other, SortType type) con
|
||||
auto res = Resource::compare(other, type);
|
||||
if (res.first != 0)
|
||||
return res;
|
||||
break;
|
||||
}
|
||||
case SortType::PACK_FORMAT: {
|
||||
auto this_ver = packFormat();
|
||||
@ -83,6 +84,7 @@ std::pair<int, bool> DataPack::compare(const Resource& other, SortType type) con
|
||||
return { 1, type == SortType::PACK_FORMAT };
|
||||
if (this_ver < other_ver)
|
||||
return { -1, type == SortType::PACK_FORMAT };
|
||||
break;
|
||||
}
|
||||
}
|
||||
return { 0, false };
|
||||
|
@ -41,9 +41,11 @@
|
||||
#include <QString>
|
||||
#include <QRegularExpression>
|
||||
|
||||
#include "MTPixmapCache.h"
|
||||
#include "MetadataHandler.h"
|
||||
#include "Version.h"
|
||||
#include "minecraft/mod/ModDetails.h"
|
||||
#include "minecraft/mod/tasks/LocalModParseTask.h"
|
||||
|
||||
static ModPlatform::ProviderCapabilities ProviderCaps;
|
||||
|
||||
@ -89,6 +91,7 @@ std::pair<int, bool> Mod::compare(const Resource& other, SortType type) const
|
||||
auto res = Resource::compare(other, type);
|
||||
if (res.first != 0)
|
||||
return res;
|
||||
break;
|
||||
}
|
||||
case SortType::VERSION: {
|
||||
auto this_ver = Version(version());
|
||||
@ -97,11 +100,13 @@ std::pair<int, bool> Mod::compare(const Resource& other, SortType type) const
|
||||
return { 1, type == SortType::VERSION };
|
||||
if (this_ver < other_ver)
|
||||
return { -1, type == SortType::VERSION };
|
||||
break;
|
||||
}
|
||||
case SortType::PROVIDER: {
|
||||
auto compare_result = QString::compare(provider().value_or("Unknown"), cast_other->provider().value_or("Unknown"), Qt::CaseInsensitive);
|
||||
if (compare_result != 0)
|
||||
return { compare_result, type == SortType::PROVIDER };
|
||||
break;
|
||||
}
|
||||
}
|
||||
return { 0, false };
|
||||
@ -121,7 +126,7 @@ bool Mod::applyFilter(QRegularExpression filter) const
|
||||
return Resource::applyFilter(filter);
|
||||
}
|
||||
|
||||
auto Mod::destroy(QDir& index_dir, bool preserve_metadata) -> bool
|
||||
auto Mod::destroy(QDir& index_dir, bool preserve_metadata, bool attempt_trash) -> bool
|
||||
{
|
||||
if (!preserve_metadata) {
|
||||
qDebug() << QString("Destroying metadata for '%1' on purpose").arg(name());
|
||||
@ -134,7 +139,7 @@ auto Mod::destroy(QDir& index_dir, bool preserve_metadata) -> bool
|
||||
}
|
||||
}
|
||||
|
||||
return Resource::destroy();
|
||||
return Resource::destroy(attempt_trash);
|
||||
}
|
||||
|
||||
auto Mod::details() const -> const ModDetails&
|
||||
@ -164,6 +169,13 @@ auto Mod::homeurl() const -> QString
|
||||
return details().homeurl;
|
||||
}
|
||||
|
||||
auto Mod::metaurl() const -> QString
|
||||
{
|
||||
if (metadata() == nullptr)
|
||||
return homeurl();
|
||||
return ModPlatform::getMetaURL(metadata()->provider, metadata()->project_id);
|
||||
}
|
||||
|
||||
auto Mod::description() const -> QString
|
||||
{
|
||||
return details().description;
|
||||
@ -201,7 +213,10 @@ void Mod::finishResolvingWithDetails(ModDetails&& details)
|
||||
m_local_details = std::move(details);
|
||||
if (metadata)
|
||||
setMetadata(std::move(metadata));
|
||||
};
|
||||
if (!iconPath().isEmpty()) {
|
||||
m_pack_image_cache_key.was_read_attempt = false;
|
||||
}
|
||||
}
|
||||
|
||||
auto Mod::provider() const -> std::optional<QString>
|
||||
{
|
||||
@ -210,6 +225,56 @@ auto Mod::provider() const -> std::optional<QString>
|
||||
return {};
|
||||
}
|
||||
|
||||
auto Mod::licenses() const -> const QList<ModLicense>&
|
||||
{
|
||||
return details().licenses;
|
||||
}
|
||||
|
||||
auto Mod::issueTracker() const -> QString
|
||||
{
|
||||
return details().issue_tracker;
|
||||
}
|
||||
|
||||
void Mod::setIcon(QImage new_image) const
|
||||
{
|
||||
QMutexLocker locker(&m_data_lock);
|
||||
|
||||
Q_ASSERT(!new_image.isNull());
|
||||
|
||||
if (m_pack_image_cache_key.key.isValid())
|
||||
PixmapCache::remove(m_pack_image_cache_key.key);
|
||||
|
||||
// scale the image to avoid flooding the pixmapcache
|
||||
auto pixmap = QPixmap::fromImage(new_image.scaled({64, 64}, Qt::AspectRatioMode::KeepAspectRatioByExpanding));
|
||||
|
||||
m_pack_image_cache_key.key = PixmapCache::insert(pixmap);
|
||||
m_pack_image_cache_key.was_ever_used = true;
|
||||
m_pack_image_cache_key.was_read_attempt = true;
|
||||
}
|
||||
|
||||
QPixmap Mod::icon(QSize size, Qt::AspectRatioMode mode) const
|
||||
{
|
||||
QPixmap cached_image;
|
||||
if (PixmapCache::find(m_pack_image_cache_key.key, &cached_image)) {
|
||||
if (size.isNull())
|
||||
return cached_image;
|
||||
return cached_image.scaled(size, mode);
|
||||
}
|
||||
|
||||
// No valid image we can get
|
||||
if ((!m_pack_image_cache_key.was_ever_used && m_pack_image_cache_key.was_read_attempt) || iconPath().isEmpty())
|
||||
return {};
|
||||
|
||||
if (m_pack_image_cache_key.was_ever_used) {
|
||||
qDebug() << "Mod" << name() << "Had it's icon evicted form the cache. reloading...";
|
||||
PixmapCache::markCacheMissByEviciton();
|
||||
}
|
||||
// Image got evicted from the cache or an attempt to load it has not been made. load it and retry.
|
||||
m_pack_image_cache_key.was_read_attempt = true;
|
||||
ModUtils::loadIconFile(*this);
|
||||
return icon(size);
|
||||
}
|
||||
|
||||
bool Mod::valid() const
|
||||
{
|
||||
return !m_local_details.mod_id.isEmpty();
|
||||
|
@ -38,6 +38,10 @@
|
||||
#include <QDateTime>
|
||||
#include <QFileInfo>
|
||||
#include <QList>
|
||||
#include <QImage>
|
||||
#include <QMutex>
|
||||
#include <QPixmap>
|
||||
#include <QPixmapCache>
|
||||
|
||||
#include <optional>
|
||||
|
||||
@ -64,6 +68,16 @@ public:
|
||||
auto authors() const -> QStringList;
|
||||
auto status() const -> ModStatus;
|
||||
auto provider() const -> std::optional<QString>;
|
||||
auto licenses() const -> const QList<ModLicense>&;
|
||||
auto issueTracker() const -> QString;
|
||||
auto metaurl() const -> QString;
|
||||
|
||||
/** Get the intneral path to the mod's icon file*/
|
||||
QString iconPath() const { return m_local_details.icon_file; };
|
||||
/** Gets the icon of the mod, converted to a QPixmap for drawing, and scaled to size. */
|
||||
[[nodiscard]] QPixmap icon(QSize size, Qt::AspectRatioMode mode = Qt::AspectRatioMode::IgnoreAspectRatio) const;
|
||||
/** Thread-safe. */
|
||||
void setIcon(QImage new_image) const;
|
||||
|
||||
auto metadata() -> std::shared_ptr<Metadata::ModStruct>;
|
||||
auto metadata() const -> const std::shared_ptr<Metadata::ModStruct>;
|
||||
@ -79,10 +93,19 @@ public:
|
||||
[[nodiscard]] bool applyFilter(QRegularExpression filter) const override;
|
||||
|
||||
// Delete all the files of this mod
|
||||
auto destroy(QDir& index_dir, bool preserve_metadata = false) -> bool;
|
||||
auto destroy(QDir& index_dir, bool preserve_metadata = false, bool attempt_trash = true) -> bool;
|
||||
|
||||
void finishResolvingWithDetails(ModDetails&& details);
|
||||
|
||||
protected:
|
||||
ModDetails m_local_details;
|
||||
|
||||
mutable QMutex m_data_lock;
|
||||
|
||||
struct {
|
||||
QPixmapCache::Key key;
|
||||
bool was_ever_used = false;
|
||||
bool was_read_attempt = false;
|
||||
} mutable m_pack_image_cache_key;
|
||||
|
||||
};
|
||||
|
@ -39,6 +39,7 @@
|
||||
|
||||
#include <QString>
|
||||
#include <QStringList>
|
||||
#include <QUrl>
|
||||
|
||||
#include "minecraft/mod/MetadataHandler.h"
|
||||
|
||||
@ -49,6 +50,84 @@ enum class ModStatus {
|
||||
Unknown, // Default status
|
||||
};
|
||||
|
||||
struct ModLicense {
|
||||
QString name = {};
|
||||
QString id = {};
|
||||
QString url = {};
|
||||
QString description = {};
|
||||
|
||||
ModLicense() {}
|
||||
|
||||
ModLicense(const QString license) {
|
||||
// FIXME: come up with a better license parseing.
|
||||
// handle SPDX identifiers? https://spdx.org/licenses/
|
||||
auto parts = license.split(' ');
|
||||
QStringList notNameParts = {};
|
||||
for (auto part : parts) {
|
||||
auto url = QUrl(part);
|
||||
if (part.startsWith("(") && part.endsWith(")"))
|
||||
url = QUrl(part.mid(1, part.size() - 2));
|
||||
|
||||
if (url.isValid() && !url.scheme().isEmpty() && !url.host().isEmpty()) {
|
||||
this->url = url.toString();
|
||||
notNameParts.append(part);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
for (auto part : notNameParts) {
|
||||
parts.removeOne(part);
|
||||
}
|
||||
|
||||
auto licensePart = parts.join(' ');
|
||||
this->name = licensePart;
|
||||
this->description = licensePart;
|
||||
|
||||
if (parts.size() == 1) {
|
||||
this->id = parts.first();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
ModLicense(const QString name, const QString id, const QString url, const QString description) {
|
||||
this->name = name;
|
||||
this->id = id;
|
||||
this->url = url;
|
||||
this->description = description;
|
||||
}
|
||||
|
||||
ModLicense(const ModLicense& other)
|
||||
: name(other.name)
|
||||
, id(other.id)
|
||||
, url(other.url)
|
||||
, description(other.description)
|
||||
{}
|
||||
|
||||
ModLicense& operator=(const ModLicense& other)
|
||||
{
|
||||
this->name = other.name;
|
||||
this->id = other.id;
|
||||
this->url = other.url;
|
||||
this->description = other.description;
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
ModLicense& operator=(const ModLicense&& other)
|
||||
{
|
||||
this->name = other.name;
|
||||
this->id = other.id;
|
||||
this->url = other.url;
|
||||
this->description = other.description;
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
bool isEmpty() {
|
||||
return this->name.isEmpty() && this->id.isEmpty() && this->url.isEmpty() && this->description.isEmpty();
|
||||
}
|
||||
};
|
||||
|
||||
struct ModDetails
|
||||
{
|
||||
/* Mod ID as defined in the ModLoader-specific metadata */
|
||||
@ -72,6 +151,15 @@ struct ModDetails
|
||||
/* List of the author's names */
|
||||
QStringList authors = {};
|
||||
|
||||
/* Issue Tracker URL */
|
||||
QString issue_tracker = {};
|
||||
|
||||
/* License */
|
||||
QList<ModLicense> licenses = {};
|
||||
|
||||
/* Path of mod logo */
|
||||
QString icon_file = {};
|
||||
|
||||
/* Installation status of the mod */
|
||||
ModStatus status = ModStatus::Unknown;
|
||||
|
||||
@ -89,6 +177,9 @@ struct ModDetails
|
||||
, homeurl(other.homeurl)
|
||||
, description(other.description)
|
||||
, authors(other.authors)
|
||||
, issue_tracker(other.issue_tracker)
|
||||
, licenses(other.licenses)
|
||||
, icon_file(other.icon_file)
|
||||
, status(other.status)
|
||||
{}
|
||||
|
||||
@ -101,6 +192,9 @@ struct ModDetails
|
||||
this->homeurl = other.homeurl;
|
||||
this->description = other.description;
|
||||
this->authors = other.authors;
|
||||
this->issue_tracker = other.issue_tracker;
|
||||
this->licenses = other.licenses;
|
||||
this->icon_file = other.icon_file;
|
||||
this->status = other.status;
|
||||
|
||||
return *this;
|
||||
@ -115,6 +209,9 @@ struct ModDetails
|
||||
this->homeurl = other.homeurl;
|
||||
this->description = other.description;
|
||||
this->authors = other.authors;
|
||||
this->issue_tracker = other.issue_tracker;
|
||||
this->licenses = other.licenses;
|
||||
this->icon_file = other.icon_file;
|
||||
this->status = other.status;
|
||||
|
||||
return *this;
|
||||
|
@ -37,6 +37,7 @@
|
||||
#include "ModFolderModel.h"
|
||||
|
||||
#include <FileSystem.h>
|
||||
#include <qheaderview.h>
|
||||
#include <QDebug>
|
||||
#include <QFileSystemWatcher>
|
||||
#include <QIcon>
|
||||
@ -52,12 +53,14 @@
|
||||
|
||||
#include "minecraft/mod/tasks/LocalModParseTask.h"
|
||||
#include "minecraft/mod/tasks/ModFolderLoadTask.h"
|
||||
#include "modplatform/ModIndex.h"
|
||||
|
||||
ModFolderModel::ModFolderModel(const QString& dir, BaseInstance* instance, bool is_indexed, bool create_dir)
|
||||
: ResourceFolderModel(QDir(dir), instance, nullptr, create_dir), m_is_indexed(is_indexed)
|
||||
{
|
||||
m_column_sort_keys = { SortType::ENABLED, SortType::NAME, SortType::VERSION, SortType::DATE, SortType::PROVIDER };
|
||||
m_column_names = QStringList({ "Enable", "Image", "Name", "Version", "Last Modified", "Provider" });
|
||||
m_column_names_translated = QStringList({ tr("Enable"), tr("Image"), tr("Name"), tr("Version"), tr("Last Modified"), tr("Provider") });
|
||||
m_column_sort_keys = { SortType::ENABLED, SortType::NAME, SortType::NAME , SortType::VERSION, SortType::DATE, SortType::PROVIDER};
|
||||
m_column_resize_modes = { QHeaderView::ResizeToContents, QHeaderView::Interactive, QHeaderView::Stretch, QHeaderView::ResizeToContents, QHeaderView::ResizeToContents, QHeaderView::ResizeToContents};
|
||||
}
|
||||
|
||||
QVariant ModFolderModel::data(const QModelIndex &index, int role) const
|
||||
@ -118,7 +121,9 @@ QVariant ModFolderModel::data(const QModelIndex &index, int role) const
|
||||
case Qt::DecorationRole: {
|
||||
if (column == NAME_COLUMN && (at(row)->isSymLinkUnder(instDirPath()) || at(row)->isMoreThanOneHardLink()))
|
||||
return APPLICATION->getThemedIcon("status-yellow");
|
||||
|
||||
if (column == ImageColumn) {
|
||||
return at(row)->icon({32, 32}, Qt::AspectRatioMode::KeepAspectRatioByExpanding);
|
||||
}
|
||||
return {};
|
||||
}
|
||||
case Qt::CheckStateRole:
|
||||
@ -142,15 +147,12 @@ QVariant ModFolderModel::headerData(int section, Qt::Orientation orientation, in
|
||||
switch (section)
|
||||
{
|
||||
case ActiveColumn:
|
||||
return QString();
|
||||
case NameColumn:
|
||||
return tr("Name");
|
||||
case VersionColumn:
|
||||
return tr("Version");
|
||||
case DateColumn:
|
||||
return tr("Last changed");
|
||||
case ProviderColumn:
|
||||
return tr("Provider");
|
||||
case ImageColumn:
|
||||
return columnNames().at(section);
|
||||
default:
|
||||
return QVariant();
|
||||
}
|
||||
@ -200,7 +202,7 @@ bool ModFolderModel::uninstallMod(const QString& filename, bool preserve_metadat
|
||||
for(auto mod : allMods()) {
|
||||
if(mod->fileinfo().fileName() == filename) {
|
||||
auto index_dir = indexDir();
|
||||
mod->destroy(index_dir, preserve_metadata);
|
||||
mod->destroy(index_dir, preserve_metadata, false);
|
||||
|
||||
update();
|
||||
|
||||
@ -213,15 +215,10 @@ bool ModFolderModel::uninstallMod(const QString& filename, bool preserve_metadat
|
||||
|
||||
bool ModFolderModel::deleteMods(const QModelIndexList& indexes)
|
||||
{
|
||||
if(!m_can_interact) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (indexes.isEmpty())
|
||||
return true;
|
||||
|
||||
for (auto i: indexes)
|
||||
{
|
||||
for (auto i : indexes) {
|
||||
if (i.column() != 0) {
|
||||
continue;
|
||||
}
|
||||
|
@ -64,6 +64,7 @@ public:
|
||||
enum Columns
|
||||
{
|
||||
ActiveColumn = 0,
|
||||
ImageColumn,
|
||||
NameColumn,
|
||||
VersionColumn,
|
||||
DateColumn,
|
||||
@ -77,6 +78,8 @@ public:
|
||||
};
|
||||
ModFolderModel(const QString &dir, BaseInstance* instance, bool is_indexed = false, bool create_dir = true);
|
||||
|
||||
virtual QString id() const override { return "mods"; }
|
||||
|
||||
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
|
||||
|
||||
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
|
||||
|
@ -71,6 +71,7 @@ std::pair<int, bool> Resource::compare(const Resource& other, SortType type) con
|
||||
return { 1, type == SortType::ENABLED };
|
||||
if (!enabled() && other.enabled())
|
||||
return { -1, type == SortType::ENABLED };
|
||||
break;
|
||||
case SortType::NAME: {
|
||||
QString this_name{ name() };
|
||||
QString other_name{ other.name() };
|
||||
@ -81,12 +82,14 @@ std::pair<int, bool> Resource::compare(const Resource& other, SortType type) con
|
||||
auto compare_result = QString::compare(this_name, other_name, Qt::CaseInsensitive);
|
||||
if (compare_result != 0)
|
||||
return { compare_result, type == SortType::NAME };
|
||||
break;
|
||||
}
|
||||
case SortType::DATE:
|
||||
if (dateTimeChanged() > other.dateTimeChanged())
|
||||
return { 1, type == SortType::DATE };
|
||||
if (dateTimeChanged() < other.dateTimeChanged())
|
||||
return { -1, type == SortType::DATE };
|
||||
break;
|
||||
}
|
||||
|
||||
return { 0, false };
|
||||
@ -145,14 +148,10 @@ bool Resource::enable(EnableAction action)
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Resource::destroy()
|
||||
bool Resource::destroy(bool attemptTrash)
|
||||
{
|
||||
m_type = ResourceType::UNKNOWN;
|
||||
|
||||
if (FS::trash(m_file_info.filePath()))
|
||||
return true;
|
||||
|
||||
return FS::deletePath(m_file_info.filePath());
|
||||
return (attemptTrash && FS::trash(m_file_info.filePath())) || FS::deletePath(m_file_info.filePath());
|
||||
}
|
||||
|
||||
bool Resource::isSymLinkUnder(const QString& instPath) const
|
||||
|
@ -92,7 +92,7 @@ class Resource : public QObject {
|
||||
}
|
||||
|
||||
// Delete all files of this resource.
|
||||
bool destroy();
|
||||
bool destroy(bool attemptTrash = true);
|
||||
|
||||
[[nodiscard]] auto isSymLink() const -> bool { return m_file_info.isSymLink(); }
|
||||
|
||||
|
@ -1,9 +1,11 @@
|
||||
#include "ResourceFolderModel.h"
|
||||
#include <QMessageBox>
|
||||
|
||||
#include <QCoreApplication>
|
||||
#include <QDebug>
|
||||
#include <QFileInfo>
|
||||
#include <QIcon>
|
||||
#include <QMenu>
|
||||
#include <QMimeData>
|
||||
#include <QStyle>
|
||||
#include <QThreadPool>
|
||||
@ -12,9 +14,12 @@
|
||||
#include "Application.h"
|
||||
#include "FileSystem.h"
|
||||
|
||||
#include "QVariantUtils.h"
|
||||
#include "minecraft/mod/tasks/BasicFolderLoadTask.h"
|
||||
|
||||
#include "settings/Setting.h"
|
||||
#include "tasks/Task.h"
|
||||
#include "ui/dialogs/CustomMessageBox.h"
|
||||
|
||||
ResourceFolderModel::ResourceFolderModel(QDir dir, BaseInstance* instance, QObject* parent, bool create_dir)
|
||||
: QAbstractListModel(parent), m_dir(dir), m_instance(instance), m_watcher(this)
|
||||
@ -74,10 +79,6 @@ bool ResourceFolderModel::stopWatching(const QStringList paths)
|
||||
|
||||
bool ResourceFolderModel::installResource(QString original_path)
|
||||
{
|
||||
if (!m_can_interact) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// NOTE: fix for GH-1178: remove trailing slash to avoid issues with using the empty result of QFileInfo::fileName
|
||||
original_path = FS::NormalizePath(original_path);
|
||||
QFileInfo file_info(original_path);
|
||||
@ -156,7 +157,7 @@ bool ResourceFolderModel::uninstallResource(QString file_name)
|
||||
{
|
||||
for (auto& resource : m_resources) {
|
||||
if (resource->fileinfo().fileName() == file_name) {
|
||||
auto res = resource->destroy();
|
||||
auto res = resource->destroy(false);
|
||||
|
||||
update();
|
||||
|
||||
@ -168,9 +169,6 @@ bool ResourceFolderModel::uninstallResource(QString file_name)
|
||||
|
||||
bool ResourceFolderModel::deleteResources(const QModelIndexList& indexes)
|
||||
{
|
||||
if (!m_can_interact)
|
||||
return false;
|
||||
|
||||
if (indexes.isEmpty())
|
||||
return true;
|
||||
|
||||
@ -191,9 +189,6 @@ bool ResourceFolderModel::deleteResources(const QModelIndexList& indexes)
|
||||
|
||||
bool ResourceFolderModel::setResourceEnabled(const QModelIndexList& indexes, EnableAction action)
|
||||
{
|
||||
if (!m_can_interact)
|
||||
return false;
|
||||
|
||||
if (indexes.isEmpty())
|
||||
return true;
|
||||
|
||||
@ -246,7 +241,9 @@ bool ResourceFolderModel::update()
|
||||
connect(m_current_update_task.get(), &Task::succeeded, this, &ResourceFolderModel::onUpdateSucceeded,
|
||||
Qt::ConnectionType::QueuedConnection);
|
||||
connect(m_current_update_task.get(), &Task::failed, this, &ResourceFolderModel::onUpdateFailed, Qt::ConnectionType::QueuedConnection);
|
||||
connect(m_current_update_task.get(), &Task::finished, this, [=] {
|
||||
connect(
|
||||
m_current_update_task.get(), &Task::finished, this,
|
||||
[=] {
|
||||
m_current_update_task.reset();
|
||||
if (m_scheduled_update) {
|
||||
m_scheduled_update = false;
|
||||
@ -254,7 +251,8 @@ bool ResourceFolderModel::update()
|
||||
} else {
|
||||
emit updateFinished();
|
||||
}
|
||||
}, Qt::ConnectionType::QueuedConnection);
|
||||
},
|
||||
Qt::ConnectionType::QueuedConnection);
|
||||
|
||||
QThreadPool::globalInstance()->start(m_current_update_task.get());
|
||||
|
||||
@ -344,15 +342,9 @@ Qt::DropActions ResourceFolderModel::supportedDropActions() const
|
||||
Qt::ItemFlags ResourceFolderModel::flags(const QModelIndex& index) const
|
||||
{
|
||||
Qt::ItemFlags defaultFlags = QAbstractListModel::flags(index);
|
||||
auto flags = defaultFlags;
|
||||
if (!m_can_interact) {
|
||||
flags &= ~Qt::ItemIsDropEnabled;
|
||||
} else {
|
||||
flags |= Qt::ItemIsDropEnabled;
|
||||
if (index.isValid()) {
|
||||
auto flags = defaultFlags | Qt::ItemIsDropEnabled;
|
||||
if (index.isValid())
|
||||
flags |= Qt::ItemIsUserCheckable;
|
||||
}
|
||||
}
|
||||
return flags;
|
||||
}
|
||||
|
||||
@ -427,7 +419,8 @@ QVariant ResourceFolderModel::data(const QModelIndex& index, int role) const
|
||||
return m_resources[row]->internal_id() +
|
||||
tr("\nWarning: This resource is symbolically linked from elsewhere. Editing it will also change the original."
|
||||
"\nCanonical Path: %1")
|
||||
.arg(at(row).fileinfo().canonicalFilePath());;
|
||||
.arg(at(row).fileinfo().canonicalFilePath());
|
||||
;
|
||||
}
|
||||
if (at(row).isMoreThanOneHardLink()) {
|
||||
return m_resources[row]->internal_id() +
|
||||
@ -460,8 +453,20 @@ bool ResourceFolderModel::setData(const QModelIndex& index, const QVariant& valu
|
||||
if (row < 0 || row >= rowCount(index.parent()) || !index.isValid())
|
||||
return false;
|
||||
|
||||
if (role == Qt::CheckStateRole)
|
||||
if (role == Qt::CheckStateRole) {
|
||||
if (m_instance != nullptr && m_instance->isRunning()) {
|
||||
auto response =
|
||||
CustomMessageBox::selectable(nullptr, "Confirm toggle",
|
||||
"If you enable/disable this resource while the game is running it may crash your game.\n"
|
||||
"Are you sure you want to do this?",
|
||||
QMessageBox::Warning, QMessageBox::Yes | QMessageBox::No, QMessageBox::No)
|
||||
->exec();
|
||||
|
||||
if (response != QMessageBox::Yes)
|
||||
return false;
|
||||
}
|
||||
return setResourceEnabled({ index }, EnableAction::TOGGLE);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
@ -471,10 +476,10 @@ QVariant ResourceFolderModel::headerData(int section, Qt::Orientation orientatio
|
||||
switch (role) {
|
||||
case Qt::DisplayRole:
|
||||
switch (section) {
|
||||
case ACTIVE_COLUMN:
|
||||
case NAME_COLUMN:
|
||||
return tr("Name");
|
||||
case DATE_COLUMN:
|
||||
return tr("Last modified");
|
||||
return columnNames().at(section);
|
||||
default:
|
||||
return {};
|
||||
}
|
||||
@ -500,6 +505,75 @@ QVariant ResourceFolderModel::headerData(int section, Qt::Orientation orientatio
|
||||
return {};
|
||||
}
|
||||
|
||||
void ResourceFolderModel::setupHeaderAction(QAction* act, int column)
|
||||
{
|
||||
Q_ASSERT(act);
|
||||
|
||||
act->setText(columnNames().at(column));
|
||||
}
|
||||
|
||||
void ResourceFolderModel::saveHiddenColumn(int column, bool hidden)
|
||||
{
|
||||
auto const setting_name = QString("UI/%1_Page/HiddenColumns").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);
|
||||
}
|
||||
|
||||
void ResourceFolderModel::loadHiddenColumns(QTreeView *tree)
|
||||
{
|
||||
auto const setting_name = QString("UI/%1_Page/HiddenColumns").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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
QMenu* ResourceFolderModel::createHeaderContextMenu(QTreeView* tree)
|
||||
{
|
||||
auto menu = new QMenu(tree);
|
||||
|
||||
menu->addSeparator()->setText(tr("Show / Hide Columns"));
|
||||
|
||||
for (int col = 0; col < columnCount(); ++col) {
|
||||
auto act = new QAction(menu);
|
||||
setupHeaderAction(act, col);
|
||||
|
||||
act->setCheckable(true);
|
||||
act->setChecked(!tree->isColumnHidden(col));
|
||||
|
||||
connect(act, &QAction::toggled, tree, [this, col, tree](bool toggled){
|
||||
tree->setColumnHidden(col, !toggled);
|
||||
for(int c = 0; c < columnCount(); ++c) {
|
||||
if (m_column_resize_modes.at(c) == QHeaderView::ResizeToContents)
|
||||
tree->resizeColumnToContents(c);
|
||||
}
|
||||
saveHiddenColumn(col, !toggled);
|
||||
});
|
||||
|
||||
menu->addAction(act);
|
||||
|
||||
}
|
||||
|
||||
return menu;
|
||||
}
|
||||
|
||||
QSortFilterProxyModel* ResourceFolderModel::createFilterProxyModel(QObject* parent)
|
||||
{
|
||||
return new ProxyModel(parent);
|
||||
@ -511,16 +585,6 @@ SortType ResourceFolderModel::columnToSortKey(size_t column) const
|
||||
return m_column_sort_keys.at(column);
|
||||
}
|
||||
|
||||
void ResourceFolderModel::enableInteraction(bool enabled)
|
||||
{
|
||||
if (m_can_interact == enabled)
|
||||
return;
|
||||
|
||||
m_can_interact = enabled;
|
||||
if (size())
|
||||
emit dataChanged(index(0), index(size() - 1));
|
||||
}
|
||||
|
||||
/* Standard Proxy Model for createFilterProxyModel */
|
||||
[[nodiscard]] bool ResourceFolderModel::ProxyModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const
|
||||
{
|
||||
@ -556,6 +620,7 @@ void ResourceFolderModel::enableInteraction(bool enabled)
|
||||
return (compare_result.first > 0);
|
||||
}
|
||||
|
||||
QString ResourceFolderModel::instDirPath() const {
|
||||
QString ResourceFolderModel::instDirPath() const
|
||||
{
|
||||
return QFileInfo(m_instance->instanceRoot()).absoluteFilePath();
|
||||
}
|
||||
|
@ -1,5 +1,8 @@
|
||||
#pragma once
|
||||
|
||||
#include <QHeaderView>
|
||||
#include <QAction>
|
||||
#include <QTreeView>
|
||||
#include <QAbstractListModel>
|
||||
#include <QDir>
|
||||
#include <QFileSystemWatcher>
|
||||
@ -11,8 +14,8 @@
|
||||
|
||||
#include "BaseInstance.h"
|
||||
|
||||
#include "tasks/Task.h"
|
||||
#include "tasks/ConcurrentTask.h"
|
||||
#include "tasks/Task.h"
|
||||
|
||||
class QSortFilterProxyModel;
|
||||
|
||||
@ -29,6 +32,8 @@ class ResourceFolderModel : public QAbstractListModel {
|
||||
ResourceFolderModel(QDir, BaseInstance* instance, QObject* parent = nullptr, bool create_dir = true);
|
||||
~ResourceFolderModel() override;
|
||||
|
||||
virtual QString id() const { return "resource"; }
|
||||
|
||||
/** Starts watching the paths for changes.
|
||||
*
|
||||
* Returns whether starting to watch all the paths was successful.
|
||||
@ -92,6 +97,7 @@ class ResourceFolderModel : public QAbstractListModel {
|
||||
|
||||
/* Basic columns */
|
||||
enum Columns { ACTIVE_COLUMN = 0, NAME_COLUMN, DATE_COLUMN, NUM_COLUMNS };
|
||||
QStringList columnNames(bool translated = true) const { return translated ? m_column_names_translated : m_column_names; };
|
||||
|
||||
[[nodiscard]] int rowCount(const QModelIndex& parent = {}) const override { return parent.isValid() ? 0 : static_cast<int>(size()); }
|
||||
[[nodiscard]] int columnCount(const QModelIndex& parent = {}) const override { return parent.isValid() ? 0 : NUM_COLUMNS; };
|
||||
@ -110,6 +116,11 @@ 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);
|
||||
QMenu* createHeaderContextMenu(QTreeView* tree);
|
||||
|
||||
/** This creates a proxy model to filter / sort the model for a UI.
|
||||
*
|
||||
* The actual comparisons and filtering are done directly by the Resource, so to modify behavior go there instead!
|
||||
@ -117,6 +128,7 @@ class ResourceFolderModel : public QAbstractListModel {
|
||||
QSortFilterProxyModel* createFilterProxyModel(QObject* parent = nullptr);
|
||||
|
||||
[[nodiscard]] SortType columnToSortKey(size_t column) const;
|
||||
[[nodiscard]] QList<QHeaderView::ResizeMode> columnResizeModes() const { return m_column_resize_modes; }
|
||||
|
||||
class ProxyModel : public QSortFilterProxyModel {
|
||||
public:
|
||||
@ -129,10 +141,6 @@ class ResourceFolderModel : public QAbstractListModel {
|
||||
|
||||
QString instDirPath() const;
|
||||
|
||||
public slots:
|
||||
void enableInteraction(bool enabled);
|
||||
void disableInteraction(bool disabled) { enableInteraction(!disabled); }
|
||||
|
||||
signals:
|
||||
void updateFinished();
|
||||
|
||||
@ -181,14 +189,19 @@ class ResourceFolderModel : public QAbstractListModel {
|
||||
* if the resource is complex and has more stuff to parse.
|
||||
*/
|
||||
virtual void onParseSucceeded(int ticket, QString resource_id);
|
||||
virtual void onParseFailed(int ticket, QString resource_id) { Q_UNUSED(ticket); Q_UNUSED(resource_id); }
|
||||
virtual void onParseFailed(int ticket, QString resource_id)
|
||||
{
|
||||
Q_UNUSED(ticket);
|
||||
Q_UNUSED(resource_id);
|
||||
}
|
||||
|
||||
protected:
|
||||
// Represents the relationship between a column's index (represented by the list index), and it's sorting key.
|
||||
// As such, the order in with they appear is very important!
|
||||
QList<SortType> m_column_sort_keys = { SortType::ENABLED, SortType::NAME, SortType::DATE };
|
||||
|
||||
bool m_can_interact = true;
|
||||
QStringList m_column_names = {"Enable", "Name", "Last Modified"};
|
||||
QStringList m_column_names_translated = {tr("Enable"), tr("Name"), tr("Last Modified")};
|
||||
QList<QHeaderView::ResizeMode> m_column_resize_modes = { QHeaderView::ResizeToContents, QHeaderView::Stretch, QHeaderView::ResizeToContents };
|
||||
|
||||
QDir m_dir;
|
||||
BaseInstance* m_instance;
|
||||
|
@ -40,7 +40,7 @@ void ResourcePack::setDescription(QString new_description)
|
||||
m_description = new_description;
|
||||
}
|
||||
|
||||
void ResourcePack::setImage(QImage new_image)
|
||||
void ResourcePack::setImage(QImage new_image) const
|
||||
{
|
||||
QMutexLocker locker(&m_data_lock);
|
||||
|
||||
@ -49,7 +49,10 @@ void ResourcePack::setImage(QImage new_image)
|
||||
if (m_pack_image_cache_key.key.isValid())
|
||||
PixmapCache::instance().remove(m_pack_image_cache_key.key);
|
||||
|
||||
m_pack_image_cache_key.key = PixmapCache::instance().insert(QPixmap::fromImage(new_image));
|
||||
// scale the image to avoid flooding the pixmapcache
|
||||
auto pixmap = QPixmap::fromImage(new_image.scaled({64, 64}, Qt::AspectRatioMode::KeepAspectRatioByExpanding));
|
||||
|
||||
m_pack_image_cache_key.key = PixmapCache::instance().insert(pixmap);
|
||||
m_pack_image_cache_key.was_ever_used = true;
|
||||
|
||||
// This can happen if the pixmap is too big to fit in the cache :c
|
||||
@ -59,21 +62,25 @@ void ResourcePack::setImage(QImage new_image)
|
||||
}
|
||||
}
|
||||
|
||||
QPixmap ResourcePack::image(QSize size)
|
||||
QPixmap ResourcePack::image(QSize size, Qt::AspectRatioMode mode) const
|
||||
{
|
||||
QPixmap cached_image;
|
||||
if (PixmapCache::instance().find(m_pack_image_cache_key.key, &cached_image)) {
|
||||
if (size.isNull())
|
||||
return cached_image;
|
||||
return cached_image.scaled(size);
|
||||
return cached_image.scaled(size, mode);
|
||||
}
|
||||
|
||||
// No valid image we can get
|
||||
if (!m_pack_image_cache_key.was_ever_used)
|
||||
if (!m_pack_image_cache_key.was_ever_used) {
|
||||
return {};
|
||||
} else {
|
||||
qDebug() << "Resource Pack" << name() << "Had it's image evicted from the cache. reloading...";
|
||||
PixmapCache::markCacheMissByEviciton();
|
||||
}
|
||||
|
||||
// Imaged got evicted from the cache. Re-process it and retry.
|
||||
ResourcePackUtils::process(*this);
|
||||
ResourcePackUtils::processPackPNG(*this);
|
||||
return image(size);
|
||||
}
|
||||
|
||||
@ -95,6 +102,7 @@ std::pair<int, bool> ResourcePack::compare(const Resource& other, SortType type)
|
||||
auto res = Resource::compare(other, type);
|
||||
if (res.first != 0)
|
||||
return res;
|
||||
break;
|
||||
}
|
||||
case SortType::PACK_FORMAT: {
|
||||
auto this_ver = packFormat();
|
||||
@ -104,6 +112,7 @@ std::pair<int, bool> ResourcePack::compare(const Resource& other, SortType type)
|
||||
return { 1, type == SortType::PACK_FORMAT };
|
||||
if (this_ver < other_ver)
|
||||
return { -1, type == SortType::PACK_FORMAT };
|
||||
break;
|
||||
}
|
||||
}
|
||||
return { 0, false };
|
||||
|
@ -31,7 +31,7 @@ class ResourcePack : public Resource {
|
||||
[[nodiscard]] QString description() const { return m_description; }
|
||||
|
||||
/** Gets the image of the resource pack, converted to a QPixmap for drawing, and scaled to size. */
|
||||
[[nodiscard]] QPixmap image(QSize size);
|
||||
[[nodiscard]] QPixmap image(QSize size, Qt::AspectRatioMode mode = Qt::AspectRatioMode::IgnoreAspectRatio) const;
|
||||
|
||||
/** Thread-safe. */
|
||||
void setPackFormat(int new_format_id);
|
||||
@ -40,7 +40,7 @@ class ResourcePack : public Resource {
|
||||
void setDescription(QString new_description);
|
||||
|
||||
/** Thread-safe. */
|
||||
void setImage(QImage new_image);
|
||||
void setImage(QImage new_image) const;
|
||||
|
||||
bool valid() const override;
|
||||
|
||||
@ -67,5 +67,5 @@ class ResourcePack : public Resource {
|
||||
struct {
|
||||
QPixmapCache::Key key;
|
||||
bool was_ever_used = false;
|
||||
} m_pack_image_cache_key;
|
||||
} mutable m_pack_image_cache_key;
|
||||
};
|
||||
|
@ -35,6 +35,8 @@
|
||||
*/
|
||||
|
||||
#include "ResourcePackFolderModel.h"
|
||||
#include <qnamespace.h>
|
||||
#include <qsize.h>
|
||||
|
||||
#include <QIcon>
|
||||
#include <QStyle>
|
||||
@ -48,7 +50,11 @@
|
||||
ResourcePackFolderModel::ResourcePackFolderModel(const QString& dir, BaseInstance* instance)
|
||||
: ResourceFolderModel(QDir(dir), instance)
|
||||
{
|
||||
m_column_sort_keys = { SortType::ENABLED, SortType::NAME, SortType::PACK_FORMAT, SortType::DATE };
|
||||
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 };
|
||||
|
||||
}
|
||||
|
||||
QVariant ResourcePackFolderModel::data(const QModelIndex& index, int role) const
|
||||
@ -84,9 +90,11 @@ QVariant ResourcePackFolderModel::data(const QModelIndex& index, int role) const
|
||||
return {};
|
||||
}
|
||||
case Qt::DecorationRole: {
|
||||
if (column == NAME_COLUMN && (at(row)->isSymLinkUnder(instDirPath()) || at(row)->isMoreThanOneHardLink()))
|
||||
if (column == NameColumn && (at(row)->isSymLinkUnder(instDirPath()) || at(row)->isMoreThanOneHardLink()))
|
||||
return APPLICATION->getThemedIcon("status-yellow");
|
||||
|
||||
if (column == ImageColumn) {
|
||||
return at(row)->image({32, 32}, Qt::AspectRatioMode::KeepAspectRatioByExpanding);
|
||||
}
|
||||
return {};
|
||||
}
|
||||
case Qt::ToolTipRole: {
|
||||
@ -94,7 +102,7 @@ QVariant ResourcePackFolderModel::data(const QModelIndex& index, int role) const
|
||||
//: The string being explained by this is in the format: ID (Lower version - Upper version)
|
||||
return tr("The resource pack format ID, as well as the Minecraft versions it was designed for.");
|
||||
}
|
||||
if (column == NAME_COLUMN) {
|
||||
if (column == NameColumn) {
|
||||
if (at(row)->isSymLinkUnder(instDirPath())) {
|
||||
return m_resources[row]->internal_id() +
|
||||
tr("\nWarning: This resource is symbolically linked from elsewhere. Editing it will also change the original."
|
||||
@ -126,13 +134,11 @@ QVariant ResourcePackFolderModel::headerData(int section, Qt::Orientation orient
|
||||
case Qt::DisplayRole:
|
||||
switch (section) {
|
||||
case ActiveColumn:
|
||||
return QString();
|
||||
case NameColumn:
|
||||
return tr("Name");
|
||||
case PackFormatColumn:
|
||||
return tr("Pack Format");
|
||||
case DateColumn:
|
||||
return tr("Last changed");
|
||||
case ImageColumn:
|
||||
return columnNames().at(section);
|
||||
default:
|
||||
return {};
|
||||
}
|
||||
@ -151,6 +157,11 @@ QVariant ResourcePackFolderModel::headerData(int section, Qt::Orientation orient
|
||||
default:
|
||||
return {};
|
||||
}
|
||||
case Qt::SizeHintRole:
|
||||
if (section == ImageColumn) {
|
||||
return QSize(64,0);
|
||||
}
|
||||
return {};
|
||||
default:
|
||||
return {};
|
||||
}
|
||||
|
@ -11,6 +11,7 @@ public:
|
||||
enum Columns
|
||||
{
|
||||
ActiveColumn = 0,
|
||||
ImageColumn,
|
||||
NameColumn,
|
||||
PackFormatColumn,
|
||||
DateColumn,
|
||||
@ -19,6 +20,8 @@ public:
|
||||
|
||||
explicit ResourcePackFolderModel(const QString &dir, BaseInstance* instance);
|
||||
|
||||
virtual QString id() const override { return "resourcepacks"; }
|
||||
|
||||
[[nodiscard]] QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
|
||||
|
||||
[[nodiscard]] QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
|
||||
|
@ -9,4 +9,6 @@ class ShaderPackFolderModel : public ResourceFolderModel {
|
||||
explicit ShaderPackFolderModel(const QString& dir, BaseInstance* instance)
|
||||
: ResourceFolderModel(QDir(dir), instance)
|
||||
{}
|
||||
|
||||
virtual QString id() const override { return "shaderpacks"; }
|
||||
};
|
||||
|
@ -23,6 +23,8 @@
|
||||
#include <QMap>
|
||||
#include <QRegularExpression>
|
||||
|
||||
#include "MTPixmapCache.h"
|
||||
|
||||
#include "minecraft/mod/tasks/LocalTexturePackParseTask.h"
|
||||
|
||||
void TexturePack::setDescription(QString new_description)
|
||||
@ -32,34 +34,41 @@ void TexturePack::setDescription(QString new_description)
|
||||
m_description = new_description;
|
||||
}
|
||||
|
||||
void TexturePack::setImage(QImage new_image)
|
||||
void TexturePack::setImage(QImage new_image) const
|
||||
{
|
||||
QMutexLocker locker(&m_data_lock);
|
||||
|
||||
Q_ASSERT(!new_image.isNull());
|
||||
|
||||
if (m_pack_image_cache_key.key.isValid())
|
||||
QPixmapCache::remove(m_pack_image_cache_key.key);
|
||||
PixmapCache::remove(m_pack_image_cache_key.key);
|
||||
|
||||
m_pack_image_cache_key.key = QPixmapCache::insert(QPixmap::fromImage(new_image));
|
||||
// scale the image to avoid flooding the pixmapcache
|
||||
auto pixmap = QPixmap::fromImage(new_image.scaled({64, 64}, Qt::AspectRatioMode::KeepAspectRatioByExpanding));
|
||||
|
||||
m_pack_image_cache_key.key = PixmapCache::insert(pixmap);
|
||||
m_pack_image_cache_key.was_ever_used = true;
|
||||
}
|
||||
|
||||
QPixmap TexturePack::image(QSize size)
|
||||
QPixmap TexturePack::image(QSize size, Qt::AspectRatioMode mode) const
|
||||
{
|
||||
QPixmap cached_image;
|
||||
if (QPixmapCache::find(m_pack_image_cache_key.key, &cached_image)) {
|
||||
if (PixmapCache::find(m_pack_image_cache_key.key, &cached_image)) {
|
||||
if (size.isNull())
|
||||
return cached_image;
|
||||
return cached_image.scaled(size);
|
||||
return cached_image.scaled(size, mode);
|
||||
}
|
||||
|
||||
// No valid image we can get
|
||||
if (!m_pack_image_cache_key.was_ever_used)
|
||||
if (!m_pack_image_cache_key.was_ever_used) {
|
||||
return {};
|
||||
} else {
|
||||
qDebug() << "Texture Pack" << name() << "Had it's image evicted from the cache. reloading...";
|
||||
PixmapCache::markCacheMissByEviciton();
|
||||
}
|
||||
|
||||
// Imaged got evicted from the cache. Re-process it and retry.
|
||||
TexturePackUtils::process(*this);
|
||||
TexturePackUtils::processPackPNG(*this);
|
||||
return image(size);
|
||||
}
|
||||
|
||||
|
@ -40,13 +40,13 @@ class TexturePack : public Resource {
|
||||
[[nodiscard]] QString description() const { return m_description; }
|
||||
|
||||
/** Gets the image of the texture pack, converted to a QPixmap for drawing, and scaled to size. */
|
||||
[[nodiscard]] QPixmap image(QSize size);
|
||||
[[nodiscard]] QPixmap image(QSize size, Qt::AspectRatioMode mode = Qt::AspectRatioMode::IgnoreAspectRatio) const;
|
||||
|
||||
/** Thread-safe. */
|
||||
void setDescription(QString new_description);
|
||||
|
||||
/** Thread-safe. */
|
||||
void setImage(QImage new_image);
|
||||
void setImage(QImage new_image) const;
|
||||
|
||||
bool valid() const override;
|
||||
|
||||
@ -65,5 +65,5 @@ class TexturePack : public Resource {
|
||||
struct {
|
||||
QPixmapCache::Key key;
|
||||
bool was_ever_used = false;
|
||||
} m_pack_image_cache_key;
|
||||
} mutable m_pack_image_cache_key;
|
||||
};
|
||||
|
@ -33,6 +33,9 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
#include <QCoreApplication>
|
||||
|
||||
#include "Application.h"
|
||||
|
||||
#include "TexturePackFolderModel.h"
|
||||
|
||||
@ -41,7 +44,13 @@
|
||||
|
||||
TexturePackFolderModel::TexturePackFolderModel(const QString& dir, BaseInstance* instance)
|
||||
: ResourceFolderModel(QDir(dir), instance)
|
||||
{}
|
||||
{
|
||||
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};
|
||||
|
||||
}
|
||||
|
||||
Task* TexturePackFolderModel::createUpdateTask()
|
||||
{
|
||||
@ -52,3 +61,96 @@ Task* TexturePackFolderModel::createParseTask(Resource& resource)
|
||||
{
|
||||
return new LocalTexturePackParseTask(m_next_resolution_ticket, static_cast<TexturePack&>(resource));
|
||||
}
|
||||
|
||||
|
||||
QVariant TexturePackFolderModel::data(const QModelIndex& index, int role) const
|
||||
{
|
||||
if (!validateIndex(index))
|
||||
return {};
|
||||
|
||||
int row = index.row();
|
||||
int column = index.column();
|
||||
|
||||
switch (role) {
|
||||
case Qt::DisplayRole:
|
||||
switch (column) {
|
||||
case NameColumn:
|
||||
return m_resources[row]->name();
|
||||
case DateColumn:
|
||||
return m_resources[row]->dateTimeChanged();
|
||||
default:
|
||||
return {};
|
||||
}
|
||||
case Qt::ToolTipRole:
|
||||
if (column == NameColumn) {
|
||||
if (at(row)->isSymLinkUnder(instDirPath())) {
|
||||
return m_resources[row]->internal_id() +
|
||||
tr("\nWarning: This resource is symbolically linked from elsewhere. Editing it will also change the original."
|
||||
"\nCanonical Path: %1")
|
||||
.arg(at(row)->fileinfo().canonicalFilePath());;
|
||||
}
|
||||
if (at(row)->isMoreThanOneHardLink()) {
|
||||
return m_resources[row]->internal_id() +
|
||||
tr("\nWarning: This resource is hard linked elsewhere. Editing it will also change the original.");
|
||||
}
|
||||
}
|
||||
|
||||
return m_resources[row]->internal_id();
|
||||
case Qt::DecorationRole: {
|
||||
if (column == NameColumn && (at(row)->isSymLinkUnder(instDirPath()) || at(row)->isMoreThanOneHardLink()))
|
||||
return APPLICATION->getThemedIcon("status-yellow");
|
||||
if (column == ImageColumn) {
|
||||
return at(row)->image({32, 32}, Qt::AspectRatioMode::KeepAspectRatioByExpanding);
|
||||
}
|
||||
return {};
|
||||
}
|
||||
case Qt::CheckStateRole:
|
||||
if (column == ActiveColumn) {
|
||||
return m_resources[row]->enabled() ? Qt::Checked : Qt::Unchecked;
|
||||
}
|
||||
return {};
|
||||
default:
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
QVariant TexturePackFolderModel::headerData(int section, Qt::Orientation orientation, int role) const
|
||||
{
|
||||
switch (role) {
|
||||
case Qt::DisplayRole:
|
||||
switch (section) {
|
||||
case ActiveColumn:
|
||||
case NameColumn:
|
||||
case DateColumn:
|
||||
case ImageColumn:
|
||||
return columnNames().at(section);
|
||||
default:
|
||||
return {};
|
||||
}
|
||||
case Qt::ToolTipRole: {
|
||||
switch (section) {
|
||||
case ActiveColumn:
|
||||
//: Here, resource is a generic term for external resources, like Mods, Resource Packs, Shader Packs, etc.
|
||||
return tr("Is the resource enabled?");
|
||||
case NameColumn:
|
||||
//: Here, resource is a generic term for external resources, like Mods, Resource Packs, Shader Packs, etc.
|
||||
return tr("The name of the resource.");
|
||||
case DateColumn:
|
||||
//: Here, resource is a generic term for external resources, like Mods, Resource Packs, Shader Packs, etc.
|
||||
return tr("The date and time this resource was last changed (or added).");
|
||||
default:
|
||||
return {};
|
||||
}
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
int TexturePackFolderModel::columnCount(const QModelIndex& parent) const
|
||||
{
|
||||
return parent.isValid() ? 0 : NUM_COLUMNS;
|
||||
}
|
||||
|
||||
|
@ -38,12 +38,35 @@
|
||||
|
||||
#include "ResourceFolderModel.h"
|
||||
|
||||
#include "TexturePack.h"
|
||||
|
||||
class TexturePackFolderModel : public ResourceFolderModel
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
|
||||
enum Columns
|
||||
{
|
||||
ActiveColumn = 0,
|
||||
ImageColumn,
|
||||
NameColumn,
|
||||
DateColumn,
|
||||
NUM_COLUMNS
|
||||
};
|
||||
|
||||
explicit TexturePackFolderModel(const QString &dir, std::shared_ptr<const BaseInstance> instance);
|
||||
|
||||
virtual QString id() const override { return "texturepacks"; }
|
||||
|
||||
[[nodiscard]] QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
|
||||
|
||||
[[nodiscard]] QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
|
||||
[[nodiscard]] int columnCount(const QModelIndex &parent) const override;
|
||||
|
||||
explicit TexturePackFolderModel(const QString &dir, BaseInstance* instance);
|
||||
[[nodiscard]] Task* createUpdateTask() override;
|
||||
[[nodiscard]] Task* createParseTask(Resource&) override;
|
||||
|
||||
RESOURCE_HELPERS(TexturePack)
|
||||
};
|
||||
|
252
launcher/minecraft/mod/tasks/GetModDependenciesTask.cpp
Normal file
252
launcher/minecraft/mod/tasks/GetModDependenciesTask.cpp
Normal file
@ -0,0 +1,252 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
/*
|
||||
* Prism Launcher - Minecraft Launcher
|
||||
* Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "GetModDependenciesTask.h"
|
||||
|
||||
#include <QDebug>
|
||||
#include <algorithm>
|
||||
#include <memory>
|
||||
#include "Json.h"
|
||||
#include "QObjectPtr.h"
|
||||
#include "minecraft/mod/MetadataHandler.h"
|
||||
#include "modplatform/ModIndex.h"
|
||||
#include "modplatform/ResourceAPI.h"
|
||||
#include "modplatform/flame/FlameAPI.h"
|
||||
#include "modplatform/modrinth/ModrinthAPI.h"
|
||||
#include "tasks/ConcurrentTask.h"
|
||||
#include "tasks/SequentialTask.h"
|
||||
#include "ui/pages/modplatform/ModModel.h"
|
||||
#include "ui/pages/modplatform/flame/FlameResourceModels.h"
|
||||
#include "ui/pages/modplatform/modrinth/ModrinthResourceModels.h"
|
||||
|
||||
static Version mcVersion(BaseInstance* inst)
|
||||
{
|
||||
return static_cast<MinecraftInstance*>(inst)->getPackProfile()->getComponent("net.minecraft")->getVersion();
|
||||
}
|
||||
|
||||
static ResourceAPI::ModLoaderTypes mcLoaders(BaseInstance* inst)
|
||||
{
|
||||
return static_cast<MinecraftInstance*>(inst)->getPackProfile()->getModLoaders().value();
|
||||
}
|
||||
|
||||
GetModDependenciesTask::GetModDependenciesTask(QObject* parent,
|
||||
BaseInstance* instance,
|
||||
ModFolderModel* folder,
|
||||
QList<std::shared_ptr<PackDependency>> selected)
|
||||
: SequentialTask(parent, tr("Get dependencies"))
|
||||
, m_selected(selected)
|
||||
, m_flame_provider{ ModPlatform::ResourceProvider::FLAME, std::make_shared<ResourceDownload::FlameModModel>(*instance),
|
||||
std::make_shared<FlameAPI>() }
|
||||
, m_modrinth_provider{ ModPlatform::ResourceProvider::MODRINTH, std::make_shared<ResourceDownload::ModrinthModModel>(*instance),
|
||||
std::make_shared<ModrinthAPI>() }
|
||||
, m_version(mcVersion(instance))
|
||||
, m_loaderType(mcLoaders(instance))
|
||||
{
|
||||
for (auto mod : folder->allMods())
|
||||
if (auto meta = mod->metadata(); meta)
|
||||
m_mods.append(meta);
|
||||
prepare();
|
||||
};
|
||||
|
||||
void GetModDependenciesTask::prepare()
|
||||
{
|
||||
for (auto sel : m_selected) {
|
||||
for (auto dep : getDependenciesForVersion(sel->version, sel->pack->provider)) {
|
||||
addTask(prepareDependencyTask(dep, sel->pack->provider, 20));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ModPlatform::Dependency GetModDependenciesTask::getOverride(const ModPlatform::Dependency& dep,
|
||||
const ModPlatform::ResourceProvider providerName)
|
||||
{
|
||||
if (auto isQuilt = m_loaderType & ResourceAPI::Quilt; isQuilt || m_loaderType & ResourceAPI::Fabric) {
|
||||
auto overide = ModPlatform::getOverrideDeps();
|
||||
auto over = std::find_if(overide.cbegin(), overide.cend(), [dep, providerName, isQuilt](auto o) {
|
||||
return o.provider == providerName && dep.addonId == (isQuilt ? o.fabric : o.quilt);
|
||||
});
|
||||
if (over != overide.cend()) {
|
||||
return { isQuilt ? over->quilt : over->fabric, dep.type };
|
||||
}
|
||||
}
|
||||
return dep;
|
||||
}
|
||||
|
||||
QList<ModPlatform::Dependency> GetModDependenciesTask::getDependenciesForVersion(const ModPlatform::IndexedVersion& version,
|
||||
const ModPlatform::ResourceProvider providerName)
|
||||
{
|
||||
QList<ModPlatform::Dependency> c_dependencies;
|
||||
for (auto ver_dep : version.dependencies) {
|
||||
if (ver_dep.type != ModPlatform::DependencyType::REQUIRED)
|
||||
continue;
|
||||
|
||||
auto isOnlyVersion = providerName == ModPlatform::ResourceProvider::MODRINTH && ver_dep.addonId.toString().isEmpty();
|
||||
if (auto dep = std::find_if(c_dependencies.begin(), c_dependencies.end(),
|
||||
[&ver_dep, isOnlyVersion](const ModPlatform::Dependency& i) {
|
||||
return isOnlyVersion ? i.version == ver_dep.version : i.addonId == ver_dep.addonId;
|
||||
});
|
||||
dep != c_dependencies.end())
|
||||
continue; // check the current dependency list
|
||||
|
||||
if (auto dep = std::find_if(m_selected.begin(), m_selected.end(),
|
||||
[&ver_dep, providerName, isOnlyVersion](std::shared_ptr<PackDependency> i) {
|
||||
return i->pack->provider == providerName && (isOnlyVersion ? i->version.version == ver_dep.version
|
||||
: i->pack->addonId == ver_dep.addonId);
|
||||
});
|
||||
dep != m_selected.end())
|
||||
continue; // check the selected versions
|
||||
|
||||
if (auto dep = std::find_if(m_mods.begin(), m_mods.end(),
|
||||
[&ver_dep, providerName, isOnlyVersion](std::shared_ptr<Metadata::ModStruct> i) {
|
||||
return i->provider == providerName &&
|
||||
(isOnlyVersion ? i->file_id == ver_dep.version : i->project_id == ver_dep.addonId);
|
||||
});
|
||||
dep != m_mods.end())
|
||||
continue; // check the existing mods
|
||||
|
||||
if (auto dep = std::find_if(m_pack_dependencies.begin(), m_pack_dependencies.end(),
|
||||
[&ver_dep, providerName, isOnlyVersion](std::shared_ptr<PackDependency> i) {
|
||||
return i->pack->provider == providerName && (isOnlyVersion ? i->version.version == ver_dep.addonId
|
||||
: i->pack->addonId == ver_dep.addonId);
|
||||
});
|
||||
dep != m_pack_dependencies.end()) // check loaded dependencies
|
||||
continue;
|
||||
|
||||
c_dependencies.append(getOverride(ver_dep, providerName));
|
||||
}
|
||||
return c_dependencies;
|
||||
};
|
||||
|
||||
Task::Ptr GetModDependenciesTask::getProjectInfoTask(std::shared_ptr<PackDependency> pDep)
|
||||
{
|
||||
auto provider = pDep->pack->provider == m_flame_provider.name ? m_flame_provider : m_modrinth_provider;
|
||||
auto responseInfo = std::make_shared<QByteArray>();
|
||||
auto info = provider.api->getProject(pDep->pack->addonId.toString(), responseInfo);
|
||||
QObject::connect(info.get(), &NetJob::succeeded, [responseInfo, provider, pDep] {
|
||||
QJsonParseError parse_error{};
|
||||
QJsonDocument doc = QJsonDocument::fromJson(*responseInfo, &parse_error);
|
||||
if (parse_error.error != QJsonParseError::NoError) {
|
||||
qWarning() << "Error while parsing JSON response for mod info at " << parse_error.offset
|
||||
<< " reason: " << parse_error.errorString();
|
||||
qDebug() << *responseInfo;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
auto obj = provider.name == ModPlatform::ResourceProvider::FLAME ? Json::requireObject(Json::requireObject(doc), "data")
|
||||
: Json::requireObject(doc);
|
||||
provider.mod->loadIndexedPack(*pDep->pack, obj);
|
||||
} catch (const JSONValidationError& e) {
|
||||
qDebug() << doc;
|
||||
qWarning() << "Error while reading mod info: " << e.cause();
|
||||
}
|
||||
});
|
||||
return info;
|
||||
}
|
||||
|
||||
Task::Ptr GetModDependenciesTask::prepareDependencyTask(const ModPlatform::Dependency& dep,
|
||||
const ModPlatform::ResourceProvider providerName,
|
||||
int level)
|
||||
{
|
||||
auto pDep = std::make_shared<PackDependency>();
|
||||
pDep->dependency = dep;
|
||||
pDep->pack = std::make_shared<ModPlatform::IndexedPack>();
|
||||
pDep->pack->addonId = dep.addonId;
|
||||
pDep->pack->provider = providerName;
|
||||
|
||||
m_pack_dependencies.append(pDep);
|
||||
auto provider = providerName == m_flame_provider.name ? m_flame_provider : m_modrinth_provider;
|
||||
|
||||
auto tasks = makeShared<SequentialTask>(
|
||||
this, QString("DependencyInfo: %1").arg(dep.addonId.toString().isEmpty() ? dep.version : dep.addonId.toString()));
|
||||
|
||||
if (!dep.addonId.toString().isEmpty()) {
|
||||
tasks->addTask(getProjectInfoTask(pDep));
|
||||
}
|
||||
|
||||
ResourceAPI::DependencySearchArgs args = { dep, m_version, m_loaderType };
|
||||
ResourceAPI::DependencySearchCallbacks callbacks;
|
||||
|
||||
callbacks.on_succeed = [dep, provider, pDep, level, this](auto& doc, auto& pack) {
|
||||
try {
|
||||
QJsonArray arr;
|
||||
if (dep.version.length() != 0 && doc.isObject()) {
|
||||
arr.append(doc.object());
|
||||
} else {
|
||||
arr = doc.isObject() ? Json::ensureArray(doc.object(), "data") : doc.array();
|
||||
}
|
||||
pDep->version = provider.mod->loadDependencyVersions(dep, arr);
|
||||
if (!pDep->version.addonId.isValid()) {
|
||||
if (m_loaderType & ResourceAPI::Quilt) { // falback for quilt
|
||||
auto overide = ModPlatform::getOverrideDeps();
|
||||
auto over = std::find_if(overide.cbegin(), overide.cend(),
|
||||
[dep, provider](auto o) { return o.provider == provider.name && dep.addonId == o.quilt; });
|
||||
if (over != overide.cend()) {
|
||||
removePack(dep.addonId);
|
||||
addTask(prepareDependencyTask({ over->fabric, dep.type }, provider.name, level));
|
||||
return;
|
||||
}
|
||||
}
|
||||
qWarning() << "Error while reading mod version empty ";
|
||||
qDebug() << doc;
|
||||
return;
|
||||
}
|
||||
pDep->version.is_currently_selected = true;
|
||||
pDep->pack->versions = { pDep->version };
|
||||
pDep->pack->versionsLoaded = true;
|
||||
|
||||
} catch (const JSONValidationError& e) {
|
||||
qDebug() << doc;
|
||||
qWarning() << "Error while reading mod version: " << e.cause();
|
||||
return;
|
||||
}
|
||||
if (level == 0) {
|
||||
qWarning() << "Dependency cycle exeeded";
|
||||
return;
|
||||
}
|
||||
if (dep.addonId.toString().isEmpty() && !pDep->version.addonId.toString().isEmpty()) {
|
||||
pDep->pack->addonId = pDep->version.addonId;
|
||||
auto dep = getOverride({ pDep->version.addonId, pDep->dependency.type }, provider.name);
|
||||
if (dep.addonId != pDep->version.addonId) {
|
||||
removePack(pDep->version.addonId);
|
||||
addTask(prepareDependencyTask(dep, provider.name, level));
|
||||
} else
|
||||
addTask(getProjectInfoTask(pDep));
|
||||
}
|
||||
for (auto dep : getDependenciesForVersion(pDep->version, provider.name)) {
|
||||
addTask(prepareDependencyTask(dep, provider.name, level - 1));
|
||||
}
|
||||
};
|
||||
|
||||
auto version = provider.api->getDependencyVersion(std::move(args), std::move(callbacks));
|
||||
tasks->addTask(version);
|
||||
return tasks;
|
||||
};
|
||||
|
||||
void GetModDependenciesTask::removePack(const QVariant addonId)
|
||||
{
|
||||
auto pred = [addonId](const std::shared_ptr<PackDependency>& v) { return v->pack->addonId == addonId; };
|
||||
#if QT_VERSION >= QT_VERSION_CHECK(6, 1, 0)
|
||||
m_pack_dependencies.removeIf(pred);
|
||||
#else
|
||||
for (auto it = m_pack_dependencies.begin(); it != m_pack_dependencies.end();)
|
||||
if (pred(*it))
|
||||
it = m_pack_dependencies.erase(it);
|
||||
else
|
||||
++it;
|
||||
#endif
|
||||
}
|
84
launcher/minecraft/mod/tasks/GetModDependenciesTask.h
Normal file
84
launcher/minecraft/mod/tasks/GetModDependenciesTask.h
Normal file
@ -0,0 +1,84 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
/*
|
||||
* Prism Launcher - Minecraft Launcher
|
||||
* Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <QDir>
|
||||
#include <QEventLoop>
|
||||
#include <QList>
|
||||
#include <QVariant>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
|
||||
#include "minecraft/mod/MetadataHandler.h"
|
||||
#include "minecraft/mod/ModFolderModel.h"
|
||||
#include "modplatform/ModIndex.h"
|
||||
#include "modplatform/ResourceAPI.h"
|
||||
#include "tasks/SequentialTask.h"
|
||||
#include "tasks/Task.h"
|
||||
#include "ui/pages/modplatform/ModModel.h"
|
||||
|
||||
class GetModDependenciesTask : public SequentialTask {
|
||||
Q_OBJECT
|
||||
public:
|
||||
using Ptr = shared_qobject_ptr<GetModDependenciesTask>;
|
||||
|
||||
struct PackDependency {
|
||||
ModPlatform::Dependency dependency;
|
||||
ModPlatform::IndexedPack::Ptr pack;
|
||||
ModPlatform::IndexedVersion version;
|
||||
PackDependency() = default;
|
||||
PackDependency(const ModPlatform::IndexedPack::Ptr p, const ModPlatform::IndexedVersion& v)
|
||||
{
|
||||
pack = p;
|
||||
version = v;
|
||||
}
|
||||
};
|
||||
|
||||
struct Provider {
|
||||
ModPlatform::ResourceProvider name;
|
||||
std::shared_ptr<ResourceDownload::ModModel> mod;
|
||||
std::shared_ptr<ResourceAPI> api;
|
||||
};
|
||||
|
||||
explicit GetModDependenciesTask(QObject* parent,
|
||||
BaseInstance* instance,
|
||||
ModFolderModel* folder,
|
||||
QList<std::shared_ptr<PackDependency>> selected);
|
||||
|
||||
auto getDependecies() const -> QList<std::shared_ptr<PackDependency>> { return m_pack_dependencies; }
|
||||
|
||||
protected slots:
|
||||
Task::Ptr prepareDependencyTask(const ModPlatform::Dependency&, const ModPlatform::ResourceProvider, int);
|
||||
QList<ModPlatform::Dependency> getDependenciesForVersion(const ModPlatform::IndexedVersion&,
|
||||
const ModPlatform::ResourceProvider providerName);
|
||||
void prepare();
|
||||
Task::Ptr getProjectInfoTask(std::shared_ptr<PackDependency> pDep);
|
||||
ModPlatform::Dependency getOverride(const ModPlatform::Dependency&, const ModPlatform::ResourceProvider providerName);
|
||||
void removePack(const QVariant addonId);
|
||||
|
||||
private:
|
||||
QList<std::shared_ptr<PackDependency>> m_pack_dependencies;
|
||||
QList<std::shared_ptr<Metadata::ModStruct>> m_mods;
|
||||
QList<std::shared_ptr<PackDependency>> m_selected;
|
||||
Provider m_flame_provider;
|
||||
Provider m_modrinth_provider;
|
||||
|
||||
Version m_version;
|
||||
ResourceAPI::ModLoaderTypes m_loaderType;
|
||||
};
|
@ -52,6 +52,10 @@ ModDetails ReadMCModInfo(QByteArray contents)
|
||||
authors = firstObj.value("authors").toArray();
|
||||
}
|
||||
|
||||
if (firstObj.contains("logoFile")) {
|
||||
details.icon_file = firstObj.value("logoFile").toString();
|
||||
}
|
||||
|
||||
for (auto author : authors) {
|
||||
details.authors.append(author.toString());
|
||||
}
|
||||
@ -166,6 +170,31 @@ ModDetails ReadMCModTOML(QByteArray contents)
|
||||
}
|
||||
details.homeurl = homeurl;
|
||||
|
||||
QString issueTrackerURL = "";
|
||||
if (auto issueTrackerURLDatum = tomlData["issueTrackerURL"].as_string()) {
|
||||
issueTrackerURL = QString::fromStdString(issueTrackerURLDatum->get());
|
||||
} else if (auto issueTrackerURLDatum = (*modsTable)["issueTrackerURL"].as_string()) {
|
||||
issueTrackerURL = QString::fromStdString(issueTrackerURLDatum->get());
|
||||
}
|
||||
details.issue_tracker = issueTrackerURL;
|
||||
|
||||
QString license = "";
|
||||
if (auto licenseDatum = tomlData["license"].as_string()) {
|
||||
license = QString::fromStdString(licenseDatum->get());
|
||||
} else if (auto licenseDatum =(*modsTable)["license"].as_string()) {
|
||||
license = QString::fromStdString(licenseDatum->get());
|
||||
}
|
||||
if (!license.isEmpty())
|
||||
details.licenses.append(ModLicense(license));
|
||||
|
||||
QString logoFile = "";
|
||||
if (auto logoFileDatum = tomlData["logoFile"].as_string()) {
|
||||
logoFile = QString::fromStdString(logoFileDatum->get());
|
||||
} else if (auto logoFileDatum =(*modsTable)["logoFile"].as_string()) {
|
||||
logoFile = QString::fromStdString(logoFileDatum->get());
|
||||
}
|
||||
details.icon_file = logoFile;
|
||||
|
||||
return details;
|
||||
}
|
||||
|
||||
@ -201,6 +230,57 @@ ModDetails ReadFabricModInfo(QByteArray contents)
|
||||
if (contact.contains("homepage")) {
|
||||
details.homeurl = contact.value("homepage").toString();
|
||||
}
|
||||
if (contact.contains("issues")) {
|
||||
details.issue_tracker = contact.value("issues").toString();
|
||||
}
|
||||
}
|
||||
|
||||
if (object.contains("license")) {
|
||||
auto license = object.value("license");
|
||||
if (license.isArray()) {
|
||||
for (auto l : license.toArray()) {
|
||||
if (l.isString()) {
|
||||
details.licenses.append(ModLicense(l.toString()));
|
||||
} else if (l.isObject()) {
|
||||
auto obj = l.toObject();
|
||||
details.licenses.append(ModLicense(obj.value("name").toString(), obj.value("id").toString(),
|
||||
obj.value("url").toString(), obj.value("description").toString()));
|
||||
}
|
||||
}
|
||||
} else if (license.isString()) {
|
||||
details.licenses.append(ModLicense(license.toString()));
|
||||
} else if (license.isObject()) {
|
||||
auto obj = license.toObject();
|
||||
details.licenses.append(ModLicense(obj.value("name").toString(), obj.value("id").toString(), obj.value("url").toString(),
|
||||
obj.value("description").toString()));
|
||||
}
|
||||
}
|
||||
|
||||
if (object.contains("icon")) {
|
||||
auto icon = object.value("icon");
|
||||
if (icon.isObject()) {
|
||||
auto obj = icon.toObject();
|
||||
// take the largest icon
|
||||
int largest = 0;
|
||||
for (auto key : obj.keys()) {
|
||||
auto size = key.split('x').first().toInt();
|
||||
if (size > largest) {
|
||||
largest = size;
|
||||
}
|
||||
}
|
||||
if (largest > 0) {
|
||||
auto key = QString::number(largest) + "x" + QString::number(largest);
|
||||
details.icon_file = obj.value(key).toString();
|
||||
} else { // parsing the sizes failed
|
||||
// take the first
|
||||
for (auto i : obj) {
|
||||
details.icon_file = i.toString();
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else if (icon.isString()) {
|
||||
details.icon_file = icon.toString();
|
||||
}
|
||||
}
|
||||
}
|
||||
return details;
|
||||
@ -238,6 +318,58 @@ ModDetails ReadQuiltModInfo(QByteArray contents)
|
||||
if (modContact.contains("homepage")) {
|
||||
details.homeurl = Json::requireString(modContact.value("homepage"));
|
||||
}
|
||||
if (modContact.contains("issues")) {
|
||||
details.issue_tracker = Json::requireString(modContact.value("issues"));
|
||||
}
|
||||
|
||||
if (modMetadata.contains("license")) {
|
||||
auto license = modMetadata.value("license");
|
||||
if (license.isArray()) {
|
||||
for (auto l : license.toArray()) {
|
||||
if (l.isString()) {
|
||||
details.licenses.append(ModLicense(l.toString()));
|
||||
} else if (l.isObject()) {
|
||||
auto obj = l.toObject();
|
||||
details.licenses.append(ModLicense(obj.value("name").toString(), obj.value("id").toString(),
|
||||
obj.value("url").toString(), obj.value("description").toString()));
|
||||
}
|
||||
}
|
||||
} else if (license.isString()) {
|
||||
details.licenses.append(ModLicense(license.toString()));
|
||||
} else if (license.isObject()) {
|
||||
auto obj = license.toObject();
|
||||
details.licenses.append(ModLicense(obj.value("name").toString(), obj.value("id").toString(), obj.value("url").toString(),
|
||||
obj.value("description").toString()));
|
||||
}
|
||||
}
|
||||
|
||||
if (modMetadata.contains("icon")) {
|
||||
auto icon = modMetadata.value("icon");
|
||||
if (icon.isObject()) {
|
||||
auto obj = icon.toObject();
|
||||
// take the largest icon
|
||||
int largest = 0;
|
||||
for (auto key : obj.keys()) {
|
||||
auto size = key.split('x').first().toInt();
|
||||
if (size > largest) {
|
||||
largest = size;
|
||||
}
|
||||
}
|
||||
if (largest > 0) {
|
||||
auto key = QString::number(largest) + "x" + QString::number(largest);
|
||||
details.icon_file = obj.value(key).toString();
|
||||
} else { // parsing the sizes failed
|
||||
// take the first
|
||||
for (auto i : obj) {
|
||||
details.icon_file = i.toString();
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else if (icon.isString()) {
|
||||
details.icon_file = icon.toString();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
return details;
|
||||
}
|
||||
@ -515,6 +647,85 @@ bool validate(QFileInfo file)
|
||||
return ModUtils::process(mod, ProcessingLevel::BasicInfoOnly) && mod.valid();
|
||||
}
|
||||
|
||||
bool processIconPNG(const Mod& mod, QByteArray&& raw_data)
|
||||
{
|
||||
auto img = QImage::fromData(raw_data);
|
||||
if (!img.isNull()) {
|
||||
mod.setIcon(img);
|
||||
} else {
|
||||
qWarning() << "Failed to parse mod logo:" << mod.iconPath() << "from" << mod.name();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool loadIconFile(const Mod& mod) {
|
||||
if (mod.iconPath().isEmpty()) {
|
||||
qWarning() << "No Iconfile set, be sure to parse the mod first";
|
||||
return false;
|
||||
}
|
||||
|
||||
auto png_invalid = [&mod]() {
|
||||
qWarning() << "Mod at" << mod.fileinfo().filePath() << "does not have a valid icon";
|
||||
return false;
|
||||
};
|
||||
|
||||
switch (mod.type()) {
|
||||
case ResourceType::FOLDER:
|
||||
{
|
||||
QFileInfo icon_info(FS::PathCombine(mod.fileinfo().filePath(), mod.iconPath()));
|
||||
if (icon_info.exists() && icon_info.isFile()) {
|
||||
QFile icon(icon_info.filePath());
|
||||
if (!icon.open(QIODevice::ReadOnly))
|
||||
return false;
|
||||
auto data = icon.readAll();
|
||||
|
||||
bool icon_result = ModUtils::processIconPNG(mod, std::move(data));
|
||||
|
||||
icon.close();
|
||||
|
||||
if (!icon_result) {
|
||||
return png_invalid(); // icon invalid
|
||||
}
|
||||
}
|
||||
}
|
||||
case ResourceType::ZIPFILE:
|
||||
{
|
||||
QuaZip zip(mod.fileinfo().filePath());
|
||||
if (!zip.open(QuaZip::mdUnzip))
|
||||
return false;
|
||||
|
||||
QuaZipFile file(&zip);
|
||||
|
||||
if (zip.setCurrentFile(mod.iconPath())) {
|
||||
if (!file.open(QIODevice::ReadOnly)) {
|
||||
qCritical() << "Failed to open file in zip.";
|
||||
zip.close();
|
||||
return png_invalid();
|
||||
}
|
||||
|
||||
auto data = file.readAll();
|
||||
|
||||
bool icon_result = ModUtils::processIconPNG(mod, std::move(data));
|
||||
|
||||
file.close();
|
||||
if (!icon_result) {
|
||||
return png_invalid(); // icon png invalid
|
||||
}
|
||||
} else {
|
||||
return png_invalid(); // could not set icon as current file.
|
||||
}
|
||||
}
|
||||
case ResourceType::LITEMOD:
|
||||
{
|
||||
return false; // can lightmods even have icons?
|
||||
}
|
||||
default:
|
||||
qWarning() << "Invalid type for mod, can not load icon.";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace ModUtils
|
||||
|
||||
LocalModParseTask::LocalModParseTask(int token, ResourceType type, const QFileInfo& modFile)
|
||||
|
@ -25,6 +25,9 @@ bool processLitemod(Mod& mod, ProcessingLevel level = ProcessingLevel::Full);
|
||||
|
||||
/** Checks whether a file is valid as a mod or not. */
|
||||
bool validate(QFileInfo file);
|
||||
|
||||
bool processIconPNG(const Mod& mod, QByteArray&& raw_data);
|
||||
bool loadIconFile(const Mod& mod);
|
||||
} // namespace ModUtils
|
||||
|
||||
class LocalModParseTask : public Task {
|
||||
|
@ -1,6 +1,6 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
/*
|
||||
* PolyMC - Minecraft Launcher
|
||||
* Prism Launcher - Minecraft Launcher
|
||||
* Copyright (c) 2022 flowln <flowlnlnln@gmail.com>
|
||||
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
|
||||
*
|
||||
@ -19,7 +19,6 @@
|
||||
|
||||
#include "LocalModUpdateTask.h"
|
||||
|
||||
#include "Application.h"
|
||||
#include "FileSystem.h"
|
||||
#include "minecraft/mod/MetadataHandler.h"
|
||||
|
||||
|
@ -165,15 +165,16 @@ bool processZIP(ResourcePack& pack, ProcessingLevel level)
|
||||
bool pack_png_result = ResourcePackUtils::processPackPNG(pack, std::move(data));
|
||||
|
||||
file.close();
|
||||
zip.close();
|
||||
if (!pack_png_result) {
|
||||
return png_invalid(); // pack.png invalid
|
||||
}
|
||||
} else {
|
||||
zip.close();
|
||||
return png_invalid(); // could not set pack.mcmeta as current file.
|
||||
}
|
||||
|
||||
zip.close();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@ -193,7 +194,7 @@ bool processMCMeta(ResourcePack& pack, QByteArray&& raw_data)
|
||||
return true;
|
||||
}
|
||||
|
||||
bool processPackPNG(ResourcePack& pack, QByteArray&& raw_data)
|
||||
bool processPackPNG(const ResourcePack& pack, QByteArray&& raw_data)
|
||||
{
|
||||
auto img = QImage::fromData(raw_data);
|
||||
if (!img.isNull()) {
|
||||
@ -205,6 +206,68 @@ bool processPackPNG(ResourcePack& pack, QByteArray&& raw_data)
|
||||
return true;
|
||||
}
|
||||
|
||||
bool processPackPNG(const ResourcePack& pack)
|
||||
{
|
||||
auto png_invalid = [&pack]() {
|
||||
qWarning() << "Resource pack at" << pack.fileinfo().filePath() << "does not have a valid pack.png";
|
||||
return false;
|
||||
};
|
||||
|
||||
switch (pack.type()) {
|
||||
case ResourceType::FOLDER:
|
||||
{
|
||||
QFileInfo image_file_info(FS::PathCombine(pack.fileinfo().filePath(), "pack.png"));
|
||||
if (image_file_info.exists() && image_file_info.isFile()) {
|
||||
QFile pack_png_file(image_file_info.filePath());
|
||||
if (!pack_png_file.open(QIODevice::ReadOnly))
|
||||
return png_invalid(); // can't open pack.png file
|
||||
|
||||
auto data = pack_png_file.readAll();
|
||||
|
||||
bool pack_png_result = ResourcePackUtils::processPackPNG(pack, std::move(data));
|
||||
|
||||
pack_png_file.close();
|
||||
if (!pack_png_result) {
|
||||
return png_invalid(); // pack.png invalid
|
||||
}
|
||||
} else {
|
||||
return png_invalid(); // pack.png does not exists or is not a valid file.
|
||||
}
|
||||
}
|
||||
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
|
||||
|
||||
QuaZipFile file(&zip);
|
||||
if (zip.setCurrentFile("pack.png")) {
|
||||
if (!file.open(QIODevice::ReadOnly)) {
|
||||
qCritical() << "Failed to open file in zip.";
|
||||
zip.close();
|
||||
return png_invalid();
|
||||
}
|
||||
|
||||
auto data = file.readAll();
|
||||
|
||||
bool pack_png_result = ResourcePackUtils::processPackPNG(pack, std::move(data));
|
||||
|
||||
file.close();
|
||||
if (!pack_png_result) {
|
||||
return png_invalid(); // pack.png invalid
|
||||
}
|
||||
} else {
|
||||
return png_invalid(); // could not set pack.mcmeta as current file.
|
||||
}
|
||||
}
|
||||
default:
|
||||
qWarning() << "Invalid type for resource pack parse task!";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool validate(QFileInfo file)
|
||||
{
|
||||
ResourcePack rp{ file };
|
||||
|
@ -35,7 +35,10 @@ bool processZIP(ResourcePack& pack, ProcessingLevel level = ProcessingLevel::Ful
|
||||
bool processFolder(ResourcePack& pack, ProcessingLevel level = ProcessingLevel::Full);
|
||||
|
||||
bool processMCMeta(ResourcePack& pack, QByteArray&& raw_data);
|
||||
bool processPackPNG(ResourcePack& pack, QByteArray&& raw_data);
|
||||
bool processPackPNG(const ResourcePack& pack, QByteArray&& raw_data);
|
||||
|
||||
/// processes ONLY the pack.png (rest of the pack may be invalid)
|
||||
bool processPackPNG(const ResourcePack& pack);
|
||||
|
||||
/** Checks whether a file is valid as a resource pack or not. */
|
||||
bool validate(QFileInfo file);
|
||||
|
@ -44,7 +44,11 @@ static const QMap<PackedResourceType, QString> s_packed_type_names = {
|
||||
namespace ResourceUtils {
|
||||
PackedResourceType identify(QFileInfo file){
|
||||
if (file.exists() && file.isFile()) {
|
||||
if (ResourcePackUtils::validate(file)) {
|
||||
if (ModUtils::validate(file)) {
|
||||
// mods can contain resource and data packs so they must be tested first
|
||||
qDebug() << file.fileName() << "is a mod";
|
||||
return PackedResourceType::Mod;
|
||||
} else if (ResourcePackUtils::validate(file)) {
|
||||
qDebug() << file.fileName() << "is a resource pack";
|
||||
return PackedResourceType::ResourcePack;
|
||||
} else if (TexturePackUtils::validate(file)) {
|
||||
@ -53,9 +57,6 @@ PackedResourceType identify(QFileInfo file){
|
||||
} else if (DataPackUtils::validate(file)) {
|
||||
qDebug() << file.fileName() << "is a data pack";
|
||||
return PackedResourceType::DataPack;
|
||||
} else if (ModUtils::validate(file)) {
|
||||
qDebug() << file.fileName() << "is a mod";
|
||||
return PackedResourceType::Mod;
|
||||
} else if (WorldSaveUtils::validate(file)) {
|
||||
qDebug() << file.fileName() << "is a world save";
|
||||
return PackedResourceType::WorldSave;
|
||||
|
@ -131,6 +131,7 @@ bool processZIP(TexturePack& pack, ProcessingLevel level)
|
||||
bool packPNG_result = TexturePackUtils::processPackPNG(pack, std::move(data));
|
||||
|
||||
file.close();
|
||||
zip.close();
|
||||
if (!packPNG_result) {
|
||||
return false;
|
||||
}
|
||||
@ -147,7 +148,7 @@ bool processPackTXT(TexturePack& pack, QByteArray&& raw_data)
|
||||
return true;
|
||||
}
|
||||
|
||||
bool processPackPNG(TexturePack& pack, QByteArray&& raw_data)
|
||||
bool processPackPNG(const TexturePack& pack, QByteArray&& raw_data)
|
||||
{
|
||||
auto img = QImage::fromData(raw_data);
|
||||
if (!img.isNull()) {
|
||||
@ -159,6 +160,70 @@ bool processPackPNG(TexturePack& pack, QByteArray&& raw_data)
|
||||
return true;
|
||||
}
|
||||
|
||||
bool processPackPNG(const TexturePack& pack)
|
||||
{
|
||||
auto png_invalid = [&pack]() {
|
||||
qWarning() << "Texture pack at" << pack.fileinfo().filePath() << "does not have a valid pack.png";
|
||||
return false;
|
||||
};
|
||||
|
||||
switch (pack.type()) {
|
||||
case ResourceType::FOLDER:
|
||||
{
|
||||
QFileInfo image_file_info(FS::PathCombine(pack.fileinfo().filePath(), "pack.png"));
|
||||
if (image_file_info.exists() && image_file_info.isFile()) {
|
||||
QFile pack_png_file(image_file_info.filePath());
|
||||
if (!pack_png_file.open(QIODevice::ReadOnly))
|
||||
return png_invalid(); // can't open pack.png file
|
||||
|
||||
auto data = pack_png_file.readAll();
|
||||
|
||||
bool pack_png_result = TexturePackUtils::processPackPNG(pack, std::move(data));
|
||||
|
||||
pack_png_file.close();
|
||||
if (!pack_png_result) {
|
||||
return png_invalid(); // pack.png invalid
|
||||
}
|
||||
} else {
|
||||
return png_invalid(); // pack.png does not exists or is not a valid file.
|
||||
}
|
||||
}
|
||||
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
|
||||
|
||||
QuaZipFile file(&zip);
|
||||
if (zip.setCurrentFile("pack.png")) {
|
||||
if (!file.open(QIODevice::ReadOnly)) {
|
||||
qCritical() << "Failed to open file in zip.";
|
||||
zip.close();
|
||||
return png_invalid();
|
||||
}
|
||||
|
||||
auto data = file.readAll();
|
||||
|
||||
bool pack_png_result = TexturePackUtils::processPackPNG(pack, std::move(data));
|
||||
|
||||
file.close();
|
||||
if (!pack_png_result) {
|
||||
zip.close();
|
||||
return png_invalid(); // pack.png invalid
|
||||
}
|
||||
} else {
|
||||
zip.close();
|
||||
return png_invalid(); // could not set pack.mcmeta as current file.
|
||||
}
|
||||
}
|
||||
default:
|
||||
qWarning() << "Invalid type for resource pack parse task!";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool validate(QFileInfo file)
|
||||
{
|
||||
TexturePack rp{ file };
|
||||
|
@ -36,7 +36,10 @@ bool processZIP(TexturePack& pack, ProcessingLevel level = ProcessingLevel::Full
|
||||
bool processFolder(TexturePack& pack, ProcessingLevel level = ProcessingLevel::Full);
|
||||
|
||||
bool processPackTXT(TexturePack& pack, QByteArray&& raw_data);
|
||||
bool processPackPNG(TexturePack& pack, QByteArray&& raw_data);
|
||||
bool processPackPNG(const TexturePack& pack, QByteArray&& raw_data);
|
||||
|
||||
/// processes ONLY the pack.png (rest of the pack may be invalid)
|
||||
bool processPackPNG(const TexturePack& pack);
|
||||
|
||||
/** Checks whether a file is valid as a texture pack or not. */
|
||||
bool validate(QFileInfo file);
|
||||
|
@ -103,7 +103,7 @@ void ModFolderLoadTask::executeTask()
|
||||
while (iter.hasNext()) {
|
||||
auto mod = iter.next().value();
|
||||
if (mod->status() == ModStatus::NotInstalled) {
|
||||
mod->destroy(m_index_dir, false);
|
||||
mod->destroy(m_index_dir, false, false);
|
||||
iter.remove();
|
||||
}
|
||||
}
|
||||
|
@ -10,6 +10,7 @@
|
||||
|
||||
#include "modplatform/flame/FlameAPI.h"
|
||||
#include "modplatform/flame/FlameModIndex.h"
|
||||
#include "modplatform/helpers/HashUtils.h"
|
||||
#include "modplatform/modrinth/ModrinthAPI.h"
|
||||
#include "modplatform/modrinth/ModrinthPackIndex.h"
|
||||
|
||||
@ -24,8 +25,8 @@ EnsureMetadataTask::EnsureMetadataTask(Mod* mod, QDir dir, ModPlatform::Resource
|
||||
auto hash_task = createNewHash(mod);
|
||||
if (!hash_task)
|
||||
return;
|
||||
connect(hash_task.get(), &Task::succeeded, [this, hash_task, mod] { m_mods.insert(hash_task->getResult(), mod); });
|
||||
connect(hash_task.get(), &Task::failed, [this, hash_task, mod] { emitFail(mod, "", RemoveFromList::No); });
|
||||
connect(hash_task.get(), &Hashing::Hasher::resultsReady, [this, mod](QString hash) { m_mods.insert(hash, mod); });
|
||||
connect(hash_task.get(), &Task::failed, [this, mod] { emitFail(mod, "", RemoveFromList::No); });
|
||||
hash_task->start();
|
||||
}
|
||||
|
||||
@ -37,8 +38,8 @@ EnsureMetadataTask::EnsureMetadataTask(QList<Mod*>& mods, QDir dir, ModPlatform:
|
||||
auto hash_task = createNewHash(mod);
|
||||
if (!hash_task)
|
||||
continue;
|
||||
connect(hash_task.get(), &Task::succeeded, [this, hash_task, mod] { m_mods.insert(hash_task->getResult(), mod); });
|
||||
connect(hash_task.get(), &Task::failed, [this, hash_task, mod] { emitFail(mod, "", RemoveFromList::No); });
|
||||
connect(hash_task.get(), &Hashing::Hasher::resultsReady, [this, mod](QString hash) { m_mods.insert(hash, mod); });
|
||||
connect(hash_task.get(), &Task::failed, [this, mod] { emitFail(mod, "", RemoveFromList::No); });
|
||||
m_hashing_task->addTask(hash_task);
|
||||
}
|
||||
}
|
||||
@ -144,7 +145,8 @@ void EnsureMetadataTask::executeTask()
|
||||
connect(project_task.get(), &Task::finished, this, [=] {
|
||||
invalidade_leftover();
|
||||
project_task->deleteLater();
|
||||
m_current_task = nullptr;
|
||||
if (m_current_task)
|
||||
m_current_task.reset();
|
||||
});
|
||||
|
||||
m_current_task = project_task;
|
||||
@ -153,7 +155,8 @@ void EnsureMetadataTask::executeTask()
|
||||
|
||||
connect(version_task.get(), &Task::finished, [=] {
|
||||
version_task->deleteLater();
|
||||
m_current_task = nullptr;
|
||||
if (m_current_task)
|
||||
m_current_task.reset();
|
||||
});
|
||||
|
||||
if (m_mods.size() > 1)
|
||||
@ -212,7 +215,7 @@ Task::Ptr EnsureMetadataTask::modrinthVersionsTask()
|
||||
{
|
||||
auto hash_type = ProviderCaps.hashType(ModPlatform::ResourceProvider::MODRINTH).first();
|
||||
|
||||
auto* response = new QByteArray();
|
||||
auto response = std::make_shared<QByteArray>();
|
||||
auto ver_task = modrinth_api.currentVersions(m_mods.keys(), hash_type, response);
|
||||
|
||||
// Prevents unfortunate timings when aborting the task
|
||||
@ -264,7 +267,7 @@ Task::Ptr EnsureMetadataTask::modrinthProjectsTask()
|
||||
for (auto const& data : m_temp_versions)
|
||||
addonIds.insert(data.addonId.toString(), data.hash);
|
||||
|
||||
auto response = new QByteArray();
|
||||
auto response = std::make_shared<QByteArray>();
|
||||
Task::Ptr proj_task;
|
||||
|
||||
if (addonIds.isEmpty()) {
|
||||
@ -345,7 +348,7 @@ Task::Ptr EnsureMetadataTask::modrinthProjectsTask()
|
||||
// Flame
|
||||
Task::Ptr EnsureMetadataTask::flameVersionsTask()
|
||||
{
|
||||
auto* response = new QByteArray();
|
||||
auto response = std::make_shared<QByteArray>();
|
||||
|
||||
QList<uint> fingerprints;
|
||||
for (auto& murmur : m_mods.keys()) {
|
||||
@ -413,7 +416,7 @@ Task::Ptr EnsureMetadataTask::flameProjectsTask()
|
||||
QHash<QString, QString> addonIds;
|
||||
for (auto const& hash : m_mods.keys()) {
|
||||
if (m_temp_versions.contains(hash)) {
|
||||
auto const& data = m_temp_versions.find(hash).value();
|
||||
auto data = m_temp_versions.find(hash).value();
|
||||
|
||||
auto id_str = data.addonId.toString();
|
||||
if (!id_str.isEmpty())
|
||||
@ -421,7 +424,7 @@ Task::Ptr EnsureMetadataTask::flameProjectsTask()
|
||||
}
|
||||
}
|
||||
|
||||
auto response = new QByteArray();
|
||||
auto response = std::make_shared<QByteArray>();
|
||||
Task::Ptr proj_task;
|
||||
|
||||
if (addonIds.isEmpty()) {
|
||||
|
@ -77,4 +77,10 @@ auto ProviderCapabilities::hash(ResourceProvider p, QIODevice* device, QString t
|
||||
return { hash.result().toHex() };
|
||||
}
|
||||
|
||||
QString getMetaURL(ResourceProvider provider, QVariant projectID)
|
||||
{
|
||||
return ((provider == ModPlatform::ResourceProvider::FLAME) ? "https://www.curseforge.com/projects/" : "https://modrinth.com/mod/") +
|
||||
projectID.toString();
|
||||
}
|
||||
|
||||
} // namespace ModPlatform
|
||||
|
@ -1,7 +1,8 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
/*
|
||||
* PolyMC - Minecraft Launcher
|
||||
* Prism Launcher - Minecraft Launcher
|
||||
* Copyright (c) 2022 flowln <flowlnlnln@gmail.com>
|
||||
* Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
@ -33,6 +34,8 @@ enum class ResourceProvider { MODRINTH, FLAME };
|
||||
|
||||
enum class ResourceType { MOD, RESOURCE_PACK, SHADER_PACK };
|
||||
|
||||
enum class DependencyType { REQUIRED, OPTIONAL, INCOMPATIBLE, EMBEDDED, TOOL, INCLUDE, UNKNOWN };
|
||||
|
||||
class ProviderCapabilities {
|
||||
public:
|
||||
auto name(ResourceProvider) -> const char*;
|
||||
@ -52,6 +55,12 @@ struct DonationData {
|
||||
QString url;
|
||||
};
|
||||
|
||||
struct Dependency {
|
||||
QVariant addonId;
|
||||
DependencyType type;
|
||||
QString version;
|
||||
};
|
||||
|
||||
struct IndexedVersion {
|
||||
QVariant addonId;
|
||||
QVariant fileId;
|
||||
@ -66,6 +75,7 @@ struct IndexedVersion {
|
||||
QString hash;
|
||||
bool is_preferred = true;
|
||||
QString changelog;
|
||||
QList<Dependency> dependencies;
|
||||
|
||||
// For internal use, not provided by APIs
|
||||
bool is_currently_selected = false;
|
||||
@ -118,6 +128,24 @@ struct IndexedPack {
|
||||
return std::any_of(versions.constBegin(), versions.constEnd(), [](auto const& v) { return v.is_currently_selected; });
|
||||
}
|
||||
};
|
||||
QString getMetaURL(ResourceProvider provider, QVariant projectID);
|
||||
|
||||
struct OverrideDep {
|
||||
QString quilt;
|
||||
QString fabric;
|
||||
QString slug;
|
||||
ModPlatform::ResourceProvider provider;
|
||||
};
|
||||
|
||||
inline auto getOverrideDeps() -> QList<OverrideDep>
|
||||
{
|
||||
return { { "634179", "306612", "API", ModPlatform::ResourceProvider::FLAME },
|
||||
{ "720410", "308769", "KotlinLibraries", ModPlatform::ResourceProvider::FLAME },
|
||||
|
||||
{ "qvIfYCYJ", "P7dR8mSH", "API", ModPlatform::ResourceProvider::MODRINTH },
|
||||
{ "lwVhp9o5", "Ha28R6CL", "KotlinLibraries", ModPlatform::ResourceProvider::MODRINTH } };
|
||||
};
|
||||
QString getMetaURL(ResourceProvider provider, QVariant projectID);
|
||||
|
||||
} // namespace ModPlatform
|
||||
|
||||
|
@ -111,6 +111,16 @@ class ResourceAPI {
|
||||
std::function<void(QJsonDocument&, ModPlatform::IndexedPack)> on_succeed;
|
||||
};
|
||||
|
||||
struct DependencySearchArgs {
|
||||
ModPlatform::Dependency dependency;
|
||||
Version mcVersion;
|
||||
ModLoaderTypes loader;
|
||||
};
|
||||
|
||||
struct DependencySearchCallbacks {
|
||||
std::function<void(QJsonDocument&, const ModPlatform::Dependency&)> on_succeed;
|
||||
};
|
||||
|
||||
public:
|
||||
/** Gets a list of available sorting methods for this API. */
|
||||
[[nodiscard]] virtual auto getSortingMethods() const -> QList<SortingMethod> = 0;
|
||||
@ -121,12 +131,12 @@ class ResourceAPI {
|
||||
qWarning() << "TODO";
|
||||
return nullptr;
|
||||
}
|
||||
[[nodiscard]] virtual Task::Ptr getProject(QString addonId, QByteArray* response) const
|
||||
[[nodiscard]] virtual Task::Ptr getProject(QString addonId, std::shared_ptr<QByteArray> response) const
|
||||
{
|
||||
qWarning() << "TODO";
|
||||
return nullptr;
|
||||
}
|
||||
[[nodiscard]] virtual Task::Ptr getProjects(QStringList addonIds, QByteArray* response) const
|
||||
[[nodiscard]] virtual Task::Ptr getProjects(QStringList addonIds, std::shared_ptr<QByteArray> response) const
|
||||
{
|
||||
qWarning() << "TODO";
|
||||
return nullptr;
|
||||
@ -143,6 +153,12 @@ class ResourceAPI {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
[[nodiscard]] virtual Task::Ptr getDependencyVersion(DependencySearchArgs&&, DependencySearchCallbacks&&) const
|
||||
{
|
||||
qWarning() << "TODO";
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
static auto getModLoaderString(ModLoaderType type) -> const QString
|
||||
{
|
||||
switch (type) {
|
||||
|
@ -82,9 +82,9 @@ void PackInstallTask::executeTask()
|
||||
{
|
||||
qDebug() << "PackInstallTask::executeTask: " << QThread::currentThreadId();
|
||||
NetJob::Ptr netJob{ new NetJob("ATLauncher::VersionFetch", APPLICATION->network()) };
|
||||
auto searchUrl = QString(BuildConfig.ATL_DOWNLOAD_SERVER_URL + "packs/%1/versions/%2/Configs.json")
|
||||
.arg(m_pack_safe_name).arg(m_version_name);
|
||||
netJob->addNetAction(Net::Download::makeByteArray(QUrl(searchUrl), &response));
|
||||
auto searchUrl =
|
||||
QString(BuildConfig.ATL_DOWNLOAD_SERVER_URL + "packs/%1/versions/%2/Configs.json").arg(m_pack_safe_name).arg(m_version_name);
|
||||
netJob->addNetAction(Net::Download::makeByteArray(QUrl(searchUrl), response));
|
||||
|
||||
QObject::connect(netJob.get(), &NetJob::succeeded, this, &PackInstallTask::onDownloadSucceeded);
|
||||
QObject::connect(netJob.get(), &NetJob::failed, this, &PackInstallTask::onDownloadFailed);
|
||||
@ -100,10 +100,11 @@ void PackInstallTask::onDownloadSucceeded()
|
||||
jobPtr.reset();
|
||||
|
||||
QJsonParseError parse_error{};
|
||||
QJsonDocument doc = QJsonDocument::fromJson(response, &parse_error);
|
||||
QJsonDocument doc = QJsonDocument::fromJson(*response, &parse_error);
|
||||
if (parse_error.error != QJsonParseError::NoError) {
|
||||
qWarning() << "Error while parsing JSON response from ATLauncher at " << parse_error.offset << " reason: " << parse_error.errorString();
|
||||
qWarning() << response;
|
||||
qWarning() << "Error while parsing JSON response from ATLauncher at " << parse_error.offset
|
||||
<< " reason: " << parse_error.errorString();
|
||||
qWarning() << *response.get();
|
||||
return;
|
||||
}
|
||||
auto obj = doc.object();
|
||||
|
@ -40,12 +40,13 @@
|
||||
#include "ATLPackManifest.h"
|
||||
|
||||
#include "InstanceTask.h"
|
||||
#include "net/NetJob.h"
|
||||
#include "settings/INISettingsObject.h"
|
||||
#include "meta/Version.h"
|
||||
#include "minecraft/MinecraftInstance.h"
|
||||
#include "minecraft/PackProfile.h"
|
||||
#include "meta/Version.h"
|
||||
#include "net/NetJob.h"
|
||||
#include "settings/INISettingsObject.h"
|
||||
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
|
||||
namespace ATLauncher {
|
||||
@ -57,7 +58,6 @@ enum class InstallMode {
|
||||
};
|
||||
|
||||
class UserInteractionSupport {
|
||||
|
||||
public:
|
||||
/**
|
||||
* Requests a user interaction to select which optional mods should be installed.
|
||||
@ -74,15 +74,19 @@ public:
|
||||
* Requests a user interaction to display a message.
|
||||
*/
|
||||
virtual void displayMessage(QString message) = 0;
|
||||
|
||||
virtual ~UserInteractionSupport() = default;
|
||||
};
|
||||
|
||||
class PackInstallTask : public InstanceTask
|
||||
{
|
||||
class PackInstallTask : public InstanceTask {
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit PackInstallTask(UserInteractionSupport *support, QString packName, QString version, InstallMode installMode = InstallMode::Install);
|
||||
virtual ~PackInstallTask(){}
|
||||
explicit PackInstallTask(UserInteractionSupport* support,
|
||||
QString packName,
|
||||
QString version,
|
||||
InstallMode installMode = InstallMode::Install);
|
||||
virtual ~PackInstallTask() { delete m_support; }
|
||||
|
||||
bool canAbort() const override { return true; }
|
||||
bool abort() override;
|
||||
@ -110,11 +114,9 @@ private:
|
||||
void installConfigs();
|
||||
void extractConfigs();
|
||||
void downloadMods();
|
||||
bool extractMods(
|
||||
const QMap<QString, VersionMod> &toExtract,
|
||||
bool extractMods(const QMap<QString, VersionMod>& toExtract,
|
||||
const QMap<QString, VersionMod>& toDecomp,
|
||||
const QMap<QString, QString> &toCopy
|
||||
);
|
||||
const QMap<QString, QString>& toCopy);
|
||||
void install();
|
||||
|
||||
private:
|
||||
@ -123,7 +125,7 @@ private:
|
||||
bool abortable = false;
|
||||
|
||||
NetJob::Ptr jobPtr;
|
||||
QByteArray response;
|
||||
std::shared_ptr<QByteArray> response = std::make_shared<QByteArray>();
|
||||
|
||||
InstallMode m_install_mode;
|
||||
QString m_pack_name;
|
||||
@ -145,7 +147,6 @@ private:
|
||||
|
||||
QFuture<bool> m_modExtractFuture;
|
||||
QFutureWatcher<bool> m_modExtractFutureWatcher;
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
} // namespace ATLauncher
|
||||
|
@ -21,6 +21,10 @@ bool Flame::FileResolvingTask::abort()
|
||||
|
||||
void Flame::FileResolvingTask::executeTask()
|
||||
{
|
||||
if (m_toProcess.files.isEmpty()) { // no file to resolve so leave it empty and emit success immediately
|
||||
emitSucceeded();
|
||||
return;
|
||||
}
|
||||
setStatus(tr("Resolving mod IDs..."));
|
||||
setProgress(0, 3);
|
||||
m_dljob.reset(new NetJob("Mod id resolver", m_network));
|
||||
@ -28,12 +32,13 @@ void Flame::FileResolvingTask::executeTask()
|
||||
// build json data to send
|
||||
QJsonObject object;
|
||||
|
||||
object["fileIds"] = QJsonArray::fromVariantList(std::accumulate(m_toProcess.files.begin(), m_toProcess.files.end(), QVariantList(), [](QVariantList& l, const File& s) {
|
||||
object["fileIds"] = QJsonArray::fromVariantList(
|
||||
std::accumulate(m_toProcess.files.begin(), m_toProcess.files.end(), QVariantList(), [](QVariantList& l, const File& s) {
|
||||
l.push_back(s.fileId);
|
||||
return l;
|
||||
}));
|
||||
QByteArray data = Json::toText(object);
|
||||
auto dl = Net::Upload::makeByteArray(QUrl("https://api.curseforge.com/v1/mods/files"), result.get(), data);
|
||||
auto dl = Net::Upload::makeByteArray(QUrl("https://api.curseforge.com/v1/mods/files"), result, data);
|
||||
m_dljob->addNetAction(dl);
|
||||
|
||||
auto step_progress = std::make_shared<TaskStepProgress>();
|
||||
@ -94,10 +99,8 @@ void Flame::FileResolvingTask::netJobFinished()
|
||||
if (!hash.isEmpty()) {
|
||||
auto url = QString("https://api.modrinth.com/v2/version_file/%1?algorithm=sha1").arg(hash);
|
||||
auto output = std::make_shared<QByteArray>();
|
||||
auto dl = Net::Download::makeByteArray(QUrl(url), output.get());
|
||||
QObject::connect(dl.get(), &Net::Download::succeeded, [&out]() {
|
||||
out.resolved = true;
|
||||
});
|
||||
auto dl = Net::Download::makeByteArray(QUrl(url), output);
|
||||
QObject::connect(dl.get(), &Net::Download::succeeded, [&out]() { out.resolved = true; });
|
||||
|
||||
m_checkJob->addNetAction(dl);
|
||||
blockedProjects.insert(&out, output);
|
||||
@ -129,7 +132,8 @@ void Flame::FileResolvingTask::netJobFinished()
|
||||
m_checkJob->start();
|
||||
}
|
||||
|
||||
void Flame::FileResolvingTask::modrinthCheckFinished() {
|
||||
void Flame::FileResolvingTask::modrinthCheckFinished()
|
||||
{
|
||||
setProgress(2, 3);
|
||||
qDebug() << "Finished with blocked mods : " << blockedProjects.size();
|
||||
|
||||
@ -157,9 +161,7 @@ void Flame::FileResolvingTask::modrinthCheckFinished() {
|
||||
// copy to an output list and filter out projects found on modrinth
|
||||
auto block = std::make_shared<QList<File*>>();
|
||||
auto it = blockedProjects.keys();
|
||||
std::copy_if(it.begin(), it.end(), std::back_inserter(*block), [](File *f) {
|
||||
return !f->resolved;
|
||||
});
|
||||
std::copy_if(it.begin(), it.end(), std::back_inserter(*block), [](File* f) { return !f->resolved; });
|
||||
// Display not found mods early
|
||||
if (!block->empty()) {
|
||||
// blocked mods found, we need the slug for displaying.... we need another job :D !
|
||||
@ -169,13 +171,13 @@ void Flame::FileResolvingTask::modrinthCheckFinished() {
|
||||
auto projectId = mod->projectId;
|
||||
auto output = std::make_shared<QByteArray>();
|
||||
auto url = QString("https://api.curseforge.com/v1/mods/%1").arg(projectId);
|
||||
auto dl = Net::Download::makeByteArray(url, output.get());
|
||||
auto dl = Net::Download::makeByteArray(url, output);
|
||||
qDebug() << "Fetching url slug for file:" << mod->fileName;
|
||||
QObject::connect(dl.get(), &Net::Download::succeeded, [block, index, output]() {
|
||||
auto mod = block->at(index); // use the shared_ptr so it is captured and only freed when we are done
|
||||
auto json = QJsonDocument::fromJson(*output);
|
||||
auto base = Json::requireString(Json::requireObject(Json::requireObject(Json::requireObject(json),"data"),"links"),
|
||||
"websiteUrl");
|
||||
auto base =
|
||||
Json::requireString(Json::requireObject(Json::requireObject(Json::requireObject(json), "data"), "links"), "websiteUrl");
|
||||
auto link = QString("%1/download/%2").arg(base, QString::number(mod->fileId));
|
||||
mod->websiteUrl = link;
|
||||
});
|
||||
|
@ -11,7 +11,7 @@
|
||||
#include "net/NetJob.h"
|
||||
#include "net/Upload.h"
|
||||
|
||||
Task::Ptr FlameAPI::matchFingerprints(const QList<uint>& fingerprints, QByteArray* response)
|
||||
Task::Ptr FlameAPI::matchFingerprints(const QList<uint>& fingerprints, std::shared_ptr<QByteArray> response)
|
||||
{
|
||||
auto netJob = makeShared<NetJob>(QString("Flame::MatchFingerprints"), APPLICATION->network());
|
||||
|
||||
@ -28,8 +28,6 @@ Task::Ptr FlameAPI::matchFingerprints(const QList<uint>& fingerprints, QByteArra
|
||||
|
||||
netJob->addNetAction(Net::Upload::makeByteArray(QString("https://api.curseforge.com/v1/fingerprints"), response, body_raw));
|
||||
|
||||
QObject::connect(netJob.get(), &NetJob::finished, [response] { delete response; });
|
||||
|
||||
return netJob;
|
||||
}
|
||||
|
||||
@ -43,7 +41,7 @@ auto FlameAPI::getModFileChangelog(int modId, int fileId) -> QString
|
||||
netJob->addNetAction(Net::Download::makeByteArray(
|
||||
QString("https://api.curseforge.com/v1/mods/%1/files/%2/changelog")
|
||||
.arg(QString::fromStdString(std::to_string(modId)), QString::fromStdString(std::to_string(fileId))),
|
||||
response.get()));
|
||||
response));
|
||||
|
||||
QObject::connect(netJob.get(), &NetJob::succeeded, [&netJob, response, &changelog] {
|
||||
QJsonParseError parse_error{};
|
||||
@ -75,8 +73,8 @@ auto FlameAPI::getModDescription(int modId) -> QString
|
||||
|
||||
auto netJob = makeShared<NetJob>(QString("Flame::ModDescription"), APPLICATION->network());
|
||||
auto response = std::make_shared<QByteArray>();
|
||||
netJob->addNetAction(Net::Download::makeByteArray(
|
||||
QString("https://api.curseforge.com/v1/mods/%1/description").arg(QString::number(modId)), response.get()));
|
||||
netJob->addNetAction(
|
||||
Net::Download::makeByteArray(QString("https://api.curseforge.com/v1/mods/%1/description").arg(QString::number(modId)), response));
|
||||
|
||||
QObject::connect(netJob.get(), &NetJob::succeeded, [&netJob, response, &description] {
|
||||
QJsonParseError parse_error{};
|
||||
@ -115,7 +113,7 @@ auto FlameAPI::getLatestVersion(VersionSearchArgs&& args) -> ModPlatform::Indexe
|
||||
auto response = std::make_shared<QByteArray>();
|
||||
ModPlatform::IndexedVersion ver;
|
||||
|
||||
netJob->addNetAction(Net::Download::makeByteArray(versions_url, response.get()));
|
||||
netJob->addNetAction(Net::Download::makeByteArray(versions_url, response));
|
||||
|
||||
QObject::connect(netJob.get(), &NetJob::succeeded, [response, args, &ver] {
|
||||
QJsonParseError parse_error{};
|
||||
@ -160,7 +158,7 @@ auto FlameAPI::getLatestVersion(VersionSearchArgs&& args) -> ModPlatform::Indexe
|
||||
return ver;
|
||||
}
|
||||
|
||||
Task::Ptr FlameAPI::getProjects(QStringList addonIds, QByteArray* response) const
|
||||
Task::Ptr FlameAPI::getProjects(QStringList addonIds, std::shared_ptr<QByteArray> response) const
|
||||
{
|
||||
auto netJob = makeShared<NetJob>(QString("Flame::GetProjects"), APPLICATION->network());
|
||||
|
||||
@ -177,13 +175,12 @@ Task::Ptr FlameAPI::getProjects(QStringList addonIds, QByteArray* response) cons
|
||||
|
||||
netJob->addNetAction(Net::Upload::makeByteArray(QString("https://api.curseforge.com/v1/mods"), response, body_raw));
|
||||
|
||||
QObject::connect(netJob.get(), &NetJob::finished, [response] { delete response; });
|
||||
QObject::connect(netJob.get(), &NetJob::failed, [body_raw] { qDebug() << body_raw; });
|
||||
|
||||
return netJob;
|
||||
}
|
||||
|
||||
Task::Ptr FlameAPI::getFiles(const QStringList& fileIds, QByteArray* response) const
|
||||
Task::Ptr FlameAPI::getFiles(const QStringList& fileIds, std::shared_ptr<QByteArray> response) const
|
||||
{
|
||||
auto netJob = makeShared<NetJob>(QString("Flame::GetFiles"), APPLICATION->network());
|
||||
|
||||
@ -200,7 +197,6 @@ Task::Ptr FlameAPI::getFiles(const QStringList& fileIds, QByteArray* response) c
|
||||
|
||||
netJob->addNetAction(Net::Upload::makeByteArray(QString("https://api.curseforge.com/v1/mods/files"), response, body_raw));
|
||||
|
||||
QObject::connect(netJob.get(), &NetJob::finished, [response] { delete response; });
|
||||
QObject::connect(netJob.get(), &NetJob::failed, [body_raw] { qDebug() << body_raw; });
|
||||
|
||||
return netJob;
|
||||
|
@ -4,7 +4,10 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <memory>
|
||||
#include "modplatform/ModIndex.h"
|
||||
#include "modplatform/ResourceAPI.h"
|
||||
#include "modplatform/helpers/NetworkResourceAPI.h"
|
||||
|
||||
class FlameAPI : public NetworkResourceAPI {
|
||||
@ -14,12 +17,14 @@ class FlameAPI : public NetworkResourceAPI {
|
||||
|
||||
auto getLatestVersion(VersionSearchArgs&& args) -> ModPlatform::IndexedVersion;
|
||||
|
||||
Task::Ptr getProjects(QStringList addonIds, QByteArray* response) const override;
|
||||
Task::Ptr matchFingerprints(const QList<uint>& fingerprints, QByteArray* response);
|
||||
Task::Ptr getFiles(const QStringList& fileIds, QByteArray* response) const;
|
||||
Task::Ptr getProjects(QStringList addonIds, std::shared_ptr<QByteArray> response) const override;
|
||||
Task::Ptr matchFingerprints(const QList<uint>& fingerprints, std::shared_ptr<QByteArray> response);
|
||||
Task::Ptr getFiles(const QStringList& fileIds, std::shared_ptr<QByteArray> response) const;
|
||||
|
||||
[[nodiscard]] auto getSortingMethods() const -> QList<ResourceAPI::SortingMethod> override;
|
||||
|
||||
static inline auto validateModLoaders(ModLoaderTypes loaders) -> bool { return loaders & (Forge | Fabric | Quilt); }
|
||||
|
||||
private:
|
||||
static int getClassId(ModPlatform::ResourceType type)
|
||||
{
|
||||
@ -48,7 +53,8 @@ class FlameAPI : public NetworkResourceAPI {
|
||||
private:
|
||||
[[nodiscard]] std::optional<QString> getSearchURL(SearchArgs const& args) const override
|
||||
{
|
||||
auto gameVersionStr = args.versions.has_value() ? QString("gameVersion=%1").arg(args.versions.value().front().toString()) : QString();
|
||||
auto gameVersionStr =
|
||||
args.versions.has_value() ? QString("gameVersion=%1").arg(args.versions.value().front().toString()) : QString();
|
||||
|
||||
QStringList get_arguments;
|
||||
get_arguments.append(QString("classId=%1").arg(getClassId(args.type)));
|
||||
@ -73,14 +79,48 @@ class FlameAPI : public NetworkResourceAPI {
|
||||
|
||||
[[nodiscard]] std::optional<QString> getVersionsURL(VersionSearchArgs const& args) const override
|
||||
{
|
||||
QString url{QString("https://api.curseforge.com/v1/mods/%1/files?pageSize=10000&").arg(args.pack.addonId.toString())};
|
||||
auto addonId = args.pack.addonId.toString();
|
||||
QString url{ QString("https://api.curseforge.com/v1/mods/%1/files?pageSize=10000&").arg(addonId) };
|
||||
|
||||
QStringList get_parameters;
|
||||
if (args.mcVersions.has_value())
|
||||
get_parameters.append(QString("gameVersion=%1").arg(args.mcVersions.value().front().toString()));
|
||||
if (args.loaders.has_value())
|
||||
get_parameters.append(QString("modLoaderType=%1").arg(getMappedModLoader(args.loaders.value())));
|
||||
|
||||
if (args.loaders.has_value()) {
|
||||
int mappedModLoader = getMappedModLoader(args.loaders.value());
|
||||
|
||||
if (args.loaders.value() & Quilt) {
|
||||
auto overide = ModPlatform::getOverrideDeps();
|
||||
auto over = std::find_if(overide.cbegin(), overide.cend(), [addonId](auto dep) {
|
||||
return dep.provider == ModPlatform::ResourceProvider::FLAME && addonId == dep.quilt;
|
||||
});
|
||||
if (over != overide.cend()) {
|
||||
mappedModLoader = 5;
|
||||
}
|
||||
}
|
||||
|
||||
get_parameters.append(QString("modLoaderType=%1").arg(mappedModLoader));
|
||||
}
|
||||
|
||||
return url + get_parameters.join('&');
|
||||
};
|
||||
|
||||
[[nodiscard]] std::optional<QString> getDependencyURL(DependencySearchArgs const& args) const override
|
||||
{
|
||||
auto mappedModLoader = getMappedModLoader(args.loader);
|
||||
auto addonId = args.dependency.addonId.toString();
|
||||
if (args.loader & Quilt) {
|
||||
auto overide = ModPlatform::getOverrideDeps();
|
||||
auto over = std::find_if(overide.cbegin(), overide.cend(), [addonId](auto dep) {
|
||||
return dep.provider == ModPlatform::ResourceProvider::FLAME && addonId == dep.quilt;
|
||||
});
|
||||
if (over != overide.cend()) {
|
||||
mappedModLoader = 5;
|
||||
}
|
||||
}
|
||||
return QString("https://api.curseforge.com/v1/mods/%1/files?pageSize=10000&gameVersion=%2&modLoaderType=%3")
|
||||
.arg(addonId)
|
||||
.arg(args.mcVersion.toString())
|
||||
.arg(mappedModLoader);
|
||||
};
|
||||
};
|
||||
|
@ -31,7 +31,7 @@ ModPlatform::IndexedPack getProjectInfo(ModPlatform::IndexedVersion& ver_info)
|
||||
|
||||
auto get_project_job = new NetJob("Flame::GetProjectJob", APPLICATION->network());
|
||||
|
||||
auto response = new QByteArray();
|
||||
auto response = std::make_shared<QByteArray>();
|
||||
auto url = QString("https://api.curseforge.com/v1/mods/%1").arg(ver_info.addonId.toString());
|
||||
auto dl = Net::Download::makeByteArray(url, response);
|
||||
get_project_job->addNetAction(dl);
|
||||
@ -75,7 +75,7 @@ ModPlatform::IndexedVersion getFileInfo(int addonId, int fileId)
|
||||
|
||||
auto get_file_info_job = new NetJob("Flame::GetFileInfoJob", APPLICATION->network());
|
||||
|
||||
auto response = new QByteArray();
|
||||
auto response = std::make_shared<QByteArray>();
|
||||
auto url = QString("https://api.curseforge.com/v1/mods/%1/files/%2").arg(QString::number(addonId), QString::number(fileId));
|
||||
auto dl = Net::Download::makeByteArray(url, response);
|
||||
get_file_info_job->addNetAction(dl);
|
||||
|
@ -153,6 +153,9 @@ bool FlameCreationTask::updateInstance()
|
||||
|
||||
old_files.remove(file.key());
|
||||
files_iterator = files.erase(files_iterator);
|
||||
|
||||
if (files_iterator != files.begin())
|
||||
files_iterator--;
|
||||
}
|
||||
}
|
||||
|
||||
@ -179,7 +182,7 @@ bool FlameCreationTask::updateInstance()
|
||||
fileIds.append(QString::number(file.fileId));
|
||||
}
|
||||
|
||||
auto* raw_response = new QByteArray;
|
||||
auto raw_response = std::make_shared<QByteArray>();
|
||||
auto job = api.getFiles(fileIds, raw_response);
|
||||
|
||||
QEventLoop loop;
|
||||
@ -467,8 +470,9 @@ void FlameCreationTask::setupDownloadJob(QEventLoop& loop)
|
||||
switch (result.type) {
|
||||
case Flame::File::Type::Folder: {
|
||||
logWarning(tr("This 'Folder' may need extracting: %1").arg(relpath));
|
||||
// fall-through intentional, we treat these as plain old mods and dump them wherever.
|
||||
// fallthrough intentional, we treat these as plain old mods and dump them wherever.
|
||||
}
|
||||
/* fallthrough */
|
||||
case Flame::File::Type::SingleFile:
|
||||
case Flame::File::Type::Mod: {
|
||||
if (!result.url.isEmpty()) {
|
||||
@ -559,6 +563,8 @@ void FlameCreationTask::validateZIPResouces()
|
||||
if (FS::move(localPath, destPath)) {
|
||||
return destPath;
|
||||
}
|
||||
} else {
|
||||
qDebug() << "Target folder of" << fileName << "is correct at" << targetFolder;
|
||||
}
|
||||
return localPath;
|
||||
};
|
||||
@ -580,6 +586,9 @@ void FlameCreationTask::validateZIPResouces()
|
||||
QString worldPath;
|
||||
|
||||
switch (type) {
|
||||
case PackedResourceType::Mod :
|
||||
validatePath(fileName, targetFolder, "mods");
|
||||
break;
|
||||
case PackedResourceType::ResourcePack :
|
||||
validatePath(fileName, targetFolder, "resourcepacks");
|
||||
break;
|
||||
@ -589,9 +598,6 @@ void FlameCreationTask::validateZIPResouces()
|
||||
case PackedResourceType::DataPack :
|
||||
validatePath(fileName, targetFolder, "datapacks");
|
||||
break;
|
||||
case PackedResourceType::Mod :
|
||||
validatePath(fileName, targetFolder, "mods");
|
||||
break;
|
||||
case PackedResourceType::ShaderPack :
|
||||
// in theroy flame API can't do this but who knows, that *may* change ?
|
||||
// better to handle it if it *does* occure in the future
|
||||
|
@ -136,8 +136,61 @@ auto FlameMod::loadIndexedPackVersion(QJsonObject& obj, bool load_changelog) ->
|
||||
}
|
||||
}
|
||||
|
||||
auto dependencies = Json::ensureArray(obj, "dependencies");
|
||||
for (auto d : dependencies) {
|
||||
auto dep = Json::ensureObject(d);
|
||||
ModPlatform::Dependency dependency;
|
||||
dependency.addonId = Json::requireInteger(dep, "modId");
|
||||
switch (Json::requireInteger(dep, "relationType")) {
|
||||
case 1: // EmbeddedLibrary
|
||||
dependency.type = ModPlatform::DependencyType::EMBEDDED;
|
||||
break;
|
||||
case 2: // OptionalDependency
|
||||
dependency.type = ModPlatform::DependencyType::OPTIONAL;
|
||||
break;
|
||||
case 3: // RequiredDependency
|
||||
dependency.type = ModPlatform::DependencyType::REQUIRED;
|
||||
break;
|
||||
case 4: // Tool
|
||||
dependency.type = ModPlatform::DependencyType::TOOL;
|
||||
break;
|
||||
case 5: // Incompatible
|
||||
dependency.type = ModPlatform::DependencyType::INCOMPATIBLE;
|
||||
break;
|
||||
case 6: // Include
|
||||
dependency.type = ModPlatform::DependencyType::INCLUDE;
|
||||
break;
|
||||
default:
|
||||
dependency.type = ModPlatform::DependencyType::UNKNOWN;
|
||||
break;
|
||||
}
|
||||
file.dependencies.append(dependency);
|
||||
}
|
||||
|
||||
if (load_changelog)
|
||||
file.changelog = api.getModFileChangelog(file.addonId.toInt(), file.fileId.toInt());
|
||||
|
||||
return file;
|
||||
}
|
||||
|
||||
ModPlatform::IndexedVersion FlameMod::loadDependencyVersions(const ModPlatform::Dependency& m, QJsonArray& arr)
|
||||
{
|
||||
QVector<ModPlatform::IndexedVersion> versions;
|
||||
for (auto versionIter : arr) {
|
||||
auto obj = versionIter.toObject();
|
||||
|
||||
auto file = loadIndexedPackVersion(obj);
|
||||
if (!file.addonId.isValid())
|
||||
file.addonId = m.addonId;
|
||||
|
||||
if (file.fileId.isValid()) // Heuristic to check if the returned value is valid
|
||||
versions.append(file);
|
||||
}
|
||||
|
||||
auto orderSortPredicate = [](const ModPlatform::IndexedVersion& a, const ModPlatform::IndexedVersion& b) -> bool {
|
||||
// dates are in RFC 3339 format
|
||||
return a.date > b.date;
|
||||
};
|
||||
std::sort(versions.begin(), versions.end(), orderSortPredicate);
|
||||
return versions.front();
|
||||
};
|
||||
|
@ -6,8 +6,8 @@
|
||||
|
||||
#include "modplatform/ModIndex.h"
|
||||
|
||||
#include "BaseInstance.h"
|
||||
#include <QNetworkAccessManager>
|
||||
#include "BaseInstance.h"
|
||||
|
||||
namespace FlameMod {
|
||||
|
||||
@ -19,5 +19,5 @@ void loadIndexedPackVersions(ModPlatform::IndexedPack& pack,
|
||||
const shared_qobject_ptr<QNetworkAccessManager>& network,
|
||||
const BaseInstance* inst);
|
||||
auto loadIndexedPackVersion(QJsonObject& obj, bool load_changelog = false) -> ModPlatform::IndexedVersion;
|
||||
|
||||
auto loadDependencyVersions(const ModPlatform::Dependency& m, QJsonArray& arr) -> ModPlatform::IndexedVersion;
|
||||
} // namespace FlameMod
|
473
launcher/modplatform/flame/FlamePackExportTask.cpp
Normal file
473
launcher/modplatform/flame/FlamePackExportTask.cpp
Normal file
@ -0,0 +1,473 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
/*
|
||||
* Prism Launcher - Minecraft Launcher
|
||||
* Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me>
|
||||
* Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "FlamePackExportTask.h"
|
||||
#include <QJsonArray>
|
||||
#include <QJsonObject>
|
||||
|
||||
#include <QCryptographicHash>
|
||||
#include <QFileInfo>
|
||||
#include <QMessageBox>
|
||||
#include <QtConcurrentRun>
|
||||
#include <algorithm>
|
||||
#include <memory>
|
||||
#include "Json.h"
|
||||
#include "MMCZip.h"
|
||||
#include "minecraft/PackProfile.h"
|
||||
#include "minecraft/mod/ModFolderModel.h"
|
||||
#include "modplatform/ModIndex.h"
|
||||
#include "modplatform/flame/FlameModIndex.h"
|
||||
#include "modplatform/helpers/HashUtils.h"
|
||||
#include "tasks/Task.h"
|
||||
|
||||
const QString FlamePackExportTask::TEMPLATE = "<li><a href=\"{url}\">{name}{authors}</a></li>\n";
|
||||
const QStringList FlamePackExportTask::FILE_EXTENSIONS({ "jar", "zip" });
|
||||
|
||||
FlamePackExportTask::FlamePackExportTask(const QString& name,
|
||||
const QString& version,
|
||||
const QString& author,
|
||||
InstancePtr instance,
|
||||
const QString& output,
|
||||
MMCZip::FilterFunction filter)
|
||||
: name(name)
|
||||
, version(version)
|
||||
, author(author)
|
||||
, instance(instance)
|
||||
, mcInstance(dynamic_cast<MinecraftInstance*>(instance.get()))
|
||||
, gameRoot(instance->gameRoot())
|
||||
, output(output)
|
||||
, filter(filter)
|
||||
{}
|
||||
|
||||
void FlamePackExportTask::executeTask()
|
||||
{
|
||||
setStatus(tr("Searching for files..."));
|
||||
setProgress(0, 5);
|
||||
collectFiles();
|
||||
}
|
||||
|
||||
bool FlamePackExportTask::abort()
|
||||
{
|
||||
if (task != nullptr) {
|
||||
task->abort();
|
||||
task = nullptr;
|
||||
emitAborted();
|
||||
return true;
|
||||
}
|
||||
|
||||
if (buildZipFuture.isRunning()) {
|
||||
buildZipFuture.cancel();
|
||||
// NOTE: Here we don't do `emitAborted()` because it will be done when `buildZipFuture` actually cancels, which may not occur
|
||||
// immediately.
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
void FlamePackExportTask::collectFiles()
|
||||
{
|
||||
setAbortable(false);
|
||||
QCoreApplication::processEvents();
|
||||
|
||||
files.clear();
|
||||
if (!MMCZip::collectFileListRecursively(instance->gameRoot(), nullptr, &files, filter)) {
|
||||
emitFailed(tr("Could not search for files"));
|
||||
return;
|
||||
}
|
||||
|
||||
pendingHashes.clear();
|
||||
resolvedFiles.clear();
|
||||
|
||||
if (mcInstance != nullptr) {
|
||||
mcInstance->loaderModList()->update();
|
||||
connect(mcInstance->loaderModList().get(), &ModFolderModel::updateFinished, this, &FlamePackExportTask::collectHashes);
|
||||
} else
|
||||
collectHashes();
|
||||
}
|
||||
|
||||
void FlamePackExportTask::collectHashes()
|
||||
{
|
||||
setAbortable(true);
|
||||
setStatus(tr("Finding file hashes..."));
|
||||
setProgress(1, 5);
|
||||
auto allMods = mcInstance->loaderModList()->allMods();
|
||||
ConcurrentTask::Ptr hashingTask(new ConcurrentTask(this, "MakeHashesTask", 10));
|
||||
task.reset(hashingTask);
|
||||
for (const QFileInfo& file : files) {
|
||||
const QString relative = gameRoot.relativeFilePath(file.absoluteFilePath());
|
||||
// require sensible file types
|
||||
if (!std::any_of(FILE_EXTENSIONS.begin(), FILE_EXTENSIONS.end(), [&relative](const QString& extension) {
|
||||
return relative.endsWith('.' + extension) || relative.endsWith('.' + extension + ".disabled");
|
||||
}))
|
||||
continue;
|
||||
|
||||
if (relative.startsWith("resourcepacks/") &&
|
||||
(relative.endsWith(".zip") || relative.endsWith(".zip.disabled"))) { // is resourcepack
|
||||
auto hashTask = Hashing::createFlameHasher(file.absoluteFilePath());
|
||||
connect(hashTask.get(), &Hashing::Hasher::resultsReady, [this, relative, file](QString hash) {
|
||||
if (m_state == Task::State::Running) {
|
||||
pendingHashes.insert(hash, { relative, file.absoluteFilePath(), relative.endsWith(".zip") });
|
||||
}
|
||||
});
|
||||
connect(hashTask.get(), &Task::failed, this, &FlamePackExportTask::emitFailed);
|
||||
hashingTask->addTask(hashTask);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (auto modIter = std::find_if(allMods.begin(), allMods.end(), [&file](Mod* mod) { return mod->fileinfo() == file; });
|
||||
modIter != allMods.end()) {
|
||||
const Mod* mod = *modIter;
|
||||
if (!mod || mod->type() == ResourceType::FOLDER) {
|
||||
continue;
|
||||
}
|
||||
if (mod->metadata() && mod->metadata()->provider == ModPlatform::ResourceProvider::FLAME) {
|
||||
resolvedFiles.insert(mod->fileinfo().absoluteFilePath(),
|
||||
{ mod->metadata()->project_id.toInt(), mod->metadata()->file_id.toInt(), mod->enabled(), true,
|
||||
mod->metadata()->name, mod->metadata()->slug, mod->authors().join(", ") });
|
||||
continue;
|
||||
}
|
||||
|
||||
auto hashTask = Hashing::createFlameHasher(mod->fileinfo().absoluteFilePath());
|
||||
connect(hashTask.get(), &Hashing::Hasher::resultsReady, [this, mod](QString hash) {
|
||||
if (m_state == Task::State::Running) {
|
||||
pendingHashes.insert(hash, { mod->name(), mod->fileinfo().absoluteFilePath(), mod->enabled(), true });
|
||||
}
|
||||
});
|
||||
connect(hashTask.get(), &Task::failed, this, &FlamePackExportTask::emitFailed);
|
||||
hashingTask->addTask(hashTask);
|
||||
}
|
||||
}
|
||||
auto progressStep = std::make_shared<TaskStepProgress>();
|
||||
connect(hashingTask.get(), &Task::finished, this, [this, progressStep] {
|
||||
progressStep->state = TaskStepState::Succeeded;
|
||||
stepProgress(*progressStep);
|
||||
});
|
||||
|
||||
connect(hashingTask.get(), &Task::succeeded, this, &FlamePackExportTask::makeApiRequest);
|
||||
connect(hashingTask.get(), &Task::failed, this, [this, progressStep](QString reason) {
|
||||
progressStep->state = TaskStepState::Failed;
|
||||
stepProgress(*progressStep);
|
||||
emitFailed(reason);
|
||||
});
|
||||
connect(hashingTask.get(), &Task::stepProgress, this, &FlamePackExportTask::propogateStepProgress);
|
||||
|
||||
connect(hashingTask.get(), &Task::progress, this, [this, progressStep](qint64 current, qint64 total) {
|
||||
progressStep->update(current, total);
|
||||
stepProgress(*progressStep);
|
||||
});
|
||||
connect(hashingTask.get(), &Task::status, this, [this, progressStep](QString status) {
|
||||
progressStep->status = status;
|
||||
stepProgress(*progressStep);
|
||||
});
|
||||
hashingTask->start();
|
||||
}
|
||||
|
||||
void FlamePackExportTask::makeApiRequest()
|
||||
{
|
||||
if (pendingHashes.isEmpty()) {
|
||||
buildZip();
|
||||
return;
|
||||
}
|
||||
|
||||
setStatus(tr("Finding versions for hashes..."));
|
||||
setProgress(2, 5);
|
||||
auto response = std::make_shared<QByteArray>();
|
||||
|
||||
QList<uint> fingerprints;
|
||||
for (auto& murmur : pendingHashes.keys()) {
|
||||
fingerprints.push_back(murmur.toUInt());
|
||||
}
|
||||
|
||||
task.reset(api.matchFingerprints(fingerprints, response));
|
||||
|
||||
connect(task.get(), &Task::succeeded, this, [this, response] {
|
||||
QJsonParseError parseError{};
|
||||
QJsonDocument doc = QJsonDocument::fromJson(*response, &parseError);
|
||||
if (parseError.error != QJsonParseError::NoError) {
|
||||
qWarning() << "Error while parsing JSON response from CurseForge::CurrentVersions at " << parseError.offset
|
||||
<< " reason: " << parseError.errorString();
|
||||
qWarning() << *response;
|
||||
|
||||
failed(parseError.errorString());
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
auto docObj = Json::requireObject(doc);
|
||||
auto dataObj = Json::requireObject(docObj, "data");
|
||||
auto dataArr = Json::requireArray(dataObj, "exactMatches");
|
||||
|
||||
if (dataArr.isEmpty()) {
|
||||
qWarning() << "No matches found for fingerprint search!";
|
||||
|
||||
return;
|
||||
}
|
||||
for (auto match : dataArr) {
|
||||
auto matchObj = Json::ensureObject(match, {});
|
||||
auto fileObj = Json::ensureObject(matchObj, "file", {});
|
||||
|
||||
if (matchObj.isEmpty() || fileObj.isEmpty()) {
|
||||
qWarning() << "Fingerprint match is empty!";
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
auto fingerprint = QString::number(Json::ensureVariant(fileObj, "fileFingerprint").toUInt());
|
||||
auto mod = pendingHashes.find(fingerprint);
|
||||
if (mod == pendingHashes.end()) {
|
||||
qWarning() << "Invalid fingerprint from the API response.";
|
||||
continue;
|
||||
}
|
||||
|
||||
setStatus(tr("Parsing API response from CurseForge for '%1'...").arg(mod->name));
|
||||
if (Json::ensureBoolean(fileObj, "isAvailable", false, "isAvailable"))
|
||||
resolvedFiles.insert(mod->path, { Json::requireInteger(fileObj, "modId"), Json::requireInteger(fileObj, "id"),
|
||||
mod->enabled, mod->isMod });
|
||||
}
|
||||
|
||||
} catch (Json::JsonException& e) {
|
||||
qDebug() << e.cause();
|
||||
qDebug() << doc;
|
||||
}
|
||||
pendingHashes.clear();
|
||||
});
|
||||
connect(task.get(), &Task::finished, this, &FlamePackExportTask::getProjectsInfo);
|
||||
connect(task.get(), &NetJob::failed, this, &FlamePackExportTask::emitFailed);
|
||||
task->start();
|
||||
}
|
||||
|
||||
void FlamePackExportTask::getProjectsInfo()
|
||||
{
|
||||
setStatus(tr("Finding project info from CurseForge..."));
|
||||
setProgress(3, 5);
|
||||
QStringList addonIds;
|
||||
for (const auto& resolved : resolvedFiles) {
|
||||
if (resolved.slug.isEmpty()) {
|
||||
addonIds << QString::number(resolved.addonId);
|
||||
}
|
||||
}
|
||||
|
||||
auto response = std::make_shared<QByteArray>();
|
||||
Task::Ptr projTask;
|
||||
|
||||
if (addonIds.isEmpty()) {
|
||||
buildZip();
|
||||
return;
|
||||
} else if (addonIds.size() == 1) {
|
||||
projTask = api.getProject(*addonIds.begin(), response);
|
||||
} else {
|
||||
projTask = api.getProjects(addonIds, response);
|
||||
}
|
||||
|
||||
connect(projTask.get(), &Task::succeeded, this, [this, response, addonIds] {
|
||||
QJsonParseError parseError{};
|
||||
auto doc = QJsonDocument::fromJson(*response, &parseError);
|
||||
if (parseError.error != QJsonParseError::NoError) {
|
||||
qWarning() << "Error while parsing JSON response from CurseForge projects task at " << parseError.offset
|
||||
<< " reason: " << parseError.errorString();
|
||||
qWarning() << *response;
|
||||
failed(parseError.errorString());
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
QJsonArray entries;
|
||||
if (addonIds.size() == 1)
|
||||
entries = { Json::requireObject(Json::requireObject(doc), "data") };
|
||||
else
|
||||
entries = Json::requireArray(Json::requireObject(doc), "data");
|
||||
|
||||
for (auto entry : entries) {
|
||||
auto entryObj = Json::requireObject(entry);
|
||||
|
||||
try {
|
||||
setStatus(tr("Parsing API response from CurseForge for '%1'...").arg(Json::requireString(entryObj, "name")));
|
||||
|
||||
ModPlatform::IndexedPack pack;
|
||||
FlameMod::loadIndexedPack(pack, entryObj);
|
||||
for (auto key : resolvedFiles.keys()) {
|
||||
auto val = resolvedFiles.value(key);
|
||||
if (val.addonId == pack.addonId) {
|
||||
val.name = pack.name;
|
||||
val.slug = pack.slug;
|
||||
QStringList authors;
|
||||
for (auto author : pack.authors)
|
||||
authors << author.name;
|
||||
|
||||
val.authors = authors.join(", ");
|
||||
resolvedFiles[key] = val;
|
||||
}
|
||||
}
|
||||
|
||||
} catch (Json::JsonException& e) {
|
||||
qDebug() << e.cause();
|
||||
qDebug() << entries;
|
||||
}
|
||||
}
|
||||
} catch (Json::JsonException& e) {
|
||||
qDebug() << e.cause();
|
||||
qDebug() << doc;
|
||||
}
|
||||
buildZip();
|
||||
});
|
||||
task.reset(projTask);
|
||||
task->start();
|
||||
}
|
||||
|
||||
void FlamePackExportTask::buildZip()
|
||||
{
|
||||
setStatus(tr("Adding files..."));
|
||||
setProgress(4, 5);
|
||||
|
||||
buildZipFuture = QtConcurrent::run(QThreadPool::globalInstance(), [this]() {
|
||||
QuaZip zip(output);
|
||||
if (!zip.open(QuaZip::mdCreate)) {
|
||||
QFile::remove(output);
|
||||
return BuildZipResult(tr("Could not create file"));
|
||||
}
|
||||
|
||||
if (buildZipFuture.isCanceled())
|
||||
return BuildZipResult();
|
||||
|
||||
QuaZipFile indexFile(&zip);
|
||||
if (!indexFile.open(QIODevice::WriteOnly, QuaZipNewInfo("manifest.json"))) {
|
||||
QFile::remove(output);
|
||||
return BuildZipResult(tr("Could not create index"));
|
||||
}
|
||||
indexFile.write(generateIndex());
|
||||
|
||||
QuaZipFile modlist(&zip);
|
||||
if (!modlist.open(QIODevice::WriteOnly, QuaZipNewInfo("modlist.html"))) {
|
||||
QFile::remove(output);
|
||||
return BuildZipResult(tr("Could not create index"));
|
||||
}
|
||||
QString content = "";
|
||||
for (auto mod : resolvedFiles) {
|
||||
if (mod.isMod) {
|
||||
content += QString(TEMPLATE)
|
||||
.replace("{name}", mod.name.toHtmlEscaped())
|
||||
.replace("{url}", ModPlatform::getMetaURL(ModPlatform::ResourceProvider::FLAME, mod.addonId).toHtmlEscaped())
|
||||
.replace("{authors}", !mod.authors.isEmpty() ? QString(" (by %1)").arg(mod.authors).toHtmlEscaped() : "");
|
||||
}
|
||||
}
|
||||
content = "<ul>" + content + "</ul>";
|
||||
modlist.write(content.toUtf8());
|
||||
|
||||
auto progressStep = std::make_shared<TaskStepProgress>();
|
||||
|
||||
size_t progress = 0;
|
||||
for (const QFileInfo& file : files) {
|
||||
if (buildZipFuture.isCanceled()) {
|
||||
QFile::remove(output);
|
||||
progressStep->state = TaskStepState::Failed;
|
||||
stepProgress(*progressStep);
|
||||
return BuildZipResult();
|
||||
}
|
||||
progressStep->update(progress, files.length());
|
||||
stepProgress(*progressStep);
|
||||
|
||||
const QString relative = gameRoot.relativeFilePath(file.absoluteFilePath());
|
||||
if (!resolvedFiles.contains(file.absoluteFilePath()) &&
|
||||
!JlCompress::compressFile(&zip, file.absoluteFilePath(), "overrides/" + relative)) {
|
||||
QFile::remove(output);
|
||||
return BuildZipResult(tr("Could not read and compress %1").arg(relative));
|
||||
}
|
||||
progress++;
|
||||
}
|
||||
|
||||
zip.close();
|
||||
|
||||
if (zip.getZipError() != 0) {
|
||||
QFile::remove(output);
|
||||
progressStep->state = TaskStepState::Failed;
|
||||
stepProgress(*progressStep);
|
||||
return BuildZipResult(tr("A zip error occurred"));
|
||||
}
|
||||
progressStep->state = TaskStepState::Succeeded;
|
||||
stepProgress(*progressStep);
|
||||
return BuildZipResult();
|
||||
});
|
||||
connect(&buildZipWatcher, &QFutureWatcher<BuildZipResult>::finished, this, &FlamePackExportTask::finish);
|
||||
buildZipWatcher.setFuture(buildZipFuture);
|
||||
}
|
||||
|
||||
void FlamePackExportTask::finish()
|
||||
{
|
||||
if (buildZipFuture.isCanceled())
|
||||
emitAborted();
|
||||
else {
|
||||
const BuildZipResult result = buildZipFuture.result();
|
||||
if (result.has_value())
|
||||
emitFailed(result.value());
|
||||
else
|
||||
emitSucceeded();
|
||||
}
|
||||
}
|
||||
|
||||
QByteArray FlamePackExportTask::generateIndex()
|
||||
{
|
||||
QJsonObject obj;
|
||||
obj["manifestType"] = "minecraftModpack";
|
||||
obj["manifestVersion"] = 1;
|
||||
obj["name"] = name;
|
||||
obj["version"] = version;
|
||||
obj["author"] = author;
|
||||
obj["overrides"] = "overrides";
|
||||
if (mcInstance) {
|
||||
QJsonObject version;
|
||||
auto profile = mcInstance->getPackProfile();
|
||||
// collect all supported components
|
||||
const ComponentPtr minecraft = profile->getComponent("net.minecraft");
|
||||
const ComponentPtr quilt = profile->getComponent("org.quiltmc.quilt-loader");
|
||||
const ComponentPtr fabric = profile->getComponent("net.fabricmc.fabric-loader");
|
||||
const ComponentPtr forge = profile->getComponent("net.minecraftforge");
|
||||
|
||||
// convert all available components to mrpack dependencies
|
||||
if (minecraft != nullptr)
|
||||
version["version"] = minecraft->m_version;
|
||||
QString id;
|
||||
if (quilt != nullptr)
|
||||
id = "quilt-" + quilt->getVersion();
|
||||
else if (fabric != nullptr)
|
||||
id = "fabric-" + fabric->getVersion();
|
||||
else if (forge != nullptr)
|
||||
id = "forge-" + forge->getVersion();
|
||||
version["modLoaders"] = QJsonArray();
|
||||
if (!id.isEmpty()) {
|
||||
QJsonObject loader;
|
||||
loader["id"] = id;
|
||||
loader["primary"] = true;
|
||||
version["modLoaders"] = QJsonArray({ loader });
|
||||
}
|
||||
obj["minecraft"] = version;
|
||||
}
|
||||
|
||||
QJsonArray files;
|
||||
for (auto mod : resolvedFiles) {
|
||||
QJsonObject file;
|
||||
file["projectID"] = mod.addonId;
|
||||
file["fileID"] = mod.version;
|
||||
file["required"] = mod.enabled;
|
||||
files << file;
|
||||
}
|
||||
obj["files"] = files;
|
||||
|
||||
return QJsonDocument(obj).toJson(QJsonDocument::Compact);
|
||||
}
|
90
launcher/modplatform/flame/FlamePackExportTask.h
Normal file
90
launcher/modplatform/flame/FlamePackExportTask.h
Normal file
@ -0,0 +1,90 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
/*
|
||||
* Prism Launcher - Minecraft Launcher
|
||||
* Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me>
|
||||
* Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <QFuture>
|
||||
#include <QFutureWatcher>
|
||||
#include "BaseInstance.h"
|
||||
#include "MMCZip.h"
|
||||
#include "minecraft/MinecraftInstance.h"
|
||||
#include "modplatform/flame/FlameAPI.h"
|
||||
#include "tasks/Task.h"
|
||||
|
||||
class FlamePackExportTask : public Task {
|
||||
public:
|
||||
FlamePackExportTask(const QString& name,
|
||||
const QString& version,
|
||||
const QString& author,
|
||||
InstancePtr instance,
|
||||
const QString& output,
|
||||
MMCZip::FilterFunction filter);
|
||||
|
||||
protected:
|
||||
void executeTask() override;
|
||||
bool abort() override;
|
||||
|
||||
private:
|
||||
static const QString TEMPLATE;
|
||||
static const QStringList FILE_EXTENSIONS;
|
||||
|
||||
// inputs
|
||||
const QString name, version, author;
|
||||
const InstancePtr instance;
|
||||
MinecraftInstance* mcInstance;
|
||||
const QDir gameRoot;
|
||||
const QString output;
|
||||
const MMCZip::FilterFunction filter;
|
||||
|
||||
typedef std::optional<QString> BuildZipResult;
|
||||
struct ResolvedFile {
|
||||
int addonId;
|
||||
int version;
|
||||
bool enabled;
|
||||
bool isMod;
|
||||
|
||||
QString name;
|
||||
QString slug;
|
||||
QString authors;
|
||||
};
|
||||
struct HashInfo {
|
||||
QString name;
|
||||
QString path;
|
||||
bool enabled;
|
||||
bool isMod;
|
||||
};
|
||||
|
||||
FlameAPI api;
|
||||
|
||||
QFileInfoList files;
|
||||
QMap<QString, HashInfo> pendingHashes{};
|
||||
QMap<QString, ResolvedFile> resolvedFiles{};
|
||||
Task::Ptr task;
|
||||
QFuture<BuildZipResult> buildZipFuture;
|
||||
QFutureWatcher<BuildZipResult> buildZipWatcher;
|
||||
|
||||
void collectFiles();
|
||||
void collectHashes();
|
||||
void makeApiRequest();
|
||||
void getProjectsInfo();
|
||||
void buildZip();
|
||||
void finish();
|
||||
|
||||
QByteArray generateIndex();
|
||||
};
|
@ -4,6 +4,7 @@
|
||||
#include <QMetaType>
|
||||
#include <QString>
|
||||
#include <QVector>
|
||||
#include "modplatform/ModIndex.h"
|
||||
|
||||
namespace Flame {
|
||||
|
||||
@ -27,8 +28,7 @@ struct ModpackExtra {
|
||||
QString sourceUrl;
|
||||
};
|
||||
|
||||
struct IndexedPack
|
||||
{
|
||||
struct IndexedPack {
|
||||
int addonId;
|
||||
QString name;
|
||||
QString description;
|
||||
@ -46,6 +46,6 @@ struct IndexedPack
|
||||
void loadIndexedPack(IndexedPack& m, QJsonObject& obj);
|
||||
void loadIndexedInfo(IndexedPack&, QJsonObject&);
|
||||
void loadIndexedPackVersions(IndexedPack& m, QJsonArray& arr);
|
||||
}
|
||||
} // namespace Flame
|
||||
|
||||
Q_DECLARE_METATYPE(Flame::IndexedPack)
|
||||
|
@ -76,13 +76,8 @@ bool Flame::File::parseFromObject(const QJsonObject& obj, bool throw_on_blocked
|
||||
// It is also optional
|
||||
type = File::Type::SingleFile;
|
||||
|
||||
if (fileName.endsWith(".zip")) {
|
||||
// this is probably a resource pack
|
||||
targetFolder = "resourcepacks";
|
||||
} else {
|
||||
// this is probably a mod, dunno what else could modpacks download
|
||||
targetFolder = "mods";
|
||||
}
|
||||
|
||||
// get the hash
|
||||
hash = QString();
|
||||
auto hashes = Json::ensureArray(obj, "hashes");
|
||||
|
200
launcher/modplatform/helpers/ExportToModList.cpp
Normal file
200
launcher/modplatform/helpers/ExportToModList.cpp
Normal file
@ -0,0 +1,200 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
/*
|
||||
* Prism Launcher - Minecraft Launcher
|
||||
* Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#include "ExportToModList.h"
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
|
||||
namespace ExportToModList {
|
||||
QString toHTML(QList<Mod*> mods, OptionalData extraData)
|
||||
{
|
||||
QStringList lines;
|
||||
for (auto mod : mods) {
|
||||
auto meta = mod->metadata();
|
||||
auto modName = mod->name().toHtmlEscaped();
|
||||
if (extraData & Url) {
|
||||
auto url = mod->metaurl().toHtmlEscaped();
|
||||
if (!url.isEmpty())
|
||||
modName = QString("<a href=\"%1\">%2</a>").arg(url, modName);
|
||||
}
|
||||
auto line = modName;
|
||||
if (extraData & Version) {
|
||||
auto ver = mod->version();
|
||||
if (ver.isEmpty() && meta != nullptr)
|
||||
ver = meta->version().toString();
|
||||
if (!ver.isEmpty())
|
||||
line += QString(" [%1]").arg(ver.toHtmlEscaped());
|
||||
}
|
||||
if (extraData & Authors && !mod->authors().isEmpty())
|
||||
line += " by " + mod->authors().join(", ").toHtmlEscaped();
|
||||
lines.append(QString("<li>%1</li>").arg(line));
|
||||
}
|
||||
return QString("<html><body><ul>\n\t%1\n</ul></body></html>").arg(lines.join("\n\t"));
|
||||
}
|
||||
|
||||
QString toMarkdown(QList<Mod*> mods, OptionalData extraData)
|
||||
{
|
||||
QStringList lines;
|
||||
for (auto mod : mods) {
|
||||
auto meta = mod->metadata();
|
||||
auto modName = mod->name();
|
||||
if (extraData & Url) {
|
||||
auto url = mod->metaurl();
|
||||
if (!url.isEmpty())
|
||||
modName = QString("[%1](%2)").arg(modName, url);
|
||||
}
|
||||
auto line = modName;
|
||||
if (extraData & Version) {
|
||||
auto ver = mod->version();
|
||||
if (ver.isEmpty() && meta != nullptr)
|
||||
ver = meta->version().toString();
|
||||
if (!ver.isEmpty())
|
||||
line += QString(" [%1]").arg(ver);
|
||||
}
|
||||
if (extraData & Authors && !mod->authors().isEmpty())
|
||||
line += " by " + mod->authors().join(", ");
|
||||
lines << "- " + line;
|
||||
}
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
QString toPlainTXT(QList<Mod*> mods, OptionalData extraData)
|
||||
{
|
||||
QStringList lines;
|
||||
for (auto mod : mods) {
|
||||
auto meta = mod->metadata();
|
||||
auto modName = mod->name();
|
||||
|
||||
auto line = modName;
|
||||
if (extraData & Url) {
|
||||
auto url = mod->metaurl();
|
||||
if (!url.isEmpty())
|
||||
line += QString(" (%1)").arg(url);
|
||||
}
|
||||
if (extraData & Version) {
|
||||
auto ver = mod->version();
|
||||
if (ver.isEmpty() && meta != nullptr)
|
||||
ver = meta->version().toString();
|
||||
if (!ver.isEmpty())
|
||||
line += QString(" [%1]").arg(ver);
|
||||
}
|
||||
if (extraData & Authors && !mod->authors().isEmpty())
|
||||
line += " by " + mod->authors().join(", ");
|
||||
lines << line;
|
||||
}
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
QString toJSON(QList<Mod*> mods, OptionalData extraData)
|
||||
{
|
||||
QJsonArray lines;
|
||||
for (auto mod : mods) {
|
||||
auto meta = mod->metadata();
|
||||
auto modName = mod->name();
|
||||
QJsonObject line;
|
||||
line["name"] = modName;
|
||||
if (extraData & Url) {
|
||||
auto url = mod->metaurl();
|
||||
if (!url.isEmpty())
|
||||
line["url"] = url;
|
||||
}
|
||||
if (extraData & Version) {
|
||||
auto ver = mod->version();
|
||||
if (ver.isEmpty() && meta != nullptr)
|
||||
ver = meta->version().toString();
|
||||
if (!ver.isEmpty())
|
||||
line["version"] = ver;
|
||||
}
|
||||
if (extraData & Authors && !mod->authors().isEmpty())
|
||||
line["authors"] = QJsonArray::fromStringList(mod->authors());
|
||||
lines << line;
|
||||
}
|
||||
QJsonDocument doc;
|
||||
doc.setArray(lines);
|
||||
return doc.toJson();
|
||||
}
|
||||
|
||||
QString toCSV(QList<Mod*> mods, OptionalData extraData)
|
||||
{
|
||||
QStringList lines;
|
||||
for (auto mod : mods) {
|
||||
QStringList data;
|
||||
auto meta = mod->metadata();
|
||||
auto modName = mod->name();
|
||||
|
||||
data << modName;
|
||||
if (extraData & Url)
|
||||
data << mod->metaurl();
|
||||
if (extraData & Version) {
|
||||
auto ver = mod->version();
|
||||
if (ver.isEmpty() && meta != nullptr)
|
||||
ver = meta->version().toString();
|
||||
data << ver;
|
||||
}
|
||||
if (extraData & Authors) {
|
||||
QString authors;
|
||||
if (mod->authors().length() == 1)
|
||||
authors = mod->authors().back();
|
||||
else if (mod->authors().length() > 1)
|
||||
authors = QString("\"%1\"").arg(mod->authors().join(","));
|
||||
data << authors;
|
||||
}
|
||||
lines << data.join(",");
|
||||
}
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
QString exportToModList(QList<Mod*> mods, Formats format, OptionalData extraData)
|
||||
{
|
||||
switch (format) {
|
||||
case HTML:
|
||||
return toHTML(mods, extraData);
|
||||
case MARKDOWN:
|
||||
return toMarkdown(mods, extraData);
|
||||
case PLAINTXT:
|
||||
return toPlainTXT(mods, extraData);
|
||||
case JSON:
|
||||
return toJSON(mods, extraData);
|
||||
case CSV:
|
||||
return toCSV(mods, extraData);
|
||||
default: {
|
||||
return QString("unknown format:%1").arg(format);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
QString exportToModList(QList<Mod*> mods, QString lineTemplate)
|
||||
{
|
||||
QStringList lines;
|
||||
for (auto mod : mods) {
|
||||
auto meta = mod->metadata();
|
||||
auto modName = mod->name();
|
||||
auto url = mod->metaurl();
|
||||
auto ver = mod->version();
|
||||
if (ver.isEmpty() && meta != nullptr)
|
||||
ver = meta->version().toString();
|
||||
auto authors = mod->authors().join(", ");
|
||||
lines << QString(lineTemplate)
|
||||
.replace("{name}", modName)
|
||||
.replace("{url}", url)
|
||||
.replace("{version}", ver)
|
||||
.replace("{authors}", authors);
|
||||
}
|
||||
return lines.join("\n");
|
||||
}
|
||||
} // namespace ExportToModList
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user