Initial release: racked Minecraft launcher (PrismLauncher fork) v0.1.0

This commit is contained in:
s8n-ru 2026-04-30 10:59:04 +01:00
commit 7f59a8e82a
1643 changed files with 177722 additions and 0 deletions

19
.clang-format Normal file
View file

@ -0,0 +1,19 @@
---
BasedOnStyle: Chromium
IndentWidth: 4
AllowShortIfStatementsOnASingleLine: false
ColumnLimit: 140
---
Language: Cpp
AccessModifierOffset: -1
AlignConsecutiveMacros: None
AlignConsecutiveAssignments: None
BraceWrapping:
AfterFunction: true
SplitEmptyFunction: false
SplitEmptyRecord: false
SplitEmptyNamespace: false
BreakBeforeBraces: Custom
BreakConstructorInitializers: BeforeComma
Cpp11BracedListStyle: false
QualifierAlignment: Left

32
.clang-tidy Normal file
View file

@ -0,0 +1,32 @@
FormatStyle: file
Checks:
"bugprone-*,clang-analyzer-*,cppcoreguidelines-*,hicpp-*,misc-*,modernize-*,performance-*,portability-*,readability-*,
-*-magic-numbers,
-*-non-private-member-variables-in-classes,
-*-special-member-functions,
-bugprone-easily-swappable-parameters,
-cppcoreguidelines-owning-memory,
-cppcoreguidelines-pro-type-static-cast-downcast,
-modernize-use-nodiscard,
-modernize-use-trailing-return-type,
-portability-avoid-pragma-once,
-readability-avoid-unconditional-preprocessor-if,
-readability-function-cognitive-complexity,
-readability-identifier-length,
-readability-redundant-access-specifiers"
CheckOptions:
misc-include-cleaner.MissingIncludes: false
readability-identifier-naming.DefaultCase: "camelBack"
readability-identifier-naming.NamespaceCase: "CamelCase"
readability-identifier-naming.ClassCase: "CamelCase"
readability-identifier-naming.ClassConstantCase: "CamelCase"
readability-identifier-naming.EnumCase: "CamelCase"
readability-identifier-naming.EnumConstantCase: "CamelCase"
readability-identifier-naming.MacroDefinitionCase: "UPPER_CASE"
readability-identifier-naming.ClassMemberPrefix: "m_"
readability-identifier-naming.StaticConstantPrefix: "s_"
readability-identifier-naming.StaticVariablePrefix: "s_"
readability-identifier-naming.GlobalConstantPrefix: "g_"
readability-implicit-bool-conversion.AllowPointerConditions: true

22
.editorconfig Normal file
View file

@ -0,0 +1,22 @@
# EditorConfig specs and documentation: https://EditorConfig.org
# top-most EditorConfig file
root = true
[*]
indent_style = space
indent_size = 4
end_of_line = lf
charset = utf-8
insert_final_newline = true
trim_trailing_whitespace = true
[*.{yml,nix}]
indent_size = 2
# 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
[CMakeLists.txt]
ij_continuation_indent_size = 4

2
.envrc Normal file
View file

@ -0,0 +1,2 @@
use nix
watch_file nix/*.nix

13
.git-blame-ignore-revs Normal file
View file

@ -0,0 +1,13 @@
# .git-blame-ignore-revs
# tabs -> spaces
bbb3b3e6f6e3c0f95873f22e6d0a4aaf350f49d9
# (nix) alejandra -> nixfmt
4c81d8c53d09196426568c4a31a4e752ed05397a
# reformat codebase
1d468ac35ad88d8c77cc83f25e3704d9bd7df01b
# format a part of codebase
5c8481a118c8fefbfe901001d7828eaf6866eac4

2
.gitattributes vendored Normal file
View file

@ -0,0 +1,2 @@
*.pem -crlf
**/testdata/** -text -diff

145
.github/workflows/build.yml vendored Normal file
View file

@ -0,0 +1,145 @@
name: Build
on:
push:
tags:
- 'v*.*.*'
workflow_dispatch:
jobs:
build:
strategy:
fail-fast: false
matrix:
include:
- os: ubuntu-latest
name: linux-x64
archive: tar.gz
- os: windows-latest
name: windows-x64
archive: zip
- os: macos-14
name: macos-arm64
archive: zip
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- name: Set up Java 21
uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '21'
- name: Set up Qt 6
uses: jurplel/install-qt-action@v4
with:
version: '6.7.2'
modules: 'qt5compat qtimageformats qtnetworkauth'
cache: true
# ---------- Linux ----------
- name: Linux deps
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y \
extra-cmake-modules \
libarchive-dev \
libqrencode-dev \
libtomlplusplus-dev \
libvulkan-dev \
gamemode-dev \
zlib1g-dev \
libgl1-mesa-dev \
ninja-build \
scdoc
- name: Build cmark from source (Linux)
if: runner.os == 'Linux'
run: |
git clone --depth=1 --branch 0.31.0 https://github.com/commonmark/cmark.git /tmp/cmark
cmake -B /tmp/cmark/build -S /tmp/cmark -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr/local -DCMARK_TESTS=OFF
sudo cmake --build /tmp/cmark/build -j --target install
# ---------- macOS ----------
- name: macOS deps
if: runner.os == 'macOS'
run: |
brew install \
extra-cmake-modules \
cmark \
libarchive \
qrencode \
tomlplusplus \
ninja
echo "PKG_CONFIG_PATH=$(brew --prefix libarchive)/lib/pkgconfig" >> $GITHUB_ENV
echo "LibArchive_ROOT=$(brew --prefix libarchive)" >> $GITHUB_ENV
# ---------- Windows ----------
- name: Windows — set up vcpkg
if: runner.os == 'Windows'
uses: lukka/run-vcpkg@v11
with:
vcpkgGitCommitId: '2d6a6cf3ac9a7cc93942c3d289a2f9c661a6f4a7'
# ---------- Configure / Build ----------
- name: Configure (Linux/macOS)
if: runner.os != 'Windows'
run: cmake -B build -S . -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=install -DLauncher_BUILD_PLATFORM=racked-portable -DBUILD_TESTING=OFF
- name: Configure (Windows)
if: runner.os == 'Windows'
run: cmake -B build -S . -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=install -DLauncher_BUILD_PLATFORM=racked-portable -DBUILD_TESTING=OFF -DCMAKE_TOOLCHAIN_FILE="${{ github.workspace }}/vcpkg/scripts/buildsystems/vcpkg.cmake"
- name: Build
run: cmake --build build -j --config Release
- name: Install
run: cmake --install build --config Release
# ---------- Package ----------
- name: Package (Linux)
if: runner.os == 'Linux'
run: |
mv install minecraft-launcher
tar czf minecraft-launcher-${{ matrix.name }}.tar.gz minecraft-launcher
- name: Package (Windows)
if: runner.os == 'Windows'
shell: pwsh
run: |
Move-Item install minecraft-launcher
Compress-Archive -Path minecraft-launcher -DestinationPath minecraft-launcher-${{ matrix.name }}.zip
- name: Package (macOS)
if: runner.os == 'macOS'
run: |
mv install minecraft-launcher
zip -r minecraft-launcher-${{ matrix.name }}.zip minecraft-launcher
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: minecraft-launcher-${{ matrix.name }}
path: minecraft-launcher-${{ matrix.name }}.${{ matrix.archive }}
release:
needs: build
runs-on: ubuntu-latest
if: startsWith(github.ref, 'refs/tags/')
permissions:
contents: write
steps:
- uses: actions/download-artifact@v4
with:
path: artifacts
merge-multiple: true
- name: Create Release
uses: softprops/action-gh-release@v2
with:
files: artifacts/*
generate_release_notes: true

80
.gitignore vendored Normal file
View file

@ -0,0 +1,80 @@
Thumbs.db
*.kdev4
.user
.directory
resources/CMakeFiles
*~
*.swp
html/
# Project Files
*.pro.user
CMakeLists.txt.user
CMakeLists.txt.user.*
CMakeSettings.json
/CMakeFiles
CMakeCache.txt
CMakeUserPresets.json
/.project
/.settings
/.idea
/.vscode
/.vs
cmake-build-*/
Debug
compile_commands.json
# Build dirs
build
/build-*
# Install dirs
install
/install-*
# Ctags File
tags
# YouCompleteMe config stuff.
.ycm_extra_conf.*
#OSX Stuff
.DS_Store
branding/
secrets/
run/
.cache/
# Nix/NixOS
.direnv/
## Used when manually invoking stdenv phases
outputs/
## Regular artifacts
result
result-*
repl-result-*
# Flatpak
.flatpak-builder
flatbuild
# Snap
*.snap
# Release archives (local builds)
release/
# Windows build artifacts
*.vcxproj*
*.sln
*.sdf
*.opensdf
x64/
Win32/
# macOS artifacts
*.dmg
*.app/

3
.gitmodules vendored Normal file
View file

@ -0,0 +1,3 @@
[submodule "libraries/libnbtplusplus"]
path = libraries/libnbtplusplus
url = https://github.com/PrismLauncher/libnbtplusplus.git

12
.markdownlint.yaml Normal file
View file

@ -0,0 +1,12 @@
# MD013/line-length - Line length
MD013: false
# MD024/no-duplicate-heading/no-duplicate-header - Multiple headings with the same content
MD024:
siblings-only: true
# MD033/no-inline-html Inline HTML
MD033: false
# MD041/first-line-heading/first-line-h1 First line in a file should be a top-level heading
MD041: false

1
.markdownlintignore Normal file
View file

@ -0,0 +1 @@
libraries/nbtplusplus

141
BUILD_AND_DEPLOY_V1.sh Executable file
View file

@ -0,0 +1,141 @@
#!/bin/bash
# Build and deploy portable Linux launcher as linux-racked-launcher-build-v1
set -e
echo "=============================================="
echo "Building Racked.ru PrismLauncher for Linux"
echo "=============================================="
echo ""
# Navigate to build directory
cd /home/admin/ai-lab/_project_minecraft/prismlauncher-racked
# Check if cmake is installed
if ! command -v cmake &> /dev/null; then
echo "❌ CMake is not installed!"
echo ""
echo "Please run this first:"
echo " bash INSTALL_DEPS.sh"
echo ""
echo "Or install manually:"
echo " sudo dnf install cmake gcc-c++ make qt6-qtbase-devel"
echo ""
exit 1
fi
# Check if Qt6 is installed
if ! command -v qmake6 &> /dev/null; then
echo "❌ Qt6 is not installed!"
echo ""
echo "Please run this first:"
echo " bash INSTALL_DEPS.sh"
echo ""
exit 1
fi
echo "✅ Dependencies found"
echo ""
# Clean old builds
echo "Cleaning old builds..."
rm -rf build-linux-portable install-linux-portable
# Build
echo "Building launcher..."
bash scripts/build-linux-portable.sh
echo ""
echo "=============================================="
echo "Creating Portable Installation"
echo "=============================================="
echo ""
# Create the v1 folder
V1_DIR="../linux-racked-launcher-build-v1"
rm -rf "$V1_DIR"
mkdir -p "$V1_DIR"
# Copy built files
echo "Copying files to $V1_DIR..."
cp -r release/Racked.ru-PrismLauncher-Linux-Portable/* "$V1_DIR"/
# Create a simple launcher script
cat > "$V1_DIR/start.sh" <<'EOF'
#!/bin/bash
# Racked.ru PrismLauncher - Portable Linux Launcher
# Version 1
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
echo "Starting Racked.ru PrismLauncher..."
echo ""
# Set environment
export LD_LIBRARY_PATH="$SCRIPT_DIR/lib64:$SCRIPT_DIR/lib:$LD_LIBRARY_PATH"
export QT_QPA_PLATFORM_PLUGIN_PATH="$SCRIPT_DIR/plugins"
export QT_PLUGIN_PATH="$SCRIPT_DIR/plugins"
# Run launcher
exec "$SCRIPT_DIR/bin/prismlauncher" "$@"
EOF
chmod +x "$V1_DIR/start.sh"
# Create a README
cat > "$V1_DIR/README.txt" <<'EOF'
==============================================
Racked.ru PrismLauncher - Linux Portable
Version 1
==============================================
This is a portable Minecraft launcher with custom
racked.ru theme (black/red minimalist design).
HOW TO RUN:
-----------
1. Open terminal in this folder
2. Run: bash start.sh
OR
Run: chmod +x start.sh && ./start.sh
FEATURES:
---------
- Portable: All data stored in this folder
- Custom racked.ru theme (black/red)
- USB-friendly: Works from any location
- No installation required
CONFIGURATION:
--------------
Edit prismlauncher.cfg to change settings
YOUR DATA:
----------
- Minecraft instances: instances/
- Settings: prismlauncher.cfg
- Cache: cache/
All data travels with this folder!
SUPPORT:
--------
Website: https://racked.ru/
==============================================
EOF
echo ""
echo "=============================================="
echo "✅ Build Complete!"
echo "=============================================="
echo ""
echo "Your launcher is ready at:"
echo " /home/admin/ai-lab/_project_minecraft/linux-racked-launcher-build-v1/"
echo ""
echo "To run it:"
echo " cd /home/admin/ai-lab/_project_minecraft/linux-racked-launcher-build-v1/"
echo " bash start.sh"
echo ""
echo "=============================================="
exit 0

159
BUILD_GUIDE.md Normal file
View file

@ -0,0 +1,159 @@
# Racked.ru PrismLauncher - Build Guide
Minimal, custom-themed PrismLauncher build with racked.ru branding and portable mode support.
## Features
- **Minimal theme**: Black and red racked.ru theme
- **Portable mode**: USB-friendly, no installation required
- **Stripped resources**: Removed unused themes to reduce size
- **Cross-platform**: Windows, macOS, and Linux support
- **Custom background**: racked_ru catpack background
## Prerequisites
### Windows
- Visual Studio 2022 (Community Edition or higher)
- Qt 6.5.3 or later (MSVC 2019 64-bit)
- CMake 3.25 or later
- Git
Install Qt using the online installer:
```
1. Download Qt Online Installer from qt.io
2. Install Qt 6.5.3 -> MSVC 2019 64-bit
3. Make sure to include Qt Network Authentication and Qt SVG modules
```
### Linux (Ubuntu/Debian)
```bash
sudo apt update
sudo apt install build-essential cmake qt6-base-dev qt6-tools-dev \
qt6-image-formats-plugins qt6-networkauth-dev zlib1g-dev libgl1-mesa-dev
```
### Linux (Fedora)
```bash
sudo dnf install gcc-c++ cmake qt6-qtbase-devel qt6-qttools-devel \
qt6-qtimageformats qt6-qtnetworkauth-devel zlib-devel mesa-libGL-devel
```
### macOS
```bash
# Install Xcode Command Line Tools
xcode-select --install
# Install Homebrew
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
# Install dependencies
brew install cmake qt6
```
## Building
### Quick Build (Current Platform)
```bash
# Clone the repository
git clone <your-repo-url>
cd prismlauncher-racked
# Run the build script
bash scripts/build-all-platforms.sh
```
### Platform-Specific Builds
#### Windows (Run in Developer Command Prompt or PowerShell)
```batch
scripts\build-windows-portable.bat
```
#### Linux/macOS
```bash
chmod +x scripts/build-linux-portable.sh # Linux only
chmod +x scripts/build-macos-portable.sh # macOS only
bash scripts/build-linux-portable.sh # Linux
bash scripts/build-macos-portable.sh # macOS
```
## Output
Builds are placed in the `release/` directory:
- `release/Racked.ru-PrismLauncher-Windows-Portable/` - Windows portable
- `release/Racked.ru-PrismLauncher-Linux-Portable/` - Linux portable
- `release/Racked.ru-PrismLauncher-macOS-Portable/` - macOS portable
### Creating Distribution Archives
**Windows (PowerShell):**
```powershell
cd release\Racked.ru-PrismLauncher-Windows-Portable
Compress-Archive -Path * -DestinationPath ..\racked-prismlauncher-windows-portable.zip
```
**Linux:**
```bash
cd release/Racked.ru-PrismLauncher-Linux-Portable
tar czf ../racked-prismlauncher-linux-portable.tar.gz .
```
**macOS:**
```bash
cd release/Racked.ru-PrismLauncher-macOS-Portable
tar czf ../racked-prismlauncher-macos-portable.tar.gz PrismLauncher.app run.sh
```
## Portable Mode
The launcher includes `portable.txt` which enables portable mode. This makes the launcher store all data (instances, settings, etc.) in the same directory as the executable, making it perfect for USB drives.
To disable portable mode, simply delete `portable.txt` from the installation directory.
## Custom Theme
The launcher uses a custom `racked.ru` theme with:
- Black background (#000000)
- White text (#ffffff)
- Red accents (#ff0000, #CD001F)
- Minimal UI elements
- Custom catpack background (racked_ru.png)
## Stripped Components
To minimize size, the following have been removed:
- All default icon themes (except flat_white)
- All default application themes (except Fusion/system defaults)
- Unnecessary Qt plugins
## Troubleshooting
### Windows: "Qt6Core.dll not found"
Ensure Qt6 bin directory is in your PATH or copy all required Qt DLLs to the output directory (the build script does this automatically).
### Linux: "Qt6 not found"
Install Qt6 development packages via your package manager. Ensure `qmake6` or `qt6-cmake` is in your PATH.
### macOS: "App cannot be opened because the developer cannot be verified"
Right-click the app, select "Open", then click "Open" again in the security dialog. Or codesign the app:
```bash
codesign --deep --force --sign "-" release/Racked.ru-PrismLauncher-macOS-Portable/PrismLauncher.app
```
### Build fails with "CMake error"
Ensure CMake version is 3.25 or higher:
```bash
cmake --version
```
## License
This project is based on PrismLauncher and follows the same licensing terms (GPL-3.0-only).
## Credits
- **Original Project**: PrismLauncher
- **Upstream fork**: Diegiwg
- **Custom Theme**: racked.ru
- **Build System**: Custom portable build scripts

112
CHANGELOG.md Normal file
View file

@ -0,0 +1,112 @@
# Changelog
All notable changes to the racked.ru launcher (PrismLauncher fork).
## [Unreleased] — 2026-04-30
### Branding
- Window title: `racked.ru launcher` (was `Prism Launcher 11.0.0-develop`)
- `Launcher_DisplayName``racked.ru launcher` (`program_info/CMakeLists.txt`)
- `setApplicationDisplayName()` no longer appends version string
- Per-file copyright headers + `Launcher_Copyright` cmake var preserved (GPL-3.0 §5c compliance)
### Removed "Cracked" branding leak
Spell-check had mangled `racked.ru``cracked` across docs/configs. Cleaned all 7 files:
- `CMakeLists.txt`, `program_info/CMakeLists.txt`, `program_info/org.prismlauncher.PrismLauncher.metainfo.xml.in`
- `README_RELEASE.md`, `PROJECT_SUMMARY.md`, `BUILD_GUIDE.md`, `scripts/create-release.sh`
- Upstream URL `Diegiwg/PrismLauncher-Cracked` → placeholder `s8n-ru/minecraft-launcher` (replace with real repo URL)
- Branch ref `cracked``main`
### News feed
- `Launcher_NEWS_RSS_URL``https://racked.ru/feed.xml` (was `prismlauncher.org/feed/feed.xml`)
- `Launcher_NEWS_OPEN_URL``https://racked.ru/news`
- News toolbar **hidden by default** (`Application.cpp` post-restoreState `findChild<QToolBar*>("newsToolBar")->hide()`). Re-enable via View menu
### Default settings (ported runtime cfg → source defaults)
| Setting | Old | New |
|---|---|---|
| `MinMemAlloc` | 512 | 384 |
| `MaxMemAlloc` | `SysInfo::defaultMaxJvmMem()` | 4096 |
| `MenuBarInsteadOfToolBar` | false | true |
### Window geometry baked defaults
First-run windows open at user-tested sizes:
- Main: 346×265
- New Instance dialog: 1112×507
- News dialog: 799×499
- Console: 782×705
- Paged settings: 871×649
(`Application.cpp` registerSetting blobs replace empty-string defaults.)
### Status bar redesign
**Per-instance (left) — `MinecraftInstance::getStatusbarDescription()`:**
- Dropped `Minecraft <version>` prefix (already shown on instance card)
- Dropped redundant per-instance "total played for X" (global widget covers it)
- Absolute timestamp `28/04/2026 14:15` → relative `2d ago`
- Comma separator → em dash `—`
- Duration: `3h 24min` → minutes only `204 min` (server parity)
**Global (center):**
- `Total playtime: 16h 26min``Total: 986 min` (minutes only)
**Result:**
```
Before: Minecraft 1.21.10, last played on 28/04/2026 14:15 for 3h 24min, total played for 16h 26min Total playtime: 16h 26min
After: last played 2d ago — 204 min Total: 986 min
```
**New helper:** `Time::relativePast(QDateTime)` in `MMCTime.{h,cpp}` — buckets `just now`, `Nm/h/d/w/mo/y ago`.
`Time::prettifyDuration` "min"/"m" suffix shortened to `m` (only call site is status bar).
### Help menu cleanup
Reddit + Discord + Matrix entries → single **Website** entry pointing at `https://racked.ru`.
- `MainWindow.ui`, `MainWindow.h`, `MainWindow.cpp` — actions/slots/handlers consolidated
### First-launch UX
If `accounts->count() == 0` on startup, show offline-username dialog (skip-able). Hooked at end of `MainWindow` ctor via `QTimer::singleShot(0, ...)`.
### ChooseOfflineNameDialog cleanup
- Window title: `Choose Offline Name``Pick a username`
- Removed `Allow invalid usernames` checkbox + slot
- Removed `Message label placeholder` body label
- Constructor still takes `message` arg for ABI compat (now unused via `Q_UNUSED`)
- Validator unchanged: `[A-Za-z0-9_]{3,16}`
### Bloat strips
**Source-side (~4M removed, ~2M off compiled binary):**
- `.github/` (136K)
- `tests/` + `BUILD_TESTING` block in root `CMakeLists.txt` (928K)
- `nix/`, `flake.nix`, `flake.lock` (28K)
- `launcher/resources/multimc/` icon theme (3M)
**multimc → racked_ru migration:**
- 71 instance icons (32x32, 50x50, 128x128, scalable) copied into `launcher/resources/racked_ru/`
- `racked_ru.qrc` extended with `prefix="/icons/racked_ru"` resource block
- `Application.cpp:950` instance icon paths repointed `multimc``racked_ru`
- `ThemeManager.h:94` `builtinIcons{"flat_white", "multimc"}``{"flat_white", "racked_ru"}`
- `launcher/CMakeLists.txt:1284` dropped `resources/multimc/multimc.qrc` from `qt_add_resources()`
- `launcher/main.cpp:56` dropped `Q_INIT_RESOURCE(multimc);`
**Runtime-side (`/home/admin/ai-lab/_projects/_minecraft/launcher/`, ~200M removed):**
- `java/java21.tar.gz` (extracted leftover): 198M
- Syncthing `*sync-conflict*` files: ~340K
- `cache/*` wipe: 5.5M
### Project relocation
Moved source from `_projects/_minecraft/source/``_github/minecraft-launcher/` (sibling pattern to `_github/minecraft-server`). Runtime build target stays at `_projects/_minecraft/launcher/` for daily-driver testing. Existing `.gitignore` excludes `build-*`, `install-*`, `release/`.
### Documentation
New docs in `docs/`:
- `SETTINGS_AUDIT.md` — runtime cfg vs source defaults diff
- `NETWORK_AUDIT.md` — full endpoint inventory; zero telemetry confirmed
- `BLOAT_AUDIT.md` — strippability tiers
- `CHANGES_2026-04-30.md` — pre-changelog session notes (superseded by this file)
---
## Pending
- Replace placeholder `s8n-ru/minecraft-launcher` repo URL with real GitHub slug
- Stand up `https://racked.ru/feed.xml` (RSS feed) so news pane populates
- Decide: ship `accounts.json`-free portable release (already clean in `release/`)

504
CMakeLists.txt Normal file
View file

@ -0,0 +1,504 @@
cmake_minimum_required(VERSION 3.25) # Required for features like `CMAKE_MSVC_DEBUG_INFORMATION_FORMAT`
project(Launcher LANGUAGES C CXX)
if(APPLE)
enable_language(OBJC OBJCXX)
endif()
string(COMPARE EQUAL "${CMAKE_SOURCE_DIR}" "${CMAKE_BUILD_DIR}" IS_IN_SOURCE_BUILD)
if(IS_IN_SOURCE_BUILD)
message(FATAL_ERROR "You are building the Launcher in-source. Please separate the build tree from the source tree.")
endif()
##################################### Set CMake options #####################################
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/cmake/")
# Output all executables and shared libs in the main build folder, not in subfolders.
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR})
if(UNIX)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR})
endif()
set(CMAKE_JAVA_TARGET_OUTPUT_DIR ${PROJECT_BINARY_DIR}/jars)
######## Set compiler flags ########
set(CMAKE_CXX_STANDARD_REQUIRED true)
set(CMAKE_C_STANDARD_REQUIRED true)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_C_STANDARD 11)
include(GenerateExportHeader)
add_compile_definitions($<$<NOT:$<CONFIG:Debug>>:QT_NO_DEBUG>)
add_compile_definitions(QT_WARN_DEPRECATED_UP_TO=0x060400)
add_compile_definitions(QT_DISABLE_DEPRECATED_UP_TO=0x060400)
if(CMAKE_CXX_COMPILER_FRONTEND_VARIANT STREQUAL "MSVC")
add_compile_options(
# /GS Adds buffer security checks, default on but included anyway to mirror gcc's fstack-protector flag
"$<$<COMPILE_LANGUAGE:C,CXX>:/GS>"
# /Gw helps reduce binary size
# /Gy allows the compiler to package individual functions
# /guard:cf enables control flow guard
"$<$<AND:$<CONFIG:Release,RelWithDebInfo>,$<COMPILE_LANGUAGE:C,CXX>>:/Gw;/Gy;/guard:cf>"
)
add_link_options(
# /LTCG allows for linking wholy optimizated programs
# /MANIFEST:NO disables generating a manifest file, we instead provide our own
# /STACK sets the stack reserve size, ATL's pack list needs 3-4 MiB as of November 2022, provide 8 MiB
"$<$<COMPILE_LANGUAGE:C,CXX>:/LTCG;/MANIFEST:NO;/STACK:8388608>"
)
# /GL enables whole program optimizations
# NOTE: With Clang, this is implemented as regular LTO and only used during linking
if(NOT CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
add_compile_options("$<$<AND:$<CONFIG:Release,RelWithDebInfo>,$<COMPILE_LANGUAGE:C,CXX>>:/GL>")
endif()
# See https://github.com/ccache/ccache/issues/1040
# TODO(@getchoo): Is sccache affected by this? Would be nice to use `ProgramDatabase`....
set(CMAKE_MSVC_DEBUG_INFORMATION_FORMAT "$<$<CONFIG:Debug,RelWithDebInfo>:Embedded>")
if(CMAKE_MSVC_RUNTIME_LIBRARY STREQUAL "MultiThreadedDLL")
set(CMAKE_MAP_IMPORTED_CONFIG_DEBUG Release "")
set(CMAKE_MAP_IMPORTED_CONFIG_RELWITHDEBINFO Release "")
endif()
else()
add_compile_options("$<$<COMPILE_LANGUAGE:C,CXX>:-fstack-protector-strong;--param=ssp-buffer-size=4>")
# Avoid re-defining _FORTIFY_SOURCE, as it can cause redefinition errors in setups that use it by default (i.e., package builds)
if(NOT (CMAKE_C_FLAGS MATCHES "-D_FORTIFY_SOURCE" OR CMAKE_CXX_FLAGS MATCHES "-D_FORTIFY_SOURCE"))
# NOTE: _FORTIFY_SOURCE requires optimizations in most newer versions of glibc
add_compile_options("$<$<AND:$<COMPILE_LANGUAGE:C,CXX>,$<CONFIG:Release,RelWithDebInfo>>:-D_FORTIFY_SOURCE=2>")
endif()
# ATL's pack list needs more than the default 1 Mib stack on windows
if(CMAKE_SYSTEM_NAME STREQUAL "Windows")
add_link_options("$<$<COMPILE_LANGUAGE:C,CXX>:-Wl,--stack,8388608>")
# -ffunction-sections and -fdata-sections help reduce binary size
# -mguard=cf enables Control Flow Guard
# TODO: Look into -gc-sections to further reduce binary size
add_compile_options("$<$<AND:$<CONFIG:Release,RelWithDebInfo>,$<COMPILE_LANGUAGE:C,CXX>>:-ffunction-sections;-fdata-sections;-mguard=cf>")
endif()
endif()
# Export compile commands for debug builds if we can (useful in LSPs like clangd)
# https://cmake.org/cmake/help/v3.31/variable/CMAKE_EXPORT_COMPILE_COMMANDS.html
if(CMAKE_GENERATOR STREQUAL "Unix Makefiles" OR CMAKE_GENERATOR MATCHES "^Ninja")
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
endif()
option(USE_CLANG_TIDY "Enable the use of clang-tidy during compilation" OFF)
if(USE_CLANG_TIDY)
find_program(CLANG_TIDY clang-tidy OPTIONAL)
if(CLANG_TIDY)
message(STATUS "Using clang-tidy during compilation")
set(CLANG_TIDY_COMMAND "${CLANG_TIDY}" "--config-file=${CMAKE_SOURCE_DIR}/.clang-tidy")
set(CMAKE_CXX_CLANG_TIDY ${CLANG_TIDY_COMMAND})
else()
message(WARNING "Unable to find `clang-tidy`. Not using during compilation")
endif()
endif()
option(DEBUG_ADDRESS_SANITIZER "Enable Address Sanitizer in Debug builds" OFF)
# If this is a Debug build turn on address sanitiser
if (DEBUG_ADDRESS_SANITIZER)
message(STATUS "Address Sanitizer enabled for Debug builds, Turn it off with -DDEBUG_ADDRESS_SANITIZER=off")
set(USE_ASAN_COMPILE_OPTIONS $<AND:$<CONFIG:Debug,RelWithDebInfo>,$<COMPILE_LANGUAGE:C,CXX>>)
if (CMAKE_CXX_COMPILER_FRONTEND_VARIANT STREQUAL "MSVC")
message(STATUS "Using Address Sanitizer compile options for MSVC frontend")
add_compile_options(
$<${USE_ASAN_COMPILE_OPTIONS}:/fsanitize=address>
$<${USE_ASAN_COMPILE_OPTIONS}:/Oy->
)
elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU" OR "${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang")
message(STATUS "Using Address Sanitizer compile options for GCC/Clang")
add_compile_options(
$<${USE_ASAN_COMPILE_OPTIONS}:-fsanitize=address,undefined>
$<${USE_ASAN_COMPILE_OPTIONS}:-fno-omit-frame-pointer>
$<${USE_ASAN_COMPILE_OPTIONS}:-fno-sanitize-recover=null>
)
link_libraries("asan" "ubsan")
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)
include(CheckIPOSupported)
check_ipo_supported(RESULT ipo_supported OUTPUT ipo_error)
if(ipo_supported)
set(CMAKE_INTERPROCEDURAL_OPTIMIZATION_RELEASE TRUE)
set(CMAKE_INTERPROCEDURAL_OPTIMIZATION_MINSIZEREL TRUE)
set(CMAKE_INTERPROCEDURAL_OPTIMIZATION_RELWITHDEBINFO TRUE)
if(CMAKE_BUILD_TYPE)
if(NOT CMAKE_BUILD_TYPE STREQUAL "Debug")
message(STATUS "IPO / LTO enabled")
else()
message(STATUS "Not enabling IPO / LTO on debug builds")
endif()
else()
message(STATUS "IPO / LTO will only be enabled for release builds")
endif()
else()
message(STATUS "IPO / LTO not supported: <${ipo_error}>")
endif()
endif()
option(BUILD_TESTING "Build the testing tree." ON)
find_package(ECM NO_MODULE REQUIRED)
set(CMAKE_MODULE_PATH "${ECM_MODULE_PATH};${CMAKE_MODULE_PATH}")
include(CTest)
include(ECMAddTests)
if(BUILD_TESTING)
enable_testing()
endif()
##################################### Set Application options #####################################
######## Set URLs ########
set(Launcher_NEWS_RSS_URL "https://racked.ru/feed.xml" CACHE STRING "URL to fetch racked.ru news RSS feed from.")
set(Launcher_NEWS_OPEN_URL "https://racked.ru/news" CACHE STRING "URL that gets opened when the user clicks 'More News'")
set(Launcher_WIKI_URL "https://prismlauncher.org/wiki/" CACHE STRING "URL that gets opened when the user clicks 'Launcher Help'")
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 in a dialog window")
set(Launcher_LOGIN_CALLBACK_URL "https://prismlauncher.org/successful-login" CACHE STRING "URL that gets opened when the user successfully logins.")
set(Launcher_LEGACY_FMLLIBS_BASE_URL "https://files.prismlauncher.org/fmllibs/" CACHE STRING "URL for legacy (<=1.5.2) FML Libraries.")
######## Set version numbers ########
set(Launcher_VERSION_MAJOR 11)
set(Launcher_VERSION_MINOR 0)
set(Launcher_VERSION_PATCH 0)
set(Launcher_VERSION_NAME "${Launcher_VERSION_MAJOR}.${Launcher_VERSION_MINOR}.${Launcher_VERSION_PATCH}")
set(Launcher_VERSION_NAME4 "${Launcher_VERSION_MAJOR}.${Launcher_VERSION_MINOR}.${Launcher_VERSION_PATCH}.0")
set(Launcher_VERSION_NAME4_COMMA "${Launcher_VERSION_MAJOR},${Launcher_VERSION_MINOR},${Launcher_VERSION_PATCH},0")
# Build platform.
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.")
# Github repo URL with releases for updater
set(Launcher_UPDATER_GITHUB_REPO "https://github.com/s8n-ru/minecraft-launcher" CACHE STRING "Base github URL for the updater.")
# Name to help updater identify valid artifacts
set(Launcher_BUILD_ARTIFACT "" CACHE STRING "Artifact name to help the updater identify valid artifacts.")
# The metadata server
set(Launcher_META_URL "https://meta.prismlauncher.org/v1/" CACHE STRING "URL to fetch Launcher's meta files from.")
# Imgur API Client ID
set(Launcher_IMGUR_CLIENT_ID "5b97b0713fba4a3" CACHE STRING "Client ID you can get from Imgur when you register an application")
# Bug tracker URL
set(Launcher_BUG_TRACKER_URL "https://github.com/s8n-ru/minecraft-launcher/issues" CACHE STRING "URL for the bug tracker.")
# Translations Platform URL
set(Launcher_TRANSLATIONS_URL "https://hosted.weblate.org/projects/prismlauncher/launcher/" CACHE STRING "URL for the translations platform.")
set(Launcher_TRANSLATION_FILES_URL "https://i18n.prismlauncher.org/" CACHE STRING "URL for the translations files.")
# Matrix Space
set(Launcher_MATRIX_URL "https://prismlauncher.org/matrix" CACHE STRING "URL to the Matrix Space")
# Discord URL
set(Launcher_DISCORD_URL "https://prismlauncher.org/discord" CACHE STRING "URL for the Discord guild.")
# Subreddit URL
set(Launcher_SUBREDDIT_URL "https://prismlauncher.org/reddit" CACHE STRING "URL for the subreddit.")
# Builds
set(Launcher_QT_VERSION_MAJOR "6" CACHE STRING "Major Qt version to build against")
option(Launcher_USE_PCH "Use precompiled headers where possible" ON)
# Java downloader
set(Launcher_ENABLE_JAVA_DOWNLOADER_DEFAULT ON)
# Although we recommend enabling this, we cannot guarantee binary compatibility on
# differing Linux/BSD/etc distributions. Downstream packagers should be explicitly opt-ing into this
# feature if they know it will work with their distribution.
if(UNIX AND NOT APPLE)
set(Launcher_ENABLE_JAVA_DOWNLOADER_DEFAULT OFF)
endif()
# Java downloader
option(Launcher_ENABLE_JAVA_DOWNLOADER "Build the java downloader feature" ${Launcher_ENABLE_JAVA_DOWNLOADER_DEFAULT})
# Native libraries
if(UNIX AND APPLE)
set(Launcher_GLFW_LIBRARY_NAME "libglfw.dylib" CACHE STRING "Name of native glfw library")
set(Launcher_OPENAL_LIBRARY_NAME "libopenal.dylib" CACHE STRING "Name of native openal library")
elseif(UNIX)
set(Launcher_GLFW_LIBRARY_NAME "libglfw.so" CACHE STRING "Name of native glfw library")
set(Launcher_OPENAL_LIBRARY_NAME "libopenal.so" CACHE STRING "Name of native openal library")
elseif(WIN32)
set(Launcher_GLFW_LIBRARY_NAME "glfw.dll" CACHE STRING "Name of native glfw library")
set(Launcher_OPENAL_LIBRARY_NAME "OpenAL.dll" CACHE STRING "Name of native openal library")
endif()
# API Keys
# NOTE: These API keys are here for convenience. If you rebrand this software or intend to break the terms of service
# of these platforms, please change these API keys beforehand.
# Be aware that if you were to use these API keys for malicious purposes they might get revoked, which might cause
# breakage to thousands of users.
# If you don't plan to use these features of this software, you can just remove these values.
# By using this key in your builds you accept the terms of use laid down in
# https://docs.microsoft.com/en-us/legal/microsoft-identity-platform/terms-of-use
set(Launcher_MSA_CLIENT_ID "c36a9fb6-4f2a-41ff-90bd-ae7cc92031eb" CACHE STRING "Client ID you can get from Microsoft Identity Platform when you register an application")
# By using this key in your builds you accept the terms and conditions laid down in
# https://support.curseforge.com/en/support/solutions/articles/9000207405-curse-forge-3rd-party-api-terms-and-conditions
# NOTE: CurseForge requires you to change this if you make any kind of derivative work.
# This key was issued specifically for Prism Launcher
set(Launcher_CURSEFORGE_API_KEY "$2a$10$wuAJuNZuted3NORVmpgUC.m8sI.pv1tOPKZyBgLFGjxFp/br0lZCC" CACHE STRING "API key for the CurseForge platform")
set(Launcher_COMPILER_NAME ${CMAKE_CXX_COMPILER_ID})
set(Launcher_COMPILER_VERSION ${CMAKE_CXX_COMPILER_VERSION})
set(Launcher_COMPILER_TARGET_SYSTEM ${CMAKE_SYSTEM_NAME})
set(Launcher_COMPILER_TARGET_SYSTEM_VERSION ${CMAKE_SYSTEM_VERSION})
set(Launcher_COMPILER_TARGET_PROCESSOR ${CMAKE_SYSTEM_PROCESSOR})
#### Check the current Git commit and branch
include(GetGitRevisionDescription)
git_get_exact_tag(Launcher_GIT_TAG)
get_git_head_revision(Launcher_GIT_REFSPEC Launcher_GIT_COMMIT)
message(STATUS "Git commit: ${Launcher_GIT_COMMIT}")
message(STATUS "Git tag: ${Launcher_GIT_TAG}")
message(STATUS "Git refspec: ${Launcher_GIT_REFSPEC}")
string(TIMESTAMP TODAY "%Y-%m-%d")
set(Launcher_BUILD_TIMESTAMP "${TODAY}")
################################ 3rd Party Libs ################################
# Find the required Qt parts
if(Launcher_QT_VERSION_MAJOR EQUAL 6)
set(QT_VERSION_MAJOR 6)
find_package(Qt6 6.4 REQUIRED COMPONENTS Core CoreTools Widgets Concurrent Network Test Xml NetworkAuth OpenGL)
find_package(Qt6 COMPONENTS DBus)
list(APPEND Launcher_QT_DBUS Qt6::DBus)
else()
message(FATAL_ERROR "Qt version ${Launcher_QT_VERSION_MAJOR} is not supported")
endif()
if(Launcher_QT_VERSION_MAJOR EQUAL 6)
set(QT_PLUGINS_DIR ${QT${QT_VERSION_MAJOR}_INSTALL_PREFIX}/${QT${QT_VERSION_MAJOR}_INSTALL_PLUGINS})
set(QT_LIBS_DIR ${QT${QT_VERSION_MAJOR}_INSTALL_PREFIX}/${QT${QT_VERSION_MAJOR}_INSTALL_LIBS})
set(QT_LIBEXECS_DIR ${QT${QT_VERSION_MAJOR}_INSTALL_PREFIX}/${QT${QT_VERSION_MAJOR}_INSTALL_LIBEXECS})
endif()
find_package(cmark REQUIRED)
if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
find_package(PkgConfig REQUIRED)
pkg_check_modules(gamemode REQUIRED IMPORTED_TARGET gamemode)
endif()
# Find libqrencode
## NOTE(@getchoo): Never use pkg-config with MSVC since the vcpkg port makes our install bundle fail to find the dll
if(MSVC)
find_path(LIBQRENCODE_INCLUDE_DIR qrencode.h REQUIRED)
find_library(LIBQRENCODE_LIBRARY_RELEASE qrencode REQUIRED)
find_library(LIBQRENCODE_LIBRARY_DEBUG qrencoded)
set(LIBQRENCODE_LIBRARIES optimized ${LIBQRENCODE_LIBRARY_RELEASE} debug ${LIBQRENCODE_LIBRARY_DEBUG})
else()
find_package(PkgConfig REQUIRED)
pkg_check_modules(libqrencode REQUIRED IMPORTED_TARGET libqrencode)
endif()
# Find libarchive through CMake packages, mainly for vcpkg
find_package(LibArchive)
# CMake packages aren't available in most distributions of libarchive, so fallback to pkg-config
if(NOT LibArchive_FOUND)
find_package(PkgConfig REQUIRED)
pkg_check_modules(libarchive REQUIRED IMPORTED_TARGET libarchive)
endif()
find_package(tomlplusplus 3.2.0)
# fallback to pkgconfig, important especially as many distros package toml++ built with meson
if(NOT tomlplusplus_FOUND)
find_package(PkgConfig REQUIRED)
pkg_check_modules(tomlplusplus REQUIRED IMPORTED_TARGET tomlplusplus>=3.2.0)
endif()
find_package(ZLIB REQUIRED)
include(ECMQtDeclareLoggingCategory)
####################################### Program Info #######################################
set(Launcher_APP_BINARY_NAME "prismlauncher" CACHE STRING "Name of the Launcher binary")
add_subdirectory(program_info)
####################################### Install layout #######################################
set(Launcher_ENABLE_UPDATER NO)
set(Launcher_BUILD_UPDATER NO)
if (NOT APPLE AND (NOT Launcher_UPDATER_GITHUB_REPO STREQUAL "" AND NOT Launcher_BUILD_ARTIFACT STREQUAL ""))
set(Launcher_BUILD_UPDATER YES)
endif()
if(NOT (UNIX AND APPLE))
# Install "portable.txt" if selected component is "portable"
install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/${Launcher_Portable_File}" DESTINATION "." COMPONENT portable EXCLUDE_FROM_ALL)
endif()
if(UNIX AND APPLE)
set(BINARY_DEST_DIR "${Launcher_Name}.app/Contents/MacOS")
set(LIBRARY_DEST_DIR "${Launcher_Name}.app/Contents/MacOS")
set(PLUGIN_DEST_DIR "${Launcher_Name}.app/Contents/MacOS")
set(FRAMEWORK_DEST_DIR "${Launcher_Name}.app/Contents/Frameworks")
set(RESOURCES_DEST_DIR "${Launcher_Name}.app/Contents/Resources")
set(JARS_DEST_DIR "${Launcher_Name}.app/Contents/MacOS/jars")
# Mac bundle settings
set(MACOSX_BUNDLE_BUNDLE_NAME "${Launcher_DisplayName}")
set(MACOSX_BUNDLE_INFO_STRING "${Launcher_DisplayName}: A custom launcher for Minecraft that allows you to easily manage multiple installations of Minecraft at once.")
set(MACOSX_BUNDLE_GUI_IDENTIFIER "${Launcher_AppID}")
set(MACOSX_BUNDLE_BUNDLE_VERSION "${Launcher_VERSION_NAME}")
set(MACOSX_BUNDLE_SHORT_VERSION_STRING "${Launcher_VERSION_NAME}")
set(MACOSX_BUNDLE_LONG_VERSION_STRING "${Launcher_VERSION_NAME}")
set(MACOSX_BUNDLE_ICON_FILE ${Launcher_Name}.icns)
set(MACOSX_BUNDLE_COPYRIGHT "${Launcher_Copyright_Mac}")
set(MACOSX_SPARKLE_UPDATE_PUBLIC_KEY "v55ZWWD6QlPoXGV6VLzOTZxZUggWeE51X8cRQyQh6vA=" CACHE STRING "Public key for Sparkle update feed")
set(MACOSX_SPARKLE_UPDATE_FEED_URL "https://prismlauncher.org/feed/appcast.xml" CACHE STRING "URL for Sparkle update feed")
set(MACOSX_SPARKLE_DOWNLOAD_URL "https://github.com/sparkle-project/Sparkle/releases/download/2.8.0/Sparkle-2.8.0.tar.xz" CACHE STRING "URL to Sparkle release archive")
set(MACOSX_SPARKLE_SHA256 "fd5681ee92bf238aaac2d08214ceaf0cc8976e452d7f882d80bac1e61581f3b1" CACHE STRING "SHA256 checksum for Sparkle release archive")
set(MACOSX_SPARKLE_DIR "${CMAKE_BINARY_DIR}/frameworks/Sparkle")
if(NOT MACOSX_SPARKLE_UPDATE_PUBLIC_KEY STREQUAL "" AND NOT MACOSX_SPARKLE_UPDATE_FEED_URL STREQUAL "")
set(Launcher_ENABLE_UPDATER YES)
endif()
# Add the icon
install(FILES ${Launcher_Branding_ICNS} DESTINATION ${RESOURCES_DEST_DIR} RENAME ${Launcher_Name}.icns)
find_program(ACTOOL_EXE actool DOC "Path to the apple asset catalog compiler")
if(ACTOOL_EXE)
execute_process(
COMMAND xcodebuild -version
OUTPUT_VARIABLE XCODE_VERSION_OUTPUT
OUTPUT_STRIP_TRAILING_WHITESPACE
)
string(REGEX MATCH "Xcode ([0-9]+\.[0-9]+)" XCODE_VERSION_MATCH "${XCODE_VERSION_OUTPUT}")
if(XCODE_VERSION_MATCH)
set(XCODE_VERSION ${CMAKE_MATCH_1})
else()
set(XCODE_VERSION 0.0)
endif()
if(XCODE_VERSION VERSION_GREATER_EQUAL 26.0)
set(ASSETS_OUT_DIR "${CMAKE_BINARY_DIR}/program_info")
set(GENERATED_ASSETS_CAR "${ASSETS_OUT_DIR}/Assets.car")
set(ICON_SOURCE "${CMAKE_CURRENT_SOURCE_DIR}/${Launcher_Branding_MAC_ICON}")
add_custom_command(
OUTPUT "${GENERATED_ASSETS_CAR}"
COMMAND ${ACTOOL_EXE} "${ICON_SOURCE}"
--compile "${ASSETS_OUT_DIR}"
--output-partial-info-plist /dev/null
--app-icon ${Launcher_Name}
--enable-on-demand-resources NO
--target-device mac
--minimum-deployment-target ${CMAKE_OSX_DEPLOYMENT_TARGET}
--platform macosx
DEPENDS "${ICON_SOURCE}"
COMMENT "Compiling asset catalog (${ICON_SOURCE})"
VERBATIM
)
add_custom_target(compile_assets ALL DEPENDS "${GENERATED_ASSETS_CAR}")
install(FILES "${GENERATED_ASSETS_CAR}" DESTINATION "${RESOURCES_DEST_DIR}")
else()
message(WARNING "Xcode ${XCODE_VERSION} is too old. Minimum required version is 26.0. Not compiling liquid glass icons.")
endif()
else()
message(WARNING "actool not found. Cannot compile macOS app icons.\n"
"Install Xcode command line tools: 'xcode-select --install'")
endif()
elseif(UNIX)
include(KDEInstallDirs)
set(BINARY_DEST_DIR "bin")
set(LIBRARY_DEST_DIR "lib${LIB_SUFFIX}")
set(JARS_DEST_DIR "share/${Launcher_Name}")
# Set RPATH
SET(Launcher_BINARY_RPATH "$ORIGIN/")
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${Launcher_Desktop} DESTINATION ${KDE_INSTALL_APPDIR})
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${Launcher_MetaInfo} DESTINATION ${KDE_INSTALL_METAINFODIR})
install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/${Launcher_SVG} DESTINATION "${KDE_INSTALL_ICONDIR}/hicolor/scalable/apps")
install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/${Launcher_PNG_256} DESTINATION "${KDE_INSTALL_ICONDIR}/hicolor/256x256/apps" RENAME "${Launcher_AppID}.png")
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${Launcher_MIMEInfo} DESTINATION ${KDE_INSTALL_MIMEDIR})
install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/launcher/qtlogging.ini" DESTINATION "share/${Launcher_Name}")
set(PLUGIN_DEST_DIR "plugins")
set(BUNDLE_DEST_DIR ".")
set(RESOURCES_DEST_DIR ".")
if(Launcher_ManPage)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${Launcher_ManPage} DESTINATION "${KDE_INSTALL_MANDIR}/man6")
endif()
# Install basic runner script if component "portable" is selected
configure_file(launcher/Launcher.in "${CMAKE_CURRENT_BINARY_DIR}/LauncherScript" @ONLY)
install(PROGRAMS "${CMAKE_CURRENT_BINARY_DIR}/LauncherScript" DESTINATION "." RENAME ${Launcher_Name} COMPONENT portable EXCLUDE_FROM_ALL)
elseif(WIN32)
set(BINARY_DEST_DIR ".")
set(LIBRARY_DEST_DIR ".")
set(PLUGIN_DEST_DIR ".")
set(RESOURCES_DEST_DIR ".")
set(JARS_DEST_DIR "jars")
else()
message(FATAL_ERROR "Platform not supported")
endif()
################################ Included Libs ################################
include(ExternalProject)
set_directory_properties(PROPERTIES EP_BASE External)
option(NBT_BUILD_SHARED "Build NBT shared library" OFF)
option(NBT_USE_ZLIB "Build NBT library with zlib support" OFF)
option(NBT_BUILD_TESTS "Build NBT library tests" OFF) #FIXME: fix unit tests.
add_subdirectory(libraries/libnbtplusplus)
add_subdirectory(libraries/launcher) # java based launcher part for Minecraft
add_subdirectory(libraries/javacheck) # java compatibility checker
add_subdirectory(libraries/rainbow) # Qt extension for colors
add_subdirectory(libraries/LocalPeer) # fork of a library from Qt solutions
add_subdirectory(libraries/murmur2) # Hash for usage with the CurseForge API
add_subdirectory(libraries/qdcss) # css parser
############################### Built Artifacts ###############################
add_subdirectory(buildconfig)
# NOTE: this must always be last to appease the CMake deity of quirky install command evaluation order.
add_subdirectory(launcher)

222
CMakePresets.json Normal file
View file

@ -0,0 +1,222 @@
{
"$schema": "https://cmake.org/cmake/help/latest/_downloads/3e2d73bff478d88a7de0de736ba5e361/schema.json",
"version": 8,
"cmakeMinimumRequired": {
"major": 3,
"minor": 28
},
"configurePresets": [
{
"name": "base",
"hidden": true,
"binaryDir": "build",
"installDir": "install",
"generator": "Ninja Multi-Config",
"cacheVariables": {
"Launcher_BUILD_ARTIFACT": "$penv{ARTIFACT_NAME}",
"Launcher_BUILD_PLATFORM": "$penv{BUILD_PLATFORM}",
"Launcher_ENABLE_JAVA_DOWNLOADER": "ON",
"ENABLE_LTO": "ON"
}
},
{
"name": "linux",
"displayName": "Linux",
"inherits": [
"base"
],
"condition": {
"type": "equals",
"lhs": "${hostSystemName}",
"rhs": "Linux"
}
},
{
"name": "macos",
"displayName": "macOS",
"inherits": [
"base"
],
"condition": {
"type": "equals",
"lhs": "${hostSystemName}",
"rhs": "Darwin"
},
"cacheVariables": {
"CMAKE_TOOLCHAIN_FILE": "$penv{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake"
}
},
{
"name": "macos_universal",
"displayName": "macOS (Universal Binary)",
"inherits": [
"macos"
],
"cacheVariables": {
"CMAKE_TOOLCHAIN_FILE": "$penv{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake",
"CMAKE_OSX_ARCHITECTURES": "x86_64;arm64",
"VCPKG_TARGET_TRIPLET": "universal-osx"
}
},
{
"name": "windows_mingw",
"displayName": "Windows (MinGW)",
"inherits": [
"base"
],
"condition": {
"type": "equals",
"lhs": "${hostSystemName}",
"rhs": "Windows"
}
},
{
"name": "windows_msvc",
"displayName": "Windows (MSVC)",
"inherits": [
"base"
],
"condition": {
"type": "equals",
"lhs": "${hostSystemName}",
"rhs": "Windows"
},
"cacheVariables": {
"CMAKE_TOOLCHAIN_FILE": "$penv{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake"
}
}
],
"buildPresets": [
{
"name": "linux",
"displayName": "Linux",
"condition": {
"type": "equals",
"lhs": "${hostSystemName}",
"rhs": "Linux"
},
"configurePreset": "linux"
},
{
"name": "macos",
"displayName": "macOS",
"condition": {
"type": "equals",
"lhs": "${hostSystemName}",
"rhs": "Darwin"
},
"configurePreset": "macos"
},
{
"name": "macos_universal",
"displayName": "macOS (Universal Binary)",
"inherits": [
"macos"
],
"configurePreset": "macos_universal"
},
{
"name": "windows_mingw",
"displayName": "Windows (MinGW)",
"condition": {
"type": "equals",
"lhs": "${hostSystemName}",
"rhs": "Windows"
},
"configurePreset": "windows_mingw"
},
{
"name": "windows_msvc",
"displayName": "Windows (MSVC)",
"condition": {
"type": "equals",
"lhs": "${hostSystemName}",
"rhs": "Windows"
},
"configurePreset": "windows_msvc"
}
],
"testPresets": [
{
"name": "base",
"hidden": true,
"output": {
"outputOnFailure": true,
"verbosity": "extra"
},
"execution": {
"noTestsAction": "error"
},
"filter": {
"exclude": {
"name": "^example64|example$"
}
}
},
{
"name": "linux",
"displayName": "Linux",
"inherits": [
"base"
],
"condition": {
"type": "equals",
"lhs": "${hostSystemName}",
"rhs": "Linux"
},
"configurePreset": "linux"
},
{
"name": "macos",
"displayName": "macOS",
"inherits": [
"base"
],
"condition": {
"type": "equals",
"lhs": "${hostSystemName}",
"rhs": "Darwin"
},
"configurePreset": "macos"
},
{
"name": "macos_universal",
"displayName": "macOS (Universal Binary)",
"inherits": [
"base"
],
"condition": {
"type": "equals",
"lhs": "${hostSystemName}",
"rhs": "Darwin"
},
"configurePreset": "macos_universal"
},
{
"name": "windows_mingw",
"displayName": "Windows (MinGW)",
"inherits": [
"base"
],
"condition": {
"type": "equals",
"lhs": "${hostSystemName}",
"rhs": "Windows"
},
"configurePreset": "windows_mingw"
},
{
"name": "windows_msvc",
"displayName": "Windows (MSVC)",
"inherits": [
"base"
],
"condition": {
"type": "equals",
"lhs": "${hostSystemName}",
"rhs": "Windows"
},
"configurePreset": "windows_msvc"
}
]
}

136
CODE_OF_CONDUCT.md Normal file
View file

@ -0,0 +1,136 @@
# Contributor Covenant Code of Conduct
This is a modified version of the Contributor Covenant.
See commit history to see our changes.
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, caste, color, religion, or sexual
identity and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the overall
community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or advances of
any kind
* Trolling (antagonistic, inflammatory, insincere behaviour), insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email address,
without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement via email at
[coc@scrumplex.net](mailto:coc@scrumplex.net) (Email
address subject to change).
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series of
actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or permanent
ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within the
community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.1, available at
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
Community Impact Guidelines were inspired by
[Mozilla's code of conduct enforcement ladder][Mozilla CoC].
For answers to common questions about this code of conduct, see the FAQ at
[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
[https://www.contributor-covenant.org/translations][translations].
[homepage]: https://www.contributor-covenant.org
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
[Mozilla CoC]: https://github.com/mozilla/diversity
[FAQ]: https://www.contributor-covenant.org/faq
[translations]: https://www.contributor-covenant.org/translations

165
CONTRIBUTING.md Normal file
View file

@ -0,0 +1,165 @@
# Contributions Guidelines
## Restrictions on Generative AI Usage (AI Policy)
> [!NOTE]
> The following is adapted from [matplotlib's contributing guide](https://matplotlib.org/devdocs/devel/contribute.html#generative-ai) and the [Linux Kernel policy guide](https://www.kernel.org/doc./html/next/process/coding-assistants.html)
We expect authentic engagement in our community.
- Do not post output from Large Language Models or similar generative AI as comments on GitHub or our discord server, as such comments tend to be formulaic and low-quality content.
- If you use generative AI tools as an aid in developing code or documentation changes, ensure that you fully understand the proposed changes and can explain why they are the correct approach.
Make sure you have added value based on your personal competency to your contributions.
Just taking some input, feeding it to an AI and posting the result is not of value to the project.
To preserve precious core developer capacity, we reserve the right to rigorously reject seemingly AI generated low-value contributions.
### Signed-off-by and Developer Certificate of Origin
AI agents MUST NOT add Signed-off-by tags. Only humans can legally certify the Developer Certificate of Origin (DCO). The human submitter is responsible for:
- Reviewing all AI-generated code
- Ensuring compliance with licensing requirements
- Adding their own Signed-off-by tag to certify the DCO
- Taking full responsibility for the contribution
See [Signing your work](#signing-your-work) for more information.
### Attribution
When AI tools contribute to development, proper attribution helps track the evolving role of AI in the development process. Contributions should include an Assisted-by tag in the commit message with the following format:
```text
Assisted-by: AGENT_NAME:MODEL_VERSION [TOOL1] [TOOL2]
```
Where:
- `AGENT_NAME` is the name of the AI tool or framework
- `MODEL_VERSION` is the specific model version used
- `[TOOL1] [TOOL2]` are optional specialized analysis tools used (e.g., coccinelle, sparse, smatch, clang-tidy)
Basic development tools (git, gcc, make, editors) should not be listed.
Example:
```text
Assisted-by: Claude:claude-3-opus coccinelle sparse
```
## Code style
All files are formatted with `clang-format` using the configuration in `.clang-format`. Ensure it is run on changed files before committing!
Please also follow the project's conventions for C++:
- Class and type names should be formatted as `PascalCase`: `MyClass`.
- Private or protected class data members should be formatted as `camelCase` prefixed with `m_`: `m_myCounter`.
- Private or protected `static` class data members should be formatted as `camelCase` prefixed with `s_`: `s_instance`.
- Public class data members should be formatted as `camelCase` without the prefix: `dateOfBirth`.
- Public, private or protected `static const` class data members should be formatted as `SCREAMING_SNAKE_CASE`: `MAX_VALUE`.
- Class function members should be formatted as `camelCase` without a prefix: `incrementCounter`.
- Global functions and non-`const` global variables should be formatted as `camelCase` without a prefix: `globalData`.
- `const` global variables and macros should be formatted as `SCREAMING_SNAKE_CASE`: `LIGHT_GRAY`.
- enum constants should be formatted as `PascalCase`: `CamelusBactrianus`
- Avoid inventing acronyms or abbreviations especially for a name of multiple words - like `tp` for `texturePack`.
- Avoid using `[[nodiscard]]` unless ignoring the return value is likely to cause a bug in cases such as:
- A function allocates memory or another resource and the caller needs to clean it up.
- A function has side effects and an error status is returned.
- A function is likely be mistaken for having side effects.
- A plain getter is unlikely to cause confusion and adding `[[nodiscard]]` can create clutter and inconsistency.
Most of these rules are included in the `.clang-tidy` file, so you can run `clang-tidy` to check for any violations.
Here is what these conventions with the formatting configuration look like:
```c++
#define AWESOMENESS 10
constexpr double PI = 3.14159;
enum class PizzaToppings { HamAndPineapple, OreoAndKetchup };
struct Person {
QString name;
QDateTime dateOfBirth;
long daysOld() const { return dateOfBirth.daysTo(QDateTime::currentDateTime()); }
};
class ImportantClass {
public:
void incrementCounter()
{
if (m_counter + 1 > MAX_COUNTER_VALUE)
throw std::runtime_error("Counter has reached limit!");
++m_counter;
}
int counter() const { return m_counter; }
private:
static constexpr int MAX_COUNTER_VALUE = 100;
int m_counter;
};
ImportantClass importantClassInstance;
```
If you see any names which do not follow these conventions, it is preferred that you leave them be - renames increase the number of changes therefore make reviewing harder and make your PR more prone to conflicts. However, if you're refactoring a whole class anyway, it's fine.
## Signing your work
In an effort to ensure that the code you contribute is actually compatible with the licenses in this codebase, we require you to sign-off all your contributions.
This can be done by appending `-s` to your `git commit` call, or by manually appending the following text to your commit message:
```text
<commit message>
Signed-off-by: Author name <Author email>
```
By signing off your work, you agree to the terms below:
```text
Developer's Certificate of Origin 1.1
By making a contribution to this project, I certify that:
(a) The contribution was created in whole or in part by me and I
have the right to submit it under the open source license
indicated in the file; or
(b) The contribution is based upon previous work that, to the best
of my knowledge, is covered under an appropriate open source
license and I have the right under that license to submit that
work with modifications, whether created in whole or in part
by me, under the same open source license (unless I am
permitted to submit under a different license), as indicated
in the file; or
(c) The contribution was provided directly to me by some other
person who certified (a), (b) or (c) and I have not modified
it.
(d) I understand and agree that this project and the contribution
are public and that a record of the contribution (including all
personal information I submit with it, including my sign-off) is
maintained indefinitely and may be redistributed consistent with
this project or the open source license(s) involved.
```
These terms will be enforced once you create a pull request, and you will be informed automatically if any of your commits aren't signed-off by you.
As a bonus, you can also [cryptographically sign your commits][gh-signing-commits] and enable [vigilant mode][gh-vigilant-mode] on GitHub.
[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.

422
COPYING.md Normal file
View file

@ -0,0 +1,422 @@
## Prism Launcher
Prism Launcher - Minecraft Launcher
Copyright (C) 2022-2026 Prism Launcher Contributors
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 3.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
This file incorporates work covered by the following copyright and
permission notice:
Copyright 2013-2021 MultiMC Contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
## PolyMC
PolyMC - Minecraft Launcher
Copyright (C) 2021-2022 PolyMC Contributors
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 3.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
This file incorporates work covered by the following copyright and
permission notice:
Copyright 2013-2021 MultiMC Contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
## MinGW-w64 runtime (Windows)
Copyright (c) 2009, 2010, 2011, 2012, 2013 by the mingw-w64 project
This license has been certified as open source. It has also been designated
as GPL compatible by the Free Software Foundation (FSF).
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions in source code must retain the accompanying copyright
notice, this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the accompanying
copyright notice, this list of conditions, and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
3. Names of the copyright holders must not be used to endorse or promote
products derived from this software without prior written permission
from the copyright holders.
4. The right to distribute this software or to use it for any purpose does
not give you the right to use Servicemarks (sm) or Trademarks (tm) of
the copyright holders. Use of them is covered by separate agreement
with the copyright holders.
5. If any files are modified, you must cause the modified files to carry
prominent notices stating that you changed the files and the date of
any change.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESSED
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Information on third party licenses used in MinGW-w64 can be found in its COPYING.MinGW-w64-runtime.txt.
## Qt 6
Copyright (C) 2022 The Qt Company Ltd and other contributors.
Contact: https://www.qt.io/licensing
Licensed under LGPL v3
## libnbt++
libnbt++ - A library for the Minecraft Named Binary Tag format.
Copyright (C) 2013, 2015 ljfa-ag
libnbt++ is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
libnbt++ 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with libnbt++. If not, see <http://www.gnu.org/licenses/>.
## rainbow (KGuiAddons)
Copyright (C) 2007 Matthew Woehlke <mw_triad@users.sourceforge.net>
Copyright (C) 2007 Olaf Schmidt <ojschmidt@kde.org>
Copyright (C) 2007 Thomas Zander <zander@kde.org>
Copyright (C) 2007 Zack Rusin <zack@kde.org>
Copyright (C) 2015 Petr Mrazek <peterix@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
## cmark
Copyright (c) 2014, John MacFarlane
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
## Batch icon set
You are free to use Batch (the "icon set") or any part thereof (the "icons")
in any personal, open-source or commercial work without obligation of payment
(monetary or otherwise) or attribution. Do not sell the icon set, host
the icon set or rent the icon set (either in existing or modified form).
While attribution is optional, it is always appreciated.
Intellectual property rights are not transferred with the download of the icons.
EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL ADAM WHITCROFT
BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL,
PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THE USE OF THE ICONS,
EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
## Material Design Icons
Copyright (c) 2014, Austin Andrews (http://materialdesignicons.com/),
with Reserved Font Name Material Design Icons.
Copyright (c) 2014, Google (http://www.google.com/design/)
uses the license at https://github.com/google/material-design-icons/blob/master/LICENSE
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
## launcher (`libraries/launcher`)
PolyMC - Minecraft Launcher
Copyright (C) 2021-2022 PolyMC Contributors
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.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give
you permission to link this library with independent modules to
produce an executable, regardless of the license terms of these
independent modules, and to copy and distribute the resulting
executable under terms of your choice, provided that you also meet,
for each linked independent module, the terms and conditions of the
license of that module. An independent module is a module which is
not derived from or based on this library. If you modify this
library, you may extend this exception to your version of the
library, but you are not obliged to do so. If you do not wish to do
so, delete this exception statement from your version.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
This file incorporates work covered by the following copyright and
permission notice:
Copyright 2013-2021 MultiMC Contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
## lionshead
Code has been taken from https://github.com/natefoo/lionshead and loosely
translated to C++ laced with Qt.
MIT License
Copyright (c) 2017 Nate Coraor
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
## tomlplusplus
MIT License
Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
## Gamemode
Copyright (c) 2017-2022, Feral Interactive
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Feral Interactive nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
## Breeze icons
Copyright (C) 2014 Uri Herrera <uri_herrera@nitrux.in> and others
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
## Oxygen Icons
The Oxygen Icon Theme
Copyright (C) 2007 Nuno Pinheiro <nuno@oxygen-icons.org>
Copyright (C) 2007 David Vignoni <david@icon-king.com>
Copyright (C) 2007 David Miller <miller@oxygen-icons.org>
Copyright (C) 2007 Johann Ollivier Lapeyre <johann@oxygen-icons.org>
Copyright (C) 2007 Kenneth Wimer <kwwii@bootsplash.org>
Copyright (C) 2007 Riccardo Iaconelli <riccardo@oxygen-icons.org>
and others
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
## libqrencode (`fukuchi/libqrencode`)
Copyright (C) 2020 libqrencode Authors
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
## vcpkg (`cmake/vcpkg-ports`)
MIT License
Copyright (c) Microsoft Corporation
Permission is hereby granted, free of charge, to any person obtaining a copy of this
software and associated documentation files (the "Software"), to deal in the Software
without restriction, including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be included in all copies
or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

74
Containerfile Normal file
View file

@ -0,0 +1,74 @@
ARG DEBIAN_VERSION=stable-slim
FROM docker.io/library/debian:${DEBIAN_VERSION}
ARG QT_ABI=gcc_64
ARG QT_ARCH=
ARG QT_HOST=linux
ARG QT_TARGET=desktop
ARG QT_VERSION=6.10.2
ARG DEBIAN_FRONTEND=noninteractive
RUN apt-get update \
&& apt-get --assume-yes upgrade \
&& apt-get --assume-yes autopurge
# Use Adoptium for Java 17
RUN apt-get --assume-yes --no-install-recommends install \
apt-transport-https ca-certificates curl gpg
RUN curl -L https://packages.adoptium.net/artifactory/api/gpg/key/public | gpg --dearmor | tee /etc/apt/trusted.gpg.d/adoptium.gpg
RUN echo "deb https://packages.adoptium.net/artifactory/deb $(awk -F= '/^VERSION_CODENAME/{print$2}' /etc/os-release) main" | tee /etc/apt/sources.list.d/adoptium.list
RUN apt-get update
# Install base dependencies
RUN apt-get --assume-yes --no-install-recommends install \
# Compilers
clang lld llvm temurin-17-jdk \
# Build system
cmake ninja-build extra-cmake-modules pkg-config \
# Dependencies
cmark gamemode-dev libarchive-dev libcmark-dev libgamemode0 libgl1-mesa-dev libqrencode-dev libtomlplusplus-dev libvulkan-dev scdoc zlib1g-dev \
# Tooling
clang-format clang-tidy git
# Use LLD by default for faster linking
ENV CMAKE_LINKER_TYPE=lld
# Prepare and install Qt
## Setup UTF-8 locale (required, apparently)
RUN apt-get --assume-yes --no-install-recommends install locales
RUN echo "C.UTF-8 UTF-8" > /etc/locale.gen
RUN locale-gen
ENV LC_ALL=C.UTF-8
## Some libraries are required for the official binaries
RUN apt-get --assume-yes --no-install-recommends install \
libglib2.0-0t64 libxkbcommon0 python3-pip
RUN pip3 install --break-system-packages aqtinstall
RUN aqt install-qt \
${QT_HOST} ${QT_TARGET} ${QT_VERSION} ${QT_ARCH} \
--outputdir /opt/qt \
--modules qtimageformats qtnetworkauth
ENV PATH=/opt/qt/${QT_VERSION}/${QT_ABI}/bin:$PATH
ENV QT_PLUGIN_PATH=/opt/qt/${QT_VERSION}/${QT_ABI}/plugins/
## We don't use these. Nuke them
RUN rm -rf \
"$QT_PLUGIN_PATH"/designer \
"$QT_PLUGIN_PATH"/help \
# "$QT_PLUGIN_PATH"/platformthemes/libqgtk3.so \
"$QT_PLUGIN_PATH"/printsupport \
"$QT_PLUGIN_PATH"/qmllint \
"$QT_PLUGIN_PATH"/qmlls \
"$QT_PLUGIN_PATH"/qmltooling \
"$QT_PLUGIN_PATH"/sqldrivers
# Setup workspace
RUN mkdir /work
WORKDIR /work
ENTRYPOINT ["bash"]
CMD ["-i"]

64
INSTALL_DEPS.sh Executable file
View file

@ -0,0 +1,64 @@
#!/bin/bash
# Install dependencies for building Racked.ru PrismLauncher on Fedora
echo "=============================================="
echo "Installing Build Dependencies"
echo "=============================================="
echo ""
echo "This will install the required packages to build the launcher."
echo "You will need to enter your sudo password."
echo ""
read -p "Continue? [y/N] " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
echo "Installation cancelled."
exit 1
fi
sudo dnf install -y \
cmake \
gcc-c++ \
make \
extra-cmake-modules \
qt6-qtbase-devel \
qt6-qttools-devel \
qt6-qtsvg-devel \
qt6-qtnetworkauth-devel \
qt6-qtimageformats \
zlib-devel \
mesa-libGL-devel \
cmark-devel \
gamemode-devel \
git \
pkgconfig
echo ""
echo "=============================================="
echo "Verifying Installation"
echo "=============================================="
echo ""
if command -v cmake &> /dev/null; then
echo "✓ CMake installed: $(cmake --version | head -n1)"
else
echo "✗ CMake installation failed"
exit 1
fi
if command -v qmake6 &> /dev/null; then
echo "✓ Qt6 installed: $(qmake6 -query QT_VERSION)"
else
echo "✗ Qt6 installation failed"
exit 1
fi
echo ""
echo "=============================================="
echo "All dependencies installed successfully!"
echo "=============================================="
echo ""
echo "You can now build the launcher by running:"
echo " bash scripts/build-linux-portable.sh"
echo ""

674
LICENSE Normal file
View file

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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, either version 3 of the License, or
(at your option) any later version.
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/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

266
PROJECT_SUMMARY.md Normal file
View file

@ -0,0 +1,266 @@
# Racked.ru PrismLauncher - Project Summary
## What Was Done
Your custom PrismLauncher has been successfully merged with the upstream PrismLauncher fork and configured for minimal, portable builds across all platforms.
## Project Structure
```
prismlauncher-racked/
├── launcher/ # Source code
│ ├── resources/
│ │ ├── racked_ru/ # Your custom theme
│ │ │ ├── theme.json # Black/red color scheme
│ │ │ ├── themeStyle.css # Qt stylesheet
│ │ │ └── racked_ru.qrc # Qt resource file
│ │ └── backgrounds/
│ │ └── backgrounds.qrc # Updated with racked_ru background
│ ├── Application.cpp # Default theme set to racked.ru
│ └── main.cpp # Only loads required resources
├── scripts/
│ ├── build-windows-portable.bat # Windows build script
│ ├── build-linux-portable.sh # Linux build script
│ ├── build-macos-portable.sh # macOS build script
│ ├── build-all-platforms.sh # Master build script
│ └── create-release.sh # Release automation
├── BUILD_GUIDE.md # Comprehensive build instructions
├── README_RELEASE.md # Quick start guide
└── .gitignore # Updated for this project
```
## Key Changes Made
### 1. Theme Integration
- Created `racked_ru` theme resource directory
- Added your custom theme.json with black/red color scheme
- Set racked.ru as default application theme
- Set flat_white as default icon theme
- Added racked_ru background cat image
### 2. Resource Stripping
Removed these themes from the build to reduce size:
- pe_dark, pe_light, pe_blue, pe_colored
- breeze_dark, breeze_light
- OSX, iOS
- flat (kept only flat_white)
### 3. Build Configuration
- Updated CMakeLists.txt to only include racked_ru and flat_white
- Updated main.cpp to only load required Qt resources
- Updated ThemeManager.h to remove unused icon themes from defaults
- Added portable.txt support for USB-friendly operation
### 4. Portable Mode
All builds are configured for portable operation:
- No installation required
- All data stored in launcher directory
- Perfect for USB drives
- No system registry or appdata usage
### 5. Cross-Platform Build Scripts
Created automated build scripts for:
- **Windows**: Batch script with MSVC support
- **Linux**: Bash script with Qt6 detection
- **macOS**: Bash script with .app bundle creation
## How to Build
### Prerequisites
**Windows:**
- Visual Studio 2022
- Qt 6.5.3+ (MSVC 2019 64-bit)
- CMake 3.25+
**Linux:**
```bash
# Ubuntu/Debian
sudo apt install build-essential cmake qt6-base-dev qt6-tools-dev qt6-networkauth-dev
# Fedora
sudo dnf install gcc-c++ cmake qt6-qtbase-devel qt6-qtnetworkauth-devel
```
**macOS:**
```bash
xcode-select --install
brew install cmake qt6
```
### Build Commands
Quick build (auto-detects platform):
```bash
cd prismlauncher-racked
bash scripts/build-all-platforms.sh
```
Platform-specific:
```bash
# Windows (in Developer Command Prompt)
scripts\build-windows-portable.bat
# Linux
bash scripts/build-linux-portable.sh
# macOS
bash scripts/build-macos-portable.sh
```
Create release:
```bash
bash scripts/create-release.sh 1.0.0
```
## Output Structure
After building, you'll have:
```
release/
├── Racked.ru-PrismLauncher-Windows-Portable/
│ ├── prismlauncher.exe
│ ├── portable.txt
│ ├── Qt6*.dll
│ ├── platforms/
│ ├── iconengines/
│ └── imageformats/
├── Racked.ru-PrismLauncher-Linux-Portable/
│ ├── bin/prismlauncher
│ ├── portable.txt
│ └── run.sh
└── Racked.ru-PrismLauncher-macOS-Portable/
├── PrismLauncher.app
├── portable.txt
└── run.sh
```
## Distribution Packages
After running create-release.sh:
```
release/
├── racked-prismlauncher-1.0.0-windows-portable.zip
├── racked-prismlauncher-1.0.0-linux-portable.tar.gz
└── racked-prismlauncher-1.0.0-macos-portable.tar.gz
```
## Custom Theme Files
### theme.json
```json
{
"colors": {
"AlternateBase": "#000000",
"Base": "#000000",
"BrightText": "#ff0000",
"Button": "#000000",
"ButtonText": "#ffffff",
"Highlight": "#4C4C4C",
"HighlightedText": "#CCCCCC",
"Link": "#CD001F",
"Text": "#ffffff",
"ToolTipBase": "#ffffff",
"ToolTipText": "#ffffff",
"Window": "#000000",
"WindowText": "#ffffff"
},
"name": "racked.ru",
"widgets": "Fusion"
}
```
### themeStyle.css
```css
QToolTip { color: #ffffff; background-color: #2a82da; border: 1px solid white; }
```
## Default Settings
The launcher is pre-configured with:
- Application Theme: racked.ru
- Icon Theme: flat_white
- Background: racked_ru
- Portable Mode: Enabled (via portable.txt)
## File Size Comparison
Your minimal build should be significantly smaller than a full PrismLauncher:
- **Before (full themes)**: ~150MB (Windows)
- **After (minimal)**: ~80-100MB (estimated, depending on Qt version)
## USB Portability Features
1. **No Installation**: Copy and run from any location
2. **Self-Contained**: All data stays in launcher folder
3. **Cross-Machine**: Works on any computer without setup
4. **Preserved Settings**: Your theme and instances travel with you
## Next Steps
1. **Build** the launcher using the provided scripts
2. **Test** on each platform you support
3. **Customize** the theme further if desired (edit theme.json)
4. **Distribute** via https://racked.ru/
5. **Update** periodically by merging upstream changes
## Updating from Upstream
To get new features from upstream:
```bash
cd prismlauncher-racked
git remote add upstream https://github.com/s8n-ru/minecraft-launcher.git
git fetch upstream
git merge upstream/main
# Resolve any conflicts, keeping your theme changes
```
## Troubleshooting
### Build fails on Linux with Qt6 errors
Install complete Qt6 development packages:
```bash
sudo apt install qt6-base-dev qt6-tools-dev qt6-svg-dev qt6-networkauth-dev
```
### Windows build missing DLLs
The build script automatically copies required Qt DLLs. If still missing, ensure Qt bin directory is in PATH.
### Theme not loading
Ensure `portable.txt` exists in the root directory, and check `prismlauncher.cfg` for:
```
ApplicationTheme=racked.ru
IconTheme=flat_white
BackgroundCat=racked_ru
```
### macOS "App is damaged"
Codesign the app:
```bash
codesign --deep --force --sign "-" release/Racked.ru-PrismLauncher-macOS-Portable/PrismLauncher.app
```
## Repository Structure
This project is organized as:
- **prismlauncher-racked/**: Modified upstream repository with your theme
- ** prismlauncher-upstream/**: Clean upstream copy (reference)
- **_project_minecraft/**: Your original launcher (backup)
## License
Based on PrismLauncher - licensed under GPL-3.0-only.
Your modifications maintain the same license.
## Credits
- **PrismLauncher Team**: Original launcher
- **Diegiwg**: Upstream fork base
- **racked.ru**: Custom theme and branding
- **Build System**: Custom portable cross-platform scripts
---
Project created: 2026-04-13
Based on: PrismLauncher upstream fork (latest commit as of date)
Build system: CMake 3.25+, Qt 6.5.3+

141
README.md Normal file
View file

@ -0,0 +1,141 @@
<div align="center">
# minecraft-launcher
**Privacy-first Minecraft launcher.**
No telemetry. No Microsoft account requirement. Runs smooth on hardware that stock Minecraft chokes on.
[![Linux](https://img.shields.io/badge/Linux-x64-black?style=flat-square&logo=linux&logoColor=white)](https://github.com/s8n-ru/minecraft-launcher/releases/latest)
[![Windows](https://img.shields.io/badge/Windows-x64-black?style=flat-square&logo=windows&logoColor=white)](https://github.com/s8n-ru/minecraft-launcher/releases/latest)
[![macOS](https://img.shields.io/badge/macOS-arm64-black?style=flat-square&logo=apple&logoColor=white)](https://github.com/s8n-ru/minecraft-launcher/releases/latest)
[![License: GPL-3.0](https://img.shields.io/badge/License-GPL_3.0-black?style=flat-square)](LICENSE)
[**Download**](https://github.com/s8n-ru/minecraft-launcher/releases/latest) · [Changelog](CHANGELOG.md) · [Audits](docs/)
<img alt="racked.ru launcher" src="docs/screenshots/launcher.png" width="55%">
</div>
---
## Why this fork exists
Stock Minecraft phones home. Stock launcher pushes Microsoft accounts. Stock client struggles on low-end machines.
This fork fixes all three.
| | Stock launcher | This fork |
|---|---|---|
| Telemetry | Yes | None |
| Microsoft account | Required | Optional, never enforced |
| News fetch on launch | Yes | Hidden, no startup call |
| Plays on weak hardware | Often won't | Yes |
| Window title | Mojang branding | `racked.ru launcher` |
Full diff: [CHANGELOG.md](CHANGELOG.md).
---
## Features
### Privacy
- **No telemetry, anywhere.** Audited every endpoint — see [docs/NETWORK_AUDIT.md](docs/NETWORK_AUDIT.md)
- **No accounts required.** Pick a username, play offline. Sign in later if you want
- **No analytics, no tracking.** Doesn't matter who you are
### Performance
- Tuned for low-end hardware
- Bundled Java 21 (no system install)
- Portable — all data in one folder, USB-friendly
### Functionality
- Modrinth, CurseForge, FTB, ATLauncher, Technic platforms
- Custom monochrome theme
- Hide news feed by default — no startup network call
---
## Download
Pre-built binaries for Linux, Windows, macOS:
→ [**Latest release**](https://github.com/s8n-ru/minecraft-launcher/releases/latest)
Linux:
```bash
tar xzf minecraft-launcher-linux-x64.tar.gz
cd minecraft-launcher
./bin/prismlauncher
```
Windows:
```
unzip minecraft-launcher-windows-x64.zip
cd minecraft-launcher
prismlauncher.exe
```
macOS (unsigned — right-click → Open → Open anyway):
```bash
unzip minecraft-launcher-macos-arm64.zip
cd minecraft-launcher
./prismlauncher.app/Contents/MacOS/prismlauncher
```
Pick a username on first launch. Done.
---
## Build from source
```bash
git clone https://github.com/s8n-ru/minecraft-launcher.git
cd minecraft-launcher
# Fedora 43
sudo dnf install cmake gcc-c++ ninja-build extra-cmake-modules \
qt6-qtbase-devel qt6-qttools-devel qt6-qtsvg-devel qt6-qtnetworkauth-devel \
libarchive-devel cmark-devel qrencode-devel tomlplusplus
# Ubuntu / Debian
sudo apt install cmake g++ ninja-build extra-cmake-modules \
qt6-base-dev qt6-tools-dev qt6-svg-dev libqt6networkauth6-dev \
libarchive-dev libcmark-dev libqrencode-dev libtomlplusplus-dev gamemode-dev libvulkan-dev
JAVA_HOME=/path/to/jdk-21 cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Release
cmake --build build -j$(nproc)
./build/prismlauncher
```
CI builds via [GitHub Actions](.github/workflows/build.yml) for all 3 platforms on every tag.
---
## Trust
This is open-source. Verify the privacy claims yourself:
- [docs/NETWORK_AUDIT.md](docs/NETWORK_AUDIT.md) — every network endpoint listed, telemetry verdict
- [docs/SETTINGS_AUDIT.md](docs/SETTINGS_AUDIT.md) — default-value diffs vs upstream
- [docs/BLOAT_AUDIT.md](docs/BLOAT_AUDIT.md) — what was stripped, why
You don't have to trust me. Read the source.
---
## Status
Personal project. No support guarantees. Bugs may bite. Use at own risk.
Pull requests welcome but not promised to merge.
---
## License
GPL-3.0-only. Per-file copyright headers preserved.
Based on [PrismLauncher](https://github.com/PrismLauncher/PrismLauncher) (GPL-3.0), itself a fork of [PolyMC](https://github.com/PolyMC/PolyMC) and [MultiMC](https://github.com/MultiMC/Launcher).

68
README_RELEASE.md Normal file
View file

@ -0,0 +1,68 @@
# Racked.ru PrismLauncher - Quick Start
## For Users (Download & Run)
### Windows
1. Download `racked-prismlauncher-*-windows-portable.zip`
2. Extract to any folder (even USB drive)
3. Run `prismlauncher.exe`
4. Enjoy your minimal black/red themed launcher!
### Linux
```bash
# Download
tar xzf racked-prismlauncher-*-linux-portable.tar.gz
cd Racked.ru-PrismLauncher-Linux-Portable
./run.sh
```
### macOS
```bash
# Download
tar xzf racked-prismlauncher-*-macos-portable.tar.gz
cd Racked.ru-PrismLauncher-macOS-Portable
./run.sh
```
## For Developers (Build from Source)
```bash
# Clone
git clone <repo-url>
cd prismlauncher-racked
# Build
bash scripts/build-all-platforms.sh
# Create release
bash scripts/create-release.sh 1.0.0
```
## Configuration
Your launcher configuration is stored in:
- `prismlauncher.cfg` (in the launcher directory for portable mode)
- `instances/` (your Minecraft instances)
- `cache/` (download cache)
All these files travel with the launcher in portable mode!
## Custom Theme Files
- `themes/racked.ru/theme.json` - Theme colors
- `themes/racked.ru/themeStyle.css` - Qt stylesheet
- `catpacks/racked_ru.png` - Background cat image
## Support
- Website: https://racked.ru/
- Issue Tracker: GitHub Issues
- Based on: PrismLauncher upstream fork (Diegiwg)
## Updating
To update to a newer version:
1. Download the new release
2. Backup your `instances/` folder and `prismlauncher.cfg`
3. Replace all other files
4. Restore your backup

168
RELEASE_CHECKLIST.md Normal file
View file

@ -0,0 +1,168 @@
# Racked.ru PrismLauncher - Release Checklist
## Pre-Release Verification
### Build Verification
- [ ] Windows build completes without errors
- [ ] Linux build completes without errors
- [ ] macOS build completes without errors
- [ ] All builds produce executable launcher
- [ ] Portable mode works (data stored locally)
- [ ] No missing DLLs or dependencies
### Theme Verification
- [ ] Application theme is racked.ru (black/red)
- [ ] Icon theme is flat_white
- [ ] Background shows racked_ru cat
- [ ] UI elements are readable
- [ ] No theme-related crashes
### Functionality Tests
- [ ] Launcher starts successfully
- [ ] Can create new instance
- [ ] Can launch Minecraft
- [ ] Settings persist between launches
- [ ] Portable mode stores data correctly
- [ ] No console errors on startup
### Size Verification
- [ ] Windows package is < 120MB
- [ ] Linux package is < 100MB
- [ ] macOS package is < 110MB
- [ ] Size reduction from full build is noticeable
### File Structure
- [ ] portable.txt present in root
- [ ] All Qt DLLs included (Windows)
- [ ] Platform plugins included
- [ ] Image format plugins included
- [ ] No unnecessary theme files
### Documentation
- [ ] BUILD_GUIDE.md is accurate
- [ ] README_RELEASE.md is clear
- [ ] PROJECT_SUMMARY.md covers all changes
- [ ] Build scripts are executable (Linux/macOS)
### Platform-Specific
#### Windows
- [ ] Runs on Windows 10/11
- [ ] No UAC errors
- [ ] Works from USB drive
- [ ] MSVC runtime DLLs included
- [ ] Qt bindings work correctly
#### Linux
- [ ] Runs on Ubuntu 22.04+
- [ ] Runs on Fedora 38+
- [ ] run.sh is executable
- [ ] LD_LIBRARY_PATH set correctly
- [ ] No missing shared libraries
#### macOS
- [ ] Runs on macOS 12+
- [ ] .app bundle is valid
- [ ] Codesigned (or instructions provided)
- [ ] No quarantine issues
- [ ] Intel and Apple Silicon support
## Release Creation
### Version Numbering
Use semantic versioning: MAJOR.MINOR.PATCH
- MAJOR: Breaking changes
- MINOR: New features
- PATCH: Bug fixes
### Create Release Package
```bash
# From project root
bash scripts/create-release.sh 1.0.0
```
### Verify Release Packages
- [ ] All three platform archives created
- [ ] Archives extract correctly
- [ ] Version number in filenames
- [ ] Release notes generated
- [ ] Archives are not corrupted
### Testing Release Packages
For each platform:
1. Extract archive to fresh directory
2. Run launcher
3. Verify theme loads
4. Create test instance
5. Verify portable mode
6. Delete test directory
## Distribution
### GitHub Release
1. Go to repository releases page
2. Create new release
3. Tag: v1.0.0
4. Title: "Racked.ru PrismLauncher v1.0.0"
5. Description: Copy from release notes
6. Upload all three archives
7. Mark as latest release
### Website (racked.ru)
Upload archives to your server:
```bash
# Example upload command
scp release/racked-prismlauncher-1.0.0-* user@racked.ru:/var/www/html/downloads/
```
### Update Download Links
Update https://racked.ru/ with new version links
## Post-Release
### Documentation
- [ ] Update CHANGELOG.md
- [ ] Update version in README
- [ ] Note any known issues
- [ ] Document platform-specific quirks
### Communication
- [ ] Announce on your website
- [ ] Update Discord/forums if applicable
- [ ] Tag upstream PrismLauncher if sharing back
### Backup
- [ ] Tag git repository
- [ ] Backup source code
- [ ] Backup build artifacts
- [ ] Keep release packages
## Known Limitations
These components were intentionally removed:
- Alternative icon themes (only flat_white kept)
- Alternative application themes (only racked.ru kept)
- Some built-in backgrounds (only racked_ru kept)
## Success Criteria
Release is successful when:
1. All three platforms build without errors
2. Launcher runs with correct theme
3. Portable mode works correctly
4. Package sizes are reasonable
5. No crash reports in first 24 hours
## Rollback Plan
If issues are found:
1. Keep previous version available
2. Document the issue
3. Fix in development branch
4. Increment patch version
5. Create new release
---
Last updated: 2026-04-13
Version: 1.0.0 (initial release)

View file

@ -0,0 +1,155 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <QObject>
#include "BuildConfig.h"
const Config BuildConfig;
Config::Config()
{
// Name and copyright
LAUNCHER_NAME = "@Launcher_Name@";
LAUNCHER_APP_BINARY_NAME = "@Launcher_APP_BINARY_NAME@";
LAUNCHER_DISPLAYNAME = "@Launcher_DisplayName@";
LAUNCHER_COPYRIGHT = "@Launcher_Copyright@";
LAUNCHER_DOMAIN = "@Launcher_Domain@";
LAUNCHER_CONFIGFILE = "@Launcher_ConfigFile@";
LAUNCHER_GIT = "@Launcher_Git@";
LAUNCHER_APPID = "@Launcher_AppID@";
LAUNCHER_SVGFILENAME = "@Launcher_SVGFileName@";
LAUNCHER_ENVNAME = "@Launcher_ENVName@";
USER_AGENT = "@Launcher_UserAgent@";
// Version information
VERSION_MAJOR = @Launcher_VERSION_MAJOR@;
VERSION_MINOR = @Launcher_VERSION_MINOR@;
VERSION_PATCH = @Launcher_VERSION_PATCH@;
BUILD_PLATFORM = "@Launcher_BUILD_PLATFORM@";
BUILD_ARTIFACT = "@Launcher_BUILD_ARTIFACT@";
BUILD_DATE = "@Launcher_BUILD_TIMESTAMP@";
UPDATER_GITHUB_REPO = "@Launcher_UPDATER_GITHUB_REPO@";
COMPILER_NAME = "@Launcher_COMPILER_NAME@";
COMPILER_VERSION = "@Launcher_COMPILER_VERSION@";
COMPILER_TARGET_SYSTEM = "@Launcher_COMPILER_TARGET_SYSTEM@";
COMPILER_TARGET_SYSTEM_VERSION = "@Launcher_COMPILER_TARGET_SYSTEM_VERSION@";
COMPILER_TARGET_SYSTEM_PROCESSOR = "@Launcher_COMPILER_TARGET_PROCESSOR@";
MAC_SPARKLE_PUB_KEY = "@MACOSX_SPARKLE_UPDATE_PUBLIC_KEY@";
MAC_SPARKLE_APPCAST_URL = "@MACOSX_SPARKLE_UPDATE_FEED_URL@";
if (!MAC_SPARKLE_PUB_KEY.isEmpty() && !MAC_SPARKLE_APPCAST_URL.isEmpty()) {
UPDATER_ENABLED = true;
} else if (!UPDATER_GITHUB_REPO.isEmpty() && !BUILD_ARTIFACT.isEmpty()) {
UPDATER_ENABLED = true;
}
#cmakedefine01 Launcher_ENABLE_JAVA_DOWNLOADER
JAVA_DOWNLOADER_ENABLED = Launcher_ENABLE_JAVA_DOWNLOADER;
GIT_COMMIT = "@Launcher_GIT_COMMIT@";
GIT_TAG = "@Launcher_GIT_TAG@";
GIT_REFSPEC = "@Launcher_GIT_REFSPEC@";
// Assume that builds outside of Git repos are "stable"
if (GIT_REFSPEC == QStringLiteral("GITDIR-NOTFOUND") || GIT_TAG == QStringLiteral("GITDIR-NOTFOUND") ||
GIT_REFSPEC == QStringLiteral("") || GIT_TAG == QStringLiteral("GIT-NOTFOUND")) {
GIT_REFSPEC = "refs/heads/stable";
GIT_TAG = versionString();
GIT_COMMIT = "";
}
if (GIT_REFSPEC.startsWith("refs/heads/")) {
VERSION_CHANNEL = GIT_REFSPEC;
VERSION_CHANNEL.remove("refs/heads/");
} else if (!GIT_COMMIT.isEmpty()) {
VERSION_CHANNEL = GIT_COMMIT.mid(0, 8);
} else {
VERSION_CHANNEL = "unknown";
}
NEWS_RSS_URL = "@Launcher_NEWS_RSS_URL@";
NEWS_OPEN_URL = "@Launcher_NEWS_OPEN_URL@";
WIKI_URL = "@Launcher_WIKI_URL@";
HELP_URL = "@Launcher_HELP_URL@";
LOGIN_CALLBACK_URL = "@Launcher_LOGIN_CALLBACK_URL@";
IMGUR_CLIENT_ID = "@Launcher_IMGUR_CLIENT_ID@";
MSA_CLIENT_ID = "@Launcher_MSA_CLIENT_ID@";
FLAME_API_KEY = "@Launcher_CURSEFORGE_API_KEY@";
META_URL = "@Launcher_META_URL@";
LEGACY_FMLLIBS_BASE_URL = "@Launcher_LEGACY_FMLLIBS_BASE_URL@";
GLFW_LIBRARY_NAME = "@Launcher_GLFW_LIBRARY_NAME@";
OPENAL_LIBRARY_NAME = "@Launcher_OPENAL_LIBRARY_NAME@";
BUG_TRACKER_URL = "@Launcher_BUG_TRACKER_URL@";
TRANSLATIONS_URL = "@Launcher_TRANSLATIONS_URL@";
TRANSLATION_FILES_URL = "@Launcher_TRANSLATION_FILES_URL@";
MATRIX_URL = "@Launcher_MATRIX_URL@";
DISCORD_URL = "@Launcher_DISCORD_URL@";
SUBREDDIT_URL = "@Launcher_SUBREDDIT_URL@";
}
QString Config::versionString() const
{
return QString("%1.%2.%3").arg(VERSION_MAJOR).arg(VERSION_MINOR).arg(VERSION_PATCH);
}
QString Config::printableVersionString() const
{
QString vstr = versionString();
// If the build is not a main release, append the channel
if (VERSION_CHANNEL != "stable" && GIT_TAG != vstr) {
vstr += "-" + VERSION_CHANNEL;
}
return vstr;
}
QString Config::compilerID() const
{
if (COMPILER_VERSION.isEmpty())
return COMPILER_NAME;
return QStringLiteral("%1 - %2").arg(COMPILER_NAME).arg(COMPILER_VERSION);
}
QString Config::systemID() const
{
return QStringLiteral("%1 %2 %3").arg(COMPILER_TARGET_SYSTEM, COMPILER_TARGET_SYSTEM_VERSION, COMPILER_TARGET_SYSTEM_PROCESSOR);
}

220
buildconfig/BuildConfig.h Normal file
View file

@ -0,0 +1,220 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org>
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
* Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QList>
#include <QString>
/**
* \brief The Config class holds all the build-time information passed from the build system.
*/
class Config {
public:
Config();
QString LAUNCHER_NAME;
QString LAUNCHER_APP_BINARY_NAME;
QString LAUNCHER_DISPLAYNAME;
QString LAUNCHER_COPYRIGHT;
QString LAUNCHER_DOMAIN;
QString LAUNCHER_CONFIGFILE;
QString LAUNCHER_GIT;
QString LAUNCHER_APPID;
QString LAUNCHER_SVGFILENAME;
QString LAUNCHER_ENVNAME;
/// The major version number.
int VERSION_MAJOR;
/// The minor version number.
int VERSION_MINOR;
/// The patch version number.
int VERSION_PATCH;
/**
* The version channel
* This is used by the updater to determine what channel the current version came from.
*/
QString VERSION_CHANNEL;
bool UPDATER_ENABLED = false;
bool JAVA_DOWNLOADER_ENABLED = false;
/// A short string identifying this build's platform or distribution.
QString BUILD_PLATFORM;
/// A short string identifying this build's valid artifacts int he updater. For example, "lin64" or "win32".
QString BUILD_ARTIFACT;
/// A string containing the build timestamp
QString BUILD_DATE;
/// A string identifying the compiler use to build
QString COMPILER_NAME;
/// A string identifying the compiler version used to build
QString COMPILER_VERSION;
/// A string identifying the compiler target system os
QString COMPILER_TARGET_SYSTEM;
/// A String identifying the compiler target system version
QString COMPILER_TARGET_SYSTEM_VERSION;
/// A String identifying the compiler target processor
QString COMPILER_TARGET_SYSTEM_PROCESSOR;
/// URL for the updater's channel
QString UPDATER_GITHUB_REPO;
/// The public key used to sign releases for the Sparkle updater appcast
QString MAC_SPARKLE_PUB_KEY;
/// URL for the Sparkle updater's appcast
QString MAC_SPARKLE_APPCAST_URL;
/// User-Agent to use.
QString USER_AGENT;
/// The git commit hash of this build
QString GIT_COMMIT;
/// The git tag of this build
QString GIT_TAG;
/// The git refspec of this build
QString GIT_REFSPEC;
/**
* This is used to fetch the news RSS feed.
* It defaults in CMakeLists.txt to "https://multimc.org/rss.xml"
*/
QString NEWS_RSS_URL;
/**
* URL that gets opened when the user clicks "More News"
*/
QString NEWS_OPEN_URL;
/**
* URL that gets opened when the user clicks 'Launcher Help'
*/
QString WIKI_URL;
/**
* URL (with arg %1 to be substituted with page-id) that gets opened when the user requests help in a dialog window
*/
QString HELP_URL;
/**
* URL that gets opened when the user succesfully logins.
*/
QString LOGIN_CALLBACK_URL;
/**
* Client ID you can get from Imgur when you register an application
*/
QString IMGUR_CLIENT_ID;
/**
* Client ID you can get from Microsoft Identity Platform when you register an application
*/
QString MSA_CLIENT_ID;
/**
* Client API key for CurseForge
*/
QString FLAME_API_KEY;
/**
* Metadata repository URL prefix
*/
QString META_URL;
QString GLFW_LIBRARY_NAME;
QString OPENAL_LIBRARY_NAME;
QString BUG_TRACKER_URL;
QString TRANSLATIONS_URL;
QString MATRIX_URL;
QString DISCORD_URL;
QString SUBREDDIT_URL;
QString DEFAULT_RESOURCE_BASE = "https://resources.download.minecraft.net/";
QString LIBRARY_BASE = "https://libraries.minecraft.net/";
QString IMGUR_BASE_URL = "https://api.imgur.com/3/";
QString LEGACY_FMLLIBS_BASE_URL;
QString TRANSLATION_FILES_URL;
QString FTB_API_BASE_URL = "https://api.feed-the-beast.com/v1/modpacks/public";
QString LEGACY_FTB_CDN_BASE_URL = "https://dist.creeper.host/FTB2/";
QString ATL_DOWNLOAD_SERVER_URL = "https://download.nodecdn.net/containers/atl/";
QString ATL_API_BASE_URL = "https://api.atlauncher.com/v1/";
QString TECHNIC_API_BASE_URL = "https://api.technicpack.net/";
/**
* The build that is reported to the Technic API.
*/
QString TECHNIC_API_BUILD = "multimc";
QString MODRINTH_STAGING_URL = "https://staging-api.modrinth.com/v2";
QString MODRINTH_PROD_URL = "https://api.modrinth.com/v2";
QStringList MODRINTH_MRPACK_HOSTS{ "cdn.modrinth.com", "github.com", "raw.githubusercontent.com", "gitlab.com" };
QString FLAME_BASE_URL = "https://api.curseforge.com/v1";
QString versionString() const;
/**
* \brief Converts the Version to a string.
* \return The version number in string format (major.minor.revision.build).
*/
QString printableVersionString() const;
/**
* \brief Compiler ID String
* \return a string of the form "Name - Version" of just "Name" if the version is empty
*/
QString compilerID() const;
/**
* \brief System ID String
* \return a string of the form "OS Verison Processor"
*/
QString systemID() const;
};
extern const Config BuildConfig;

View file

@ -0,0 +1,11 @@
######## Configure the file with build properties ########
configure_file("${CMAKE_CURRENT_SOURCE_DIR}/BuildConfig.cpp.in" "${CMAKE_CURRENT_BINARY_DIR}/BuildConfig.cpp")
add_library(BuildConfig STATIC
BuildConfig.h
${CMAKE_CURRENT_BINARY_DIR}/BuildConfig.cpp
)
target_link_libraries(BuildConfig Qt${QT_VERSION_MAJOR}::Core)
target_include_directories(BuildConfig PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}")

View file

@ -0,0 +1,284 @@
# - Returns a version string from Git
#
# These functions force a re-configure on each git commit so that you can
# trust the values of the variables in your build system.
#
# get_git_head_revision(<refspecvar> <hashvar> [ALLOW_LOOKING_ABOVE_CMAKE_SOURCE_DIR])
#
# Returns the refspec and sha hash of the current head revision
#
# git_describe(<var> [<additional arguments to git describe> ...])
#
# Returns the results of git describe on the source tree, and adjusting
# the output so that it tests false if an error occurs.
#
# git_describe_working_tree(<var> [<additional arguments to git describe> ...])
#
# Returns the results of git describe on the working tree (--dirty option),
# and adjusting the output so that it tests false if an error occurs.
#
# git_get_exact_tag(<var> [<additional arguments to git describe> ...])
#
# Returns the results of git describe --exact-match on the source tree,
# and adjusting the output so that it tests false if there was no exact
# matching tag.
#
# git_local_changes(<var>)
#
# Returns either "CLEAN" or "DIRTY" with respect to uncommitted changes.
# Uses the return code of "git diff-index --quiet HEAD --".
# Does not regard untracked files.
#
# Requires CMake 2.6 or newer (uses the 'function' command)
#
# Original Author:
# 2009-2020 Ryan Pavlik <ryan.pavlik@gmail.com> <abiryan@ryand.net>
# http://academic.cleardefinition.com
#
# Copyright 2009-2013, Iowa State University.
# Copyright 2013-2020, Ryan Pavlik
# Copyright 2013-2020, Contributors
# SPDX-License-Identifier: BSL-1.0
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
if(__get_git_revision_description)
return()
endif()
set(__get_git_revision_description YES)
# We must run the following at "include" time, not at function call time,
# to find the path to this module rather than the path to a calling list file
get_filename_component(_gitdescmoddir ${CMAKE_CURRENT_LIST_FILE} PATH)
# Function _git_find_closest_git_dir finds the next closest .git directory
# that is part of any directory in the path defined by _start_dir.
# The result is returned in the parent scope variable whose name is passed
# as variable _git_dir_var. If no .git directory can be found, the
# function returns an empty string via _git_dir_var.
#
# Example: Given a path C:/bla/foo/bar and assuming C:/bla/.git exists and
# neither foo nor bar contain a file/directory .git. This wil return
# C:/bla/.git
#
function(_git_find_closest_git_dir _start_dir _git_dir_var)
set(cur_dir "${_start_dir}")
set(git_dir "${_start_dir}/.git")
while(NOT EXISTS "${git_dir}")
# .git dir not found, search parent directories
set(git_previous_parent "${cur_dir}")
get_filename_component(cur_dir "${cur_dir}" DIRECTORY)
if(cur_dir STREQUAL git_previous_parent)
# We have reached the root directory, we are not in git
set(${_git_dir_var}
""
PARENT_SCOPE)
return()
endif()
set(git_dir "${cur_dir}/.git")
endwhile()
set(${_git_dir_var}
"${git_dir}"
PARENT_SCOPE)
endfunction()
function(get_git_head_revision _refspecvar _hashvar)
_git_find_closest_git_dir("${CMAKE_CURRENT_SOURCE_DIR}" GIT_DIR)
if("${ARGN}" STREQUAL "ALLOW_LOOKING_ABOVE_CMAKE_SOURCE_DIR")
set(ALLOW_LOOKING_ABOVE_CMAKE_SOURCE_DIR TRUE)
else()
set(ALLOW_LOOKING_ABOVE_CMAKE_SOURCE_DIR FALSE)
endif()
if(NOT "${GIT_DIR}" STREQUAL "")
file(RELATIVE_PATH _relative_to_source_dir "${CMAKE_SOURCE_DIR}"
"${GIT_DIR}")
if("${_relative_to_source_dir}" MATCHES "[.][.]" AND NOT ALLOW_LOOKING_ABOVE_CMAKE_SOURCE_DIR)
# We've gone above the CMake root dir.
set(GIT_DIR "")
endif()
endif()
if("${GIT_DIR}" STREQUAL "")
set(${_refspecvar}
"GITDIR-NOTFOUND"
PARENT_SCOPE)
set(${_hashvar}
"GITDIR-NOTFOUND"
PARENT_SCOPE)
return()
endif()
# Check if the current source dir is a git submodule or a worktree.
# In both cases .git is a file instead of a directory.
#
if(NOT IS_DIRECTORY ${GIT_DIR})
# The following git command will return a non empty string that
# points to the super project working tree if the current
# source dir is inside a git submodule.
# Otherwise the command will return an empty string.
#
execute_process(
COMMAND "${GIT_EXECUTABLE}" rev-parse
--show-superproject-working-tree
WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
OUTPUT_VARIABLE out
ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE)
if(NOT "${out}" STREQUAL "")
# If out is empty, GIT_DIR/CMAKE_CURRENT_SOURCE_DIR is in a submodule
file(READ ${GIT_DIR} submodule)
string(REGEX REPLACE "gitdir: (.*)$" "\\1" GIT_DIR_RELATIVE
${submodule})
string(STRIP ${GIT_DIR_RELATIVE} GIT_DIR_RELATIVE)
get_filename_component(SUBMODULE_DIR ${GIT_DIR} PATH)
get_filename_component(GIT_DIR ${SUBMODULE_DIR}/${GIT_DIR_RELATIVE}
ABSOLUTE)
set(HEAD_SOURCE_FILE "${GIT_DIR}/HEAD")
else()
# GIT_DIR/CMAKE_CURRENT_SOURCE_DIR is in a worktree
file(READ ${GIT_DIR} worktree_ref)
# The .git directory contains a path to the worktree information directory
# inside the parent git repo of the worktree.
#
string(REGEX REPLACE "gitdir: (.*)$" "\\1" git_worktree_dir
${worktree_ref})
string(STRIP ${git_worktree_dir} git_worktree_dir)
_git_find_closest_git_dir("${git_worktree_dir}" GIT_DIR)
set(HEAD_SOURCE_FILE "${git_worktree_dir}/HEAD")
endif()
else()
set(HEAD_SOURCE_FILE "${GIT_DIR}/HEAD")
endif()
set(GIT_DATA "${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/git-data")
if(NOT EXISTS "${GIT_DATA}")
file(MAKE_DIRECTORY "${GIT_DATA}")
endif()
if(NOT EXISTS "${HEAD_SOURCE_FILE}")
return()
endif()
set(HEAD_FILE "${GIT_DATA}/HEAD")
configure_file("${HEAD_SOURCE_FILE}" "${HEAD_FILE}" COPYONLY)
configure_file("${_gitdescmoddir}/GetGitRevisionDescription.cmake.in"
"${GIT_DATA}/grabRef.cmake" @ONLY)
include("${GIT_DATA}/grabRef.cmake")
set(${_refspecvar}
"${HEAD_REF}"
PARENT_SCOPE)
set(${_hashvar}
"${HEAD_HASH}"
PARENT_SCOPE)
endfunction()
function(git_describe _var)
if(NOT GIT_FOUND)
find_package(Git QUIET)
endif()
get_git_head_revision(refspec hash)
if(NOT GIT_FOUND)
set(${_var}
"GIT-NOTFOUND"
PARENT_SCOPE)
return()
endif()
if(NOT hash)
set(${_var}
"HEAD-HASH-NOTFOUND"
PARENT_SCOPE)
return()
endif()
# TODO sanitize
#if((${ARGN}" MATCHES "&&") OR
# (ARGN MATCHES "||") OR
# (ARGN MATCHES "\\;"))
# message("Please report the following error to the project!")
# message(FATAL_ERROR "Looks like someone's doing something nefarious with git_describe! Passed arguments ${ARGN}")
#endif()
#message(STATUS "Arguments to execute_process: ${ARGN}")
execute_process(
COMMAND "${GIT_EXECUTABLE}" describe --tags --always ${hash} ${ARGN}
WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
RESULT_VARIABLE res
OUTPUT_VARIABLE out
ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE)
if(NOT res EQUAL 0)
set(out "${out}-${res}-NOTFOUND")
endif()
set(${_var}
"${out}"
PARENT_SCOPE)
endfunction()
function(git_describe_working_tree _var)
if(NOT GIT_FOUND)
find_package(Git QUIET)
endif()
if(NOT GIT_FOUND)
set(${_var}
"GIT-NOTFOUND"
PARENT_SCOPE)
return()
endif()
execute_process(
COMMAND "${GIT_EXECUTABLE}" describe --dirty ${ARGN}
WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
RESULT_VARIABLE res
OUTPUT_VARIABLE out
ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE)
if(NOT res EQUAL 0)
set(out "${out}-${res}-NOTFOUND")
endif()
set(${_var}
"${out}"
PARENT_SCOPE)
endfunction()
function(git_get_exact_tag _var)
git_describe(out --exact-match ${ARGN})
set(${_var}
"${out}"
PARENT_SCOPE)
endfunction()
function(git_local_changes _var)
if(NOT GIT_FOUND)
find_package(Git QUIET)
endif()
get_git_head_revision(refspec hash)
if(NOT GIT_FOUND)
set(${_var}
"GIT-NOTFOUND"
PARENT_SCOPE)
return()
endif()
if(NOT hash)
set(${_var}
"HEAD-HASH-NOTFOUND"
PARENT_SCOPE)
return()
endif()
execute_process(
COMMAND "${GIT_EXECUTABLE}" diff-index --quiet HEAD --
WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
RESULT_VARIABLE res
OUTPUT_VARIABLE out
ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE)
if(res EQUAL 0)
set(${_var}
"CLEAN"
PARENT_SCOPE)
else()
set(${_var}
"DIRTY"
PARENT_SCOPE)
endif()
endfunction()

View file

@ -0,0 +1,43 @@
#
# Internal file for GetGitRevisionDescription.cmake
#
# Requires CMake 2.6 or newer (uses the 'function' command)
#
# Original Author:
# 2009-2010 Ryan Pavlik <rpavlik@iastate.edu> <abiryan@ryand.net>
# http://academic.cleardefinition.com
# Iowa State University HCI Graduate Program/VRAC
#
# Copyright 2009-2012, Iowa State University
# Copyright 2011-2015, Contributors
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
# SPDX-License-Identifier: BSL-1.0
set(HEAD_HASH)
file(READ "@HEAD_FILE@" HEAD_CONTENTS LIMIT 1024)
string(STRIP "${HEAD_CONTENTS}" HEAD_CONTENTS)
if(HEAD_CONTENTS MATCHES "ref")
# named branch
string(REPLACE "ref: " "" HEAD_REF "${HEAD_CONTENTS}")
if(EXISTS "@GIT_DIR@/${HEAD_REF}")
configure_file("@GIT_DIR@/${HEAD_REF}" "@GIT_DATA@/head-ref" COPYONLY)
else()
configure_file("@GIT_DIR@/packed-refs" "@GIT_DATA@/packed-refs" COPYONLY)
file(READ "@GIT_DATA@/packed-refs" PACKED_REFS)
if(${PACKED_REFS} MATCHES "([0-9a-z]*) ${HEAD_REF}")
set(HEAD_HASH "${CMAKE_MATCH_1}")
endif()
endif()
else()
# detached HEAD
configure_file("@GIT_DIR@/HEAD" "@GIT_DATA@/head-ref" COPYONLY)
endif()
if(NOT HEAD_HASH)
file(READ "@GIT_DATA@/head-ref" HEAD_HASH LIMIT 1024)
string(STRIP "${HEAD_HASH}" HEAD_HASH)
endif()

37
cmake/GitFunctions.cmake Normal file
View file

@ -0,0 +1,37 @@
if(__GITFUNCTIONS_CMAKE__)
return()
endif()
set(__GITFUNCTIONS_CMAKE__ TRUE)
find_package(Git QUIET)
include(CMakeParseArguments)
if(GIT_FOUND)
function(git_run)
set(oneValueArgs OUTPUT_VAR DEFAULT)
set(multiValueArgs COMMAND)
cmake_parse_arguments(GIT_RUN "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
execute_process(COMMAND ${GIT_EXECUTABLE} ${GIT_RUN_COMMAND}
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
RESULT_VARIABLE GIT_RESULTVAR
OUTPUT_VARIABLE GIT_OUTVAR
OUTPUT_STRIP_TRAILING_WHITESPACE
)
if(GIT_RESULTVAR EQUAL 0)
set(${GIT_RUN_OUTPUT_VAR} "${GIT_OUTVAR}" PARENT_SCOPE)
else()
set(${GIT_RUN_OUTPUT_VAR} ${GIT_RUN_DEFAULT})
message(STATUS "Failed to run Git: ${GIT_OUTVAR}")
endif()
endfunction()
else()
function(git_run)
set(oneValueArgs OUTPUT_VAR DEFAULT)
set(multiValueArgs COMMAND)
cmake_parse_arguments(GIT_RUN "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
set(${GIT_RUN_OUTPUT_VAR} ${GIT_RUN_DEFAULT})
endfunction(git_run)
endif()

View file

@ -0,0 +1,99 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSCameraUsageDescription</key>
<string>A Minecraft mod wants to access your camera.</string>
<key>NSMicrophoneUsageDescription</key>
<string>A Minecraft mod wants to access your microphone.</string>
<key>NSDownloadsFolderUsageDescription</key>
<string>${Launcher_DisplayName} uses access to your Downloads folder to help you more quickly add mods that can't be automatically downloaded to your instance. You can change where ${Launcher_DisplayName} scans for downloaded mods in Settings or the prompt that appears.</string>
<key>NSLocalNetworkUsageDescription</key>
<string>Minecraft uses the local network to find and connect to LAN servers.</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
<key>NSHighResolutionCapable</key>
<string>True</string>
<key>CFBundleDevelopmentRegion</key>
<string>English</string>
<key>CFBundleExecutable</key>
<string>${MACOSX_BUNDLE_EXECUTABLE_NAME}</string>
<key>CFBundleGetInfoString</key>
<string>${MACOSX_BUNDLE_INFO_STRING}</string>
<key>CFBundleIconFile</key>
<string>${Launcher_Name}</string>
<key>CFBundleIconName</key>
<string>${Launcher_Name}</string>
<key>CFBundleIdentifier</key>
<string>${MACOSX_BUNDLE_GUI_IDENTIFIER}</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleLongVersionString</key>
<string>${MACOSX_BUNDLE_LONG_VERSION_STRING}</string>
<key>CFBundleName</key>
<string>${MACOSX_BUNDLE_BUNDLE_NAME}</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>${MACOSX_BUNDLE_SHORT_VERSION_STRING}</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>${MACOSX_BUNDLE_BUNDLE_VERSION}</string>
<key>CSResourcesFileMapped</key>
<true/>
<key>LSRequiresCarbon</key>
<true/>
<key>LSApplicationCategoryType</key>
<string>public.app-category.games</string>
<key>NSHumanReadableCopyright</key>
<string>${MACOSX_BUNDLE_COPYRIGHT}</string>
<key>SUPublicEDKey</key>
<string>${MACOSX_SPARKLE_UPDATE_PUBLIC_KEY}</string>
<key>SUFeedURL</key>
<string>${MACOSX_SPARKLE_UPDATE_FEED_URL}</string>
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeExtensions</key>
<array>
<string>zip</string>
<string>mrpack</string>
</array>
<key>CFBundleTypeName</key>
<string>${Launcher_DisplayName} instance</string>
<key>CFBundleTypeOSTypes</key>
<array>
<string>TEXT</string>
<string>utxt</string>
<string>TUTX</string>
<string>****</string>
</array>
<key>CFBundleTypeRole</key>
<string>Viewer</string>
<key>LSHandlerRank</key>
<string>Alternate</string>
</dict>
</array>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>Curseforge</string>
<key>CFBundleURLSchemes</key>
<array>
<string>curseforge</string>
</array>
</dict>
<dict>
<key>CFBundleURLName</key>
<string>${Launcher_Name}</string>
<key>CFBundleURLSchemes</key>
<array>
<string>prismlauncher</string>
<string>${MACOSX_BUNDLE_EXECUTABLE_NAME}</string>
</array>
</dict>
</array>
</dict>
</plist>

View file

@ -0,0 +1,3 @@
The only difference between this and the upstream vcpkg port is the addition of `universal-osx.patch`. It's very annoying we need to bundle this entire tree to do that.
-@getchoo

View file

@ -0,0 +1,13 @@
diff --git a/mesonbuild/cmake/toolchain.py b/mesonbuild/cmake/toolchain.py
index 11a00be5d..89ae490ff 100644
--- a/mesonbuild/cmake/toolchain.py
+++ b/mesonbuild/cmake/toolchain.py
@@ -202,7 +202,7 @@ class CMakeToolchain:
@staticmethod
def is_cmdline_option(compiler: 'Compiler', arg: str) -> bool:
if compiler.get_argument_syntax() == 'msvc':
- return arg.startswith('/')
+ return arg.startswith(('/','-'))
else:
if os.path.basename(compiler.get_exe()) == 'zig' and arg in {'ar', 'cc', 'c++', 'dlltool', 'lib', 'ranlib', 'objcopy', 'rc'}:
return True

View file

@ -0,0 +1,45 @@
diff --git a/mesonbuild/dependencies/python.py b/mesonbuild/dependencies/python.py
index 883a29a..d9a82af 100644
--- a/mesonbuild/dependencies/python.py
+++ b/mesonbuild/dependencies/python.py
@@ -232,8 +232,10 @@ class _PythonDependencyBase(_Base):
else:
if self.is_freethreaded:
libpath = Path('libs') / f'python{vernum}t.lib'
+ libpath = Path('libs') / f'..' / f'..' / f'..' / f'lib' / f'python{vernum}t.lib'
else:
libpath = Path('libs') / f'python{vernum}.lib'
+ libpath = Path('libs') / f'..' / f'..' / f'..' / f'lib' / f'python{vernum}.lib'
# For a debug build, pyconfig.h may force linking with
# pythonX_d.lib (see meson#10776). This cannot be avoided
# and won't work unless we also have a debug build of
@@ -250,6 +252,8 @@ class _PythonDependencyBase(_Base):
vscrt = self.env.coredata.optstore.get_value('b_vscrt')
if vscrt in {'mdd', 'mtd', 'from_buildtype', 'static_from_buildtype'}:
vscrt_debug = True
+ if is_debug_build:
+ libpath = Path('libs') / f'..' / f'..' / f'..' / f'debug/lib' / f'python{vernum}_d.lib'
if is_debug_build and vscrt_debug and not self.variables.get('Py_DEBUG'):
mlog.warning(textwrap.dedent('''\
Using a debug build type with MSVC or an MSVC-compatible compiler
@@ -350,9 +354,10 @@ class PythonSystemDependency(SystemDependency, _PythonDependencyBase):
self.is_found = True
# compile args
+ verdot = self.variables.get('py_version_short')
inc_paths = mesonlib.OrderedSet([
self.variables.get('INCLUDEPY'),
- self.paths.get('include'),
+ self.paths.get('include') + f'/../../../include/python${verdot}',
self.paths.get('platinclude')])
self.compile_args += ['-I' + path for path in inc_paths if path]
@@ -416,7 +421,7 @@ def python_factory(env: 'Environment', for_machine: 'MachineChoice',
candidates.append(functools.partial(wrap_in_pythons_pc_dir, pkg_name, env, kwargs, installation))
# We only need to check both, if a python install has a LIBPC. It might point to the wrong location,
# e.g. relocated / cross compilation, but the presence of LIBPC indicates we should definitely look for something.
- if pkg_libdir is not None:
+ if True or pkg_libdir is not None:
candidates.append(functools.partial(PythonPkgConfigDependency, pkg_name, env, kwargs, installation))
else:
candidates.append(functools.partial(PkgConfigDependency, 'python3', env, kwargs))

View file

@ -0,0 +1,52 @@
From a16ec8b0fb6d7035b669a13edd4d97ff0c307a0b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Martin=20D=C3=B8rum?= <martid0311@gmail.com>
Date: Fri, 2 May 2025 10:56:28 +0200
Subject: [PATCH] cpp: fix _LIBCPP_ENABLE_ASSERTIONS warning
libc++ deprecated _LIBCPP_ENABLE_ASSERTIONS from version 18.
However, the libc++ shipped with Apple Clang backported that
deprecation in version 17 already,
which is the version which Apple currently ships for macOS.
This PR changes the _LIBCPP_ENABLE_ASSERTIONS deprecation check
to use version ">=17" on Apple Clang.
---
mesonbuild/compilers/cpp.py | 12 ++++++++++--
1 file changed, 10 insertions(+), 2 deletions(-)
diff --git a/mesonbuild/compilers/cpp.py b/mesonbuild/compilers/cpp.py
index 01b9bb9fa34f..f7dc150e8608 100644
--- a/mesonbuild/compilers/cpp.py
+++ b/mesonbuild/compilers/cpp.py
@@ -311,6 +311,9 @@ def get_option_link_args(self, target: 'BuildTarget', env: 'Environment', subpro
return libs
return []
+ def is_libcpp_enable_assertions_deprecated(self) -> bool:
+ return version_compare(self.version, ">=18")
+
def get_assert_args(self, disable: bool, env: 'Environment') -> T.List[str]:
if disable:
return ['-DNDEBUG']
@@ -323,7 +326,7 @@ def get_assert_args(self, disable: bool, env: 'Environment') -> T.List[str]:
if self.language_stdlib_provider(env) == 'stdc++':
return ['-D_GLIBCXX_ASSERTIONS=1']
else:
- if version_compare(self.version, '>=18'):
+ if self.is_libcpp_enable_assertions_deprecated():
return ['-D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_FAST']
elif version_compare(self.version, '>=15'):
return ['-D_LIBCPP_ENABLE_ASSERTIONS=1']
@@ -343,7 +346,12 @@ class ArmLtdClangCPPCompiler(ClangCPPCompiler):
class AppleClangCPPCompiler(AppleCompilerMixin, AppleCPPStdsMixin, ClangCPPCompiler):
- pass
+ def is_libcpp_enable_assertions_deprecated(self) -> bool:
+ # Upstream libc++ deprecated _LIBCPP_ENABLE_ASSERTIONS
+ # in favor of _LIBCPP_HARDENING_MODE from version 18 onwards,
+ # but Apple Clang 17's libc++ has back-ported that change.
+ # See: https://github.com/mesonbuild/meson/issues/14440
+ return version_compare(self.version, ">=17")
class EmscriptenCPPCompiler(EmscriptenMixin, ClangCPPCompiler):

View file

@ -0,0 +1,5 @@
file(MAKE_DIRECTORY "${CURRENT_PACKAGES_DIR}/tools/meson")
file(INSTALL "${SOURCE_PATH}/meson.py"
"${SOURCE_PATH}/mesonbuild"
DESTINATION "${CURRENT_PACKAGES_DIR}/tools/meson"
)

View file

@ -0,0 +1,13 @@
diff --git a/mesonbuild/dependencies/misc.py b/mesonbuild/dependencies/misc.py
--- a/mesonbuild/dependencies/misc.py
+++ b/mesonbuild/dependencies/misc.py
@@ -593,7 +593,8 @@ iconv_factory = DependencyFactory(
packages['intl'] = intl_factory = DependencyFactory(
'intl',
+ [DependencyMethods.BUILTIN, DependencyMethods.SYSTEM, DependencyMethods.CMAKE],
+ cmake_name='Intl',
- [DependencyMethods.BUILTIN, DependencyMethods.SYSTEM],
builtin_class=IntlBuiltinDependency,
system_class=IntlSystemDependency,
)

View file

@ -0,0 +1,43 @@
[binaries]
cmake = ['@CMAKE_COMMAND@']
ninja = ['@NINJA@']
pkg-config = ['@PKGCONFIG@']
@MESON_MT@
@MESON_AR@
@MESON_RC@
@MESON_C@
@MESON_C_LD@
@MESON_CXX@
@MESON_CXX_LD@
@MESON_OBJC@
@MESON_OBJC_LD@
@MESON_OBJCPP@
@MESON_OBJCPP_LD@
@MESON_FC@
@MESON_FC_LD@
@MESON_WINDRES@
@MESON_ADDITIONAL_BINARIES@
[properties]
cmake_toolchain_file = '@SCRIPTS@/buildsystems/vcpkg.cmake'
@MESON_ADDITIONAL_PROPERTIES@
[cmake]
CMAKE_BUILD_TYPE = '@MESON_CMAKE_BUILD_TYPE@'
VCPKG_TARGET_TRIPLET = '@TARGET_TRIPLET@'
VCPKG_HOST_TRIPLET = '@_HOST_TRIPLET@'
VCPKG_CHAINLOAD_TOOLCHAIN_FILE = '@VCPKG_CHAINLOAD_TOOLCHAIN_FILE@'
VCPKG_CRT_LINKAGE = '@VCPKG_CRT_LINKAGE@'
_VCPKG_INSTALLED_DIR = '@_VCPKG_INSTALLED_DIR@'
@MESON_HOST_MACHINE@
@MESON_BUILD_MACHINE@
[built-in options]
default_library = '@MESON_DEFAULT_LIBRARY@'
werror = false
@MESON_CFLAGS@
@MESON_CXXFLAGS@
@MESON_FCFLAGS@
@MESON_OBJCFLAGS@
@MESON_OBJCPPFLAGS@
# b_vscrt
@MESON_VSCRT_LINKAGE@
# c_winlibs/cpp_winlibs
@MESON_WINLIBS@

View file

@ -0,0 +1,45 @@
# This port represents a dependency on the Meson build system.
# In the future, it is expected that this port acquires and installs Meson.
# Currently is used in ports that call vcpkg_find_acquire_program(MESON) in order to force rebuilds.
set(VCPKG_POLICY_CMAKE_HELPER_PORT enabled)
set(patches
meson-intl.patch
adjust-python-dep.patch
adjust-args.patch
remove-freebsd-pcfile-specialization.patch
fix-libcpp-enable-assertions.patch # https://github.com/mesonbuild/meson/pull/14548, Remove in 1.8.3
universal-osx.patch # NOTE(@getchoo): THIS IS THE ONLY CHANGE NEEDED FOR PRISM
)
set(scripts
vcpkg-port-config.cmake
vcpkg_configure_meson.cmake
vcpkg_install_meson.cmake
meson.template.in
)
set(to_hash
"${CMAKE_CURRENT_LIST_DIR}/vcpkg.json"
"${CMAKE_CURRENT_LIST_DIR}/portfile.cmake"
)
foreach(file IN LISTS patches scripts)
set(filepath "${CMAKE_CURRENT_LIST_DIR}/${file}")
list(APPEND to_hash "${filepath}")
file(COPY "${filepath}" DESTINATION "${CURRENT_PACKAGES_DIR}/share/${PORT}")
endforeach()
set(meson_path_hash "")
foreach(filepath IN LISTS to_hash)
file(SHA1 "${filepath}" to_append)
string(APPEND meson_path_hash "${to_append}")
endforeach()
string(SHA512 meson_path_hash "${meson_path_hash}")
string(SUBSTRING "${meson_path_hash}" 0 6 MESON_SHORT_HASH)
list(TRANSFORM patches REPLACE [[^(..*)$]] [["${CMAKE_CURRENT_LIST_DIR}/\0"]])
list(JOIN patches "\n " PATCHES)
configure_file("${CMAKE_CURRENT_LIST_DIR}/vcpkg-port-config.cmake" "${CURRENT_PACKAGES_DIR}/share/${PORT}/vcpkg-port-config.cmake" @ONLY)
vcpkg_install_copyright(FILE_LIST "${VCPKG_ROOT_DIR}/LICENSE.txt")
include("${CURRENT_PACKAGES_DIR}/share/${PORT}/vcpkg-port-config.cmake")

View file

@ -0,0 +1,23 @@
diff --git a/mesonbuild/modules/pkgconfig.py b/mesonbuild/modules/pkgconfig.py
index cc0450a52..13501466d 100644
--- a/mesonbuild/modules/pkgconfig.py
+++ b/mesonbuild/modules/pkgconfig.py
@@ -701,16 +701,8 @@ class PkgConfigModule(NewExtensionModule):
pcfile = filebase + '.pc'
pkgroot = pkgroot_name = kwargs['install_dir'] or default_install_dir
if pkgroot is None:
- m = state.environment.machines.host
- if m.is_freebsd():
- pkgroot = os.path.join(_as_str(state.environment.coredata.optstore.get_value_for(OptionKey('prefix'))), 'libdata', 'pkgconfig')
- pkgroot_name = os.path.join('{prefix}', 'libdata', 'pkgconfig')
- elif m.is_haiku():
- pkgroot = os.path.join(_as_str(state.environment.coredata.optstore.get_value_for(OptionKey('prefix'))), 'develop', 'lib', 'pkgconfig')
- pkgroot_name = os.path.join('{prefix}', 'develop', 'lib', 'pkgconfig')
- else:
- pkgroot = os.path.join(_as_str(state.environment.coredata.optstore.get_value_for(OptionKey('libdir'))), 'pkgconfig')
- pkgroot_name = os.path.join('{libdir}', 'pkgconfig')
+ pkgroot = os.path.join(_as_str(state.environment.coredata.optstore.get_value_for(OptionKey('libdir'))), 'pkgconfig')
+ pkgroot_name = os.path.join('{libdir}', 'pkgconfig')
relocatable = state.get_option('pkgconfig.relocatable')
self._generate_pkgconfig_file(state, deps, subdirs, name, description, url,
version, pcfile, conflicts, variables,

View file

@ -0,0 +1,16 @@
diff --git a/mesonbuild/compilers/detect.py b/mesonbuild/compilers/detect.py
index f57957f0b..a72e72a0b 100644
--- a/mesonbuild/compilers/detect.py
+++ b/mesonbuild/compilers/detect.py
@@ -1472,6 +1472,11 @@ def _get_clang_compiler_defines(compiler: T.List[str], lang: str) -> T.Dict[str,
"""
from .mixins.clang import clang_lang_map
+ # Filter out `-arch` flags passed to the compiler for Universal Binaries
+ # https://github.com/mesonbuild/meson/issues/5290
+ # https://github.com/mesonbuild/meson/issues/8206
+ compiler = [arg for i, arg in enumerate(compiler) if not (i > 0 and compiler[i - 1] == "-arch") and not arg == "-arch"]
+
def _try_obtain_compiler_defines(args: T.List[str]) -> str:
mlog.debug(f'Running command: {join_args(args)}')
p, output, error = Popen_safe(compiler + args, write='', stdin=subprocess.PIPE)

View file

@ -0,0 +1,62 @@
include("${CURRENT_HOST_INSTALLED_DIR}/share/vcpkg-cmake-get-vars/vcpkg-port-config.cmake")
# Overwrite builtin scripts
include("${CMAKE_CURRENT_LIST_DIR}/vcpkg_configure_meson.cmake")
include("${CMAKE_CURRENT_LIST_DIR}/vcpkg_install_meson.cmake")
set(meson_short_hash @MESON_SHORT_HASH@)
# Setup meson:
set(program MESON)
set(program_version @VERSION@)
set(program_name meson)
set(search_names meson meson.py)
set(ref "${program_version}")
set(path_to_search "${DOWNLOADS}/tools/meson-${program_version}-${meson_short_hash}")
set(download_urls "https://github.com/mesonbuild/meson/archive/${ref}.tar.gz")
set(download_filename "meson-${ref}.tar.gz")
set(download_sha512 bd2e65f0863d9cb974e659ff502d773e937b8a60aaddfd7d81e34cd2c296c8e82bf214d790ac089ba441543059dfc2677ba95ed51f676df9da420859f404a907)
find_program(SCRIPT_MESON NAMES ${search_names} PATHS "${path_to_search}" NO_DEFAULT_PATH) # NO_DEFAULT_PATH due top patching
if(NOT SCRIPT_MESON)
vcpkg_download_distfile(archive_path
URLS ${download_urls}
SHA512 "${download_sha512}"
FILENAME "${download_filename}"
)
file(REMOVE_RECURSE "${path_to_search}")
file(REMOVE_RECURSE "${path_to_search}-tmp")
file(MAKE_DIRECTORY "${path_to_search}-tmp")
file(ARCHIVE_EXTRACT INPUT "${archive_path}"
DESTINATION "${path_to_search}-tmp"
#PATTERNS "**/mesonbuild/*" "**/*.py"
)
z_vcpkg_apply_patches(
SOURCE_PATH "${path_to_search}-tmp/meson-${ref}"
PATCHES
@PATCHES@
)
file(MAKE_DIRECTORY "${path_to_search}")
file(RENAME "${path_to_search}-tmp/meson-${ref}/meson.py" "${path_to_search}/meson.py")
file(RENAME "${path_to_search}-tmp/meson-${ref}/mesonbuild" "${path_to_search}/mesonbuild")
file(REMOVE_RECURSE "${path_to_search}-tmp")
set(SCRIPT_MESON "${path_to_search}/meson.py")
endif()
# Check required python version
vcpkg_find_acquire_program(PYTHON3)
vcpkg_execute_in_download_mode(
COMMAND "${PYTHON3}" --version
OUTPUT_VARIABLE version_contents
WORKING_DIRECTORY "${CURRENT_BUILDTREES_DIR}"
)
string(REGEX MATCH [[[0-9]+\.[0-9]+\.[0-9]+]] python_ver "${version_contents}")
set(min_required 3.7)
if(python_ver VERSION_LESS "${min_required}")
message(FATAL_ERROR "Found Python version '${python_ver} at ${PYTHON3}' is insufficient for meson. meson requires at least version '${min_required}'")
else()
message(STATUS "Found Python version '${python_ver} at ${PYTHON3}'")
endif()
message(STATUS "Using meson: ${SCRIPT_MESON}")

View file

@ -0,0 +1,11 @@
{
"name": "vcpkg-tool-meson",
"version": "1.8.2",
"description": "Meson build system",
"homepage": "https://github.com/mesonbuild/meson",
"license": "Apache-2.0",
"supports": "native",
"dependencies": [
"vcpkg-cmake-get-vars"
]
}

View file

@ -0,0 +1,480 @@
function(z_vcpkg_meson_set_proglist_variables config_type)
if(VCPKG_TARGET_IS_WINDOWS)
set(proglist MT AR)
else()
set(proglist AR RANLIB STRIP NM OBJDUMP DLLTOOL MT)
endif()
foreach(prog IN LISTS proglist)
if(VCPKG_DETECTED_CMAKE_${prog})
if(meson_${prog})
string(TOUPPER "MESON_${meson_${prog}}" var_to_set)
set("${var_to_set}" "${meson_${prog}} = ['${VCPKG_DETECTED_CMAKE_${prog}}']" PARENT_SCOPE)
elseif(${prog} STREQUAL AR AND VCPKG_COMBINED_STATIC_LINKER_FLAGS_${config_type})
# Probably need to move AR somewhere else
string(TOLOWER "${prog}" proglower)
z_vcpkg_meson_convert_compiler_flags_to_list(ar_flags "${VCPKG_COMBINED_STATIC_LINKER_FLAGS_${config_type}}")
list(PREPEND ar_flags "${VCPKG_DETECTED_CMAKE_${prog}}")
z_vcpkg_meson_convert_list_to_python_array(ar_flags ${ar_flags})
set("MESON_AR" "${proglower} = ${ar_flags}" PARENT_SCOPE)
else()
string(TOUPPER "MESON_${prog}" var_to_set)
string(TOLOWER "${prog}" proglower)
set("${var_to_set}" "${proglower} = ['${VCPKG_DETECTED_CMAKE_${prog}}']" PARENT_SCOPE)
endif()
endif()
endforeach()
set(compilers "${arg_LANGUAGES}")
if(VCPKG_TARGET_IS_WINDOWS)
list(APPEND compilers RC)
endif()
set(meson_RC windres)
set(meson_Fortran fortran)
set(meson_CXX cpp)
foreach(prog IN LISTS compilers)
if(VCPKG_DETECTED_CMAKE_${prog}_COMPILER)
string(TOUPPER "MESON_${prog}" var_to_set)
if(meson_${prog})
if(VCPKG_COMBINED_${prog}_FLAGS_${config_type})
# Need compiler flags in prog vars for sanity check.
z_vcpkg_meson_convert_compiler_flags_to_list(${prog}flags "${VCPKG_COMBINED_${prog}_FLAGS_${config_type}}")
endif()
list(PREPEND ${prog}flags "${VCPKG_DETECTED_CMAKE_${prog}_COMPILER}")
list(FILTER ${prog}flags EXCLUDE REGEX "(-|/)nologo") # Breaks compiler detection otherwise
z_vcpkg_meson_convert_list_to_python_array(${prog}flags ${${prog}flags})
set("${var_to_set}" "${meson_${prog}} = ${${prog}flags}" PARENT_SCOPE)
if (DEFINED VCPKG_DETECTED_CMAKE_${prog}_COMPILER_ID
AND NOT VCPKG_DETECTED_CMAKE_${prog}_COMPILER_ID MATCHES "^(GNU|Intel)$"
AND VCPKG_DETECTED_CMAKE_LINKER)
string(TOUPPER "MESON_${prog}_LD" var_to_set)
set(${var_to_set} "${meson_${prog}}_ld = ['${VCPKG_DETECTED_CMAKE_LINKER}']" PARENT_SCOPE)
endif()
else()
if(VCPKG_COMBINED_${prog}_FLAGS_${config_type})
# Need compiler flags in prog vars for sanity check.
z_vcpkg_meson_convert_compiler_flags_to_list(${prog}flags "${VCPKG_COMBINED_${prog}_FLAGS_${config_type}}")
endif()
list(PREPEND ${prog}flags "${VCPKG_DETECTED_CMAKE_${prog}_COMPILER}")
list(FILTER ${prog}flags EXCLUDE REGEX "(-|/)nologo") # Breaks compiler detection otherwise
z_vcpkg_meson_convert_list_to_python_array(${prog}flags ${${prog}flags})
string(TOLOWER "${prog}" proglower)
set("${var_to_set}" "${proglower} = ${${prog}flags}" PARENT_SCOPE)
if (DEFINED VCPKG_DETECTED_CMAKE_${prog}_COMPILER_ID
AND NOT VCPKG_DETECTED_CMAKE_${prog}_COMPILER_ID MATCHES "^(GNU|Intel)$"
AND VCPKG_DETECTED_CMAKE_LINKER)
string(TOUPPER "MESON_${prog}_LD" var_to_set)
set(${var_to_set} "${proglower}_ld = ['${VCPKG_DETECTED_CMAKE_LINKER}']" PARENT_SCOPE)
endif()
endif()
endif()
endforeach()
endfunction()
function(z_vcpkg_meson_convert_compiler_flags_to_list out_var compiler_flags)
separate_arguments(cmake_list NATIVE_COMMAND "${compiler_flags}")
list(TRANSFORM cmake_list REPLACE ";" [[\\;]])
set("${out_var}" "${cmake_list}" PARENT_SCOPE)
endfunction()
function(z_vcpkg_meson_convert_list_to_python_array out_var)
z_vcpkg_function_arguments(flag_list 1)
vcpkg_list(REMOVE_ITEM flag_list "") # remove empty elements if any
vcpkg_list(JOIN flag_list "', '" flag_list)
set("${out_var}" "['${flag_list}']" PARENT_SCOPE)
endfunction()
# Generates the required compiler properties for meson
function(z_vcpkg_meson_set_flags_variables config_type)
if(VCPKG_TARGET_IS_WINDOWS AND NOT VCPKG_TARGET_IS_MINGW)
set(libpath_flag /LIBPATH:)
else()
set(libpath_flag -L)
endif()
if(config_type STREQUAL "DEBUG")
set(path_suffix "/debug")
else()
set(path_suffix "")
endif()
set(includepath "-I${CURRENT_INSTALLED_DIR}/include")
set(libpath "${libpath_flag}${CURRENT_INSTALLED_DIR}${path_suffix}/lib")
foreach(lang IN LISTS arg_LANGUAGES)
z_vcpkg_meson_convert_compiler_flags_to_list(${lang}flags "${VCPKG_COMBINED_${lang}_FLAGS_${config_type}}")
if(lang MATCHES "^(C|CXX)$")
vcpkg_list(APPEND ${lang}flags "${includepath}")
endif()
z_vcpkg_meson_convert_list_to_python_array(${lang}flags ${${lang}flags})
set(lang_mapping "${lang}")
if(lang STREQUAL "Fortran")
set(lang_mapping "FC")
endif()
string(TOLOWER "${lang_mapping}" langlower)
if(lang STREQUAL "CXX")
set(langlower cpp)
endif()
set(MESON_${lang_mapping}FLAGS "${langlower}_args = ${${lang}flags}\n")
set(linker_flags "${VCPKG_COMBINED_SHARED_LINKER_FLAGS_${config_type}}")
z_vcpkg_meson_convert_compiler_flags_to_list(linker_flags "${linker_flags}")
vcpkg_list(APPEND linker_flags "${libpath}")
z_vcpkg_meson_convert_list_to_python_array(linker_flags ${linker_flags})
string(APPEND MESON_${lang_mapping}FLAGS "${langlower}_link_args = ${linker_flags}\n")
set(MESON_${lang_mapping}FLAGS "${MESON_${lang_mapping}FLAGS}" PARENT_SCOPE)
endforeach()
endfunction()
function(z_vcpkg_get_build_and_host_system build_system host_system is_cross) #https://mesonbuild.com/Cross-compilation.html
set(build_unknown FALSE)
if(CMAKE_HOST_WIN32)
if(DEFINED ENV{PROCESSOR_ARCHITEW6432})
set(build_arch $ENV{PROCESSOR_ARCHITEW6432})
else()
set(build_arch $ENV{PROCESSOR_ARCHITECTURE})
endif()
if(build_arch MATCHES "(amd|AMD)64")
set(build_cpu_fam x86_64)
set(build_cpu x86_64)
elseif(build_arch MATCHES "(x|X)86")
set(build_cpu_fam x86)
set(build_cpu i686)
elseif(build_arch MATCHES "^(ARM|arm)64$")
set(build_cpu_fam aarch64)
set(build_cpu armv8)
elseif(build_arch MATCHES "^(ARM|arm)$")
set(build_cpu_fam arm)
set(build_cpu armv7hl)
else()
if(NOT DEFINED VCPKG_MESON_CROSS_FILE OR NOT DEFINED VCPKG_MESON_NATIVE_FILE)
message(WARNING "Unsupported build architecture ${build_arch}! Please set VCPKG_MESON_(CROSS|NATIVE)_FILE to a meson file containing the build_machine entry!")
endif()
set(build_unknown TRUE)
endif()
elseif(CMAKE_HOST_UNIX)
# at this stage, CMAKE_HOST_SYSTEM_PROCESSOR is not defined
execute_process(
COMMAND uname -m
OUTPUT_VARIABLE MACHINE
OUTPUT_STRIP_TRAILING_WHITESPACE
COMMAND_ERROR_IS_FATAL ANY)
# Show real machine architecture to visually understand whether we are in a native Apple Silicon terminal or running under Rosetta emulation
debug_message("Machine: ${MACHINE}")
if(MACHINE MATCHES "arm64|aarch64")
set(build_cpu_fam aarch64)
set(build_cpu armv8)
elseif(MACHINE MATCHES "armv7h?l")
set(build_cpu_fam arm)
set(build_cpu ${MACHINE})
elseif(MACHINE MATCHES "x86_64|amd64")
set(build_cpu_fam x86_64)
set(build_cpu x86_64)
elseif(MACHINE MATCHES "x86|i686")
set(build_cpu_fam x86)
set(build_cpu i686)
elseif(MACHINE MATCHES "i386")
set(build_cpu_fam x86)
set(build_cpu i386)
elseif(MACHINE MATCHES "loongarch64")
set(build_cpu_fam loongarch64)
set(build_cpu loongarch64)
else()
# https://github.com/mesonbuild/meson/blob/master/docs/markdown/Reference-tables.md#cpu-families
if(NOT DEFINED VCPKG_MESON_CROSS_FILE OR NOT DEFINED VCPKG_MESON_NATIVE_FILE)
message(WARNING "Unhandled machine: ${MACHINE}! Please set VCPKG_MESON_(CROSS|NATIVE)_FILE to a meson file containing the build_machine entry!")
endif()
set(build_unknown TRUE)
endif()
else()
if(NOT DEFINED VCPKG_MESON_CROSS_FILE OR NOT DEFINED VCPKG_MESON_NATIVE_FILE)
message(WARNING "Failed to detect the build architecture! Please set VCPKG_MESON_(CROSS|NATIVE)_FILE to a meson file containing the build_machine entry!")
endif()
set(build_unknown TRUE)
endif()
set(build "[build_machine]\n") # Machine the build is performed on
string(APPEND build "endian = 'little'\n")
if(CMAKE_HOST_WIN32)
string(APPEND build "system = 'windows'\n")
elseif(CMAKE_HOST_APPLE)
string(APPEND build "system = 'darwin'\n")
elseif(CYGWIN)
string(APPEND build "system = 'cygwin'\n")
elseif(CMAKE_HOST_UNIX)
string(APPEND build "system = 'linux'\n")
else()
set(build_unknown TRUE)
endif()
if(DEFINED build_cpu_fam)
string(APPEND build "cpu_family = '${build_cpu_fam}'\n")
endif()
if(DEFINED build_cpu)
string(APPEND build "cpu = '${build_cpu}'")
endif()
if(NOT build_unknown)
set(${build_system} "${build}" PARENT_SCOPE)
endif()
set(host_unkown FALSE)
if(VCPKG_TARGET_ARCHITECTURE MATCHES "(amd|AMD|x|X)64")
set(host_cpu_fam x86_64)
set(host_cpu x86_64)
elseif(VCPKG_TARGET_ARCHITECTURE MATCHES "(x|X)86")
set(host_cpu_fam x86)
set(host_cpu i686)
elseif(VCPKG_TARGET_ARCHITECTURE MATCHES "^(ARM|arm)64$")
set(host_cpu_fam aarch64)
set(host_cpu armv8)
elseif(VCPKG_TARGET_ARCHITECTURE MATCHES "^(ARM|arm)$")
set(host_cpu_fam arm)
set(host_cpu armv7hl)
elseif(VCPKG_TARGET_ARCHITECTURE MATCHES "loongarch64")
set(host_cpu_fam loongarch64)
set(host_cpu loongarch64)
elseif(VCPKG_TARGET_ARCHITECTURE MATCHES "wasm32")
set(host_cpu_fam wasm32)
set(host_cpu wasm32)
else()
if(NOT DEFINED VCPKG_MESON_CROSS_FILE OR NOT DEFINED VCPKG_MESON_NATIVE_FILE)
message(WARNING "Unsupported target architecture ${VCPKG_TARGET_ARCHITECTURE}! Please set VCPKG_MESON_(CROSS|NATIVE)_FILE to a meson file containing the host_machine entry!" )
endif()
set(host_unkown TRUE)
endif()
set(host "[host_machine]\n") # host=target in vcpkg.
string(APPEND host "endian = 'little'\n")
if(NOT VCPKG_CMAKE_SYSTEM_NAME OR VCPKG_TARGET_IS_MINGW OR VCPKG_TARGET_IS_UWP)
set(meson_system_name "windows")
else()
string(TOLOWER "${VCPKG_CMAKE_SYSTEM_NAME}" meson_system_name)
endif()
string(APPEND host "system = '${meson_system_name}'\n")
string(APPEND host "cpu_family = '${host_cpu_fam}'\n")
string(APPEND host "cpu = '${host_cpu}'")
if(NOT host_unkown)
set(${host_system} "${host}" PARENT_SCOPE)
endif()
if(NOT build_cpu_fam MATCHES "${host_cpu_fam}"
OR VCPKG_TARGET_IS_ANDROID OR VCPKG_TARGET_IS_IOS OR VCPKG_TARGET_IS_UWP
OR (VCPKG_TARGET_IS_MINGW AND NOT CMAKE_HOST_WIN32))
set(${is_cross} TRUE PARENT_SCOPE)
endif()
endfunction()
function(z_vcpkg_meson_setup_extra_windows_variables config_type)
## b_vscrt
if(VCPKG_CRT_LINKAGE STREQUAL "static")
set(crt_type "mt")
else()
set(crt_type "md")
endif()
if(config_type STREQUAL "DEBUG")
set(crt_type "${crt_type}d")
endif()
set(MESON_VSCRT_LINKAGE "b_vscrt = '${crt_type}'" PARENT_SCOPE)
## winlibs
separate_arguments(c_winlibs NATIVE_COMMAND "${VCPKG_DETECTED_CMAKE_C_STANDARD_LIBRARIES}")
separate_arguments(cpp_winlibs NATIVE_COMMAND "${VCPKG_DETECTED_CMAKE_CXX_STANDARD_LIBRARIES}")
z_vcpkg_meson_convert_list_to_python_array(c_winlibs ${c_winlibs})
z_vcpkg_meson_convert_list_to_python_array(cpp_winlibs ${cpp_winlibs})
set(MESON_WINLIBS "c_winlibs = ${c_winlibs}\n")
string(APPEND MESON_WINLIBS "cpp_winlibs = ${cpp_winlibs}")
set(MESON_WINLIBS "${MESON_WINLIBS}" PARENT_SCOPE)
endfunction()
function(z_vcpkg_meson_setup_variables config_type)
set(meson_var_list VSCRT_LINKAGE WINLIBS MT AR RC C C_LD CXX CXX_LD OBJC OBJC_LD OBJCXX OBJCXX_LD FC FC_LD WINDRES CFLAGS CXXFLAGS OBJCFLAGS OBJCXXFLAGS FCFLAGS SHARED_LINKER_FLAGS)
foreach(var IN LISTS meson_var_list)
set(MESON_${var} "")
endforeach()
if(VCPKG_TARGET_IS_WINDOWS)
z_vcpkg_meson_setup_extra_windows_variables("${config_type}")
endif()
z_vcpkg_meson_set_proglist_variables("${config_type}")
z_vcpkg_meson_set_flags_variables("${config_type}")
foreach(var IN LISTS meson_var_list)
set(MESON_${var} "${MESON_${var}}" PARENT_SCOPE)
endforeach()
endfunction()
function(vcpkg_generate_meson_cmd_args)
cmake_parse_arguments(PARSE_ARGV 0 arg
""
"OUTPUT;CONFIG"
"OPTIONS;LANGUAGES;ADDITIONAL_BINARIES;ADDITIONAL_PROPERTIES"
)
if(NOT arg_LANGUAGES)
set(arg_LANGUAGES C CXX)
endif()
vcpkg_list(JOIN arg_ADDITIONAL_BINARIES "\n" MESON_ADDITIONAL_BINARIES)
vcpkg_list(JOIN arg_ADDITIONAL_PROPERTIES "\n" MESON_ADDITIONAL_PROPERTIES)
set(buildtype "${arg_CONFIG}")
if(NOT VCPKG_CHAINLOAD_TOOLCHAIN_FILE)
z_vcpkg_select_default_vcpkg_chainload_toolchain()
endif()
vcpkg_list(APPEND VCPKG_CMAKE_CONFIGURE_OPTIONS "-DVCPKG_LANGUAGES=${arg_LANGUAGES}")
vcpkg_cmake_get_vars(cmake_vars_file)
debug_message("Including cmake vars from: ${cmake_vars_file}")
include("${cmake_vars_file}")
vcpkg_list(APPEND arg_OPTIONS --backend ninja --wrap-mode nodownload -Doptimization=plain)
z_vcpkg_get_build_and_host_system(MESON_HOST_MACHINE MESON_BUILD_MACHINE IS_CROSS)
if(arg_CONFIG STREQUAL "DEBUG")
set(suffix "dbg")
else()
string(SUBSTRING "${arg_CONFIG}" 0 3 suffix)
string(TOLOWER "${suffix}" suffix)
endif()
set(meson_input_file_${buildtype} "${CURRENT_BUILDTREES_DIR}/meson-${TARGET_TRIPLET}-${suffix}.log")
if(IS_CROSS)
# VCPKG_CROSSCOMPILING is not used since it regresses a lot of ports in x64-windows-x triplets
# For consistency this should proably be changed in the future?
vcpkg_list(APPEND arg_OPTIONS --native "${SCRIPTS}/buildsystems/meson/none.txt")
vcpkg_list(APPEND arg_OPTIONS --cross "${meson_input_file_${buildtype}}")
else()
vcpkg_list(APPEND arg_OPTIONS --native "${meson_input_file_${buildtype}}")
endif()
# User provided cross/native files
if(VCPKG_MESON_NATIVE_FILE)
vcpkg_list(APPEND arg_OPTIONS --native "${VCPKG_MESON_NATIVE_FILE}")
endif()
if(VCPKG_MESON_NATIVE_FILE_${buildtype})
vcpkg_list(APPEND arg_OPTIONS --native "${VCPKG_MESON_NATIVE_FILE_${buildtype}}")
endif()
if(VCPKG_MESON_CROSS_FILE)
vcpkg_list(APPEND arg_OPTIONS --cross "${VCPKG_MESON_CROSS_FILE}")
endif()
if(VCPKG_MESON_CROSS_FILE_${buildtype})
vcpkg_list(APPEND arg_OPTIONS --cross "${VCPKG_MESON_CROSS_FILE_${buildtype}}")
endif()
vcpkg_list(APPEND arg_OPTIONS --libdir lib) # else meson install into an architecture describing folder
vcpkg_list(APPEND arg_OPTIONS --pkgconfig.relocatable)
if(arg_CONFIG STREQUAL "RELEASE")
vcpkg_list(APPEND arg_OPTIONS -Ddebug=false --prefix "${CURRENT_PACKAGES_DIR}")
vcpkg_list(APPEND arg_OPTIONS "--pkg-config-path;['${CURRENT_INSTALLED_DIR}/lib/pkgconfig','${CURRENT_INSTALLED_DIR}/share/pkgconfig']")
if(VCPKG_TARGET_IS_WINDOWS)
vcpkg_list(APPEND arg_OPTIONS "-Dcmake_prefix_path=['${CURRENT_INSTALLED_DIR}','${CURRENT_INSTALLED_DIR}/debug','${CURRENT_INSTALLED_DIR}/share']")
else()
vcpkg_list(APPEND arg_OPTIONS "-Dcmake_prefix_path=['${CURRENT_INSTALLED_DIR}','${CURRENT_INSTALLED_DIR}/debug']")
endif()
elseif(arg_CONFIG STREQUAL "DEBUG")
vcpkg_list(APPEND arg_OPTIONS -Ddebug=true --prefix "${CURRENT_PACKAGES_DIR}/debug" --includedir ../include)
vcpkg_list(APPEND arg_OPTIONS "--pkg-config-path;['${CURRENT_INSTALLED_DIR}/debug/lib/pkgconfig','${CURRENT_INSTALLED_DIR}/share/pkgconfig']")
if(VCPKG_TARGET_IS_WINDOWS)
vcpkg_list(APPEND arg_OPTIONS "-Dcmake_prefix_path=['${CURRENT_INSTALLED_DIR}/debug','${CURRENT_INSTALLED_DIR}','${CURRENT_INSTALLED_DIR}/share']")
else()
vcpkg_list(APPEND arg_OPTIONS "-Dcmake_prefix_path=['${CURRENT_INSTALLED_DIR}/debug','${CURRENT_INSTALLED_DIR}']")
endif()
else()
message(FATAL_ERROR "Unknown configuration. Only DEBUG and RELEASE are valid values.")
endif()
# Allow overrides / additional configuration variables from triplets
if(DEFINED VCPKG_MESON_CONFIGURE_OPTIONS)
vcpkg_list(APPEND arg_OPTIONS ${VCPKG_MESON_CONFIGURE_OPTIONS})
endif()
if(DEFINED VCPKG_MESON_CONFIGURE_OPTIONS_${buildtype})
vcpkg_list(APPEND arg_OPTIONS ${VCPKG_MESON_CONFIGURE_OPTIONS_${buildtype}})
endif()
if(VCPKG_LIBRARY_LINKAGE STREQUAL "dynamic")
set(MESON_DEFAULT_LIBRARY shared)
else()
set(MESON_DEFAULT_LIBRARY static)
endif()
set(MESON_CMAKE_BUILD_TYPE "${cmake_build_type_${buildtype}}")
z_vcpkg_meson_setup_variables(${buildtype})
configure_file("${CMAKE_CURRENT_FUNCTION_LIST_DIR}/meson.template.in" "${meson_input_file_${buildtype}}" @ONLY)
set("${arg_OUTPUT}" ${arg_OPTIONS} PARENT_SCOPE)
endfunction()
function(vcpkg_configure_meson)
# parse parameters such that semicolons in options arguments to COMMAND don't get erased
cmake_parse_arguments(PARSE_ARGV 0 arg
"NO_PKG_CONFIG"
"SOURCE_PATH"
"OPTIONS;OPTIONS_DEBUG;OPTIONS_RELEASE;LANGUAGES;ADDITIONAL_BINARIES;ADDITIONAL_NATIVE_BINARIES;ADDITIONAL_CROSS_BINARIES;ADDITIONAL_PROPERTIES"
)
if(DEFINED arg_ADDITIONAL_NATIVE_BINARIES OR DEFINED arg_ADDITIONAL_CROSS_BINARIES)
message(WARNING "Options ADDITIONAL_(NATIVE|CROSS)_BINARIES have been deprecated. Only use ADDITIONAL_BINARIES!")
endif()
vcpkg_list(APPEND arg_ADDITIONAL_BINARIES ${arg_ADDITIONAL_NATIVE_BINARIES} ${arg_ADDITIONAL_CROSS_BINARIES})
vcpkg_list(REMOVE_DUPLICATES arg_ADDITIONAL_BINARIES)
file(REMOVE_RECURSE "${CURRENT_BUILDTREES_DIR}/${TARGET_TRIPLET}-rel")
file(REMOVE_RECURSE "${CURRENT_BUILDTREES_DIR}/${TARGET_TRIPLET}-dbg")
vcpkg_find_acquire_program(MESON)
get_filename_component(CMAKE_PATH "${CMAKE_COMMAND}" DIRECTORY)
vcpkg_add_to_path("${CMAKE_PATH}") # Make CMake invokeable for Meson
vcpkg_find_acquire_program(NINJA)
if(NOT arg_NO_PKG_CONFIG)
vcpkg_find_acquire_program(PKGCONFIG)
set(ENV{PKG_CONFIG} "${PKGCONFIG}")
endif()
vcpkg_find_acquire_program(PYTHON3)
get_filename_component(PYTHON3_DIR "${PYTHON3}" DIRECTORY)
vcpkg_add_to_path(PREPEND "${PYTHON3_DIR}")
set(buildtypes "")
if(NOT DEFINED VCPKG_BUILD_TYPE OR VCPKG_BUILD_TYPE STREQUAL "debug")
set(buildname "DEBUG")
set(cmake_build_type_${buildname} "Debug")
vcpkg_list(APPEND buildtypes "${buildname}")
set(path_suffix_${buildname} "debug/")
set(suffix_${buildname} "dbg")
endif()
if(NOT DEFINED VCPKG_BUILD_TYPE OR VCPKG_BUILD_TYPE STREQUAL "release")
set(buildname "RELEASE")
set(cmake_build_type_${buildname} "Release")
vcpkg_list(APPEND buildtypes "${buildname}")
set(path_suffix_${buildname} "")
set(suffix_${buildname} "rel")
endif()
# configure build
foreach(buildtype IN LISTS buildtypes)
message(STATUS "Configuring ${TARGET_TRIPLET}-${suffix_${buildtype}}")
file(MAKE_DIRECTORY "${CURRENT_BUILDTREES_DIR}/${TARGET_TRIPLET}-${suffix_${buildtype}}")
vcpkg_generate_meson_cmd_args(
OUTPUT cmd_args
CONFIG ${buildtype}
LANGUAGES ${arg_LANGUAGES}
OPTIONS ${arg_OPTIONS} ${arg_OPTIONS_${buildtype}}
ADDITIONAL_BINARIES ${arg_ADDITIONAL_BINARIES}
ADDITIONAL_PROPERTIES ${arg_ADDITIONAL_PROPERTIES}
)
vcpkg_execute_required_process(
COMMAND ${MESON} setup ${cmd_args} ${arg_SOURCE_PATH}
WORKING_DIRECTORY "${CURRENT_BUILDTREES_DIR}/${TARGET_TRIPLET}-${suffix_${buildtype}}"
LOGNAME config-${TARGET_TRIPLET}-${suffix_${buildtype}}
SAVE_LOG_FILES
meson-logs/meson-log.txt
meson-info/intro-dependencies.json
meson-logs/install-log.txt
)
message(STATUS "Configuring ${TARGET_TRIPLET}-${suffix_${buildtype}} done")
endforeach()
endfunction()

View file

@ -0,0 +1,71 @@
function(vcpkg_install_meson)
cmake_parse_arguments(PARSE_ARGV 0 arg "ADD_BIN_TO_PATH" "" "")
vcpkg_find_acquire_program(NINJA)
unset(ENV{DESTDIR}) # installation directory was already specified with '--prefix' option
if(VCPKG_TARGET_IS_OSX)
vcpkg_backup_env_variables(VARS SDKROOT MACOSX_DEPLOYMENT_TARGET)
set(ENV{SDKROOT} "${VCPKG_DETECTED_CMAKE_OSX_SYSROOT}")
set(ENV{MACOSX_DEPLOYMENT_TARGET} "${VCPKG_DETECTED_CMAKE_OSX_DEPLOYMENT_TARGET}")
endif()
foreach(buildtype IN ITEMS "debug" "release")
if(DEFINED VCPKG_BUILD_TYPE AND NOT VCPKG_BUILD_TYPE STREQUAL buildtype)
continue()
endif()
if(buildtype STREQUAL "debug")
set(short_buildtype "dbg")
else()
set(short_buildtype "rel")
endif()
message(STATUS "Package ${TARGET_TRIPLET}-${short_buildtype}")
if(arg_ADD_BIN_TO_PATH)
vcpkg_backup_env_variables(VARS PATH)
if(buildtype STREQUAL "debug")
vcpkg_add_to_path(PREPEND "${CURRENT_INSTALLED_DIR}/debug/bin")
else()
vcpkg_add_to_path(PREPEND "${CURRENT_INSTALLED_DIR}/bin")
endif()
endif()
vcpkg_execute_required_process(
COMMAND "${NINJA}" install -v
WORKING_DIRECTORY "${CURRENT_BUILDTREES_DIR}/${TARGET_TRIPLET}-${short_buildtype}"
LOGNAME package-${TARGET_TRIPLET}-${short_buildtype}
)
if(arg_ADD_BIN_TO_PATH)
vcpkg_restore_env_variables(VARS PATH)
endif()
endforeach()
vcpkg_list(SET renamed_libs)
if(VCPKG_TARGET_IS_WINDOWS AND VCPKG_LIBRARY_LINKAGE STREQUAL static AND NOT VCPKG_TARGET_IS_MINGW)
# Meson names all static libraries lib<name>.a which basically breaks the world
file(GLOB_RECURSE gen_libraries "${CURRENT_PACKAGES_DIR}*/**/lib*.a")
foreach(gen_library IN LISTS gen_libraries)
get_filename_component(libdir "${gen_library}" DIRECTORY)
get_filename_component(libname "${gen_library}" NAME)
string(REGEX REPLACE ".a$" ".lib" fixed_librawname "${libname}")
string(REGEX REPLACE "^lib" "" fixed_librawname "${fixed_librawname}")
file(RENAME "${gen_library}" "${libdir}/${fixed_librawname}")
# For cmake fixes.
string(REGEX REPLACE ".a$" "" origin_librawname "${libname}")
string(REGEX REPLACE ".lib$" "" fixed_librawname "${fixed_librawname}")
vcpkg_list(APPEND renamed_libs ${fixed_librawname})
set(${librawname}_old ${origin_librawname})
set(${librawname}_new ${fixed_librawname})
endforeach()
file(GLOB_RECURSE cmake_files "${CURRENT_PACKAGES_DIR}*/*.cmake")
foreach(cmake_file IN LISTS cmake_files)
foreach(current_lib IN LISTS renamed_libs)
vcpkg_replace_string("${cmake_file}" "${${current_lib}_old}" "${${current_lib}_new}" IGNORE_UNCHANGED)
endforeach()
endforeach()
endif()
if(VCPKG_TARGET_IS_OSX)
vcpkg_restore_env_variables(VARS SDKROOT MACOSX_DEPLOYMENT_TARGET)
endif()
endfunction()

View file

@ -0,0 +1,8 @@
# See https://github.com/microsoft/vcpkg/discussions/19454
# NOTE: Try to keep in sync with default arm64-osx definition
set(VCPKG_TARGET_ARCHITECTURE x64)
set(VCPKG_CRT_LINKAGE dynamic)
set(VCPKG_LIBRARY_LINKAGE static)
set(VCPKG_CMAKE_SYSTEM_NAME Darwin)
set(VCPKG_OSX_ARCHITECTURES "arm64;x86_64")

4
default.nix Normal file
View file

@ -0,0 +1,4 @@
(import (fetchTarball {
url = "https://github.com/edolstra/flake-compat/archive/ff81ac966bb2cae68946d5ed5fc4994f96d0ffec.tar.gz";
sha256 = "sha256-NeCCThCEP3eCl2l/+27kNNK7QrwZB1IJCrXfrbv5oqU=";
}) { src = ./.; }).defaultNix

150
docs/ADD_JAVA_GUIDE.md Normal file
View file

@ -0,0 +1,150 @@
# Adding Java 21 to Your Launcher (For Minecraft 1.21.10)
## The Issue
Minecraft 1.21.10 requires **Java 21**, but your system has Java 25 (too new).
## Quick Solution - Install Java 21 Locally (No Root Needed)
### Step 1: Download Java 21
```bash
# Go to your launcher folder
cd /home/admin/ai-lab/_projects/_minecraft/launcher/
# Create java directory
mkdir -p java
# Download Adoptium Java 21 (portable tar.gz)
cd java
wget https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.5%2B11/OpenJDK21U-jdk_x64_linux_hotspot_21.0.5_11.tar.gz
# Extract it
tar xzf OpenJDK21U-jdk_x64_linux_hotspot_21.0.5_11.tar.gz
# Verify
ls -la
# You should see: jdk-21.0.5+11/
```
### Step 2: Configure Launcher to Use It
**Option A: Via Launcher GUI (Easiest)**
1. Run your launcher: `bash start.sh`
2. Go to **Settings** (gear icon)
3. Click **Java** tab
4. Under "Java Installation", click **"Auto-detect"** or **"Browse"**
5. Navigate to: `/home/admin/ai-lab/_projects/_minecraft/launcher/java/jdk-21.0.5+11/bin/java`
6. Click **OK**
**Option B: Edit Config File Directly**
```bash
cd /home/admin/ai-lab/_projects/_minecraft/launcher/
# Edit the config file
nano bin/prismlauncher.cfg
# Find or add these lines:
JavaPath=/home/admin/ai-lab/_projects/_minecraft/launcher/java/jdk-21.0.5+11/bin/java
JavaDetect=true
# Save (Ctrl+X, Y, Enter)
```
### Step 3: Test It
```bash
# Run launcher
cd /home/admin/ai-lab/_projects/_minecraft/launcher/
bash start.sh
# Create a 1.21.10 instance
# It should now work without version errors!
```
## Alternative Java 21 Downloads
If the above link doesn't work:
### Amazon Corretto 21
```bash
cd java
wget https://corretto.aws/downloads/latest/amazon-corretto-21-x64-linux-jdk.tar.gz
tar xzf amazon-corretto-21-x64-linux-jdk.tar.gz
```
### Azul Zulu 21
```bash
cd java
wget https://cdn.azul.com/zulu/bin/zulu21.38.21-ca-jdk21.0.5-linux_x64.tar.gz
tar xzf zulu21.38.21-ca-jdk21.0.5-linux_x64.tar.gz
```
## Verify It's Working
```bash
# Test the Java version
java/jdk-21.0.5+11/bin/java -version
# Should output:
# openjdk version "21.0.5"
# OpenJDK Runtime Environment ...
# OpenJDK 64-Bit Server VM ...
```
## Permanent Storage
With this setup:
- ✅ Java is stored **inside your launcher folder**
- ✅ Portable - travels with the launcher
- ✅ Works from USB drives
- ✅ No root/sudo needed
- ✅ Doesn't affect system Java
## Folder Structure After Adding Java
```
launcher/
├── start.sh
├── bin/
│ └── prismlauncher
├── java/
│ └── jdk-21.0.5+11/ ← Java 21 installed here
│ ├── bin/
│ │ └── java ← Point to this
│ └── (other files)
└── share/
```
## For Minecraft 1.21.10
**Required Java Versions:**
- Minimum: Java 21
- Recommended: Java 21.0.5 or later
**NOT Compatible:**
- ❌ Java 8 (too old)
- ❌ Java 17 (too old for 1.21)
- ❌ Java 25 (too new, causes issues)
## Quick Install Script
Copy-paste this entire block to auto-install Java 21:
```bash
cd /home/admin/ai-lab/_projects/_minecraft/launcher/
mkdir -p java && cd java
wget https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.5%2B11/OpenJDK21U-jdk_x64_linux_hotspot_21.0.5_11.tar.gz
tar xzf OpenJDK21U-jdk_x64_linux_hotspot_21.0.5_11.tar.gz
cd ..
echo "Java installed!"
ls -la java/
echo ""
echo "Now configure your launcher to use:"
echo "java/jdk-21.0.5+11/bin/java"
```
---
**Updated:** 2026-04-13
**For:** Minecraft 1.21.10
**Java Version:** 21.0.5+11 (LTS)

164
docs/BLOAT_AUDIT.md Normal file
View file

@ -0,0 +1,164 @@
# Bloat Audit — racked.ru launcher
**Date:** 2026-04-30
**Total runtime size:** ~1.3 GB (`launcher/`)
**Goal:** identify what's strippable without breaking "load Minecraft reliably"
---
## TL;DR
| Category | Size | Strippable? |
|---|---|---|
| Mojang game assets (`assets/`) | 552M | **No** — needed by MC |
| Bundled Java 21 (`java/jdk-21.0.9+10/`) | 346M | No, but see below |
| Java tar.gz leftover (`java/java21.tar.gz`) | **198M** | **YES — instant win** |
| MC libraries (`libraries/`) | 99M | No |
| User instance (`instances/Fabulously Optimized/`) | 88M | No (user data) |
| Launcher binary (`bin/prismlauncher`) | 15M | Partial (strip + LTO) |
| Cache (`cache/`) | 5.5M | Yes (regenerated) |
| Translations | 692K | Mostly (see below) |
| Misc state (logs, metacache, sync-conflicts) | ~1M | Yes |
**Quick wins:** **~200 MB instantly** (java tar.gz + sync conflicts + cache).
---
## Runtime layout (`launcher/`)
```
552M assets/ Mojang resources — textures, sounds. Lookup by hash. KEEP.
543M java/
198M java21.tar.gz ← extracted already, DELETE
346M jdk-21.0.9+10/ runtime, KEEP (or move outside launcher)
99M libraries/ MC + Fabric + Forge libs, on-demand cache. KEEP.
88M instances/ user world + modpack. SACRED.
15M bin/prismlauncher main binary
5.5M cache/ HTTP/asset cache, REGENERATES. delete-safe.
692K translations/
319K mmc_en_GB.qm keep
316K mmc_en_GB.sync-conflict...qm ← Syncthing leftover, DELETE
26K index_v2.json keep
26K index_v2.sync-conflict...json ← DELETE
196K images/ backgrounds (cat). Strip if no cat wanted.
56K share/
40K metacache/
12K icons/
0 themes/ iconthemes/ catpacks/ empty
```
### Immediate deletes (safe, ~200M):
```bash
cd launcher/
rm java/java21.tar.gz # 198M
rm translations/*.sync-conflict-* # 316K + 26K
rm prismlauncher.sync-conflict-*.cfg metacache.sync-conflict-* 2>/dev/null
rm -rf cache/* # 5.5M (regens)
```
### Optional moves:
- **Java outside launcher folder** — if portability not strictly USB-required, point `JavaPath` at a system Java 21 install. Saves 346M from the launcher tree. Already configured in `prismlauncher.cfg:JavaPath`.
---
## Source bloat (`source/`, ~13M)
Compile-time only. Trimming reduces binary size + build time.
### Icon themes — biggest source bloat (~5.5M)
`source/launcher/resources/` contains **17 icon theme dirs**:
| Theme | Size | Used? |
|---|---|---|
| `multimc/` | 3.0M | No (legacy) |
| `backgrounds/` | 1.4M | Cat backgrounds |
| `sources/` | 400K | SVG masters |
| `flat_white/` | 208K | **YES (default)** |
| `flat/` | 208K | No |
| `breeze_light/` `breeze_dark/` | 408K | No |
| `pe_light/dark/colored/blue/` | 752K | No |
| `iOS/` `OSX/` | 324K | No |
| `racked_ru/` | 12K | YES (custom) |
| `shaders/` `assets/` `documents/` | 36K | Various |
**Strippable:** all except `flat_white/`, `racked_ru/`, `sources/`, `assets/`, `shaders/`. Saves ~5M from binary qrc.
### Mod platforms (`source/launcher/modplatform/`, 564K)
| Platform | Size | Modern? |
|---|---|---|
| `flame/` (CurseForge) | 124K | Yes |
| `modrinth/` | 92K | Yes |
| `atlauncher/` | 80K | Niche |
| `technic/` | 52K | Dying |
| `legacy_ftb/` | 36K | Dead |
| `ftb/` | 32K | Use modrinth instead |
| `import_ftb/` | 24K | Pair w/ ftb |
| `packwiz/` | 20K | Niche |
**Recommended keep:** `flame/`, `modrinth/`, helpers, generic. **Strippable:** atlauncher + technic + legacy_ftb + ftb + import_ftb + packwiz = ~244K source, ~1-2M off binary after compile.
### News system
Already audited (`NETWORK_AUDIT.md`). News fetches RSS from prismlauncher.org on every startup. Strippable:
- `source/launcher/news/``NewsChecker.cpp/h`, `NewsEntry.cpp/h`
- `source/launcher/ui/dialogs/NewsDialog.{cpp,h,ui}`
- News toolbar button in `MainWindow.ui`
- `news.svg` icons across themes
Saves: ~30K source, removes 1 outbound network call on startup, removes "News" toolbar button.
### Other strip candidates
| Component | Source size | Worth stripping? |
|---|---|---|
| `tests/` | 928K | **Already excluded from runtime build** — leave for dev, or `rm -rf` if no tests run |
| `nix/` + `flake.*` | 28K | If not building via Nix, delete |
| `.github/` | 136K | Workflows for upstream CI, drop in fork |
| `program_info/` translations of metainfo | 888K | Bulk is icons (.icns/.ico/.png), required for OS integration |
| `libraries/` (vendored quazip, tomlplusplus, etc.) | 648K | Required, system libs an option but fragile |
| Setup wizard (`launcher/ui/setupwizard/`) | 68K | First-run only — keep |
| Screenshots gallery (`launcher/ui/screenshots`?) | 24K | Niche |
---
## Stripped binary
`bin/prismlauncher` 15M. Likely already release-built. Confirm:
```bash
file bin/prismlauncher # should say "stripped"
strip --strip-all bin/prismlauncher 2>/dev/null # idempotent
```
If unstripped, can drop several MB.
LTO + `-Os` at CMake configure: `-DCMAKE_BUILD_TYPE=MinSizeRel -DCMAKE_INTERPROCEDURAL_OPTIMIZATION=ON` — typically 1020% binary shrink.
---
## Reliability cost of each strip
| Strip | Reliability impact |
|---|---|
| Delete java tar.gz | Zero — already extracted |
| Delete sync-conflicts | Zero |
| Delete cache/ | Zero — regenerates on first launch |
| Drop unused icon themes | Zero — user can't pick them anyway |
| Drop FTB/Technic/ATLauncher modplatforms | Zero **if** user only uses CurseForge/Modrinth |
| Disable news | Zero — purely informational, also removes online startup hit |
| Move bundled Java to system Java | Low — if system Java 21 missing, breaks. Keep bundled for portability |
| Strip backgrounds | Zero — cat purely cosmetic |
| Drop multimc/ icon theme | Zero — legacy default replaced by flat_white |
None of the proposed strips touch MC launching, auth, asset download, mod loading, or world saves.
---
## Recommended action plan (ordered by ROI)
1. **Now (~200M, zero risk):** delete `java/java21.tar.gz`, sync-conflict files, `cache/*`
2. **Source trim, next rebuild:** drop 12 unused icon themes, FTB/Technic/ATLauncher modplatforms, news system
3. **Build flags:** `MinSizeRel` + LTO + `strip --strip-all`
4. **Optional:** move Java out of `launcher/` if portability not required
Estimated final size after all: **~700 MB** (down from 1.3 GB). Most remaining is non-strippable (Mojang assets, MC libs, user instance, Java).

View file

@ -0,0 +1,93 @@
# Source changes — 2026-04-30
All edits in `source/`. Rebuild required, then move build artifact into `launcher/`.
## Branding
| File | Change |
|---|---|
| `program_info/CMakeLists.txt` | `Launcher_DisplayName``"racked.ru launcher"` (was `"Prism Launcher"`) |
| `launcher/Application.cpp:300` | `setApplicationDisplayName()` no longer appends version. Window title becomes `racked.ru launcher` (was `Prism Launcher 11.0.0-develop`) |
`Launcher_CommonName` left as `PrismLauncher` — used for binary name, install paths, env var prefix. Changing it would require renaming `bin/prismlauncher`, `prismlauncher.cfg`, and `PRISMLAUNCHER_DATA_DIR` env handling. Display-only rebrand is cleaner.
## "Cracked" scrub — DONE
All 7 files cleaned. `Diegiwg/PrismLauncher-Cracked` URLs → placeholder `s8n-ru/minecraft-launcher`. Doc prose rephrased to "PrismLauncher upstream fork (Diegiwg)". Per-file copyright headers + LICENSE preserved (GPL-3.0 §5c).
Files touched: `CMakeLists.txt`, `program_info/CMakeLists.txt`, `program_info/org.prismlauncher.PrismLauncher.metainfo.xml.in`, `README_RELEASE.md`, `PROJECT_SUMMARY.md`, `BUILD_GUIDE.md`, `scripts/create-release.sh`.
**Open:** placeholder repo slug `s8n-ru/minecraft-launcher` — replace with real repo URL once chosen.
## News feed → racked.ru
| File | Setting | Old | New |
|---|---|---|---|
| `CMakeLists.txt:174` | `Launcher_NEWS_RSS_URL` | `https://prismlauncher.org/feed/feed.xml` | `https://racked.ru/feed.xml` |
| `CMakeLists.txt:175` | `Launcher_NEWS_OPEN_URL` | `https://prismlauncher.org/news` | `https://racked.ru/news` |
**Open:** racked.ru must serve a valid RSS feed at `/feed.xml` or news pane stays empty + retries. Until ready, optional disable by setting URLs blank.
## Default settings (ported runtime → source defaults)
| File | Setting | Old default | New default |
|---|---|---|---|
| `launcher/Application.cpp` | `MinMemAlloc` | 512 | 384 |
| `launcher/Application.cpp` | `MaxMemAlloc` | `SysInfo::defaultMaxJvmMem()` | 4096 |
| `launcher/Application.cpp` | `MenuBarInsteadOfToolBar` | false | true |
See `SETTINGS_AUDIT.md` for full diff table.
## Bloat strips — DONE
### Source-side
| Target | Action | Saved |
|---|---|---|
| `.github/` | deleted | 136K |
| `tests/` + `if(BUILD_TESTING)` block in `CMakeLists.txt:503-505` | deleted | ~928K |
| `nix/`, `flake.nix`, `flake.lock` | deleted | ~28K |
| `launcher/resources/multimc/` icon theme | deleted (3M) but instance icons preserved (see below) | ~2.5M |
### multimc → racked_ru migration
multimc theme had only `Application.cpp:950` hardcoded reference (default instance icons) plus Qt theme fallback. Plan B chosen — extracted the 71 instance icons into `racked_ru/`, dropped rest of multimc.
| File | Change |
|---|---|
| `launcher/resources/racked_ru/{32x32,50x50,128x128,scalable}/instances/` | new — copied from multimc |
| `launcher/resources/racked_ru/racked_ru.qrc` | added 71 file entries under `prefix="/icons/racked_ru"` |
| `launcher/CMakeLists.txt:1284` | removed `resources/multimc/multimc.qrc` from `qt_add_resources()` |
| `launcher/Application.cpp:950-951` | `:/icons/multimc/...instances/``:/icons/racked_ru/...instances/` |
| `launcher/ui/themes/ThemeManager.h:94` | `builtinIcons{"flat_white", "multimc"}``{"flat_white", "racked_ru"}` |
**Risk note:** non-instance multimc icons (proxy, language, atlauncher logo, etc.) no longer baked. flat_white covers most UI icons. If a niche icon is missing in active theme, blank slot. Surface during test, easy fix (copy missing icon from upstream multimc archive into flat_white or racked_ru).
### Runtime-side (`launcher/`)
| Deleted | Saved |
|---|---|
| `java/java21.tar.gz` (extracted archive leftover) | 198M |
| `*sync-conflict*` (Syncthing leftovers, 4 files) | ~340K |
| `cache/*` (regens on first launch) | ~5.5M |
`launcher/` size: 1.3G → 1.1G.
## Verification (after rebuild)
1. `cd source && cmake -B build -S . -DCMAKE_BUILD_TYPE=Release && cmake --build build -j$(nproc)`
2. Move new `prismlauncher` binary + resource artifacts into `launcher/bin/` and `launcher/share/` as appropriate
3. Run `launcher/run.sh`
4. Check:
- Window title = `racked.ru launcher` (no version suffix)
- Settings → Appearance → Icon Theme dropdown lists `flat_white` + `racked_ru` only
- Instance List shows valid kitten/Minecraft instance icons (not blank squares)
- News pane shows racked.ru content (or empty/retrying if feed not yet live)
- "Fabulously Optimized" instance launches Minecraft cleanly
## Out of scope (per user decision)
- Modplatform strips (ATLauncher / Technic / FTB / Legacy FTB / Import FTB / Packwiz) — kept (nostalgia)
- Other icon themes (flat, breeze_*, pe_*, iOS, OSX) — kept
- `backgrounds/` cat art — kept
- Java bundle — kept (instant-play guarantee)

572
docs/MINECRAFT_LAUNCHER.md Normal file
View file

@ -0,0 +1,572 @@
# Minecraft Launcher Project - Complete Documentation
**Location:** `/home/admin/ai-lab/_projects/_minecraft/`
**Last Updated:** 2026-04-13
---
## Table of Contents
1. [Project Overview](#project-overview)
2. [Current Setup](#current-setup)
3. [Build System](#build-system)
4. [Custom Theme](#custom-theme)
5. [Development History](#development-history)
6. [File Structure](#file-structure)
7. [Configuration](#configuration)
8. [Deployment](#deployment)
9. [Troubleshooting](#troubleshooting)
10. [Future Work](#future-work)
---
## Project Overview
This project contains a **custom-branded PrismLauncher** for Minecraft, themed as "racked.ru" with a minimalist black and red design. The launcher is built from PrismLauncher-Cracked and customized for portable operation (USB-friendly, no installation required).
### Key Features
- **Minimalist Design**: Black background with red accents
- **Portable Mode**: All data stored locally, perfect for USB drives
- **Cross-Platform**: Builds available for Windows, Linux, and macOS
- **Stripped Resources**: Removed unused themes to minimize size
- **Custom Branding**: racked.ru theme and catpack background
---
## Current Setup
### Launcher Location
```
/home/admin/ai-lab/_projects/_minecraft/racked.ru - minecraft/
```
### Current Launcher Contents (as of 2026-04-13)
- `prismlauncher.exe` - Main launcher executable (Windows)
- `prismlauncher.cfg` - Configuration file with custom theme settings
- `portable.txt` - Enables portable mode
- `Qt6*.dll` - Qt framework libraries
- `platforms/` - Qt platform plugins
- `iconengines/` - Icon rendering plugins
- `imageformats/` - Image format support
- `themes/racked.ru/` - Custom theme files
- `catpacks/racked_ru.png` - Background cat image
- `instances/racked.ru/` - Minecraft instance with mods
### Configuration (prismlauncher.cfg)
```ini
[General]
ConfigVersion=1.2
ApplicationTheme=racked.ru
IconTheme=flat_white
BackgroundCat=racked_ru
Language=en_US
MenuBarInsteadOfToolBar=true
StatusBarVisible=false
TheCat=true
```
---
## Build System
### Build Repository
The build system and source code are maintained in:
```
/home/admin/ai-lab/_projects/_minecraft/source/
```
### Build Scripts Available
#### Linux Scripts
| Script | Purpose |
|--------|---------|
| `setup-and-build.sh` | One-command setup and build |
| `scripts/build-linux-portable.sh` | Build for Linux |
| `scripts/deploy-to-minecraft-folder.sh` | Build and deploy automatically |
| `scripts/build-windows-from-linux.sh` | Cross-compile for Windows |
| `scripts/build-all-platforms-linux.sh` | Multi-platform build |
| `scripts/create-release.sh` | Create versioned release packages |
#### Windows Scripts (Legacy)
| Script | Purpose |
|--------|---------|
| `scripts/build-windows-portable.bat` | Build for Windows |
| `scripts/deploy-to-minecraft-folder.bat` | Deploy to Windows folder |
### Build Process (Linux)
**Quick Build:**
```bash
cd /home/admin/ai-lab/_projects/_minecraft/source
bash setup-and-build.sh
```
This:
1. Installs dependencies (Fedora packages)
2. Builds the launcher
3. Creates portable release in `release/`
**Deploy Build:**
```bash
bash scripts/deploy-to-minecraft-folder.sh
```
This:
1. Builds the launcher
2. Backs up current installation
3. Deploys new version to `racked.ru - minecraft/`
### Build Dependencies (Fedora)
```bash
sudo dnf install -y \
cmake gcc-c++ make \
qt6-qtbase-devel qt6-qttools-devel qt6-qtsvg-devel \
qt6-qtnetworkauth-devel qt6-qtimageformats \
zlib-devel mesa-libGL-devel
```
---
## Custom Theme
### Theme Location
```
source/launcher/resources/racked_ru/
```
### Theme Files
#### theme.json
```json
{
"colors": {
"AlternateBase": "#000000",
"Base": "#000000",
"BrightText": "#ff0000",
"Button": "#000000",
"ButtonText": "#ffffff",
"Highlight": "#4C4C4C",
"HighlightedText": "#CCCCCC",
"Link": "#CD001F",
"Text": "#ffffff",
"ToolTipBase": "#ffffff",
"ToolTipText": "#ffffff",
"Window": "#000000",
"WindowText": "#ffffff",
"fadeAmount": 0.5,
"fadeColor": "#000000"
},
"name": "racked.ru",
"widgets": "Fusion"
}
```
#### themeStyle.css
```css
QToolTip { color: #ffffff; background-color: #2a82da; border: 1px solid white; }
```
### Background
- File: `catpacks/racked_ru.png`
- Custom cat image displayed in launcher background
- Configured via `BackgroundCat=racked_ru` in config
### Theme Changes Made
1. Removed all default themes (pe_dark, pe_light, pe_blue, etc.)
2. Kept only flat_white icon theme for minimalism
3. Added custom racked.ru theme with black/red colors
4. Set racked.ru as default application theme
5. Set flat_white as default icon theme
---
## Development History
### Timeline
#### 2026-04-13 - Project Creation
- Cloned upstream PrismLauncher-Cracked repository
- Created custom racked.ru theme integration
- Stripped unused themes and resources
- Implemented cross-platform build system for Linux
- Created automated deployment scripts
- Configured portable mode support
#### Changes Made
1. **Theme Integration**
- Added racked.ru theme with custom colors
- Set as default theme in Application.cpp
- Updated main.cpp to load only required resources
- Modified ThemeManager to remove unused themes
2. **Resource Optimization**
- Removed 10+ unused icon themes
- Removed unused application themes
- Reduced build size significantly
- Kept only flat_white and racked.ru themes
3. **Portable Mode**
- Added portable.txt to launcher root
- Configured builds to be USB-friendly
- All data stored locally in launcher directory
4. **Build System**
- Created Linux-first build scripts
- Added cross-compilation support for Windows
- Automated deployment to minecraft folder
- Created release packaging scripts
### Upstream Base
- **Project**: PrismLauncher-Cracked
- **Repository**: https://github.com/Diegiwg/PrismLauncher-Cracked
- **License**: GPL-3.0-only
- **Qt Version**: 6.5.3+
---
## File Structure
### Current Launcher (Production)
```
racked.ru - minecraft/
├── prismlauncher.exe # Main executable
├── prismlauncher.cfg # Configuration
├── portable.txt # Enables portable mode
├── Qt6Core.dll # Qt libraries
├── Qt6Gui.dll
├── Qt6Widgets.dll
├── Qt6Network.dll
├── ... (other Qt DLLs)
├── platforms/ # Qt platform plugins
│ └── qwindows.dll
├── iconengines/ # Icon rendering
├── imageformats/ # Image support
├── themes/
│ └── racked.ru/
│ ├── theme.json
│ └── themeStyle.css
├── catpacks/
│ └── racked_ru.png
├── instances/
│ └── racked.ru/ # Minecraft instance
│ └── minecraft/
│ └── config/ # Mod configurations
├── cache/ # Download cache
├── meta/ # Metadata
├── translations/ # Language files
└── logs/ # Log files
```
### Build System (Development)
```
source/
├── launcher/ # Source code
│ ├── resources/
│ │ └── racked_ru/ # Custom theme
│ ├── Application.cpp # Modified defaults
│ └── main.cpp # Resource loading
├── scripts/
│ ├── setup-and-build.sh
│ ├── build-linux-portable.sh
│ ├── deploy-to-minecraft-folder.sh
│ ├── build-windows-from-linux.sh
│ ├── build-all-platforms-linux.sh
│ └── create-release.sh
├── README_LINUX.md
├── LINUX_SETUP.md
├── LINUX_QUICKSTART.md
├── BUILD_GUIDE.md
├── PROJECT_SUMMARY.md
└── RELEASE_CHECKLIST.md
```
---
## Configuration
### Default Settings
These are the default settings configured in the build:
```ini
ApplicationTheme=racked.ru # Custom black/red theme
IconTheme=flat_white # Minimal white icons
BackgroundCat=racked_ru # Custom background image
MenuBarInsteadOfToolBar=true # Menu bar layout
StatusBarVisible=false # Minimal UI
TheCat=true # Enable background cat
```
### User Configuration
User-specific settings are stored in `prismlauncher.cfg` in the launcher directory (portable mode) or in system config directory (if portable.txt is removed).
### Java Configuration
The launcher auto-detects Java installations. Current settings:
```ini
AutomaticJavaDownload=true
AutomaticJavaSwitch=true
JavaVersion=21.0.7
JavaArchitecture=64
```
---
## Deployment
### Deploy to Current Location
**Linux (Recommended):**
```bash
cd /home/admin/ai-lab/_projects/_minecraft/source
bash scripts/deploy-to-minecraft-folder.sh
```
**Manual Deployment:**
```bash
# Build first
bash scripts/build-linux-portable.sh
# Backup current launcher
mv "racked.ru - minecraft" "racked.ru - minecraft-backup-$(date +%Y%m%d)"
# Copy new build
cp -r release/Racked.ru-PrismLauncher-Linux-Portable/* "racked.ru - minecraft/"
```
### Deployment Locations
**Current Production:**
```
/home/admin/ai-lab/_projects/_minecraft/racked.ru - minecraft/
```
**Backup Location (after deploy):**
```
/home/admin/ai-lab/_projects/_minecraft/racked.ru - minecraft-backup-YYYYMMDD/
```
### Release Packages
Release packages are created in:
```
source/release/
├── racked-prismlauncher-<version>-linux-portable.tar.gz
├── racked-prismlauncher-<version>-windows-portable.zip
└── racked-prismlauncher-<version>-macos-portable.tar.gz
```
To create a release:
```bash
bash scripts/create-release.sh 1.0.0
```
---
## Troubleshooting
### Java Requirements for Minecraft 1.21.10
**Minecraft 1.21.10 requires Java 21.** Your system has Java 25 which is too new.
**Solution:** Install Java 21 locally (no root needed)
- See `ADD_JAVA_GUIDE.md` for complete instructions
- Quick fix: Download from https://github.com/adoptium/temurin21-binaries
- Place Java in: `launcher/java/`
- Configure launcher to use: `java/jdk-21.0.5+11/bin/java`
**Quick Install Script:**
```bash
cd launcher/
mkdir -p java && cd java
wget https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.5%2B11/OpenJDK21U-jdk_x64_linux_hotspot_21.0.5_11.tar.gz
tar xzf OpenJDK21U-jdk_x64_linux_hotspot_21.0.5_11.tar.gz
```
### Common Issues
#### Launcher Won't Start
**Linux:**
```bash
# Check missing dependencies
ldd release/Racked.ru-PrismLauncher-Linux-Portable/bin/prismlauncher
# Install Qt6 if missing
sudo dnf install qt6-qtbase
```
**Windows:**
```bash
# Ensure all DLLs are present
# Rebuild with: scripts\build-windows-portable.bat
```
#### Theme Not Loading
1. Check `prismlauncher.cfg` for correct theme settings
2. Verify theme files exist in `themes/racked.ru/`
3. Rebuild launcher if files are missing
#### Portable Mode Not Working
1. Ensure `portable.txt` exists in launcher root
2. Check file permissions (must be readable)
3. Delete and recreate if necessary
#### Build Fails on Linux
```bash
# Install dependencies
sudo dnf install cmake gcc-c++ make qt6-qtbase-devel
# Clean build
rm -rf build-linux-portable/ install-linux-portable/
bash scripts/build-linux-portable.sh
```
#### Cross-Compilation for Windows Fails
```bash
# Install MinGW
sudo dnf install mingw64-gcc-c++ mingw64-qt6-qtbase
# Verify
x86_64-w64-mingw32-g++ --version
```
### Backup and Recovery
**Backup Current Launcher:**
```bash
cp -r "racked.ru - minecraft" "racked.ru - minecraft-backup-$(date +%Y%m%d)"
```
**Restore from Backup:**
```bash
rm -rf "racked.ru - minecraft"
mv "racked.ru - minecraft-backup-YYYYMMDD" "racked.ru - minecraft"
```
**Preserve Data:**
Before any deployment, backup:
- `instances/` folder (your Minecraft instances)
- `prismlauncher.cfg` (your settings)
- Any custom mods or resource packs
---
## Future Work
### Planned Improvements
#### 1. Automatic Updates
- [ ] Implement update checker
- [ ] Create update script
- [ ] Add update notifications
#### 2. Custom Branding
- [ ] Custom launcher icon
- [ ] Custom splash screen
- [ ] Custom about dialog
- [ ] Branded installer (optional)
#### 3. Performance Optimization
- [ ] Further reduce binary size
- [ ] Optimize startup time
- [ ] Reduce memory footprint
#### 4. Distribution
- [ ] Upload to racked.ru website
- [ ] Create GitHub releases
- [ ] Set up auto-update server
- [ ] Package for Linux distros (Flatpak, AppImage)
#### 5. Documentation
- [ ] User guide
- [ ] Mod installation guide
- [ ] Server connection guide
- [ ] Video tutorial
### Known Limitations
1. **macOS Builds**: Cannot cross-compile from Linux easily
- Solution: Build natively on macOS
2. **Windows Builds**: Require MinGW or native Windows
- Currently supports cross-compilation from Linux
3. **Size**: Still includes full Qt6 framework
- ~100-150MB minimum due to Qt dependencies
4. **Updates**: Manual update process
- Must rebuild and redeploy for updates
### Wishlist
- [ ] Custom modpack manager
- [ ] Integrated server browser
- [ ] Custom news feed from racked.ru
- [ ] Integrated voice chat
- [ ] Performance monitoring
- [ ] Shader pack manager
---
## Additional Resources
### Documentation Files
- `README_LINUX.md` - Complete Linux build guide
- `LINUX_SETUP.md` - Detailed setup instructions
- `LINUX_QUICKSTART.md` - Quick reference
- `BUILD_GUIDE.md` - Cross-platform build guide
- `PROJECT_SUMMARY.md` - Technical overview
- `RELEASE_CHECKLIST.md` - Release verification
### External Resources
- **PrismLauncher**: https://prismlauncher.org/
- **PrismLauncher-Cracked**: https://github.com/Diegiwg/PrismLauncher-Cracked
- **Qt Framework**: https://www.qt.io/
- **racked.ru Website**: https://racked.ru/
### Support
- **Issues**: GitHub Issues in source
- **Discord**: (Add your Discord link)
- **Website**: https://racked.ru/
---
## Quick Reference
### Most Common Commands
**Build from scratch:**
```bash
cd /home/admin/ai-lab/_projects/_minecraft/source
bash setup-and-build.sh
```
**Deploy to minecraft folder:**
```bash
bash scripts/deploy-to-minecraft-folder.sh
```
**Create release:**
```bash
bash scripts/create-release.sh 1.0.0
```
**Run built launcher:**
```bash
cd release/Racked.ru-PrismLauncher-Linux-Portable/
./run.sh
```
### Important Locations
```
Project Root: /home/admin/ai-lab/_projects/_minecraft/
Current Launcher: /home/admin/ai-lab/_projects/_minecraft/racked.ru - minecraft/
Build System: /home/admin/ai-lab/_projects/_minecraft/source/
Upstream Reference: /home/admin/ai-lab/prismlauncher-cracked-upstream/
```
---
**Version**: 1.0.0 (Initial Release)
**Build Date**: 2026-04-13
**Maintained By**: racked.ru team
**License**: GPL-3.0-only (based on PrismLauncher)

104
docs/NETWORK_AUDIT.md Normal file
View file

@ -0,0 +1,104 @@
# Network & Telemetry Audit — racked.ru launcher (PrismLauncher fork)
**Date:** 2026-04-30
**Scope:** `source/` tree — what the launcher contacts over the network, and whether anything phones home.
## Verdict: No telemetry, no analytics, no crash reporting.
Grep for `sentry|analytics|telemetry|tracking|google-analytics|mixpanel|amplitude|posthog|crashreport` across `*.cpp/*.h/CMakeLists` returns **zero hits**. (One false positive: a contributor's email `sentrycraft123@gmail.com` in copyright headers — unrelated to Sentry SDK.)
PrismLauncher upstream has never shipped telemetry. This fork preserves that.
---
## News feed — does it pull from online?
**Yes.** It is an RSS feed download.
- Code: `source/launcher/news/NewsChecker.cpp` constructs a `NetJob` and downloads the feed configured at build time.
- Caller: `source/launcher/ui/MainWindow.cpp:279`
```cpp
m_newsChecker.reset(new NewsChecker(APPLICATION->network(), BuildConfig.NEWS_RSS_URL));
```
- URL is set in `source/CMakeLists.txt`:
```cmake
set(Launcher_NEWS_RSS_URL "https://prismlauncher.org/feed/feed.xml" ...)
set(Launcher_NEWS_OPEN_URL "https://prismlauncher.org/news" ...)
```
- Trigger: fires on launcher startup (constructor of MainWindow).
**Implication for racked.ru fork:**
- Currently still hitting `prismlauncher.org` for news. If you want zero outbound to upstream, override at CMake configure time:
```bash
-DLauncher_NEWS_RSS_URL=https://racked.ru/feed.xml \
-DLauncher_NEWS_OPEN_URL=https://racked.ru/news
```
Or set both to empty string to disable. (Empty URL → `NetJob` fails silently.)
---
## All network endpoints in source
Grouped by purpose. None are telemetry.
### Auth / account (Microsoft / Mojang) — required to play
- `https://login.microsoftonline.com/consumers/oauth2/v2.0/{authorize,devicecode,token}`
- `https://login.live.com/login.srf`
- `http://auth.xboxlive.com`
- `https://api.minecraftservices.com/...` (profile, skins, capes, entitlements, MSA migration)
- `https://account.microsoft.com/family/`
- `https://help.minecraft.net/...`
### Game assets
- `https://libraries.minecraft.net/`
### Mod platforms (user-driven)
- `https://api.modrinth.com/v2`, `https://modrinth.com/mod/`, `https://docs.modrinth.com/...`
- `https://api.curseforge.com/v1`, `https://docs.curseforge.com/`
- `https://api.atlauncher.com/v1/`, `http://api.technicpack.net/modpack/`
- `https://api.feed-the-beast.com/v1/modpacks/public`, `https://dist.creeper.host/FTB2/`
### Pastebins (user-driven, log upload)
- `https://api.mclo.gs`, `https://api.paste.gg/v1/pastes`, `https://hst.sh`, `https://0x0.st`
- `https://api.imgur.com/3/`, `https://imgur.com/a/`
### Updater / news / help (Prism)
- `https://api.github.com/repos/...` — version checks
- `https://prismlauncher.org/feed/feed.xml` — news RSS (see above)
- `https://prismlauncher.org/news` — "More news" button
- Help URL template in CMake: `https://prismlauncher.org/wiki/help-pages/%1`
- Bug tracker: `https://github.com/Diegiwg/PrismLauncher-Cracked/issues` ← **upstream-fork URL, points at the original "Cracked" project**
- Translations: `https://hosted.weblate.org/projects/prismlauncher/launcher/`
- Matrix/Discord/Subreddit: all `prismlauncher.org` redirects
### Documentation links (opened in browser only when user clicks)
- `minecraft.wiki`, `fabricmc.net/wiki`, `docs.microsoft.com`, etc.
---
## Risk summary
| Vector | Risk | Mitigation |
|---|---|---|
| Telemetry | None | n/a |
| Crash reporting | None | n/a |
| News RSS leaks IP to prismlauncher.org on startup | Low (single GET, no UA fingerprint beyond `Launcher_UserAgent` = `PrismLauncher/<version>`) | Override `Launcher_NEWS_RSS_URL` to racked.ru or empty |
| Update check via api.github.com | Low (anonymous, rate-limited) | Override `BUG_TRACKER_URL` and consider disabling updater path |
| User-Agent identifies fork by name + version | Low | Override `Launcher_UserAgent` if anonymity desired |
---
## Recommended CMake overrides for racked.ru build
```cmake
-DLauncher_NEWS_RSS_URL=https://racked.ru/feed.xml
-DLauncher_NEWS_OPEN_URL=https://racked.ru/news
-DLauncher_HELP_URL=https://racked.ru/help/%1
-DLauncher_BUG_TRACKER_URL=https://racked.ru/bugs
-DLauncher_MATRIX_URL=https://racked.ru/matrix
-DLauncher_DISCORD_URL=https://racked.ru/discord
-DLauncher_SUBREDDIT_URL=https://racked.ru
-DLauncher_TRANSLATIONS_URL=https://racked.ru/translate
```
Or set them blank to disable the menu items entirely.

30
docs/SETTINGS_AUDIT.md Normal file
View file

@ -0,0 +1,30 @@
# Settings Audit — runtime cfg vs source defaults
**Date:** 2026-04-30
**Source:** `source/launcher/Application.cpp` (registerSetting block lines ~644900)
**Runtime:** `launcher/prismlauncher.cfg`
## Diffs found
| Setting | Source default | Runtime value | Action |
|---|---|---|---|
| `MinMemAlloc` | `512` | `384` | **Ported** → source now defaults `384` |
| `MaxMemAlloc` | `SysInfo::defaultMaxJvmMem()` (system-detected, often 8G+) | `4096` | **Ported** → source now defaults `4096` |
| `MenuBarInsteadOfToolBar` | `false` | `true` | **Ported** → source now defaults `true` |
| `FallbackMRBlockedMods` | `true` (bool) | `2` (Qt::CheckState::Checked) | **Not changed** — already truthy. Stored as enum because UI uses tri-state checkbox; behaviorally identical |
| `ApplicationTheme` | `"racked.ru"` | `"system"` | Runtime override only. Default already correct |
| `BackgroundCat` | `"racked_ru"` | (not set in cfg, irrelevant) | Default correct |
| `IconTheme` | `"flat_white"` | `"flat_white"` | Match |
| `AutomaticJavaDownload` | dynamic (`JavaPath` empty) | `false` | User-toggled, leave dynamic |
| `AutomaticJavaSwitch` | dynamic | `true` | Same |
| `NumberOfConcurrentTasks` | `10` | `10` | Match |
| `NumberOfConcurrentDownloads` | `6` | `6` | Match |
## Files changed
- `source/launcher/Application.cpp` — three default values updated (Min/MaxMemAlloc, MenuBarInsteadOfToolBar)
## Notes
- `JavaPath`, `LastHostname`, geometry blobs, `SelectedInstance`, `Language` are user/host-specific. Not ported.
- `OnlineFixes=false`, `EnableFeralGamemode=false`, `EnableMangoHud=false`, `UseDiscreteGpu=false`, `UseZink=false` — match defaults.

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

2066
launcher/Application.cpp Normal file

File diff suppressed because it is too large Load diff

325
launcher/Application.h Normal file
View file

@ -0,0 +1,325 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.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
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <memory>
#include <QApplication>
#include <QDateTime>
#include <QDebug>
#include <QFlag>
#include <QIcon>
#include <QMutex>
#include <QUrl>
#include "QObjectPtr.h"
#include "minecraft/auth/MinecraftAccount.h"
class LaunchController;
class LocalPeer;
class InstanceWindow;
class MainWindow;
class ViewLogWindow;
class SetupWizard;
class GenericPageProvider;
class QFile;
class HttpMetaCache;
class SettingsObject;
class InstanceList;
class AccountList;
class IconList;
class QNetworkAccessManager;
class JavaInstallList;
class ExternalUpdater;
class BaseProfilerFactory;
class BaseDetachedToolFactory;
class TranslationsModel;
class ITheme;
class MCEditTool;
class ThemeManager;
class IconTheme;
class BaseInstance;
class LogModel;
struct MinecraftTarget;
class MinecraftAccount;
namespace Meta {
class Index;
}
#if defined(APPLICATION)
#undef APPLICATION
#endif
#define APPLICATION (static_cast<Application*>(QCoreApplication::instance()))
// Used for checking if is a test
#if defined(APPLICATION_DYN)
#undef APPLICATION_DYN
#endif
#define APPLICATION_DYN (dynamic_cast<Application*>(QCoreApplication::instance()))
class Application : public QApplication {
Q_OBJECT
public:
enum Status { StartingUp, Failed, Succeeded, Initialized };
enum Capability {
None = 0,
SupportsMSA = 1 << 0,
SupportsFlame = 1 << 1,
SupportsGameMode = 1 << 2,
SupportsMangoHud = 1 << 3,
};
Q_DECLARE_FLAGS(Capabilities, Capability)
public:
Application(int& argc, char** argv);
virtual ~Application();
bool event(QEvent* event) override;
SettingsObject* settings() const { return m_settings.get(); }
qint64 timeSinceStart() const { return m_startTime.msecsTo(QDateTime::currentDateTime()); }
QIcon logo();
ThemeManager* themeManager() { return m_themeManager.get(); }
ExternalUpdater* updater() { return m_updater.get(); }
void triggerUpdateCheck();
TranslationsModel* translations();
JavaInstallList* javalist();
InstanceList* instances() const { return m_instances.get(); }
IconList* icons() const { return m_icons.get(); }
MCEditTool* mcedit() const { return m_mcedit.get(); }
AccountList* accounts() const { return m_accounts.get(); }
Status status() const { return m_status; }
const QMap<QString, std::shared_ptr<BaseProfilerFactory>>& profilers() const { return m_profilers; }
void updateProxySettings(QString proxyTypeStr, QString addr, int port, QString user, QString password);
QNetworkAccessManager* network();
HttpMetaCache* metacache();
Meta::Index* metadataIndex();
void updateCapabilities();
void detectLibraries();
/*!
* Finds and returns the full path to a jar file.
* Returns a null-string if it could not be found.
*/
QString getJarPath(QString jarFile);
QString getMSAClientID();
QString getFlameAPIKey();
QString getModrinthAPIToken();
QString getUserAgent();
/// this is the root of the 'installation'. Used for automatic updates
const QString& root() { return m_rootPath; }
/// the data path the application is using
const QString& dataRoot() { return m_dataPath; }
/// the java installed path the application is using
const QString javaPath();
bool isPortable() { return m_portable; }
const Capabilities capabilities() { return m_capabilities; }
/*!
* Opens a json file using either a system default editor, or, if not empty, the editor
* specified in the settings
*/
bool openJsonEditor(const QString& filename);
InstanceWindow* showInstanceWindow(BaseInstance* instance, QString page = QString());
MainWindow* showMainWindow(bool minimized = false);
ViewLogWindow* showLogWindow();
void updateIsRunning(bool running);
bool updatesAreAllowed();
void ShowGlobalSettings(class QWidget* parent, QString open_page = QString());
bool updaterEnabled();
QString updaterBinaryName();
QUrl normalizeImportUrl(const QString& url);
signals:
void updateAllowedChanged(bool status);
void globalSettingsAboutToOpen();
void globalSettingsApplied();
int currentCatChanged(int index);
void oauthReplyRecieved(QVariantMap);
#ifdef Q_OS_MACOS
void clickedOnDock();
#endif
public slots:
bool launch(BaseInstance* instance,
LaunchMode mode = LaunchMode::Normal,
std::shared_ptr<MinecraftTarget> targetToJoin = nullptr,
shared_qobject_ptr<MinecraftAccount> accountToUse = nullptr,
const QString& offlineName = QString());
bool kill(BaseInstance* instance);
void closeCurrentWindow();
private slots:
void on_windowClose();
void messageReceived(const QByteArray& message);
void controllerFinished();
void setupWizardFinished(int status);
private:
bool handleDataMigration(const QString& currentData, const QString& oldData, const QString& name, const QString& configFile) const;
bool createSetupWizard();
void performMainStartupAction();
// sets the fatal error message and m_status to Failed.
void showFatalErrorMessage(const QString& title, const QString& content);
private:
void addRunningInstance();
void subRunningInstance();
bool shouldExitNow() const;
private:
QHash<QString, int> m_qsaveResources;
mutable QMutex m_qsaveResourcesMutex;
private:
QDateTime m_startTime;
std::unique_ptr<QNetworkAccessManager> m_network;
std::unique_ptr<ExternalUpdater> m_updater;
std::unique_ptr<AccountList> m_accounts;
std::unique_ptr<HttpMetaCache> m_metacache;
std::unique_ptr<Meta::Index> m_metadataIndex;
std::unique_ptr<SettingsObject> m_settings;
std::unique_ptr<InstanceList> m_instances;
std::unique_ptr<IconList> m_icons;
std::unique_ptr<JavaInstallList> m_javalist;
std::unique_ptr<TranslationsModel> m_translations;
std::unique_ptr<GenericPageProvider> m_globalSettingsProvider;
std::unique_ptr<MCEditTool> m_mcedit;
QSet<QString> m_features;
std::unique_ptr<ThemeManager> m_themeManager;
QMap<QString, std::shared_ptr<BaseProfilerFactory>> m_profilers;
QString m_rootPath;
QString m_dataPath;
Status m_status = Application::StartingUp;
Capabilities m_capabilities;
bool m_portable = false;
#ifdef Q_OS_MACOS
Qt::ApplicationState m_prevAppState = Qt::ApplicationInactive;
#endif
// FIXME: attach to instances instead.
struct InstanceXtras {
InstanceWindow* window = nullptr;
std::unique_ptr<LaunchController> controller;
};
std::map<QString, InstanceXtras> m_instanceExtras;
mutable QMutex m_instanceExtrasMutex;
// main state variables
size_t m_openWindows = 0;
size_t m_runningInstances = 0;
bool m_updateRunning = false;
// main window, if any
MainWindow* m_mainWindow = nullptr;
// log window, if any
ViewLogWindow* m_viewLogWindow = nullptr;
// peer launcher instance connector - used to implement single instance launcher and signalling
LocalPeer* m_peerInstance = nullptr;
SetupWizard* m_setupWizard = nullptr;
public:
QString m_detectedGLFWPath;
QString m_detectedOpenALPath;
QString m_instanceIdToLaunch;
QString m_serverToJoin;
QString m_worldToJoin;
QString m_profileToUse;
bool m_launchOffline = false;
QString m_offlineName;
bool m_liveCheck = false;
QList<QUrl> m_urlsToImport;
QString m_instanceIdToShowWindowOf;
bool m_showMainWindow = false;
std::unique_ptr<QFile> logFile;
std::unique_ptr<LogModel> logModel;
public:
void addQSavePath(QString);
void removeQSavePath(QString);
bool checkQSavePath(QString);
};

View file

@ -0,0 +1,67 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ApplicationMessage.h"
#include <QJsonDocument>
#include <QJsonObject>
#include "Json.h"
void ApplicationMessage::parse(const QByteArray& input)
{
auto doc = Json::requireDocument(input, "ApplicationMessage");
auto root = Json::requireObject(doc, "ApplicationMessage");
command = root.value("command").toString();
args.clear();
auto parsedArgs = root.value("args").toObject();
for (auto iter = parsedArgs.constBegin(); iter != parsedArgs.constEnd(); iter++) {
args.insert(iter.key(), iter.value().toString());
}
}
QByteArray ApplicationMessage::serialize()
{
QJsonObject root;
root.insert("command", command);
QJsonObject outArgs;
for (auto iter = args.constBegin(); iter != args.constEnd(); iter++) {
outArgs.insert(iter.key(), iter.value());
}
root.insert("args", outArgs);
return Json::toText(root);
}

View file

@ -0,0 +1,13 @@
#pragma once
#include <QByteArray>
#include <QHash>
#include <QString>
struct ApplicationMessage {
QString command;
QHash<QString, QString> args;
QByteArray serialize();
void parse(const QByteArray& input);
};

25
launcher/AssertHelpers.h Normal file
View file

@ -0,0 +1,25 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2025 Octol1ttle <l1ttleofficial@outlook.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
#if defined(ASSERT_NEVER)
#error ASSERT_NEVER already defined
#else
#define ASSERT_NEVER(cond) (Q_ASSERT((cond) == false), (cond))
#endif

View file

@ -0,0 +1,56 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <QFile>
#include "BaseInstaller.h"
#include "FileSystem.h"
#include "minecraft/MinecraftInstance.h"
BaseInstaller::BaseInstaller() {}
bool BaseInstaller::isApplied(MinecraftInstance* on)
{
return QFile::exists(filename(on->instanceRoot()));
}
bool BaseInstaller::add(MinecraftInstance* to)
{
if (!patchesDir(to->instanceRoot()).exists()) {
QDir(to->instanceRoot()).mkdir("patches");
}
if (isApplied(to)) {
if (!remove(to)) {
return false;
}
}
return true;
}
bool BaseInstaller::remove(MinecraftInstance* from)
{
return FS::deletePath(filename(from->instanceRoot()));
}
QString BaseInstaller::filename(const QString& root) const
{
return patchesDir(root).absoluteFilePath(id() + ".json");
}
QDir BaseInstaller::patchesDir(const QString& root) const
{
return QDir(root + "/patches/");
}

44
launcher/BaseInstaller.h Normal file
View file

@ -0,0 +1,44 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <memory>
#include "BaseVersion.h"
class MinecraftInstance;
class QDir;
class QString;
class QObject;
class Task;
class BaseVersion;
class BaseInstaller {
public:
BaseInstaller();
virtual ~BaseInstaller() {};
bool isApplied(MinecraftInstance* on);
virtual bool add(MinecraftInstance* to);
virtual bool remove(MinecraftInstance* from);
virtual Task* createInstallTask(MinecraftInstance* instance, BaseVersion::Ptr version, QObject* parent) = 0;
protected:
virtual QString id() const = 0;
QString filename(const QString& root) const;
QDir patchesDir(const QString& root) const;
};

487
launcher/BaseInstance.cpp Normal file
View file

@ -0,0 +1,487 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
* Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org>
* Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "BaseInstance.h"
#include <QDebug>
#include <QDir>
#include <QFileInfo>
#include <QJsonDocument>
#include <QJsonObject>
#include "Application.h"
#include "Json.h"
#include "launch/LaunchTask.h"
#include "settings/INISettingsObject.h"
#include "settings/OverrideSetting.h"
#include "settings/Setting.h"
#include "BuildConfig.h"
#include "Commandline.h"
#include "FileSystem.h"
int getConsoleMaxLines(SettingsObject* settings)
{
auto lineSetting = settings->getSetting("ConsoleMaxLines");
bool conversionOk = false;
int maxLines = lineSetting->get().toInt(&conversionOk);
if (!conversionOk) {
maxLines = lineSetting->defValue().toInt();
qWarning() << "ConsoleMaxLines has nonsensical value, defaulting to" << maxLines;
}
return maxLines;
}
bool shouldStopOnConsoleOverflow(SettingsObject* settings)
{
return settings->get("ConsoleOverflowStop").toBool();
}
BaseInstance::BaseInstance(SettingsObject* globalSettings, std::unique_ptr<SettingsObject> settings, const QString& rootDir) : QObject()
{
m_settings = std::move(settings);
m_global_settings = globalSettings;
m_rootDir = rootDir;
m_settings->registerSetting("name", "Unnamed Instance");
m_settings->registerSetting("iconKey", "default");
m_settings->registerSetting("notes", "");
m_settings->registerSetting("lastLaunchTime", 0);
m_settings->registerSetting("totalTimePlayed", 0);
if (m_settings->get("totalTimePlayed").toLongLong() < 0)
m_settings->reset("totalTimePlayed");
m_settings->registerSetting("lastTimePlayed", 0);
m_settings->registerSetting("linkedInstances", "[]");
m_settings->registerSetting("shortcuts", QString());
// Game time override
auto gameTimeOverride = m_settings->registerSetting("OverrideGameTime", false);
m_settings->registerOverride(globalSettings->getSetting("ShowGameTime"), gameTimeOverride);
m_settings->registerOverride(globalSettings->getSetting("RecordGameTime"), gameTimeOverride);
// NOTE: Sometimees InstanceType is already registered, as it was used to identify the type of
// a locally stored instance
if (!m_settings->getSetting("InstanceType"))
m_settings->registerSetting("InstanceType", "");
// Custom Commands
auto commandSetting = m_settings->registerSetting({ "OverrideCommands", "OverrideLaunchCmd" }, false);
m_settings->registerOverride(globalSettings->getSetting("PreLaunchCommand"), commandSetting);
m_settings->registerOverride(globalSettings->getSetting("WrapperCommand"), commandSetting);
m_settings->registerOverride(globalSettings->getSetting("PostExitCommand"), commandSetting);
// Console
auto consoleSetting = m_settings->registerSetting("OverrideConsole", false);
m_settings->registerOverride(globalSettings->getSetting("ShowConsole"), consoleSetting);
m_settings->registerOverride(globalSettings->getSetting("AutoCloseConsole"), consoleSetting);
m_settings->registerOverride(globalSettings->getSetting("ShowConsoleOnError"), consoleSetting);
m_settings->registerOverride(globalSettings->getSetting("LogPrePostOutput"), consoleSetting);
m_settings->registerPassthrough(globalSettings->getSetting("ConsoleMaxLines"), nullptr);
m_settings->registerPassthrough(globalSettings->getSetting("ConsoleOverflowStop"), nullptr);
// Managed Packs
m_settings->registerSetting("ManagedPack", false);
m_settings->registerSetting("ManagedPackType", "");
m_settings->registerSetting("ManagedPackID", "");
m_settings->registerSetting("ManagedPackName", "");
m_settings->registerSetting("ManagedPackVersionID", "");
m_settings->registerSetting("ManagedPackVersionName", "");
m_settings->registerSetting("ManagedPackURL", "");
m_settings->registerSetting("Profiler", "");
}
BaseInstance::~BaseInstance() {}
QString BaseInstance::getPreLaunchCommand()
{
return settings()->get("PreLaunchCommand").toString();
}
QString BaseInstance::getWrapperCommand()
{
return settings()->get("WrapperCommand").toString();
}
QString BaseInstance::getPostExitCommand()
{
return settings()->get("PostExitCommand").toString();
}
bool BaseInstance::isManagedPack() const
{
return m_settings->get("ManagedPack").toBool();
}
QString BaseInstance::getManagedPackType() const
{
return m_settings->get("ManagedPackType").toString();
}
QString BaseInstance::getManagedPackID() const
{
return m_settings->get("ManagedPackID").toString();
}
QString BaseInstance::getManagedPackName() const
{
return m_settings->get("ManagedPackName").toString();
}
QString BaseInstance::getManagedPackVersionID() const
{
return m_settings->get("ManagedPackVersionID").toString();
}
QString BaseInstance::getManagedPackVersionName() const
{
return m_settings->get("ManagedPackVersionName").toString();
}
void BaseInstance::setManagedPack(const QString& type,
const QString& id,
const QString& name,
const QString& versionId,
const QString& version)
{
m_settings->set("ManagedPack", true);
m_settings->set("ManagedPackType", type);
m_settings->set("ManagedPackID", id);
m_settings->set("ManagedPackName", name);
m_settings->set("ManagedPackVersionID", versionId);
m_settings->set("ManagedPackVersionName", version);
}
void BaseInstance::copyManagedPack(BaseInstance& other)
{
m_settings->set("ManagedPack", other.isManagedPack());
m_settings->set("ManagedPackType", other.getManagedPackType());
m_settings->set("ManagedPackID", other.getManagedPackID());
m_settings->set("ManagedPackName", other.getManagedPackName());
m_settings->set("ManagedPackVersionID", other.getManagedPackVersionID());
m_settings->set("ManagedPackVersionName", other.getManagedPackVersionName());
if (APPLICATION->settings()->get("AutomaticJavaSwitch").toBool() && m_settings->get("AutomaticJava").toBool() &&
m_settings->get("OverrideJavaLocation").toBool()) {
m_settings->set("OverrideJavaLocation", false);
m_settings->set("JavaPath", "");
}
}
QStringList BaseInstance::getLinkedInstances() const
{
auto setting = m_settings->get("linkedInstances").toString();
return Json::toStringList(setting);
}
void BaseInstance::setLinkedInstances(const QStringList& list)
{
m_settings->set("linkedInstances", Json::fromStringList(list));
}
void BaseInstance::addLinkedInstanceId(const QString& id)
{
auto linkedInstances = getLinkedInstances();
linkedInstances.append(id);
setLinkedInstances(linkedInstances);
}
bool BaseInstance::removeLinkedInstanceId(const QString& id)
{
auto linkedInstances = getLinkedInstances();
int numRemoved = linkedInstances.removeAll(id);
setLinkedInstances(linkedInstances);
return numRemoved > 0;
}
bool BaseInstance::isLinkedToInstanceId(const QString& id) const
{
auto linkedInstances = getLinkedInstances();
return linkedInstances.contains(id);
}
void BaseInstance::iconUpdated(QString key)
{
if (iconKey() == key) {
emit propertiesChanged(this);
}
}
void BaseInstance::invalidate()
{
changeStatus(Status::Gone);
qDebug() << "Instance" << id() << "has been invalidated.";
}
void BaseInstance::changeStatus(BaseInstance::Status newStatus)
{
Status status = currentStatus();
if (status != newStatus) {
m_status = newStatus;
emit statusChanged(status, newStatus);
}
}
BaseInstance::Status BaseInstance::currentStatus() const
{
return m_status;
}
QString BaseInstance::id() const
{
return QFileInfo(instanceRoot()).fileName();
}
bool BaseInstance::isRunning() const
{
return m_isRunning;
}
void BaseInstance::setRunning(bool running)
{
if (running == m_isRunning)
return;
m_isRunning = running;
emit runningStatusChanged(running);
}
void BaseInstance::setMinecraftRunning(bool running)
{
if (!settings()->get("RecordGameTime").toBool()) {
return;
}
if (running) {
m_timeStarted = QDateTime::currentDateTime();
setLastLaunch(m_timeStarted.toMSecsSinceEpoch());
} else {
QDateTime timeEnded = QDateTime::currentDateTime();
qint64 current = settings()->get("totalTimePlayed").toLongLong();
settings()->set("totalTimePlayed", current + m_timeStarted.secsTo(timeEnded));
settings()->set("lastTimePlayed", m_timeStarted.secsTo(timeEnded));
emit propertiesChanged(this);
}
}
int64_t BaseInstance::totalTimePlayed() const
{
qint64 current = m_settings->get("totalTimePlayed").toLongLong();
if (m_isRunning) {
QDateTime timeNow = QDateTime::currentDateTime();
return current + m_timeStarted.secsTo(timeNow);
}
return current;
}
int64_t BaseInstance::lastTimePlayed() const
{
if (m_isRunning) {
QDateTime timeNow = QDateTime::currentDateTime();
return m_timeStarted.secsTo(timeNow);
}
return m_settings->get("lastTimePlayed").toLongLong();
}
void BaseInstance::resetTimePlayed()
{
settings()->reset("totalTimePlayed");
settings()->reset("lastTimePlayed");
}
QString BaseInstance::instanceType() const
{
return m_settings->get("InstanceType").toString();
}
QString BaseInstance::instanceRoot() const
{
return m_rootDir;
}
SettingsObject* BaseInstance::settings()
{
loadSpecificSettings();
return m_settings.get();
}
bool BaseInstance::canLaunch() const
{
return (!hasVersionBroken() && !isRunning());
}
bool BaseInstance::reloadSettings()
{
return m_settings->reload();
}
qint64 BaseInstance::lastLaunch() const
{
return m_settings->get("lastLaunchTime").value<qint64>();
}
void BaseInstance::setLastLaunch(qint64 val)
{
// FIXME: if no change, do not set. setting involves saving a file.
m_settings->set("lastLaunchTime", val);
emit propertiesChanged(this);
}
void BaseInstance::setNotes(QString val)
{
// FIXME: if no change, do not set. setting involves saving a file.
m_settings->set("notes", val);
}
QString BaseInstance::notes() const
{
return m_settings->get("notes").toString();
}
void BaseInstance::setIconKey(QString val)
{
// FIXME: if no change, do not set. setting involves saving a file.
m_settings->set("iconKey", val);
emit propertiesChanged(this);
}
QString BaseInstance::iconKey() const
{
return m_settings->get("iconKey").toString();
}
void BaseInstance::setName(QString val)
{
// FIXME: if no change, do not set. setting involves saving a file.
m_settings->set("name", val);
emit propertiesChanged(this);
}
bool BaseInstance::syncInstanceDirName(const QString& newRoot) const
{
auto oldRoot = instanceRoot();
return oldRoot == newRoot || QFile::rename(oldRoot, newRoot);
}
void BaseInstance::registerShortcut(const ShortcutData& data)
{
auto currentShortcuts = shortcuts();
currentShortcuts.append(data);
qDebug() << "Registering shortcut for instance" << id() << "with name" << data.name << "and path" << data.filePath;
setShortcuts(currentShortcuts);
}
void BaseInstance::setShortcuts(const QList<ShortcutData>& shortcuts)
{
// FIXME: if no change, do not set. setting involves saving a file.
QJsonArray array;
for (const auto& elem : shortcuts) {
array.append(QJsonObject{ { "name", elem.name }, { "filePath", elem.filePath }, { "target", static_cast<int>(elem.target) } });
}
QJsonDocument document;
document.setArray(array);
m_settings->set("shortcuts", QString::fromUtf8(document.toJson(QJsonDocument::Compact)));
}
QList<ShortcutData> BaseInstance::shortcuts() const
{
auto data = m_settings->get("shortcuts").toString().toUtf8();
QJsonParseError parseError;
auto document = QJsonDocument::fromJson(data, &parseError);
if (parseError.error != QJsonParseError::NoError || !document.isArray())
return {};
QList<ShortcutData> results;
for (const auto& elem : document.array()) {
if (!elem.isObject())
continue;
auto dict = elem.toObject();
if (!dict.contains("name") || !dict.contains("filePath") || !dict.contains("target"))
continue;
int value = dict["target"].toInt(-1);
if (!dict["name"].isString() || !dict["filePath"].isString() || value < 0 || value >= 3)
continue;
QString shortcutName = dict["name"].toString();
QString filePath = dict["filePath"].toString();
if (!QDir(filePath).exists()) {
qWarning() << "Shortcut" << shortcutName << "for instance" << name() << "have non-existent path" << filePath;
continue;
}
results.append({ shortcutName, filePath, static_cast<ShortcutTarget>(value) });
}
return results;
}
QString BaseInstance::name() const
{
return m_settings->get("name").toString();
}
QString BaseInstance::windowTitle() const
{
return BuildConfig.LAUNCHER_DISPLAYNAME + ": " + name();
}
// FIXME: why is this here? move it to MinecraftInstance!!!
QStringList BaseInstance::extraArguments()
{
return Commandline::splitArgs(settings()->get("JvmArgs").toString());
}
LaunchTask* BaseInstance::getLaunchTask()
{
return m_launchProcess.get();
}
void BaseInstance::updateRuntimeContext()
{
// NOOP
}
bool BaseInstance::isLegacy()
{
return traits().contains("legacyLaunch") || traits().contains("alphaLaunch");
}

329
launcher/BaseInstance.h Normal file
View file

@ -0,0 +1,329 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
* Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org>
* Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <cassert>
#include <QDataStream>
#include <QDateTime>
#include <QList>
#include <QMenu>
#include <QObject>
#include <QProcess>
#include <QSet>
#include "QObjectPtr.h"
#include "settings/SettingsObject.h"
#include "BaseVersionList.h"
#include "MessageLevel.h"
#include "minecraft/auth/MinecraftAccount.h"
#include "settings/INIFile.h"
#include "net/Mode.h"
#include "RuntimeContext.h"
#include "minecraft/launch/MinecraftTarget.h"
class QDir;
class Task;
class LaunchTask;
class BaseInstance;
/// Shortcut saving target representations
enum class ShortcutTarget { Desktop, Applications, Other };
/// Shortcut data representation
struct ShortcutData {
QString name;
QString filePath;
ShortcutTarget target = ShortcutTarget::Other;
};
/// Console settings
int getConsoleMaxLines(SettingsObject* settings);
bool shouldStopOnConsoleOverflow(SettingsObject* settings);
/*!
* \brief Base class for instances.
* This class implements many functions that are common between instances and
* provides a standard interface for all instances.
*
* To create a new instance type, create a new class inheriting from this class
* and implement the pure virtual functions.
*/
class BaseInstance : public QObject {
Q_OBJECT
protected:
/// no-touchy!
BaseInstance(SettingsObject* globalSettings, std::unique_ptr<SettingsObject> settings, const QString& rootDir);
public: /* types */
enum class Status {
Present,
Gone // either nuked or invalidated
};
public:
/// virtual destructor to make sure the destruction is COMPLETE
virtual ~BaseInstance();
virtual void saveNow() = 0;
/***
* the instance has been invalidated - it is no longer tracked by the launcher for some reason,
* but it has not necessarily been deleted.
*
* Happens when the instance folder changes to some other location, or the instance is removed by external means.
*/
void invalidate();
/// The instance's ID. The ID SHALL be determined by LAUNCHER internally. The ID IS guaranteed to
/// be unique.
virtual QString id() const;
void setMinecraftRunning(bool running);
void setRunning(bool running);
bool isRunning() const;
int64_t totalTimePlayed() const;
int64_t lastTimePlayed() const;
void resetTimePlayed();
/// get the type of this instance
QString instanceType() const;
/// Path to the instance's root directory.
QString instanceRoot() const;
/// Path to the instance's game root directory.
virtual QString gameRoot() const { return instanceRoot(); }
/// Path to the instance's mods directory.
virtual QString modsRoot() const = 0;
QString name() const;
void setName(QString val);
/// Sync name and rename instance dir accordingly; returns true if successful
bool syncInstanceDirName(const QString& newRoot) const;
/// Register a created shortcut
void registerShortcut(const ShortcutData& data);
QList<ShortcutData> shortcuts() const;
void setShortcuts(const QList<ShortcutData>& shortcuts);
/// Value used for instance window titles
QString windowTitle() const;
QString iconKey() const;
void setIconKey(QString val);
QString notes() const;
void setNotes(QString val);
QString getPreLaunchCommand();
QString getPostExitCommand();
QString getWrapperCommand();
bool isManagedPack() const;
QString getManagedPackType() const;
QString getManagedPackID() const;
QString getManagedPackName() const;
QString getManagedPackVersionID() const;
QString getManagedPackVersionName() const;
void setManagedPack(const QString& type, const QString& id, const QString& name, const QString& versionId, const QString& version);
void copyManagedPack(BaseInstance& other);
virtual QStringList extraArguments();
/// Traits. Normally inside the version, depends on instance implementation.
virtual QSet<QString> traits() const = 0;
/**
* Gets the time that the instance was last launched.
* Stored in milliseconds since epoch.
*/
qint64 lastLaunch() const;
/// Sets the last launched time to 'val' milliseconds since epoch
void setLastLaunch(qint64 val = QDateTime::currentMSecsSinceEpoch());
/*!
* \brief Gets this instance's settings object.
* This settings object stores instance-specific settings.
*
* Note that this method is not const.
* It may call loadSpecificSettings() to ensure those are loaded.
*
* \return A pointer to this instance's settings object.
*/
virtual SettingsObject* settings();
/*!
* \brief Loads settings specific to an instance type if they're not already loaded.
*/
virtual void loadSpecificSettings() = 0;
/// returns a valid update task
virtual QList<Task::Ptr> createUpdateTask() = 0;
/// returns a valid launcher (task container)
virtual LaunchTask* createLaunchTask(AuthSessionPtr account, MinecraftTarget::Ptr targetToJoin) = 0;
/// returns the current launch task (if any)
LaunchTask* getLaunchTask();
/*!
* Create envrironment variables for running the instance
*/
virtual QProcessEnvironment createEnvironment() = 0;
virtual QProcessEnvironment createLaunchEnvironment() = 0;
/*!
* Returns the root folder to use for looking up log files
*/
virtual QStringList getLogFileSearchPaths() = 0;
virtual QString getStatusbarDescription() = 0;
/// FIXME: this really should be elsewhere...
virtual QString instanceConfigFolder() const = 0;
/// get variables this instance exports
virtual QMap<QString, QString> getVariables() = 0;
virtual QString typeName() const = 0;
virtual void updateRuntimeContext();
RuntimeContext runtimeContext() const { return m_runtimeContext; }
bool hasVersionBroken() const { return m_hasBrokenVersion; }
void setVersionBroken(bool value)
{
if (m_hasBrokenVersion != value) {
m_hasBrokenVersion = value;
emit propertiesChanged(this);
}
}
bool hasUpdateAvailable() const { return m_hasUpdate; }
void setUpdateAvailable(bool value)
{
if (m_hasUpdate != value) {
m_hasUpdate = value;
emit propertiesChanged(this);
}
}
bool hasCrashed() const { return m_crashed; }
void setCrashed(bool value)
{
if (m_crashed != value) {
m_crashed = value;
emit propertiesChanged(this);
}
}
virtual bool canLaunch() const;
virtual bool canEdit() const = 0;
virtual bool canExport() const = 0;
virtual void populateLaunchMenu(QMenu* menu) = 0;
bool reloadSettings();
/**
* 'print' a verbose description of the instance into a QStringList
*/
virtual QStringList verboseDescription(AuthSessionPtr session, MinecraftTarget::Ptr targetToJoin) = 0;
Status currentStatus() const;
QStringList getLinkedInstances() const;
void setLinkedInstances(const QStringList& list);
void addLinkedInstanceId(const QString& id);
bool removeLinkedInstanceId(const QString& id);
bool isLinkedToInstanceId(const QString& id) const;
bool isLegacy();
protected:
void changeStatus(Status newStatus);
SettingsObject* globalSettings() const { return m_global_settings; }
bool isSpecificSettingsLoaded() const { return m_specific_settings_loaded; }
void setSpecificSettingsLoaded(bool loaded) { m_specific_settings_loaded = loaded; }
signals:
/*!
* \brief Signal emitted when properties relevant to the instance view change
*/
void propertiesChanged(BaseInstance* inst);
void launchTaskChanged(LaunchTask*);
void runningStatusChanged(bool running);
void profilerChanged();
void statusChanged(Status from, Status to);
protected slots:
void iconUpdated(QString key);
protected: /* data */
QString m_rootDir;
std::unique_ptr<SettingsObject> m_settings;
// InstanceFlags m_flags;
bool m_isRunning = false;
std::unique_ptr<LaunchTask> m_launchProcess;
QDateTime m_timeStarted;
RuntimeContext m_runtimeContext;
private: /* data */
Status m_status = Status::Present;
bool m_crashed = false;
bool m_hasUpdate = false;
bool m_hasBrokenVersion = false;
SettingsObject* m_global_settings;
bool m_specific_settings_loaded = false;
};
Q_DECLARE_METATYPE(shared_qobject_ptr<BaseInstance>)
// Q_DECLARE_METATYPE(BaseInstance::InstanceFlag)
// Q_DECLARE_OPERATORS_FOR_FLAGS(BaseInstance::InstanceFlags)

51
launcher/BaseVersion.h Normal file
View file

@ -0,0 +1,51 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QMetaType>
#include <QString>
#include <memory>
/*!
* An abstract base class for versions.
*/
class BaseVersion {
public:
// TODO: delete
using Ptr = std::shared_ptr<BaseVersion>;
virtual ~BaseVersion() {}
/*!
* A string used to identify this version in config files.
* This should be unique within the version list or shenanigans will occur.
*/
virtual QString descriptor() const = 0;
/*!
* The name of this version as it is displayed to the user.
* For example: "1.5.1"
*/
virtual QString name() const = 0;
/*!
* This should return a string that describes
* the kind of version this is (Stable, Beta, Snapshot, whatever)
*/
virtual QString typeString() const = 0;
virtual bool operator<(BaseVersion& a) const { return name() < a.name(); }
virtual bool operator>(BaseVersion& a) const { return name() > a.name(); }
};
Q_DECLARE_METATYPE(BaseVersion::Ptr)

View file

@ -0,0 +1,125 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "BaseVersionList.h"
#include "BaseVersion.h"
BaseVersionList::BaseVersionList(QObject* parent) : QAbstractListModel(parent) {}
BaseVersion::Ptr BaseVersionList::findVersion(const QString& descriptor)
{
for (int i = 0; i < count(); i++) {
if (at(i)->descriptor() == descriptor)
return at(i);
}
return nullptr;
}
BaseVersion::Ptr BaseVersionList::getRecommended() const
{
if (count() <= 0)
return nullptr;
else
return at(0);
}
QVariant BaseVersionList::data(const QModelIndex& index, int role) const
{
if (!index.isValid())
return QVariant();
if (index.row() > count())
return QVariant();
BaseVersion::Ptr version = at(index.row());
switch (role) {
case VersionPointerRole:
return QVariant::fromValue(version);
case VersionRole:
return version->name();
case VersionIdRole:
return version->descriptor();
case TypeRole:
return version->typeString();
case JavaMajorRole: {
auto major = version->name();
if (major.startsWith("java")) {
major = "Java " + major.mid(4);
}
return major;
}
default:
return QVariant();
}
}
BaseVersionList::RoleList BaseVersionList::providesRoles() const
{
return { VersionPointerRole, VersionRole, VersionIdRole, TypeRole };
}
int BaseVersionList::rowCount(const QModelIndex& parent) const
{
// Return count
return parent.isValid() ? 0 : count();
}
int BaseVersionList::columnCount(const QModelIndex& parent) const
{
return parent.isValid() ? 0 : 1;
}
QHash<int, QByteArray> BaseVersionList::roleNames() const
{
QHash<int, QByteArray> roles = QAbstractListModel::roleNames();
roles.insert(VersionRole, "version");
roles.insert(VersionIdRole, "versionId");
roles.insert(ParentVersionRole, "parentGameVersion");
roles.insert(RecommendedRole, "recommended");
roles.insert(LatestRole, "latest");
roles.insert(TypeRole, "type");
roles.insert(BranchRole, "branch");
roles.insert(PathRole, "path");
roles.insert(JavaNameRole, "javaName");
roles.insert(CPUArchitectureRole, "architecture");
roles.insert(JavaMajorRole, "javaMajor");
return roles;
}

120
launcher/BaseVersionList.h Normal file
View file

@ -0,0 +1,120 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QAbstractListModel>
#include <QObject>
#include <QVariant>
#include "BaseVersion.h"
#include "QObjectPtr.h"
#include "tasks/Task.h"
/*!
* \brief Class that each instance type's version list derives from.
* Version lists are the lists that keep track of the available game versions
* for that instance. This list will not be loaded on startup. It will be loaded
* when the list's load function is called. Before using the version list, you
* should check to see if it has been loaded yet and if not, load the list.
*
* Note that this class also inherits from QAbstractListModel. Methods from that
* class determine how this version list shows up in a list view. Said methods
* all have a default implementation, but they can be overridden by plugins to
* change the behavior of the list.
*/
class BaseVersionList : public QAbstractListModel {
Q_OBJECT
public:
enum ModelRoles {
VersionPointerRole = Qt::UserRole,
VersionRole,
VersionIdRole,
ParentVersionRole,
RecommendedRole,
LatestRole,
TypeRole,
BranchRole,
PathRole,
JavaNameRole,
JavaMajorRole,
CPUArchitectureRole,
SortRole
};
using RoleList = QList<int>;
explicit BaseVersionList(QObject* parent = 0);
/*!
* \brief Gets a task that will reload the version list.
* Simply execute the task to load the list.
* The task returned by this function should reset the model when it's done.
* \return A pointer to a task that reloads the version list.
*/
virtual Task::Ptr getLoadTask() = 0;
//! Checks whether or not the list is loaded. If this returns false, the list should be
// loaded.
virtual bool isLoaded() = 0;
//! Gets the version at the given index.
virtual const BaseVersion::Ptr at(int i) const = 0;
//! Returns the number of versions in the list.
virtual int count() const = 0;
//////// List Model Functions ////////
QVariant data(const QModelIndex& index, int role) const override;
int rowCount(const QModelIndex& parent) const override;
int columnCount(const QModelIndex& parent) const override;
QHash<int, QByteArray> roleNames() const override;
//! which roles are provided by this version list?
virtual RoleList providesRoles() const;
/*!
* \brief Finds a version by its descriptor.
* \param descriptor The descriptor of the version to find.
* \return A const pointer to the version with the given descriptor. NULL if
* one doesn't exist.
*/
virtual BaseVersion::Ptr findVersion(const QString& descriptor);
/*!
* \brief Gets the recommended version from this list
* If the list doesn't support recommended versions, this works exactly as getLatestStable
*/
virtual BaseVersion::Ptr getRecommended() const;
/*!
* Sorts the version list.
*/
virtual void sortVersions() = 0;
protected slots:
/*!
* Updates this list with the given list of versions.
* This is done by copying each version in the given list and inserting it
* into this one.
* We need to do this so that we can set the parents of the versions are set to this
* version list. This can't be done in the load task, because the versions the load
* task creates are on the load task's thread and Qt won't allow their parents
* to be set to something created on another thread.
* To get around that problem, we invoke this method on the GUI thread, which
* then copies the versions and sets their parents correctly.
* \param versions List of versions whose parents should be set.
*/
virtual void updateListData(QList<BaseVersion::Ptr> versions) = 0;
};

1683
launcher/CMakeLists.txt Normal file

File diff suppressed because it is too large Load diff

85
launcher/Commandline.cpp Normal file
View file

@ -0,0 +1,85 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2013-2021 MultiMC Contributors
*
* Authors: Orochimarufan <orochimarufan.x3@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "Commandline.h"
/**
* @file libutil/src/cmdutils.cpp
*/
namespace Commandline {
// commandline splitter
QStringList splitArgs(QString args)
{
QStringList argv;
QString current;
bool escape = false;
QChar inquotes;
for (int i = 0; i < args.length(); i++) {
QChar cchar = args.at(i);
// \ escaped
if (escape) {
current += cchar;
escape = false;
// in "quotes"
} else if (!inquotes.isNull()) {
if (cchar == '\\')
escape = true;
else if (cchar == inquotes)
inquotes = QChar::Null;
else
current += cchar;
// otherwise
} else {
if (cchar == ' ') {
if (!current.isEmpty()) {
argv << current;
current.clear();
}
} else if (cchar == '"' || cchar == '\'')
inquotes = cchar;
else
current += cchar;
}
}
if (!current.isEmpty())
argv << current;
return argv;
}
} // namespace Commandline

36
launcher/Commandline.h Normal file
View file

@ -0,0 +1,36 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Authors: Orochimarufan <orochimarufan.x3@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QString>
#include <QStringList>
/**
* @file libutil/include/cmdutils.h
* @brief commandline parsing and processing utilities
*/
namespace Commandline {
/**
* @brief split a string into argv items like a shell would do
* @param args the argument string
* @return a QStringList containing all arguments
*/
QStringList splitArgs(QString args);
} // namespace Commandline

View file

@ -0,0 +1,85 @@
// SPDX-FileCopyrightText: 2022 Sefa Eyeoglu <contact@scrumplex.net>
//
// SPDX-License-Identifier: GPL-3.0-only
#include "DataMigrationTask.h"
#include "FileSystem.h"
#include <QDirIterator>
#include <QFileInfo>
#include <QMap>
#include <QtConcurrent>
DataMigrationTask::DataMigrationTask(const QString& sourcePath, const QString& targetPath, Filter pathMatcher)
: Task(), m_sourcePath(sourcePath), m_targetPath(targetPath), m_pathMatcher(pathMatcher), m_copy(sourcePath, targetPath)
{
m_copy.matcher(m_pathMatcher).whitelist(true);
}
void DataMigrationTask::executeTask()
{
setStatus(tr("Scanning files..."));
// 1. Scan
// Check how many files we gotta copy
m_copyFuture = QtConcurrent::run(QThreadPool::globalInstance(), [this] {
return m_copy(true); // dry run to collect amount of files
});
connect(&m_copyFutureWatcher, &QFutureWatcher<bool>::finished, this, &DataMigrationTask::dryRunFinished);
connect(&m_copyFutureWatcher, &QFutureWatcher<bool>::canceled, this, &DataMigrationTask::dryRunAborted);
m_copyFutureWatcher.setFuture(m_copyFuture);
}
void DataMigrationTask::dryRunFinished()
{
disconnect(&m_copyFutureWatcher, &QFutureWatcher<bool>::finished, this, &DataMigrationTask::dryRunFinished);
disconnect(&m_copyFutureWatcher, &QFutureWatcher<bool>::canceled, this, &DataMigrationTask::dryRunAborted);
if (!m_copyFuture.isValid() || !m_copyFuture.result()) {
emitFailed(tr("Failed to scan source path."));
return;
}
// 2. Copy
// Actually copy all files now.
m_toCopy = m_copy.totalCopied();
connect(&m_copy, &FS::copy::fileCopied, [&, this](const QString& relativeName) {
QString shortenedName = relativeName;
// shorten the filename to hopefully fit into one line
if (shortenedName.length() > 50)
shortenedName = relativeName.left(20) + "" + relativeName.right(29);
setProgress(m_copy.totalCopied(), m_toCopy);
setStatus(tr("Copying %1…").arg(shortenedName));
});
m_copyFuture = QtConcurrent::run(QThreadPool::globalInstance(), [this] {
return m_copy(false); // actually copy now
});
connect(&m_copyFutureWatcher, &QFutureWatcher<bool>::finished, this, &DataMigrationTask::copyFinished);
connect(&m_copyFutureWatcher, &QFutureWatcher<bool>::canceled, this, &DataMigrationTask::copyAborted);
m_copyFutureWatcher.setFuture(m_copyFuture);
}
void DataMigrationTask::dryRunAborted()
{
emitAborted();
}
void DataMigrationTask::copyFinished()
{
disconnect(&m_copyFutureWatcher, &QFutureWatcher<bool>::finished, this, &DataMigrationTask::copyFinished);
disconnect(&m_copyFutureWatcher, &QFutureWatcher<bool>::canceled, this, &DataMigrationTask::copyAborted);
if (!m_copyFuture.isValid() || !m_copyFuture.result()) {
emitFailed(tr("Some paths could not be copied!"));
return;
}
emitSucceeded();
}
void DataMigrationTask::copyAborted()
{
emitAborted();
}

View file

@ -0,0 +1,42 @@
// SPDX-FileCopyrightText: 2022 Sefa Eyeoglu <contact@scrumplex.net>
//
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "FileSystem.h"
#include "Filter.h"
#include "tasks/Task.h"
#include <QFuture>
#include <QFutureWatcher>
/*
* Migrate existing data from other MMC-like launchers.
*/
class DataMigrationTask : public Task {
Q_OBJECT
public:
explicit DataMigrationTask(const QString& sourcePath, const QString& targetPath, Filter pathmatcher);
~DataMigrationTask() override = default;
protected:
virtual void executeTask() override;
protected slots:
void dryRunFinished();
void dryRunAborted();
void copyFinished();
void copyAborted();
private:
const QString& m_sourcePath;
const QString& m_targetPath;
const Filter m_pathMatcher;
FS::copy m_copy;
int m_toCopy = 0;
QFuture<bool> m_copyFuture;
QFutureWatcher<bool> m_copyFutureWatcher;
};

View file

@ -0,0 +1,87 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2022 dada513 <dada513@protonmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2013-2022 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "DesktopServices.h"
#include <QDebug>
#include <QDesktopServices>
#include <QDir>
#include <QProcess>
#include "FileSystem.h"
namespace DesktopServices {
bool openPath(const QFileInfo& path, bool ensureFolderPathExists)
{
qDebug() << "Opening path" << path;
if (ensureFolderPathExists) {
FS::ensureFolderPathExists(path);
}
return openUrl(QUrl::fromLocalFile(QFileInfo(path).absoluteFilePath()));
}
bool openPath(const QString& path, bool ensureFolderPathExists)
{
return openPath(QFileInfo(path), ensureFolderPathExists);
}
bool run(const QString& application, const QStringList& args, const QString& workingDirectory, qint64* pid)
{
qDebug() << "Running" << application << "with args" << args.join(' ');
return QProcess::startDetached(application, args, workingDirectory, pid);
}
bool openUrl(const QUrl& url)
{
qDebug() << "Opening URL" << url.toString();
return QDesktopServices::openUrl(url);
}
bool isFlatpak()
{
#ifdef Q_OS_LINUX
return QFile::exists("/.flatpak-info");
#else
return false;
#endif
}
bool isSnap()
{
#ifdef Q_OS_LINUX
return getenv("SNAP");
#else
return false;
#endif
}
} // namespace DesktopServices

View file

@ -0,0 +1,44 @@
#pragma once
#include <QString>
#include <QUrl>
class QFileInfo;
/**
* This wraps around QDesktopServices and adds workarounds where needed
* Use this instead of QDesktopServices!
*/
namespace DesktopServices {
/**
* Open a path in whatever application is applicable.
* @param ensureFolderPathExists Make sure the path exists
*/
bool openPath(const QFileInfo& path, bool ensureFolderPathExists = false);
/**
* Open a path in whatever application is applicable.
* @param ensureFolderPathExists Make sure the path exists
*/
bool openPath(const QString& path, bool ensureFolderPathExists = false);
/**
* Run an application
*/
bool run(const QString& application, const QStringList& args, const QString& workingDirectory = QString(), qint64* pid = 0);
/**
* Open the URL, most likely in a browser. Maybe.
*/
bool openUrl(const QUrl& url);
/**
* Determine whether the launcher is running in a Flatpak environment
*/
bool isFlatpak();
/**
* Determine whether the launcher is running in a Snap environment
*/
bool isSnap();
} // namespace DesktopServices

52
launcher/Exception.h Normal file
View file

@ -0,0 +1,52 @@
// SPDX-License-Identifier: GPL-3.0-only AND Apache-2.0
/*
* Prism Launcher - Minecraft Launcher
* Copyright (c) 2024 TheKodeToad <TheKodeToad@proton.me>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QDebug>
#include <QString>
#include <exception>
class Exception : public std::exception {
public:
Exception(const QString& message) : std::exception(), m_message(message.toUtf8()) { qCritical() << "Exception:" << message; }
Exception(const Exception& other) : std::exception(), m_message(other.m_message) {}
virtual ~Exception() noexcept {}
const char* what() const noexcept { return m_message.constData(); }
QString cause() const { return QString::fromUtf8(m_message); }
private:
QByteArray m_message;
};

View file

@ -0,0 +1,36 @@
#pragma once
template <typename T>
inline void clamp(T& current, T min, T max)
{
if (current < min) {
current = min;
} else if (current > max) {
current = max;
}
}
// List of numbers from min to max. Next is exponent times bigger than previous.
class ExponentialSeries {
public:
ExponentialSeries(unsigned min, unsigned max, unsigned exponent = 2)
{
m_current = m_min = min;
m_max = max;
m_exponent = exponent;
}
void reset() { m_current = m_min; }
unsigned operator()()
{
unsigned retval = m_current;
m_current *= m_exponent;
clamp(m_current, m_min, m_max);
return retval;
}
unsigned m_current;
unsigned m_min;
unsigned m_max;
unsigned m_exponent;
};

View file

@ -0,0 +1,47 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "FastFileIconProvider.h"
#include <QApplication>
#include <QStyle>
QIcon FastFileIconProvider::icon(const QFileInfo& info) const
{
#if QT_VERSION >= QT_VERSION_CHECK(6, 4, 0)
bool link = info.isSymbolicLink() || info.isAlias() || info.isShortcut();
#else
// in versions prior to 6.4 we don't have access to isAlias
bool link = info.isSymLink();
#endif
QStyle::StandardPixmap icon;
if (info.isDir()) {
if (link)
icon = QStyle::SP_DirLinkIcon;
else
icon = QStyle::SP_DirIcon;
} else {
if (link)
icon = QStyle::SP_FileLinkIcon;
else
icon = QStyle::SP_FileIcon;
}
return QApplication::style()->standardIcon(icon);
}

View file

@ -0,0 +1,26 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <QFileIconProvider>
class FastFileIconProvider : public QFileIconProvider {
public:
QIcon icon(const QFileInfo& info) const override;
};

View file

@ -0,0 +1,310 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
* Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "FileIgnoreProxy.h"
#include <QDebug>
#include <QFileSystemModel>
#include <QSortFilterProxyModel>
#include <QStack>
#include "FileSystem.h"
#include "SeparatorPrefixTree.h"
#include "StringUtils.h"
FileIgnoreProxy::FileIgnoreProxy(QString root, QObject* parent) : QSortFilterProxyModel(parent), m_root(root) {}
// NOTE: Sadly, we have to do sorting ourselves.
bool FileIgnoreProxy::lessThan(const QModelIndex& left, const QModelIndex& right) const
{
QFileSystemModel* fsm = qobject_cast<QFileSystemModel*>(sourceModel());
if (!fsm) {
return QSortFilterProxyModel::lessThan(left, right);
}
bool asc = sortOrder() == Qt::AscendingOrder ? true : false;
QFileInfo leftFileInfo = fsm->fileInfo(left);
QFileInfo rightFileInfo = fsm->fileInfo(right);
if (!leftFileInfo.isDir() && rightFileInfo.isDir()) {
return !asc;
}
if (leftFileInfo.isDir() && !rightFileInfo.isDir()) {
return asc;
}
// sort and proxy model breaks the original model...
if (sortColumn() == 0) {
return StringUtils::naturalCompare(leftFileInfo.fileName(), rightFileInfo.fileName(), Qt::CaseInsensitive) < 0;
}
if (sortColumn() == 1) {
auto leftSize = leftFileInfo.size();
auto rightSize = rightFileInfo.size();
if ((leftSize == rightSize) || (leftFileInfo.isDir() && rightFileInfo.isDir())) {
return StringUtils::naturalCompare(leftFileInfo.fileName(), rightFileInfo.fileName(), Qt::CaseInsensitive) < 0 ? asc : !asc;
}
return leftSize < rightSize;
}
return QSortFilterProxyModel::lessThan(left, right);
}
Qt::ItemFlags FileIgnoreProxy::flags(const QModelIndex& index) const
{
if (!index.isValid())
return Qt::NoItemFlags;
auto sourceIndex = mapToSource(index);
Qt::ItemFlags flags = sourceIndex.flags();
if (index.column() == 0) {
flags |= Qt::ItemIsUserCheckable;
if (sourceIndex.model()->hasChildren(sourceIndex)) {
flags |= Qt::ItemIsAutoTristate;
}
}
return flags;
}
QVariant FileIgnoreProxy::data(const QModelIndex& index, int role) const
{
QModelIndex sourceIndex = mapToSource(index);
if (index.column() == 0 && role == Qt::CheckStateRole) {
QFileSystemModel* fsm = qobject_cast<QFileSystemModel*>(sourceModel());
auto blockedPath = relPath(fsm->filePath(sourceIndex));
auto cover = m_blocked.cover(blockedPath);
if (!cover.isNull()) {
return QVariant(Qt::Unchecked);
} else if (m_blocked.exists(blockedPath)) {
return QVariant(Qt::PartiallyChecked);
} else {
return QVariant(Qt::Checked);
}
}
return sourceIndex.data(role);
}
bool FileIgnoreProxy::setData(const QModelIndex& index, const QVariant& value, int role)
{
if (index.column() == 0 && role == Qt::CheckStateRole) {
Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
return setFilterState(index, state);
}
QModelIndex sourceIndex = mapToSource(index);
return QSortFilterProxyModel::sourceModel()->setData(sourceIndex, value, role);
}
QString FileIgnoreProxy::relPath(const QString& path) const
{
return QDir(m_root).relativeFilePath(path);
}
bool FileIgnoreProxy::setFilterState(QModelIndex index, Qt::CheckState state)
{
QFileSystemModel* fsm = qobject_cast<QFileSystemModel*>(sourceModel());
if (!fsm) {
return false;
}
QModelIndex sourceIndex = mapToSource(index);
auto blockedPath = relPath(fsm->filePath(sourceIndex));
bool changed = false;
if (state == Qt::Unchecked) {
// blocking a path
auto& node = m_blocked.insert(blockedPath);
// get rid of all blocked nodes below
node.clear();
changed = true;
} else if (state == Qt::Checked || state == Qt::PartiallyChecked) {
if (!m_blocked.remove(blockedPath)) {
auto cover = m_blocked.cover(blockedPath);
qDebug() << "Blocked by cover" << cover;
// uncover
m_blocked.remove(cover);
// block all contents, except for any cover
QModelIndex rootIndex = fsm->index(FS::PathCombine(m_root, cover));
QModelIndex doing = rootIndex;
int row = 0;
QStack<QModelIndex> todo;
while (1) {
auto node = fsm->index(row, 0, doing);
if (!node.isValid()) {
if (!todo.size()) {
break;
} else {
doing = todo.pop();
row = 0;
continue;
}
}
auto relpath = relPath(fsm->filePath(node));
if (blockedPath.startsWith(relpath)) // cover found?
{
// continue processing cover later
todo.push(node);
} else {
// or just block this one.
m_blocked.insert(relpath);
}
row++;
}
}
changed = true;
}
if (changed) {
// update the thing
emit dataChanged(index, index, { Qt::CheckStateRole });
// update everything above index
QModelIndex up = index.parent();
while (1) {
if (!up.isValid())
break;
emit dataChanged(up, up, { Qt::CheckStateRole });
up = up.parent();
}
// and everything below the index
QModelIndex doing = index;
int row = 0;
QStack<QModelIndex> todo;
while (1) {
auto node = this->index(row, 0, doing);
if (!node.isValid()) {
if (!todo.size()) {
break;
} else {
doing = todo.pop();
row = 0;
continue;
}
}
emit dataChanged(node, node, { Qt::CheckStateRole });
todo.push(node);
row++;
}
// siblings and unrelated nodes are ignored
}
return true;
}
bool FileIgnoreProxy::shouldExpand(QModelIndex index)
{
QModelIndex sourceIndex = mapToSource(index);
QFileSystemModel* fsm = qobject_cast<QFileSystemModel*>(sourceModel());
if (!fsm) {
return false;
}
auto blockedPath = relPath(fsm->filePath(sourceIndex));
auto found = m_blocked.find(blockedPath);
if (found) {
return !found->leaf();
}
return false;
}
void FileIgnoreProxy::setBlockedPaths(QStringList paths)
{
beginResetModel();
m_blocked.clear();
m_blocked.insert(paths);
endResetModel();
}
bool FileIgnoreProxy::filterAcceptsColumn(int source_column, const QModelIndex& source_parent) const
{
Q_UNUSED(source_parent)
// adjust the columns you want to filter out here
// return false for those that will be hidden
if (source_column == 2 || source_column == 3)
return false;
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
{
if (m_ignoreFiles.contains(fileInfo.fileName())) {
return true;
}
for (const auto& suffix : m_ignoreFilesSuffixes) {
if (fileInfo.fileName().endsWith(suffix)) {
return true;
}
}
if (m_ignoreFilePaths.covers(relPath(fileInfo.absoluteFilePath()))) {
return true;
}
return false;
}
bool FileIgnoreProxy::filterFile(const QFileInfo& file) const
{
return m_blocked.covers(relPath(file.absoluteFilePath())) || ignoreFile(file);
}
void FileIgnoreProxy::loadBlockedPathsFromFile(const QString& fileName)
{
QFile ignoreFile(fileName);
if (!ignoreFile.open(QIODevice::ReadOnly)) {
return;
}
auto ignoreData = ignoreFile.readAll();
auto string = QString::fromUtf8(ignoreData);
setBlockedPaths(string.split('\n', Qt::SkipEmptyParts));
}
void FileIgnoreProxy::saveBlockedPathsToFile(const QString& fileName)
{
auto ignoreData = blockedPaths().toStringList().join('\n').toUtf8();
try {
FS::write(fileName, ignoreData);
} catch (const Exception& e) {
qWarning() << e.cause();
}
}

View file

@ -0,0 +1,91 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
* Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QFileInfo>
#include <QSortFilterProxyModel>
#include "SeparatorPrefixTree.h"
class FileIgnoreProxy : public QSortFilterProxyModel {
Q_OBJECT
public:
FileIgnoreProxy(QString root, QObject* parent);
// NOTE: Sadly, we have to do sorting ourselves.
bool lessThan(const QModelIndex& left, const QModelIndex& right) const;
virtual Qt::ItemFlags flags(const QModelIndex& index) const;
virtual QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
virtual bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole);
QString relPath(const QString& path) const;
bool setFilterState(QModelIndex index, Qt::CheckState state);
bool shouldExpand(QModelIndex index);
void setBlockedPaths(QStringList paths);
inline const SeparatorPrefixTree<'/'>& blockedPaths() const { return m_blocked; }
inline SeparatorPrefixTree<'/'>& blockedPaths() { return m_blocked; }
// list of file names that need to be removed completely from model
inline QStringList& ignoreFilesWithName() { return m_ignoreFiles; }
inline QStringList& ignoreFilesWithSuffix() { return m_ignoreFilesSuffixes; }
// list of relative paths that need to be removed completely from model
inline SeparatorPrefixTree<'/'>& ignoreFilesWithPath() { return m_ignoreFilePaths; }
bool filterFile(const QFileInfo& fileName) const;
void loadBlockedPathsFromFile(const QString& fileName);
void saveBlockedPathsToFile(const QString& fileName);
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 m_root;
SeparatorPrefixTree<'/'> m_blocked;
QStringList m_ignoreFiles;
QStringList m_ignoreFilesSuffixes;
SeparatorPrefixTree<'/'> m_ignoreFilePaths;
};

1724
launcher/FileSystem.cpp Normal file

File diff suppressed because it is too large Load diff

571
launcher/FileSystem.h Normal file
View file

@ -0,0 +1,571 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
* Copyright (C) 2022 TheKodeToad <TheKodeToad@proton.me>
* Copyright (C) 2022 Rachel Powers <508861+Ryex@users.noreply.github.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "Exception.h"
#include "Filter.h"
#include <system_error>
#include <QDir>
#include <QFlags>
#include <QLocalServer>
#include <QObject>
#include <QPair>
#include <QThread>
namespace FS {
class FileSystemException : public ::Exception {
public:
FileSystemException(const QString& message) : Exception(message) {}
};
/**
* write data to a file safely
*/
void write(const QString& filename, const QByteArray& data);
/**
* append data to a file safely
*/
void appendSafe(const QString& filename, const QByteArray& data);
/**
* append data to a file
*/
void append(const QString& filename, const QByteArray& data);
/**
* read data from a file safely
*/
QByteArray read(const QString& filename);
/**
* Update the last changed timestamp of an existing file
*/
bool updateTimestamp(const QString& filename);
/**
* Creates all the folders in a path for the specified path
* last segment of the path is treated as a file name and is ignored!
*/
bool ensureFilePathExists(QString filenamepath);
/**
* Creates all the folders in a path for the specified path
* last segment of the path is treated as a folder name and is created!
*/
bool ensureFolderPathExists(const QFileInfo folderPath);
/**
* Creates all the folders in a path for the specified path
* last segment of the path is treated as a folder name and is created!
*/
bool ensureFolderPathExists(const QString folderPathName);
/**
* @brief Copies a directory and it's contents from src to dest
*/
class copy : public QObject {
Q_OBJECT
public:
copy(const QString& src, const QString& dst, QObject* parent = nullptr) : QObject(parent)
{
m_src.setPath(src);
m_dst.setPath(dst);
}
copy& followSymlinks(const bool follow)
{
m_followSymlinks = follow;
return *this;
}
copy& matcher(Filter filter)
{
m_matcher = std::move(filter);
return *this;
}
copy& whitelist(bool whitelist)
{
m_whitelist = whitelist;
return *this;
}
copy& overwrite(const bool overwrite)
{
m_overwrite = overwrite;
return *this;
}
bool operator()(bool dryRun = false) { return operator()(QString(), dryRun); }
qsizetype totalCopied() { return m_copied; }
qsizetype 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:
bool operator()(const QString& offset, bool dryRun = false);
private:
bool m_followSymlinks = true;
Filter m_matcher = nullptr;
bool m_whitelist = false;
bool m_overwrite = false;
QDir m_src;
QDir m_dst;
qsizetype m_copied;
QStringList m_failedPaths;
};
struct LinkPair {
QString src;
QString dst;
};
struct LinkResult {
QString src;
QString dst;
QString err_msg;
int err_value;
};
class ExternalLinkFileProcess : public QThread {
Q_OBJECT
public:
ExternalLinkFileProcess(QString server, bool useHardLinks, QObject* parent = nullptr)
: QThread(parent), m_useHardLinks(useHardLinks), m_server(server)
{}
void run() override
{
runLinkFile();
emit processExited();
}
signals:
void processExited();
private:
void runLinkFile();
bool m_useHardLinks = false;
QString m_server;
};
/**
* @brief links (a file / a directory and it's contents) from src to dest
*/
class create_link : public QObject {
Q_OBJECT
public:
create_link(const QList<LinkPair> path_pairs, QObject* parent = nullptr) : QObject(parent) { m_path_pairs.append(path_pairs); }
create_link(const QString& src, const QString& dst, QObject* parent = nullptr) : QObject(parent)
{
LinkPair pair = { src, dst };
m_path_pairs.append(pair);
}
create_link& useHardLinks(const bool useHard)
{
m_useHardLinks = useHard;
return *this;
}
create_link& matcher(Filter filter)
{
m_matcher = std::move(filter);
return *this;
}
create_link& whitelist(bool whitelist)
{
m_whitelist = whitelist;
return *this;
}
create_link& linkRecursively(bool recursive)
{
m_recursive = recursive;
return *this;
}
create_link& setMaxDepth(int depth)
{
m_max_depth = depth;
return *this;
}
create_link& debug(bool d)
{
m_debug = d;
return *this;
}
std::error_code getOSError() { return m_os_err; }
bool operator()(bool dryRun = false) { return operator()(QString(), dryRun); }
int totalLinked() { return m_linked; }
int totalToLink() { return static_cast<int>(m_links_to_make.size()); }
void runPrivileged() { runPrivileged(QString()); }
void runPrivileged(const QString& offset);
QList<LinkResult> getResults() { return m_path_results; }
signals:
void fileLinked(const QString& srcName, const QString& dstName);
void linkFailed(const QString& srcName, const QString& dstName, const QString& err_msg, int err_value);
void finished();
void finishedPrivileged(bool gotResults);
private:
bool operator()(const QString& offset, bool dryRun = false);
void make_link_list(const QString& offset);
bool make_links();
private:
bool m_useHardLinks = false;
Filter m_matcher = nullptr;
bool m_whitelist = false;
bool m_recursive = true;
/// @brief >= -1 = infinite, 0 = link files at src/* to dest/*, 1 = link files at src/*/* to dest/*/*, etc.
int m_max_depth = -1;
QList<LinkPair> m_path_pairs;
QList<LinkResult> m_path_results;
QList<LinkPair> m_links_to_make;
int m_linked;
bool m_debug = false;
std::error_code m_os_err;
QLocalServer m_linkServer;
};
/**
* @brief moves a file by renaming it
* @param source source file path
* @param dest destination filepath
*
*/
bool move(const QString& source, const QString& dest);
/**
* Delete a folder recursively
*/
bool deletePath(QString path);
bool removeFiles(QStringList listFile);
/**
* Trash a folder / file
*/
bool trash(QString path, QString* pathInTrash = nullptr);
QString PathCombine(const QString& path1, const QString& path2);
QString PathCombine(const QString& path1, const QString& path2, const QString& path3);
QString PathCombine(const QString& path1, const QString& path2, const QString& path3, const QString& path4);
QString AbsolutePath(const QString& path);
/**
* @brief depth of path. "foo.txt" -> 0 , "bar/foo.txt" -> 1, /baz/bar/foo.txt -> 2, etc.
*
* @param path path to measure
* @return int number of components before base path
*/
int pathDepth(const QString& path);
/**
* @brief cut off segments of path until it is a max of length depth
*
* @param path path to truncate
* @param depth max depth of new path
* @return QString truncated path
*/
QString pathTruncate(const QString& path, int depth);
/**
* Resolve an executable
*
* Will resolve:
* single executable (by name)
* relative path
* absolute path
*
* @return absolute path to executable or null string
*/
QString ResolveExecutable(QString path);
/**
* Normalize path
*
* Any paths inside the current directory will be normalized to relative paths (to current)
* Other paths will be made absolute
*
* Returns false if the path logic somehow filed (and normalizedPath in invalid)
*/
QString NormalizePath(QString path);
QString RemoveInvalidFilenameChars(QString string, QChar replaceWith = '-');
QString RemoveInvalidPathChars(QString string, QChar replaceWith = '-');
QString DirNameFromString(QString string, QString inDir = ".");
/// Checks if the a given Path contains "!"
bool checkProblemticPathJava(QDir folder);
// Get the Directory representing the User's Desktop
QString getDesktopDir();
// Get the Directory representing the User's Applications directory
QString getApplicationsDir();
// Overrides one folder with the contents of another, preserving items exclusive to the first folder
// Equivalent to doing QDir::rename, but allowing for overrides
bool overrideFolder(QString overwritten_path, QString override_path);
/**
* Creates a shortcut to the specified target file at the specified destination path.
* Returns null QString if creation failed; otherwise returns the path to the created shortcut.
*/
QString createShortcut(QString destination, QString target, QStringList args, QString name, QString icon);
enum class FilesystemType {
FAT,
NTFS,
REFS,
EXT,
EXT_2_OLD,
EXT_2_3_4,
XFS,
BTRFS,
NFS,
ZFS,
APFS,
HFS,
HFSPLUS,
HFSX,
FUSEBLK,
F2FS,
BCACHEFS,
UNKNOWN
};
/**
* @brief Ordered Mapping of enum types to reported filesystem names
* this mapping is non exsaustive, it just attempts to capture the filesystems which could be reasonalbly be in use .
* all string values are in uppercase, use `QString.toUpper()` or equivalent during lookup.
*
* QMap is ordered
*
*/
static const QMap<FilesystemType, QStringList> s_filesystem_type_names = { { FilesystemType::FAT, { "FAT" } },
{ FilesystemType::NTFS, { "NTFS" } },
{ FilesystemType::REFS, { "REFS" } },
{ FilesystemType::EXT_2_OLD, { "EXT_2_OLD", "EXT2_OLD" } },
{ FilesystemType::EXT_2_3_4,
{ "EXT2/3/4", "EXT_2_3_4", "EXT2", "EXT3", "EXT4" } },
{ FilesystemType::EXT, { "EXT" } },
{ FilesystemType::XFS, { "XFS" } },
{ FilesystemType::BTRFS, { "BTRFS" } },
{ FilesystemType::NFS, { "NFS" } },
{ FilesystemType::ZFS, { "ZFS" } },
{ FilesystemType::APFS, { "APFS" } },
{ FilesystemType::HFS, { "HFS" } },
{ FilesystemType::HFSPLUS, { "HFSPLUS" } },
{ FilesystemType::HFSX, { "HFSX" } },
{ FilesystemType::FUSEBLK, { "FUSEBLK" } },
{ FilesystemType::F2FS, { "F2FS" } },
{ FilesystemType::BCACHEFS, { "BCACHEFS" } },
{ FilesystemType::UNKNOWN, { "UNKNOWN" } } };
/**
* @brief Get the string name of Filesystem enum object
*
* @param type
* @return QString
*/
QString getFilesystemTypeName(FilesystemType type);
/**
* @brief Get the Filesystem enum object from a name
* Does a lookup of the type name and returns an exact match
*
* @param name
* @return FilesystemType
*/
FilesystemType getFilesystemType(const QString& name);
/**
* @brief Get the Filesystem enum object from a name
* Does a fuzzy lookup of the type name and returns an apropreate match
*
* @param name
* @return FilesystemType
*/
FilesystemType getFilesystemTypeFuzzy(const QString& name);
struct FilesystemInfo {
FilesystemType fsType = FilesystemType::UNKNOWN;
QString fsTypeName;
int blockSize;
qint64 bytesAvailable;
qint64 bytesFree;
qint64 bytesTotal;
QString name;
QString rootPath;
};
/**
* @brief path to the near ancestor that exists
*
*/
QString nearestExistentAncestor(const QString& path);
/**
* @brief colect information about the filesystem under a file
*
*/
FilesystemInfo statFS(const QString& path);
static const QList<FilesystemType> s_clone_filesystems = { FilesystemType::BTRFS, FilesystemType::APFS, FilesystemType::ZFS,
FilesystemType::XFS, FilesystemType::REFS, FilesystemType::BCACHEFS };
/**
* @brief if the Filesystem is reflink/clone capable
*
*/
bool canCloneOnFS(const QString& path);
bool canCloneOnFS(const FilesystemInfo& info);
bool canCloneOnFS(FilesystemType type);
/**
* @brief if the Filesystems are reflink/clone capable and both are on the same device
*
*/
bool canClone(const QString& src, const QString& dst);
/**
* @brief Copies a directory and it's contents from src to dest
*/
class clone : public QObject {
Q_OBJECT
public:
clone(const QString& src, const QString& dst, QObject* parent = nullptr) : QObject(parent)
{
m_src.setPath(src);
m_dst.setPath(dst);
}
clone& matcher(Filter filter)
{
m_matcher = std::move(filter);
return *this;
}
clone& whitelist(bool whitelist)
{
m_whitelist = whitelist;
return *this;
}
bool operator()(bool dryRun = false) { return operator()(QString(), dryRun); }
qsizetype totalCloned() { return m_cloned; }
qsizetype totalFailed() { return m_failedClones.length(); }
QList<QPair<QString, QString>> failed() { return m_failedClones; }
signals:
void fileCloned(const QString& src, const QString& dst);
void cloneFailed(const QString& src, const QString& dst);
private:
bool operator()(const QString& offset, bool dryRun = false);
private:
Filter m_matcher = nullptr;
bool m_whitelist = false;
QDir m_src;
QDir m_dst;
qsizetype m_cloned;
QList<QPair<QString, QString>> m_failedClones;
};
/**
* @brief clone/reflink file from src to dst
*
*/
bool clone_file(const QString& src, const QString& dst, std::error_code& ec);
#if defined(Q_OS_WIN)
bool win_ioctl_clone(const std::wstring& src_path, const std::wstring& dst_path, std::error_code& ec);
#elif defined(Q_OS_LINUX)
bool linux_ficlone(const std::string& src_path, const std::string& dst_path, std::error_code& ec);
#elif defined(Q_OS_MACOS) || defined(Q_OS_FREEBSD) || defined(Q_OS_OPENBSD)
bool macos_bsd_clonefile(const std::string& src_path, const std::string& dst_path, std::error_code& ec);
#endif
static const QList<FilesystemType> s_non_link_filesystems = {
FilesystemType::FAT,
};
/**
* @brief if the Filesystem is symlink capable
*
*/
bool canLinkOnFS(const QString& path);
bool canLinkOnFS(const FilesystemInfo& info);
bool canLinkOnFS(FilesystemType type);
/**
* @brief if the Filesystem is symlink capable on both ends
*
*/
bool canLink(const QString& src, const QString& dst);
uintmax_t hardLinkCount(const QString& path);
#ifdef Q_OS_WIN
QString getPathNameInLocal8bit(const QString& file);
#endif
QString getUniqueResourceName(const QString& filePath);
} // namespace FS

54
launcher/Filter.h Normal file
View file

@ -0,0 +1,54 @@
#pragma once
#include <QRegularExpression>
#include <QString>
using Filter = std::function<bool(const QString&)>;
namespace Filters {
inline Filter inverse(Filter filter)
{
return [filter = std::move(filter)](const QString& src) { return !filter(src); };
}
inline Filter any(QList<Filter> filters)
{
return [filters = std::move(filters)](const QString& src) {
for (auto& filter : filters)
if (filter(src))
return true;
return false;
};
}
inline Filter equals(QString pattern)
{
return [pattern = std::move(pattern)](const QString& src) { return src == pattern; };
}
inline Filter equalsAny(QStringList patterns = {})
{
return [patterns = std::move(patterns)](const QString& src) { return patterns.isEmpty() || patterns.contains(src); };
}
inline Filter equalsOrEmpty(QString pattern)
{
return [pattern = std::move(pattern)](const QString& src) { return src.isEmpty() || src == pattern; };
}
inline Filter contains(QString pattern)
{
return [pattern = std::move(pattern)](const QString& src) { return src.contains(pattern); };
}
inline Filter startsWith(QString pattern)
{
return [pattern = std::move(pattern)](const QString& src) { return src.startsWith(pattern); };
}
inline Filter regexp(QRegularExpression pattern)
{
return [pattern = std::move(pattern)](const QString& src) { return pattern.match(src).hasMatch(); };
}
} // namespace Filters

219
launcher/GZip.cpp Normal file
View file

@ -0,0 +1,219 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "GZip.h"
#include <zlib.h>
#include <QByteArray>
#include <QDebug>
#include <QFile>
bool GZip::unzip(const QByteArray& compressedBytes, QByteArray& uncompressedBytes)
{
if (compressedBytes.size() == 0) {
uncompressedBytes = compressedBytes;
return true;
}
unsigned uncompLength = compressedBytes.size();
uncompressedBytes.clear();
uncompressedBytes.resize(uncompLength);
z_stream strm;
memset(&strm, 0, sizeof(strm));
strm.next_in = (Bytef*)compressedBytes.data();
strm.avail_in = compressedBytes.size();
bool done = false;
if (inflateInit2(&strm, (16 + MAX_WBITS)) != Z_OK) {
return false;
}
int err = Z_OK;
while (!done) {
// If our output buffer is too small
if (strm.total_out >= uncompLength) {
uncompressedBytes.resize(uncompLength * 2);
uncompLength *= 2;
}
strm.next_out = reinterpret_cast<Bytef*>((uncompressedBytes.data() + strm.total_out));
strm.avail_out = uncompLength - strm.total_out;
// Inflate another chunk.
err = inflate(&strm, Z_SYNC_FLUSH);
if (err == Z_STREAM_END)
done = true;
else if (err != Z_OK) {
break;
}
}
if (inflateEnd(&strm) != Z_OK || !done) {
return false;
}
uncompressedBytes.resize(strm.total_out);
return true;
}
bool GZip::zip(const QByteArray& uncompressedBytes, QByteArray& compressedBytes)
{
if (uncompressedBytes.size() == 0) {
compressedBytes = uncompressedBytes;
return true;
}
unsigned compLength = qMin(uncompressedBytes.size(), 16);
compressedBytes.clear();
compressedBytes.resize(compLength);
z_stream zs;
memset(&zs, 0, sizeof(zs));
if (deflateInit2(&zs, Z_DEFAULT_COMPRESSION, Z_DEFLATED, (16 + MAX_WBITS), 8, Z_DEFAULT_STRATEGY) != Z_OK) {
return false;
}
zs.next_in = (Bytef*)uncompressedBytes.data();
zs.avail_in = uncompressedBytes.size();
int ret;
compressedBytes.resize(uncompressedBytes.size());
unsigned offset = 0;
unsigned temp = 0;
do {
auto remaining = compressedBytes.size() - offset;
if (remaining < 1) {
compressedBytes.resize(compressedBytes.size() * 2);
}
zs.next_out = reinterpret_cast<Bytef*>((compressedBytes.data() + offset));
temp = zs.avail_out = compressedBytes.size() - offset;
ret = deflate(&zs, Z_FINISH);
offset += temp - zs.avail_out;
} while (ret == Z_OK);
compressedBytes.resize(offset);
if (deflateEnd(&zs) != Z_OK) {
return false;
}
if (ret != Z_STREAM_END) {
return false;
}
return true;
}
int inf(QFile* source, std::function<bool(const QByteArray&)> handleBlock)
{
constexpr auto CHUNK = 16384;
int ret;
unsigned have;
z_stream strm;
memset(&strm, 0, sizeof(strm));
char in[CHUNK];
unsigned char out[CHUNK];
ret = inflateInit2(&strm, (16 + MAX_WBITS));
if (ret != Z_OK)
return ret;
/* decompress until deflate stream ends or end of file */
do {
strm.avail_in = source->read(in, CHUNK);
if (source->error()) {
(void)inflateEnd(&strm);
return Z_ERRNO;
}
if (strm.avail_in == 0)
break;
strm.next_in = reinterpret_cast<Bytef*>(in);
/* run inflate() on input until output buffer not full */
do {
strm.avail_out = CHUNK;
strm.next_out = out;
ret = inflate(&strm, Z_NO_FLUSH);
assert(ret != Z_STREAM_ERROR); /* state not clobbered */
switch (ret) {
case Z_NEED_DICT:
ret = Z_DATA_ERROR;
[[fallthrough]];
case Z_DATA_ERROR:
case Z_MEM_ERROR:
(void)inflateEnd(&strm);
return ret;
}
have = CHUNK - strm.avail_out;
if (!handleBlock(QByteArray(reinterpret_cast<const char*>(out), have))) {
(void)inflateEnd(&strm);
return Z_OK;
}
} while (strm.avail_out == 0);
/* done when inflate() says it's done */
} while (ret != Z_STREAM_END);
/* clean up and return */
(void)inflateEnd(&strm);
return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
}
QString zerr(int ret)
{
switch (ret) {
case Z_ERRNO:
return QObject::tr("error handling file");
case Z_STREAM_ERROR:
return QObject::tr("invalid compression level");
case Z_DATA_ERROR:
return QObject::tr("invalid or incomplete deflate data");
case Z_MEM_ERROR:
return QObject::tr("out of memory");
case Z_VERSION_ERROR:
return QObject::tr("zlib version mismatch!");
}
return {};
}
QString GZip::readGzFileByBlocks(QFile* source, std::function<bool(const QByteArray&)> handleBlock)
{
auto ret = inf(source, handleBlock);
return zerr(ret);
}

11
launcher/GZip.h Normal file
View file

@ -0,0 +1,11 @@
#pragma once
#include <QByteArray>
#include <QFile>
namespace GZip {
bool unzip(const QByteArray& compressedBytes, QByteArray& uncompressedBytes);
bool zip(const QByteArray& uncompressedBytes, QByteArray& compressedBytes);
QString readGzFileByBlocks(QFile* source, std::function<bool(const QByteArray&)> handleBlock);
} // namespace GZip

333
launcher/HardwareInfo.cpp Normal file
View file

@ -0,0 +1,333 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2026 Octol1ttle <l1ttleofficial@outlook.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 "HardwareInfo.h"
#include <QCoreApplication>
#include <QOffscreenSurface>
#include <QOpenGLFunctions>
#include <QProcessEnvironment>
#include "BuildConfig.h"
#ifndef Q_OS_MACOS
#include <QVulkanInstance>
#include <QVulkanWindow>
#endif
namespace {
bool vulkanInfo(QStringList& out)
{
if (!QProcessEnvironment::systemEnvironment()
.value(QStringLiteral("%1_DISABLE_GLVULKAN").arg(BuildConfig.LAUNCHER_ENVNAME))
.isEmpty()) {
return false;
}
#ifndef Q_OS_MACOS
QVulkanInstance inst;
if (!inst.create()) {
qWarning() << "Vulkan instance creation failed, VkResult:" << inst.errorCode();
out << "Couldn't get Vulkan device information";
return false;
}
QVulkanWindow window;
window.setVulkanInstance(&inst);
for (auto device : window.availablePhysicalDevices()) {
const auto supportedVulkanVersion = QVersionNumber(VK_API_VERSION_MAJOR(device.apiVersion), VK_API_VERSION_MINOR(device.apiVersion),
VK_API_VERSION_PATCH(device.apiVersion));
out << QString("Found Vulkan device: %1 (API version %2)").arg(device.deviceName).arg(supportedVulkanVersion.toString());
}
#endif
return true;
}
bool openGlInfo(QStringList& out)
{
if (!QProcessEnvironment::systemEnvironment()
.value(QStringLiteral("%1_DISABLE_GLVULKAN").arg(BuildConfig.LAUNCHER_ENVNAME))
.isEmpty()) {
return false;
}
QOpenGLContext ctx;
if (!ctx.create()) {
qWarning() << "OpenGL context creation failed";
out << "Couldn't get OpenGL device information";
return false;
}
QOffscreenSurface surface;
surface.create();
ctx.makeCurrent(&surface);
auto* f = ctx.functions();
f->initializeOpenGLFunctions();
auto toQString = [](const GLubyte* str) { return QString(reinterpret_cast<const char*>(str)); };
out << "OpenGL driver vendor: " + toQString(f->glGetString(GL_VENDOR));
out << "OpenGL renderer: " + toQString(f->glGetString(GL_RENDERER));
out << "OpenGL driver version: " + toQString(f->glGetString(GL_VERSION));
return true;
}
} // namespace
#ifndef Q_OS_LINUX
QStringList HardwareInfo::gpuInfo()
{
QStringList info;
vulkanInfo(info);
openGlInfo(info);
return info;
}
#endif
#ifdef Q_OS_WINDOWS
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <QSettings>
#include "windows.h"
QString HardwareInfo::cpuInfo()
{
const QSettings registry(R"(HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System\CentralProcessor\0)", QSettings::NativeFormat);
return registry.value("ProcessorNameString").toString();
}
uint64_t HardwareInfo::totalRamMiB()
{
MEMORYSTATUSEX status;
status.dwLength = sizeof status;
if (GlobalMemoryStatusEx(&status) == TRUE) {
// transforming bytes -> mib
return status.ullTotalPhys / 1024 / 1024;
}
qWarning() << "Could not get total RAM: GlobalMemoryStatusEx";
return 0;
}
uint64_t HardwareInfo::availableRamMiB()
{
MEMORYSTATUSEX status;
status.dwLength = sizeof status;
if (GlobalMemoryStatusEx(&status) == TRUE) {
// transforming bytes -> mib
return status.ullAvailPhys / 1024 / 1024;
}
qWarning() << "Could not get available RAM: GlobalMemoryStatusEx";
return 0;
}
#elif defined(Q_OS_MACOS)
#include "mach/mach.h"
#include "sys/sysctl.h"
QString HardwareInfo::cpuInfo()
{
std::array<char, 512> buffer;
size_t bufferSize = buffer.size();
if (sysctlbyname("machdep.cpu.brand_string", &buffer, &bufferSize, nullptr, 0) == 0) {
return QString(buffer.data());
}
qWarning() << "Could not get CPU model: sysctlbyname";
return "";
}
uint64_t HardwareInfo::totalRamMiB()
{
uint64_t memsize;
size_t memsizeSize = sizeof memsize;
if (sysctlbyname("hw.memsize", &memsize, &memsizeSize, nullptr, 0) == 0) {
// transforming bytes -> mib
return memsize / 1024 / 1024;
}
qWarning() << "Could not get total RAM: sysctlbyname";
return 0;
}
uint64_t HardwareInfo::availableRamMiB()
{
mach_port_t host_port = mach_host_self();
mach_msg_type_number_t count = HOST_VM_INFO64_COUNT;
vm_statistics64_data_t vm_stats;
if (host_statistics64(host_port, HOST_VM_INFO64, reinterpret_cast<host_info64_t>(&vm_stats), &count) == KERN_SUCCESS) {
// transforming bytes -> mib
return (vm_stats.free_count + vm_stats.inactive_count) * vm_page_size / 1024 / 1024;
}
qWarning() << "Could not get available RAM: host_statistics64";
return 0;
}
#elif defined(Q_OS_LINUX)
#include <fstream>
namespace {
QString afterColon(QString& str)
{
return str.remove(0, str.indexOf(':') + 2).trimmed();
}
} // namespace
QString HardwareInfo::cpuInfo()
{
std::ifstream cpuin("/proc/cpuinfo");
for (std::string line; std::getline(cpuin, line);) {
// model name : AMD Ryzen 7 5800X 8-Core Processor
if (QString str = QString::fromStdString(line); str.startsWith("model name")) {
return afterColon(str);
}
}
qWarning() << "Could not get CPU model: /proc/cpuinfo";
return "unknown";
}
uint64_t readMemInfo(QString searchTarget)
{
std::ifstream memin("/proc/meminfo");
for (std::string line; std::getline(memin, line);) {
// MemTotal: 16287480 kB
if (QString str = QString::fromStdString(line); str.startsWith(searchTarget)) {
bool ok = false;
const uint total = str.simplified().section(' ', 1, 1).toUInt(&ok);
if (!ok) {
qWarning() << "Could not read /proc/meminfo: failed to parse string:" << str;
return 0;
}
// transforming kib -> mib
return total / 1024;
}
}
qWarning() << "Could not read /proc/meminfo: search target not found:" << searchTarget;
return 0;
}
uint64_t HardwareInfo::totalRamMiB()
{
return readMemInfo("MemTotal");
}
uint64_t HardwareInfo::availableRamMiB()
{
return readMemInfo("MemAvailable");
}
QStringList HardwareInfo::gpuInfo()
{
QStringList list;
const bool vulkanSuccess = vulkanInfo(list);
const bool openGlSuccess = openGlInfo(list);
if (vulkanSuccess || openGlSuccess) {
return list;
}
std::array<char, 512> buffer;
FILE* lspci = popen("lspci -k", "r");
if (!lspci) {
return { "Could not detect GPUs: lspci is not present" };
}
bool readingGpuInfo = false;
QString currentModel = "";
while (fgets(buffer.data(), 512, lspci) != nullptr) {
QString str(buffer.data());
// clang-format off
// 04:00.0 VGA compatible controller: Advanced Micro Devices, Inc. [AMD/ATI] Ellesmere [Radeon RX 470/480/570/570X/580/580X/590] (rev e7)
// Subsystem: Sapphire Technology Limited Radeon RX 580 Pulse 4GB
// Kernel driver in use: amdgpu
// Kernel modules: amdgpu
// clang-format on
if (str.contains("VGA compatible controller")) {
readingGpuInfo = true;
} else if (!str.startsWith('\t')) {
readingGpuInfo = false;
}
if (!readingGpuInfo) {
continue;
}
if (str.contains("Subsystem")) {
currentModel = "Found GPU: " + afterColon(str);
}
if (str.contains("Kernel driver in use")) {
currentModel += " (using driver " + afterColon(str);
}
if (str.contains("Kernel modules")) {
currentModel += ", available drivers: " + afterColon(str) + ")";
list.append(currentModel);
}
}
pclose(lspci);
return list;
}
#else
QString HardwareInfo::cpuInfo()
{
return "unknown";
}
#if defined(Q_OS_FREEBSD) || defined(Q_OS_OPENBSD)
#include <cstdio>
uint64_t HardwareInfo::totalRamMiB()
{
char buff[512];
FILE* fp = popen("sysctl hw.physmem", "r");
if (fp != nullptr) {
if (fgets(buff, 512, fp) != nullptr) {
std::string str(buff);
uint64_t mem = std::stoull(str.substr(12, std::string::npos));
// transforming kib -> mib
return mem / 1024;
}
}
return 0;
}
#else
uint64_t HardwareInfo::totalRamMiB()
{
return 0;
}
#endif
uint64_t HardwareInfo::availableRamMiB()
{
return 0;
}
#endif

29
launcher/HardwareInfo.h Normal file
View file

@ -0,0 +1,29 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2026 Octol1ttle <l1ttleofficial@outlook.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 <QString>
#include <cstdint>
namespace HardwareInfo {
QString cpuInfo();
uint64_t totalRamMiB();
uint64_t availableRamMiB();
QStringList gpuInfo();
} // namespace HardwareInfo

View file

@ -0,0 +1,192 @@
//
// Created by marcelohdez on 10/22/22.
//
#include "InstanceCopyPrefs.h"
bool InstanceCopyPrefs::allTrue() const
{
return copySaves && keepPlaytime && copyGameOptions && copyResourcePacks && copyShaderPacks && copyServers && copyMods &&
copyScreenshots;
}
// Returns a single RegEx string of the selected folders/files to filter out (ex: ".minecraft/saves|.minecraft/server.dat")
QString InstanceCopyPrefs::getSelectedFiltersAsRegex() const
{
return getSelectedFiltersAsRegex({});
}
QString InstanceCopyPrefs::getSelectedFiltersAsRegex(const QStringList& additionalFilters) const
{
QStringList filters;
if (!copySaves)
filters << "saves";
if (!copyGameOptions)
filters << "options.txt";
if (!copyResourcePacks)
filters << "resourcepacks"
<< "texturepacks";
if (!copyShaderPacks)
filters << "shaderpacks";
if (!copyServers)
filters << "servers.dat"
<< "servers.dat_old"
<< "server-resource-packs";
if (!copyMods)
filters << "coremods"
<< "mods"
<< "config";
if (!copyScreenshots)
filters << "screenshots";
for (auto filter : additionalFilters) {
filters << filter;
}
// If we have any filters to add, join them as a single regex string to return:
if (!filters.isEmpty()) {
const QString MC_ROOT = "[.]?minecraft/";
// Ensure first filter starts with root, then join other filters with OR regex before root (ex: ".minecraft/saves|.minecraft/mods"):
return MC_ROOT + filters.join("|" + MC_ROOT);
}
return {};
}
// ======= Getters =======
bool InstanceCopyPrefs::isCopySavesEnabled() const
{
return copySaves;
}
bool InstanceCopyPrefs::isKeepPlaytimeEnabled() const
{
return keepPlaytime;
}
bool InstanceCopyPrefs::isCopyGameOptionsEnabled() const
{
return copyGameOptions;
}
bool InstanceCopyPrefs::isCopyResourcePacksEnabled() const
{
return copyResourcePacks;
}
bool InstanceCopyPrefs::isCopyShaderPacksEnabled() const
{
return copyShaderPacks;
}
bool InstanceCopyPrefs::isCopyServersEnabled() const
{
return copyServers;
}
bool InstanceCopyPrefs::isCopyModsEnabled() const
{
return copyMods;
}
bool InstanceCopyPrefs::isCopyScreenshotsEnabled() const
{
return copyScreenshots;
}
bool InstanceCopyPrefs::isUseSymLinksEnabled() const
{
return useSymLinks;
}
bool InstanceCopyPrefs::isUseHardLinksEnabled() const
{
return useHardLinks;
}
bool InstanceCopyPrefs::isLinkRecursivelyEnabled() const
{
return linkRecursively;
}
bool InstanceCopyPrefs::isDontLinkSavesEnabled() const
{
return dontLinkSaves;
}
bool InstanceCopyPrefs::isUseCloneEnabled() const
{
return useClone;
}
// ======= Setters =======
void InstanceCopyPrefs::enableCopySaves(bool b)
{
copySaves = b;
}
void InstanceCopyPrefs::enableKeepPlaytime(bool b)
{
keepPlaytime = b;
}
void InstanceCopyPrefs::enableCopyGameOptions(bool b)
{
copyGameOptions = b;
}
void InstanceCopyPrefs::enableCopyResourcePacks(bool b)
{
copyResourcePacks = b;
}
void InstanceCopyPrefs::enableCopyShaderPacks(bool b)
{
copyShaderPacks = b;
}
void InstanceCopyPrefs::enableCopyServers(bool b)
{
copyServers = b;
}
void InstanceCopyPrefs::enableCopyMods(bool b)
{
copyMods = b;
}
void InstanceCopyPrefs::enableCopyScreenshots(bool b)
{
copyScreenshots = b;
}
void InstanceCopyPrefs::enableUseSymLinks(bool b)
{
useSymLinks = b;
}
void InstanceCopyPrefs::enableLinkRecursively(bool b)
{
linkRecursively = b;
}
void InstanceCopyPrefs::enableUseHardLinks(bool b)
{
useHardLinks = b;
}
void InstanceCopyPrefs::enableDontLinkSaves(bool b)
{
dontLinkSaves = b;
}
void InstanceCopyPrefs::enableUseClone(bool b)
{
useClone = b;
}

View file

@ -0,0 +1,57 @@
//
// Created by marcelohdez on 10/22/22.
//
#pragma once
#include <QStringList>
struct InstanceCopyPrefs {
public:
bool allTrue() const;
QString getSelectedFiltersAsRegex() const;
QString getSelectedFiltersAsRegex(const QStringList& additionalFilters) const;
// Getters
bool isCopySavesEnabled() const;
bool isKeepPlaytimeEnabled() const;
bool isCopyGameOptionsEnabled() const;
bool isCopyResourcePacksEnabled() const;
bool isCopyShaderPacksEnabled() const;
bool isCopyServersEnabled() const;
bool isCopyModsEnabled() const;
bool isCopyScreenshotsEnabled() const;
bool isUseSymLinksEnabled() const;
bool isLinkRecursivelyEnabled() const;
bool isUseHardLinksEnabled() const;
bool isDontLinkSavesEnabled() const;
bool isUseCloneEnabled() const;
// Setters
void enableCopySaves(bool b);
void enableKeepPlaytime(bool b);
void enableCopyGameOptions(bool b);
void enableCopyResourcePacks(bool b);
void enableCopyShaderPacks(bool b);
void enableCopyServers(bool b);
void enableCopyMods(bool b);
void enableCopyScreenshots(bool b);
void enableUseSymLinks(bool b);
void enableLinkRecursively(bool b);
void enableUseHardLinks(bool b);
void enableDontLinkSaves(bool b);
void enableUseClone(bool b);
protected: // data
bool copySaves = true;
bool keepPlaytime = true;
bool copyGameOptions = true;
bool copyResourcePacks = true;
bool copyShaderPacks = true;
bool copyServers = true;
bool copyMods = true;
bool copyScreenshots = true;
bool useSymLinks = false;
bool linkRecursively = false;
bool useHardLinks = false;
bool dontLinkSaves = false;
bool useClone = false;
};

View file

@ -0,0 +1,199 @@
#include "InstanceCopyTask.h"
#include <QDebug>
#include <QtConcurrentRun>
#include <memory>
#include "FileSystem.h"
#include "Filter.h"
#include "NullInstance.h"
#include "settings/INISettingsObject.h"
#include "tasks/Task.h"
InstanceCopyTask::InstanceCopyTask(BaseInstance* origInstance, const InstanceCopyPrefs& prefs)
{
m_origInstance = origInstance;
m_keepPlaytime = prefs.isKeepPlaytimeEnabled();
m_useLinks = prefs.isUseSymLinksEnabled();
m_linkRecursively = prefs.isLinkRecursivelyEnabled();
m_useHardLinks = prefs.isLinkRecursivelyEnabled() && prefs.isUseHardLinksEnabled();
m_copySaves = prefs.isLinkRecursivelyEnabled() && prefs.isDontLinkSavesEnabled() && prefs.isCopySavesEnabled();
m_useClone = prefs.isUseCloneEnabled();
QString filters = prefs.getSelectedFiltersAsRegex();
if (m_useLinks || m_useHardLinks) {
if (!filters.isEmpty())
filters += "|";
filters += "instance.cfg";
}
qDebug() << "CopyFilters:" << filters;
if (!filters.isEmpty()) {
// Set regex filter:
// FIXME: get this from the original instance type...
QRegularExpression regexp(filters, QRegularExpression::CaseInsensitiveOption);
m_matcher = Filters::regexp(regexp);
}
}
void InstanceCopyTask::executeTask()
{
setStatus(tr("Copying instance %1").arg(m_origInstance->name()));
m_copyFuture = QtConcurrent::run(QThreadPool::globalInstance(), [this] {
if (m_useClone) {
FS::clone folderClone(m_origInstance->instanceRoot(), m_stagingPath);
folderClone.matcher(m_matcher);
folderClone(true);
setProgress(0, folderClone.totalCloned());
connect(&folderClone, &FS::clone::fileCloned,
[this](QString src, QString dst) { setProgress(m_progress + 1, m_progressTotal); });
return folderClone();
}
if (m_useLinks || m_useHardLinks) {
std::unique_ptr<FS::copy> savesCopy;
if (m_copySaves) {
QFileInfo mcDir(FS::PathCombine(m_stagingPath, "minecraft"));
QFileInfo dotMCDir(FS::PathCombine(m_stagingPath, ".minecraft"));
QString staging_mc_dir;
if (dotMCDir.exists() && !mcDir.exists())
staging_mc_dir = dotMCDir.filePath();
else
staging_mc_dir = mcDir.filePath();
savesCopy = std::make_unique<FS::copy>(FS::PathCombine(m_origInstance->gameRoot(), "saves"),
FS::PathCombine(staging_mc_dir, "saves"));
(*savesCopy)(true);
setProgress(0, savesCopy->totalCopied());
connect(savesCopy.get(), &FS::copy::fileCopied, [this](QString src) { setProgress(m_progress + 1, m_progressTotal); });
}
FS::create_link folderLink(m_origInstance->instanceRoot(), m_stagingPath);
int depth = m_linkRecursively ? -1 : 0; // we need to at least link the top level instead of the instance folder
folderLink.linkRecursively(true).setMaxDepth(depth).useHardLinks(m_useHardLinks).matcher(m_matcher);
folderLink(true);
setProgress(0, m_progressTotal + folderLink.totalToLink());
connect(&folderLink, &FS::create_link::fileLinked,
[this](QString src, QString dst) { setProgress(m_progress + 1, m_progressTotal); });
bool there_were_errors = false;
if (!folderLink()) {
#if defined Q_OS_WIN32
if (!m_useHardLinks) {
setProgress(0, m_progressTotal);
qDebug() << "EXPECTED: Link failure, Windows requires permissions for symlinks";
qDebug() << "attempting to run with privelage";
QEventLoop loop;
bool got_priv_results = false;
connect(&folderLink, &FS::create_link::finishedPrivileged, this, [&got_priv_results, &loop](bool gotResults) {
if (!gotResults) {
qDebug() << "Privileged run exited without results!";
}
got_priv_results = gotResults;
loop.quit();
});
folderLink.runPrivileged();
loop.exec(); // wait for the finished signal
for (auto result : folderLink.getResults()) {
if (result.err_value != 0) {
there_were_errors = true;
}
}
if (savesCopy) {
there_were_errors |= !(*savesCopy)();
}
return got_priv_results && !there_were_errors;
}
#else
qDebug() << "Link Failed!" << folderLink.getOSError().value() << folderLink.getOSError().message().c_str();
#endif
return false;
}
if (savesCopy) {
there_were_errors |= !(*savesCopy)();
}
return !there_were_errors;
}
FS::copy folderCopy(m_origInstance->instanceRoot(), m_stagingPath);
folderCopy.matcher(m_matcher);
folderCopy(true);
setProgress(0, folderCopy.totalCopied());
connect(&folderCopy, &FS::copy::fileCopied, [this]() { setProgress(m_progress + 1, m_progressTotal); });
return folderCopy();
});
connect(&m_copyFutureWatcher, &QFutureWatcher<bool>::finished, this, &InstanceCopyTask::copyFinished);
connect(&m_copyFutureWatcher, &QFutureWatcher<bool>::canceled, this, &InstanceCopyTask::copyAborted);
m_copyFutureWatcher.setFuture(m_copyFuture);
}
void InstanceCopyTask::copyFinished()
{
auto successful = m_copyFuture.result();
if (!successful) {
emitFailed(tr("Instance folder copy failed."));
return;
}
// FIXME: shouldn't this be able to report errors?
auto instanceSettings = std::make_unique<INISettingsObject>(FS::PathCombine(m_stagingPath, "instance.cfg"));
BaseInstance* inst(new NullInstance(m_globalSettings, std::move(instanceSettings), m_stagingPath));
inst->setName(name());
inst->setIconKey(m_instIcon);
if (!m_keepPlaytime) {
inst->resetTimePlayed();
}
if (m_useLinks) {
inst->addLinkedInstanceId(m_origInstance->id());
auto allowed_symlinks_file = QFileInfo(FS::PathCombine(inst->gameRoot(), "allowed_symlinks.txt"));
QByteArray allowed_symlinks;
if (allowed_symlinks_file.exists()) {
allowed_symlinks.append(FS::read(allowed_symlinks_file.filePath()));
if (allowed_symlinks.right(1) != "\n")
allowed_symlinks.append("\n"); // we want to be on a new line
}
allowed_symlinks.append(m_origInstance->gameRoot().toUtf8());
allowed_symlinks.append("\n");
if (allowed_symlinks_file.isSymLink())
FS::deletePath(
allowed_symlinks_file
.filePath()); // we dont want to modify the original. also make sure the resulting file is not itself a link.
try {
FS::write(allowed_symlinks_file.filePath(), allowed_symlinks);
} catch (const FS::FileSystemException& e) {
qCritical() << "Failed to write symlink :" << e.cause();
}
}
emitSucceeded();
}
void InstanceCopyTask::copyAborted()
{
emitFailed(tr("Instance folder copy has been aborted."));
return;
}
bool InstanceCopyTask::abort()
{
if (m_copyFutureWatcher.isRunning()) {
m_copyFutureWatcher.cancel();
// NOTE: Here we don't do `emitAborted()` because it will be done when `m_copyFutureWatcher` actually cancels, which may not occur
// immediately.
return true;
}
return false;
}

View file

@ -0,0 +1,39 @@
#pragma once
#include <QFuture>
#include <QFutureWatcher>
#include <QUrl>
#include "BaseInstance.h"
#include "BaseVersion.h"
#include "Filter.h"
#include "InstanceCopyPrefs.h"
#include "InstanceTask.h"
#include "net/NetJob.h"
#include "settings/SettingsObject.h"
#include "tasks/Task.h"
class InstanceCopyTask : public InstanceTask {
Q_OBJECT
public:
explicit InstanceCopyTask(BaseInstance* origInstance, const InstanceCopyPrefs& prefs);
protected:
//! Entry point for tasks.
virtual void executeTask() override;
bool abort() override;
void copyFinished();
void copyAborted();
private:
/* data */
BaseInstance* m_origInstance;
QFuture<bool> m_copyFuture;
QFutureWatcher<bool> m_copyFutureWatcher;
Filter m_matcher;
bool m_keepPlaytime;
bool m_useLinks = false;
bool m_useHardLinks = false;
bool m_copySaves = false;
bool m_linkRecursively = false;
bool m_useClone = false;
};

View file

@ -0,0 +1,135 @@
#include "InstanceCreationTask.h"
#include <QDebug>
#include <QFile>
#include "InstanceTask.h"
#include "minecraft/MinecraftLoadAndCheck.h"
#include "tasks/SequentialTask.h"
bool InstanceCreationTask::abort()
{
if (!canAbort()) {
return false;
}
m_abort = true;
if (m_gameFilesTask) {
return m_gameFilesTask->abort();
}
return true;
}
void InstanceCreationTask::executeTask()
{
setAbortable(true);
if (updateInstance()) {
emitSucceeded();
return;
}
// When the user aborted in the update stage.
if (m_abort) {
emitAborted();
return;
}
m_instance = createInstance();
if (!m_instance) {
if (m_abort)
return;
qWarning() << "Instance creation failed!";
if (!m_error_message.isEmpty()) {
qWarning() << "Reason:" << m_error_message;
emitFailed(tr("Error while creating new instance:\n%1").arg(m_error_message));
} else {
emitFailed(tr("Error while creating new instance."));
}
return;
}
// If this is set, it means we're updating an instance. So, we now need to remove the
// files scheduled to, and we'd better not let the user abort in the middle of it, since it'd
// put the instance in an invalid state.
if (shouldOverride()) {
bool deleteFailed = false;
setAbortable(false);
setStatus(tr("Removing old conflicting files..."));
qDebug() << "Removing old files";
for (const QString& path : m_filesToRemove) {
if (!QFile::exists(path))
continue;
qDebug() << "Removing" << path;
if (!QFile::remove(path)) {
qCritical() << "Could not remove" << path;
deleteFailed = true;
}
}
if (deleteFailed) {
emitFailed(tr("Failed to remove old conflicting files."));
return;
}
}
if (!m_abort) {
setAbortable(true);
setAbortButtonText(tr("Skip"));
qDebug() << "Downloading game files";
auto updateTasks = m_instance->createUpdateTask();
if (updateTasks.isEmpty()) {
emitSucceeded();
return;
}
auto task = makeShared<SequentialTask>();
task->addTask(makeShared<MinecraftLoadAndCheck>(m_instance.get(), Net::Mode::Online));
for (const auto& t : updateTasks) {
task->addTask(t);
}
connect(task.get(), &Task::finished, this, [this, task] {
if (task->wasSuccessful() || m_abort) {
emitSucceeded();
} else {
emitFailed(tr("Could not download game files: %1").arg(task->failReason()));
}
});
propagateFromOther(task.get());
setDetails(tr("Downloading game files"));
m_gameFilesTask = task;
m_gameFilesTask->start();
}
}
void InstanceCreationTask::scheduleToDelete(QWidget* parent, QDir dir, QString path, bool checkDisabled)
{
if (path.isEmpty()) {
return;
}
if (path.startsWith("saves/")) {
if (m_shouldDeleteSaves == ShouldDeleteSaves::NotAsked) {
m_shouldDeleteSaves = askIfShouldDeleteSaves(parent);
}
if (m_shouldDeleteSaves == ShouldDeleteSaves::No) {
return;
}
}
qDebug() << "Scheduling" << path << "for removal";
m_filesToRemove.append(dir.absoluteFilePath(path));
if (checkDisabled) {
if (path.endsWith(".disabled")) { // remove it if it was enabled/disabled by user
m_filesToRemove.append(dir.absoluteFilePath(path.chopped(9)));
} else {
m_filesToRemove.append(dir.absoluteFilePath(path + ".disabled"));
}
}
}

View file

@ -0,0 +1,53 @@
#pragma once
#include "BaseVersion.h"
#include "InstanceTask.h"
#include "minecraft/MinecraftInstance.h"
class InstanceCreationTask : public InstanceTask {
Q_OBJECT
public:
InstanceCreationTask() = default;
virtual ~InstanceCreationTask() = default;
bool abort() override;
protected:
void executeTask() final override;
/**
* Tries to update an already existing instance.
*
* This can be implemented by subclasses to provide a way of updating an already existing
* instance, according to that implementation's concept of 'identity' (i.e. instances that
* are updates / downgrades of one another).
*
* If this returns true, createInstance() will not run, so you should do all update steps in here.
* Otherwise, createInstance() is run as normal.
*/
virtual bool updateInstance() { return false; };
/**
* Creates a new instance.
*
* Returns the instance if it was created or nullptr otherwise.
*/
virtual std::unique_ptr<MinecraftInstance> createInstance() { return nullptr; }
QString getError() const { return m_error_message; }
protected:
void setError(const QString& message) { m_error_message = message; };
void scheduleToDelete(QWidget* parent, QDir dir, QString path, bool checkDisabled = false);
protected:
bool m_abort = false;
QStringList m_filesToRemove;
ShouldDeleteSaves m_shouldDeleteSaves;
private:
QString m_error_message;
std::unique_ptr<MinecraftInstance> m_instance;
Task::Ptr m_gameFilesTask;
};

View file

@ -0,0 +1,126 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "InstanceDirUpdate.h"
#include <QCheckBox>
#include "Application.h"
#include "FileSystem.h"
#include "InstanceList.h"
#include "ui/dialogs/CustomMessageBox.h"
QString askToUpdateInstanceDirName(BaseInstance* instance, const QString& oldName, const QString& newName, QWidget* parent)
{
if (oldName == newName)
return QString();
QString renamingMode = APPLICATION->settings()->get("InstRenamingMode").toString();
if (renamingMode == "MetadataOnly")
return QString();
auto oldRoot = instance->instanceRoot();
auto newDirName = FS::DirNameFromString(newName, QFileInfo(oldRoot).dir().absolutePath());
auto newRoot = FS::PathCombine(QFileInfo(oldRoot).dir().absolutePath(), newDirName);
if (oldRoot == newRoot)
return QString();
if (oldRoot == FS::PathCombine(QFileInfo(oldRoot).dir().absolutePath(), newName))
return QString();
// Check for conflict
if (QDir(newRoot).exists()) {
QMessageBox::warning(parent, QObject::tr("Cannot rename instance"),
QObject::tr("New instance root (%1) already exists. <br />Only the metadata will be renamed.").arg(newRoot));
return QString();
}
// Ask if we should rename
if (renamingMode == "AskEverytime") {
auto checkBox = new QCheckBox(QObject::tr("&Remember my choice"), parent);
auto dialog =
CustomMessageBox::selectable(parent, QObject::tr("Rename instance folder"),
QObject::tr("Would you also like to rename the instance folder?\n\n"
"Old name: %1\n"
"New name: %2")
.arg(oldName, newName),
QMessageBox::Question, QMessageBox::No | QMessageBox::Yes, QMessageBox::NoButton, checkBox);
auto res = dialog->exec();
if (checkBox->isChecked()) {
if (res == QMessageBox::Yes)
APPLICATION->settings()->set("InstRenamingMode", "PhysicalDir");
else
APPLICATION->settings()->set("InstRenamingMode", "MetadataOnly");
}
if (res == QMessageBox::No)
return QString();
}
// Check for linked instances
if (!checkLinkedInstances(instance->id(), parent, QObject::tr("Renaming")))
return QString();
// Now we can confirm that a renaming is happening
if (!instance->syncInstanceDirName(newRoot)) {
QMessageBox::warning(parent, QObject::tr("Cannot rename instance"),
QObject::tr("An error occurred when performing the following renaming operation: <br/>"
" - Old instance root: %1<br/>"
" - New instance root: %2<br/>"
"Only the metadata is renamed.")
.arg(oldRoot, newRoot));
return QString();
}
return newRoot;
}
bool checkLinkedInstances(const QString& id, QWidget* parent, const QString& verb)
{
auto linkedInstances = APPLICATION->instances()->getLinkedInstancesById(id);
if (!linkedInstances.empty()) {
auto response = CustomMessageBox::selectable(parent, QObject::tr("There are linked instances"),
QObject::tr("The following instance(s) might reference files in this instance:\n\n"
"%1\n\n"
"%2 it could break the other instance(s), \n\n"
"Do you wish to proceed?",
nullptr, linkedInstances.count())
.arg(linkedInstances.join("\n"))
.arg(verb),
QMessageBox::Warning, QMessageBox::Yes | QMessageBox::No, QMessageBox::No)
->exec();
if (response != QMessageBox::Yes)
return false;
}
return true;
}

View file

@ -0,0 +1,43 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "BaseInstance.h"
/// Update instanceRoot to make it sync with name/id; return newRoot if a directory rename happened
QString askToUpdateInstanceDirName(BaseInstance* instance, const QString& oldName, const QString& newName, QWidget* parent);
/// Check if there are linked instances, and display a warning; return true if the operation should proceed
bool checkLinkedInstances(const QString& id, QWidget* parent, const QString& verb);

View file

@ -0,0 +1,432 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
* Copyright (c) 2022 flowln <flowlnlnln@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "InstanceImportTask.h"
#include "Application.h"
#include "FileSystem.h"
#include "NullInstance.h"
#include "QObjectPtr.h"
#include "archive/ArchiveReader.h"
#include "archive/ExtractZipTask.h"
#include "icons/IconList.h"
#include "icons/IconUtils.h"
#include "modplatform/flame/FlameInstanceCreationTask.h"
#include "modplatform/modrinth/ModrinthInstanceCreationTask.h"
#include "modplatform/technic/TechnicPackProcessor.h"
#include "settings/INISettingsObject.h"
#include "tasks/Task.h"
#include "net/ApiDownload.h"
#include <QFileInfo>
#include <QtConcurrentRun>
#include <memory>
InstanceImportTask::InstanceImportTask(const QUrl& sourceUrl, QWidget* parent, QMap<QString, QString>&& extra_info)
: m_sourceUrl(sourceUrl), m_extra_info(extra_info), m_parent(parent)
{}
bool InstanceImportTask::abort()
{
if (!canAbort())
return false;
bool wasAborted = false;
if (m_task)
wasAborted = m_task->abort();
return wasAborted;
}
void InstanceImportTask::executeTask()
{
setAbortable(true);
if (m_sourceUrl.isLocalFile()) {
m_archivePath = m_sourceUrl.toLocalFile();
processZipPack();
} else {
setStatus(tr("Downloading modpack:\n%1").arg(m_sourceUrl.toString()));
downloadFromUrl();
}
}
void InstanceImportTask::downloadFromUrl()
{
const QString path(m_sourceUrl.host() + '/' + m_sourceUrl.path());
auto entry = APPLICATION->metacache()->resolveEntry("general", path);
entry->setStale(true);
m_archivePath = entry->getFullPath();
auto filesNetJob = makeShared<NetJob>(tr("Modpack download"), APPLICATION->network());
filesNetJob->addNetAction(Net::ApiDownload::makeCached(m_sourceUrl, entry));
connect(filesNetJob.get(), &NetJob::succeeded, this, &InstanceImportTask::processZipPack);
connect(filesNetJob.get(), &NetJob::progress, this, &InstanceImportTask::setProgress);
connect(filesNetJob.get(), &NetJob::stepProgress, this, &InstanceImportTask::propagateStepProgress);
connect(filesNetJob.get(), &NetJob::failed, this, &InstanceImportTask::emitFailed);
connect(filesNetJob.get(), &NetJob::aborted, this, &InstanceImportTask::emitAborted);
m_task.reset(filesNetJob);
filesNetJob->start();
}
QString cleanPath(QString path)
{
if (path == ".")
return QString();
QString result = path;
if (result.startsWith("./"))
result = result.mid(2);
return result;
}
void InstanceImportTask::processZipPack()
{
setStatus(tr("Attempting to determine instance type"));
QDir extractDir(m_stagingPath);
qDebug() << "Attempting to create instance from" << m_archivePath;
// open the zip and find relevant files in it
MMCZip::ArchiveReader packZip(m_archivePath);
qDebug() << "Attempting to determine instance type";
QString root;
// NOTE: Prioritize modpack platforms that aren't searched for recursively.
// Especially Flame has a very common filename for its manifest, which may appear inside overrides for example
// https://docs.modrinth.com/docs/modpacks/format_definition/#storage
auto detectInstance = [this, &extractDir, &root](MMCZip::ArchiveReader::File* f, bool& stop) {
if (!isRunning()) {
stop = true;
return true;
}
auto fileName = f->filename();
if (fileName == "modrinth.index.json") {
// process as Modrinth pack
qDebug() << "Modrinth:" << true;
m_modpackType = ModpackType::Modrinth;
stop = true;
} else if (fileName == "bin/modpack.jar" || fileName == "bin/version.json") {
// process as Technic pack
qDebug() << "Technic:" << true;
extractDir.mkpath("minecraft");
extractDir.cd("minecraft");
m_modpackType = ModpackType::Technic;
stop = true;
} else if (fileName == "manifest.json") {
qDebug() << "Flame:" << true;
m_modpackType = ModpackType::Flame;
stop = true;
} else if (QFileInfo fileInfo(fileName); fileInfo.fileName() == "instance.cfg") {
qDebug() << "MultiMC:" << true;
m_modpackType = ModpackType::MultiMC;
root = cleanPath(fileInfo.path());
stop = true;
}
QCoreApplication::processEvents();
return true;
};
if (!packZip.parse(detectInstance)) {
emitFailed(tr("Unable to open supplied modpack zip file."));
return;
}
if (m_modpackType == ModpackType::Unknown) {
emitFailed(tr("Archive does not contain a recognized modpack type."));
return;
}
setStatus(tr("Extracting modpack"));
// make sure we extract just the pack
auto zipTask = makeShared<MMCZip::ExtractZipTask>(m_archivePath, extractDir, root);
auto progressStep = std::make_shared<TaskStepProgress>();
connect(zipTask.get(), &Task::finished, this, [this, progressStep] {
progressStep->state = TaskStepState::Succeeded;
stepProgress(*progressStep);
});
connect(zipTask.get(), &Task::succeeded, this, &InstanceImportTask::extractFinished, Qt::QueuedConnection);
connect(zipTask.get(), &Task::aborted, this, &InstanceImportTask::emitAborted);
connect(zipTask.get(), &Task::failed, this, [this, progressStep](QString reason) {
progressStep->state = TaskStepState::Failed;
stepProgress(*progressStep);
emitFailed(reason);
});
connect(zipTask.get(), &Task::stepProgress, this, &InstanceImportTask::propagateStepProgress);
connect(zipTask.get(), &Task::progress, this, [this, progressStep](qint64 current, qint64 total) {
progressStep->update(current, total);
stepProgress(*progressStep);
});
connect(zipTask.get(), &Task::status, this, [this, progressStep](QString status) {
progressStep->status = status;
stepProgress(*progressStep);
});
connect(zipTask.get(), &Task::warningLogged, this, [this](const QString& line) { m_Warnings.append(line); });
m_task.reset(zipTask);
zipTask->start();
}
void InstanceImportTask::extractFinished()
{
setAbortable(false);
QDir extractDir(m_stagingPath);
qDebug() << "Fixing permissions for extracted pack files...";
QDirIterator it(extractDir, QDirIterator::Subdirectories);
while (it.hasNext()) {
auto filepath = it.next();
QFileInfo file(filepath);
auto permissions = QFile::permissions(filepath);
auto origPermissions = permissions;
if (file.isDir()) {
// Folder +rwx for current user
permissions |= QFileDevice::Permission::ReadUser | QFileDevice::Permission::WriteUser | QFileDevice::Permission::ExeUser;
} else {
// File +rw for current user
permissions |= QFileDevice::Permission::ReadUser | QFileDevice::Permission::WriteUser;
}
if (origPermissions != permissions) {
if (!QFile::setPermissions(filepath, permissions)) {
logWarning(tr("Could not fix permissions for %1").arg(filepath));
} else {
qDebug() << "Fixed" << filepath;
}
}
}
switch (m_modpackType) {
case ModpackType::MultiMC:
processMultiMC();
return;
case ModpackType::Technic:
processTechnic();
return;
case ModpackType::Flame:
processFlame();
return;
case ModpackType::Modrinth:
processModrinth();
return;
case ModpackType::Unknown:
emitFailed(tr("Archive does not contain a recognized modpack type."));
return;
}
}
bool installIcon(QString root, QString instIconKey)
{
auto importIconPath = IconUtils::findBestIconIn(root, instIconKey);
if (importIconPath.isNull() || !QFile::exists(importIconPath))
importIconPath = IconUtils::findBestIconIn(root, "icon.png");
if (importIconPath.isNull() || !QFile::exists(importIconPath))
importIconPath = IconUtils::findBestIconIn(FS::PathCombine(root, "overrides"), "icon.png");
if (!importIconPath.isNull() && QFile::exists(importIconPath)) {
// import icon
auto iconList = APPLICATION->icons();
if (iconList->iconFileExists(instIconKey)) {
iconList->deleteIcon(instIconKey);
}
iconList->installIcon(importIconPath, instIconKey + "." + QFileInfo(importIconPath).suffix());
return true;
}
return false;
}
void InstanceImportTask::processFlame()
{
shared_qobject_ptr<FlameCreationTask> inst_creation_task = nullptr;
if (!m_extra_info.isEmpty()) {
auto pack_id_it = m_extra_info.constFind("pack_id");
Q_ASSERT(pack_id_it != m_extra_info.constEnd());
auto pack_id = pack_id_it.value();
auto pack_version_id_it = m_extra_info.constFind("pack_version_id");
Q_ASSERT(pack_version_id_it != m_extra_info.constEnd());
auto pack_version_id = pack_version_id_it.value();
QString original_instance_id;
auto original_instance_id_it = m_extra_info.constFind("original_instance_id");
if (original_instance_id_it != m_extra_info.constEnd())
original_instance_id = original_instance_id_it.value();
inst_creation_task =
makeShared<FlameCreationTask>(m_stagingPath, m_globalSettings, m_parent, pack_id, pack_version_id, original_instance_id);
} else {
// FIXME: Find a way to get IDs in directly imported ZIPs
inst_creation_task = makeShared<FlameCreationTask>(m_stagingPath, m_globalSettings, m_parent, QString(), QString());
}
inst_creation_task->setName(*this);
// if the icon was specified by user, use that. otherwise pull icon from the pack
if (m_instIcon == "default") {
auto iconKey = QString("Flame_%1_Icon").arg(name());
if (installIcon(m_stagingPath, iconKey)) {
m_instIcon = iconKey;
}
}
inst_creation_task->setIcon(m_instIcon);
inst_creation_task->setGroup(m_instGroup);
inst_creation_task->setConfirmUpdate(shouldConfirmUpdate());
auto weak = inst_creation_task.toWeakRef();
connect(inst_creation_task.get(), &Task::succeeded, this, [this, weak] {
if (auto sp = weak.lock()) {
setOverride(sp->shouldOverride(), sp->originalInstanceID());
}
emitSucceeded();
});
connect(inst_creation_task.get(), &Task::failed, this, &InstanceImportTask::emitFailed);
connect(inst_creation_task.get(), &Task::progress, this, &InstanceImportTask::setProgress);
connect(inst_creation_task.get(), &Task::stepProgress, this, &InstanceImportTask::propagateStepProgress);
connect(inst_creation_task.get(), &Task::status, this, &InstanceImportTask::setStatus);
connect(inst_creation_task.get(), &Task::details, this, &InstanceImportTask::setDetails);
connect(inst_creation_task.get(), &Task::aborted, this, &InstanceImportTask::emitAborted);
connect(inst_creation_task.get(), &Task::abortStatusChanged, this, &Task::setAbortable);
connect(inst_creation_task.get(), &Task::abortButtonTextChanged, this, &Task::setAbortButtonText);
connect(inst_creation_task.get(), &Task::warningLogged, this, [this](const QString& line) { m_Warnings.append(line); });
m_task.reset(inst_creation_task);
setAbortable(true);
m_task->start();
}
void InstanceImportTask::processTechnic()
{
shared_qobject_ptr<Technic::TechnicPackProcessor> packProcessor{ new Technic::TechnicPackProcessor };
connect(packProcessor.get(), &Technic::TechnicPackProcessor::succeeded, this, &InstanceImportTask::emitSucceeded);
connect(packProcessor.get(), &Technic::TechnicPackProcessor::failed, this, &InstanceImportTask::emitFailed);
packProcessor->run(m_globalSettings, name(), m_instIcon, m_stagingPath);
}
void InstanceImportTask::processMultiMC()
{
QString configPath = FS::PathCombine(m_stagingPath, "instance.cfg");
auto instanceSettings = std::make_unique<INISettingsObject>(configPath);
NullInstance instance(m_globalSettings, std::move(instanceSettings), m_stagingPath);
// reset time played on import... because packs.
instance.resetTimePlayed();
// set a new nice name
instance.setName(name());
// if the icon was specified by user, use that. otherwise pull icon from the pack
if (m_instIcon != "default") {
instance.setIconKey(m_instIcon);
} else {
m_instIcon = instance.iconKey();
installIcon(instance.instanceRoot(), m_instIcon);
}
emitSucceeded();
}
void InstanceImportTask::processModrinth()
{
shared_qobject_ptr<ModrinthCreationTask> inst_creation_task = nullptr;
if (!m_extra_info.isEmpty()) {
auto pack_id_it = m_extra_info.constFind("pack_id");
Q_ASSERT(pack_id_it != m_extra_info.constEnd());
auto pack_id = pack_id_it.value();
QString pack_version_id;
auto pack_version_id_it = m_extra_info.constFind("pack_version_id");
if (pack_version_id_it != m_extra_info.constEnd())
pack_version_id = pack_version_id_it.value();
QString original_instance_id;
auto original_instance_id_it = m_extra_info.constFind("original_instance_id");
if (original_instance_id_it != m_extra_info.constEnd())
original_instance_id = original_instance_id_it.value();
inst_creation_task =
makeShared<ModrinthCreationTask>(m_stagingPath, m_globalSettings, m_parent, pack_id, pack_version_id, original_instance_id);
} else {
QString pack_id;
if (!m_sourceUrl.isEmpty()) {
static const QRegularExpression s_regex(R"(data\/([^\/]*)\/versions)");
pack_id = s_regex.match(m_sourceUrl.toString()).captured(1);
}
// FIXME: Find a way to get the ID in directly imported ZIPs
inst_creation_task = makeShared<ModrinthCreationTask>(m_stagingPath, m_globalSettings, m_parent, pack_id);
}
inst_creation_task->setName(*this);
// if the icon was specified by user, use that. otherwise pull icon from the pack
if (m_instIcon == "default") {
auto iconKey = QString("Modrinth_%1_Icon").arg(name());
if (installIcon(m_stagingPath, iconKey)) {
m_instIcon = iconKey;
}
}
inst_creation_task->setIcon(m_instIcon);
inst_creation_task->setGroup(m_instGroup);
inst_creation_task->setConfirmUpdate(shouldConfirmUpdate());
auto weak = inst_creation_task.toWeakRef();
connect(inst_creation_task.get(), &Task::succeeded, this, [this, weak] {
if (auto sp = weak.lock()) {
setOverride(sp->shouldOverride(), sp->originalInstanceID());
}
emitSucceeded();
});
connect(inst_creation_task.get(), &Task::failed, this, &InstanceImportTask::emitFailed);
connect(inst_creation_task.get(), &Task::progress, this, &InstanceImportTask::setProgress);
connect(inst_creation_task.get(), &Task::stepProgress, this, &InstanceImportTask::propagateStepProgress);
connect(inst_creation_task.get(), &Task::status, this, &InstanceImportTask::setStatus);
connect(inst_creation_task.get(), &Task::details, this, &InstanceImportTask::setDetails);
connect(inst_creation_task.get(), &Task::aborted, this, &InstanceImportTask::emitAborted);
connect(inst_creation_task.get(), &Task::abortStatusChanged, this, &Task::setAbortable);
connect(inst_creation_task.get(), &Task::abortButtonTextChanged, this, &Task::setAbortButtonText);
connect(inst_creation_task.get(), &Task::warningLogged, this, [this](const QString& line) { m_Warnings.append(line); });
m_task.reset(inst_creation_task);
setAbortable(true);
m_task->start();
}

View file

@ -0,0 +1,83 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QFuture>
#include <QFutureWatcher>
#include <QUrl>
#include "InstanceTask.h"
class InstanceImportTask : public InstanceTask {
Q_OBJECT
public:
explicit InstanceImportTask(const QUrl& sourceUrl, QWidget* parent = nullptr, QMap<QString, QString>&& extra_info = {});
virtual ~InstanceImportTask() = default;
bool abort() override;
protected:
//! Entry point for tasks.
virtual void executeTask() override;
private:
void processMultiMC();
void processTechnic();
void processFlame();
void processModrinth();
private slots:
void processZipPack();
void extractFinished();
private: /* data */
QUrl m_sourceUrl;
QString m_archivePath;
Task::Ptr m_task;
enum class ModpackType {
Unknown,
MultiMC,
Technic,
Flame,
Modrinth,
} m_modpackType = ModpackType::Unknown;
// Extra info we might need, that's available before, but can't be derived from
// the source URL / the resource it points to alone.
QMap<QString, QString> m_extra_info;
// FIXME: nuke
QWidget* m_parent;
void downloadFromUrl();
};

1087
launcher/InstanceList.cpp Normal file

File diff suppressed because it is too large Load diff

210
launcher/InstanceList.h Normal file
View file

@ -0,0 +1,210 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QAbstractListModel>
#include <QList>
#include <QObject>
#include <QPair>
#include <QSet>
#include <QStack>
#include "BaseInstance.h"
class QFileSystemWatcher;
class InstanceTask;
struct InstanceName;
using InstanceId = QString;
using GroupId = QString;
using InstanceLocator = std::pair<BaseInstance*, int>;
enum class InstCreateError { NoCreateError = 0, NoSuchVersion, UnknownCreateError, InstExists, CantCreateDir };
enum class GroupsState { NotLoaded, Steady, Dirty };
struct TrashShortcutItem {
ShortcutData data;
QString trashPath;
};
struct TrashHistoryItem {
QString id;
QString path;
QString trashPath;
QString groupName;
QList<TrashShortcutItem> shortcuts;
};
class InstanceList : public QAbstractListModel {
Q_OBJECT
public:
explicit InstanceList(SettingsObject* settings, const QString& instDir, QObject* parent = 0);
virtual ~InstanceList();
public:
QModelIndex index(int row, int column = 0, const QModelIndex& parent = QModelIndex()) const override;
int rowCount(const QModelIndex& parent = QModelIndex()) const override;
QVariant data(const QModelIndex& index, int role) const override;
Qt::ItemFlags flags(const QModelIndex& index) const override;
bool setData(const QModelIndex& index, const QVariant& value, int role) override;
enum AdditionalRoles {
GroupRole = Qt::UserRole,
InstancePointerRole = 0x34B1CB48, ///< Return pointer to real instance
InstanceIDRole = 0x34B1CB49 ///< Return id if the instance
};
/*!
* \brief Error codes returned by functions in the InstanceList class.
* NoError Indicates that no error occurred.
* UnknownError indicates that an unspecified error occurred.
*/
enum InstListError { NoError = 0, UnknownError };
BaseInstance* at(int i) const { return m_instances.at(i).get(); }
int count() const { return static_cast<int>(m_instances.size()); }
InstListError loadList();
void saveNow();
/* O(n) */
BaseInstance* getInstanceById(QString id) const;
/* O(n) */
BaseInstance* getInstanceByManagedName(const QString& managed_name) const;
QModelIndex getInstanceIndexById(const QString& id) const;
QStringList getGroups();
bool isGroupCollapsed(const QString& groupName);
GroupId getInstanceGroup(const InstanceId& id) const;
void setInstanceGroup(const InstanceId& id, GroupId name);
void deleteGroup(const GroupId& name);
void renameGroup(const GroupId& src, const GroupId& dst);
bool trashInstance(const InstanceId& id);
bool trashedSomething() const;
bool undoTrashInstance();
void deleteInstance(const InstanceId& id);
// Wrap an instance creation task in some more task machinery and make it ready to be used
Task* wrapInstanceTask(InstanceTask* task);
/**
* Create a new empty staging area for instance creation and @return a path/key top commit it later.
* Used by instance manipulation tasks.
*/
QString getStagedInstancePath();
/**
* Commit the staging area given by @keyPath to the provider - used when creation succeeds.
* Used by instance manipulation tasks.
* should_override is used when another similar instance already exists, and we want to override it
* - for instance, when updating it.
*/
bool commitStagedInstance(const QString& keyPath, const InstanceName& instanceName, QString groupName, const InstanceTask&);
/**
* Destroy a previously created staging area given by @keyPath - used when creation fails.
* Used by instance manipulation tasks.
*/
bool destroyStagingPath(const QString& keyPath);
int getTotalPlayTime();
Qt::DropActions supportedDragActions() const override;
Qt::DropActions supportedDropActions() const override;
bool canDropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent) const override;
bool dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent) override;
QStringList mimeTypes() const override;
QMimeData* mimeData(const QModelIndexList& indexes) const override;
QStringList getLinkedInstancesById(const QString& id) const;
signals:
void dataIsInvalid();
void instancesChanged();
void instanceSelectRequest(QString instanceId);
void groupsChanged(QSet<QString> groups);
public slots:
void on_InstFolderChanged(const Setting& setting, QVariant value);
void on_GroupStateChanged(const QString& group, bool collapsed);
private slots:
void propertiesChanged(BaseInstance* inst);
void providerUpdated();
void instanceDirContentsChanged(const QString& path);
private:
int getInstIndex(BaseInstance* inst) const;
void updateTotalPlayTime();
void suspendWatch();
void resumeWatch();
void add(std::vector<std::unique_ptr<BaseInstance>>& list);
void loadGroupList();
void saveGroupList();
QList<InstanceId> discoverInstances();
std::unique_ptr<BaseInstance> loadInstance(const InstanceId& id);
void increaseGroupCount(const QString& group);
void decreaseGroupCount(const QString& group);
private:
int m_watchLevel = 0;
int totalPlayTime = 0;
bool m_dirty = false;
std::vector<std::unique_ptr<BaseInstance>> m_instances;
// id -> refs
QMap<QString, int> m_groupNameCache;
SettingsObject* m_globalSettings;
QString m_instDir;
QFileSystemWatcher* m_watcher;
// FIXME: this is so inefficient that looking at it is almost painful.
QSet<QString> m_collapsedGroups;
QMap<InstanceId, GroupId> m_instanceGroupIndex;
QSet<InstanceId> instanceSet;
bool m_groupsLoaded = false;
bool m_instancesProbed = false;
QStack<TrashHistoryItem> m_trashHistory;
};

Some files were not shown because too many files have changed in this diff Show more