63 Commits
Author SHA1 Message Date
objz 2b900253d0 bump to 0.5.1 2026-09-16 10:45:43 +02:00
objz e77ae06bea fix(discovery): hide restricted CurseForge projects 2026-09-15 22:03:27 +02:00
objz 3f2f514097 fix(config-sync): roll back failed profile saves 2026-09-15 21:42:05 +02:00
objz 297a52aed8 fix(ci): install xcb before publishing crate 2026-09-14 21:43:10 +02:00
objz ca1a4c40a5 chore: release 0.5.0 2026-09-14 20:17:57 +02:00
Consti Bauer cab6b2e804 Merge pull request #44 from objz/feat/settings-popups
feat(settings): add launcher and instance editors
2026-09-14 20:12:13 +02:00
objz 95670fc3d9 fix(settings): show instance name in editor title 2026-09-05 14:06:19 +02:00
objz a31ed6e510 fix(settings): simplify shortcut guide picker 2026-09-05 13:47:45 +02:00
objz 8b46a5168f feat(settings): control shortcut guides 2026-09-05 13:37:45 +02:00
objz ea63cf7b40 test(config): compare migrated paths semantically 2026-09-05 00:10:31 +02:00
objz cd234db299 fix(ci): install xcb for Linux builds 2026-09-05 00:00:41 +02:00
objz 31edc0dbf8 fix(settings): keep editor updates consistent 2026-09-04 23:54:38 +02:00
objz ccc09419fb fix(settings): normalize persisted values 2026-09-04 23:54:26 +02:00
objz 9a408769c5 fix(instance): harden config and shortcut persistence 2026-09-04 23:54:03 +02:00
objz a25f7d20c8 fix(runtime): validate and repair launch caches 2026-09-04 23:53:57 +02:00
objz 1079680513 fix(config): preserve values during schema upgrades 2026-09-04 23:53:35 +02:00
objz d078035394 fix(notifications): honor queue and slide timing 2026-09-04 23:53:27 +02:00
objz 5853ce4fd3 fix: refine default and provider badges 2026-09-04 22:30:29 +02:00
objz a5fdbaf74a fix: restore Minecraft default resolution action 2026-09-04 22:26:14 +02:00
objz 429e46b7b7 fix: label detected default resolution 2026-09-04 22:24:24 +02:00
objz 78ea2f0f54 fix: use concrete launcher resolution default 2026-09-04 22:16:35 +02:00
objz 033a8b144a fix: capitalize launcher choice values 2026-09-04 22:00:27 +02:00
objz 31d56f80fa fix: restore compact border preview 2026-09-04 21:55:59 +02:00
objz 773e57dd76 fix: format detected image protocol labels 2026-09-04 21:53:05 +02:00
objz ad9902bc9a fix: clean up border style row 2026-09-04 21:52:04 +02:00
objz f38cd24fae fix: simplify border style preview 2026-09-04 21:49:00 +02:00
objz 8f7e117438 fix: polish launcher settings rows 2026-09-04 21:28:04 +02:00
objz 5ba1e70e39 fix: align launcher settings controls 2026-09-04 21:18:09 +02:00
objz 53191bc23b feat: expand launcher settings 2026-09-04 20:57:07 +02:00
objz e8d67322b0 fix: refine runtime change confirmation 2026-09-04 20:13:04 +02:00
objz 8de0cbaa09 feat: add instance launch settings 2026-09-04 20:06:22 +02:00
objz 59407ee01d feat: confirm automatic Java changes 2026-09-04 16:16:15 +02:00
objz 3566d6b50d fix: preserve status badges in selectors 2026-09-04 15:46:29 +02:00
objz 17aff8ec6d feat: refine settings feedback and controls 2026-09-04 15:34:05 +02:00
objz 45d9b85abf fix: normalize settings popup styling 2026-09-04 15:22:52 +02:00
objz 5f99de36ba fix: refine runtime and resolution controls 2026-09-04 15:09:18 +02:00
objz 8739ab2421 fix: simplify runtime change flow 2026-09-04 15:01:47 +02:00
objz f97e3a3780 fix: align settings selection behavior 2026-09-04 14:42:37 +02:00
objz fa6220649f feat: autosave settings changes 2026-09-04 14:26:24 +02:00
objz 6ce48b640a fix: refine settings interactions 2026-09-04 14:18:52 +02:00
objz 84ec724d4f fix: refine settings popup visuals 2026-09-04 13:28:39 +02:00
objz d5d77c222e feat: polish settings controls 2026-09-04 12:48:48 +02:00
objz 4edc920912 feat: add interactive settings controls 2026-09-04 12:32:18 +02:00
objz ff64920b7b refactor: simplify settings editors 2026-09-04 12:02:06 +02:00
objz 6a4cab9405 refactor: streamline interactive settings controls 2026-09-03 21:33:31 +02:00
objz 0b6618c661 feat: redesign settings popup controls 2026-09-03 21:14:17 +02:00
objz 94362f0947 fix: restore settings panel workflow 2026-09-03 20:56:58 +02:00
objz c95f2d17ff feat: add in-TUI settings editors 2026-09-03 20:44:44 +02:00
objz 8c94e126c3 fix(net): match natives exclude prefixes on windows
PathBuf renders zip entry paths with the host separator, so prefix
checks against 'META-INF/' never matched and excluded entries were
extracted anyway; normalize separators before matching.
2026-08-25 15:30:20 +02:00
objz 937e9dac1f fix(lint): use as_chunks for constant-size row pairs
Satisfies clippy::chunks_exact_to_as_chunks on newer toolchains where
CI builds with -D warnings.
2026-08-25 15:30:20 +02:00
objz e1cce7b5b3 fixed fmt 2026-08-24 19:17:37 +02:00
objz e99e307790 test: tighten weak assertions and isolate global state
Assert the full InstanceConfig on JSON roundtrip (adds PartialEq to
the derive), verify kill signal delivery, check defaults in the
missing-config test, and take TEST_LOCK plus clear progress state in
the mrpack unsafe-path test like its siblings.
2026-08-24 19:15:03 +02:00
objz 7a6145342d fix(cli): pad table columns by display width
Byte-length padding misaligned columns for non-ASCII names; widths and
padding now use display width via ratatui's Span.
2026-08-24 19:14:49 +02:00
objz 0db8421caf fix(tui): report failed instance renames
A rejected rename (invalid name, collision) now pushes an error toast
instead of silently keeping the old name.
2026-08-24 19:14:49 +02:00
objz cc3b783ab1 perf(content): replace manifest linear scans with binary search
record() and upsert() use partition_point on the path-sorted file list
and reconcile_inventory appends records in order instead of upserting
each one, dropping full rescans from O(n^2) to O(n log n).
2026-08-24 19:14:49 +02:00
objz 7f07c7636c fix(migrate): find legacy desktop shortcuts by sanitized name
mcl named shortcut files with the sanitized instance name, but the
migration looked them up by raw display name and never matched; the
windows lookup keeps the legacy .bat extension.
2026-08-24 19:14:40 +02:00
objz 41a5fe0aa9 fix(instance): swap mirrored config dirs atomically
mirror_dir now copies into a sibling temp directory and renames it
into place only when complete, instead of deleting the destination
up front where a mid-copy failure destroyed the current config.
2026-08-24 19:14:40 +02:00
objz c0833d4bb1 fix(instance): make launch log filenames collision-safe
Use millisecond-precision timestamps so a same-second relaunch no
longer truncates the previous log file.
2026-08-24 19:14:40 +02:00
objz 51bb896f91 fix(instance): reject unsafe instance rename targets
rename() now runs validate_name on the new name so paths like ../x or
.x cannot move instances out of (or hide them inside) the instances
root; failures surface as an error toast in the TUI.
2026-08-24 19:14:20 +02:00
objz 40db30ce5a fix(net): verify modrinth pack downloads before use
download_mrpack now routes through the shared temp-file download with
size/hash verification and rename instead of writing the final path
directly.
2026-08-24 19:14:20 +02:00
objz 4803fe9e3f feat(net): fetch native libraries and verify mojang downloads
Model natives/classifiers/extract on Library, download the matching
native classifier jar and unpack it into versions/<id>/natives so
pre-1.13 versions can launch. Cached client jar, libraries and assets
are now checked against their recorded size and sha1 instead of a bare
exists(), and fresh client jar downloads are verified before use.
2026-08-24 19:14:09 +02:00
objz edd8a34b14 fix(auth): preserve account selection and persist store atomically
set_active with an out-of-range index no longer deactivates every
account, re-adding the active account keeps it selected, and the
accounts file (holding refresh tokens) is written via write_atomic.
2026-08-24 19:14:01 +02:00
objz 29ad70fa16 chore: add SPDX copyright headers 2026-08-24 19:13:43 +02:00
217 changed files with 11843 additions and 607 deletions

No files matched your search

+3
View File
@@ -3,3 +3,6 @@
with: with:
distribution: temurin distribution: temurin
java-version: "21" java-version: "21"
- name: install Linux build dependencies
if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install --yes libxcb1-dev
+3
View File
@@ -103,6 +103,9 @@ jobs:
with: with:
"distribution": "temurin" "distribution": "temurin"
"java-version": "21" "java-version": "21"
- name: install Linux build dependencies
if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install --yes libxcb1-dev
- name: Install dist - name: Install dist
run: ${{ matrix.install_dist.run }} run: ${{ matrix.install_dist.run }}
# Get the dist-manifest # Get the dist-manifest
+5
View File
@@ -68,6 +68,9 @@ jobs:
- uses: Swatinem/rust-cache@v2 - uses: Swatinem/rust-cache@v2
with: with:
key: ${{ matrix.os }} key: ${{ matrix.os }}
- name: install Linux build dependencies
if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install --yes libxcb1-dev
- run: cargo build --locked - run: cargo build --locked
- run: cargo test --locked --all-targets - run: cargo test --locked --all-targets
@@ -86,4 +89,6 @@ jobs:
distribution: temurin distribution: temurin
java-version: "21" java-version: "21"
- uses: Swatinem/rust-cache@v2 - uses: Swatinem/rust-cache@v2
- name: install Linux build dependencies
run: sudo apt-get update && sudo apt-get install --yes libxcb1-dev
- run: cargo test --locked --all-targets -- --ignored - run: cargo test --locked --all-targets -- --ignored
+3
View File
@@ -35,6 +35,9 @@ jobs:
- name: install Rust - name: install Rust
uses: dtolnay/rust-toolchain@stable uses: dtolnay/rust-toolchain@stable
- name: install Linux build dependencies
run: sudo apt-get update && sudo apt-get install --yes libxcb1-dev
- name: publish to crates.io - name: publish to crates.io
run: | run: |
if [ "${{ inputs.dry_run }}" = "true" ]; then if [ "${{ inputs.dry_run }}" = "true" ]; then
+5
View File
@@ -0,0 +1,5 @@
Copyright (C) 2026 Constantin Bauer
Unless otherwise stated, the source code in this repository is
copyrighted by Constantin Bauer and licensed under the GNU General Public
License v3.0. See LICENSE for the full license text.
Generated
+466 -2
View File
@@ -297,6 +297,15 @@ dependencies = [
"zeroize", "zeroize",
] ]
[[package]]
name = "block2"
version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5"
dependencies = [
"objc2",
]
[[package]] [[package]]
name = "bon" name = "bon"
version = "3.9.1" version = "3.9.1"
@@ -789,6 +798,12 @@ dependencies = [
"cmov", "cmov",
] ]
[[package]]
name = "cursor-icon"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f"
[[package]] [[package]]
name = "darling" name = "darling"
version = "0.21.3" version = "0.21.3"
@@ -1019,6 +1034,37 @@ dependencies = [
"winapi", "winapi",
] ]
[[package]]
name = "dispatch2"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"
dependencies = [
"bitflags 2.13.1",
"objc2",
]
[[package]]
name = "display-info"
version = "0.5.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e0aca670967c2528799e316f9f97913efcc034867614d55681dd41a1c2f7830"
dependencies = [
"fxhash",
"log",
"objc2",
"objc2-app-kit",
"objc2-core-foundation",
"objc2-core-graphics",
"objc2-foundation",
"scopeguard",
"smithay-client-toolkit",
"thiserror 2.0.18",
"widestring",
"windows 0.62.2",
"xcb",
]
[[package]] [[package]]
name = "displaydoc" name = "displaydoc"
version = "0.2.5" version = "0.2.5"
@@ -1048,6 +1094,12 @@ dependencies = [
"litrs", "litrs",
] ]
[[package]]
name = "downcast-rs"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2"
[[package]] [[package]]
name = "either" name = "either"
version = "1.15.0" version = "1.15.0"
@@ -1392,6 +1444,15 @@ dependencies = [
"slab", "slab",
] ]
[[package]]
name = "fxhash"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c31b6d751ae2c7f11320402d34e41349dd1016f8d5d45e48c4312bc8625af50c"
dependencies = [
"byteorder",
]
[[package]] [[package]]
name = "gdb-command" name = "gdb-command"
version = "0.7.8" version = "0.7.8"
@@ -2623,6 +2684,174 @@ dependencies = [
"url", "url",
] ]
[[package]]
name = "objc2"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f"
dependencies = [
"objc2-encode",
]
[[package]]
name = "objc2-app-kit"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c"
dependencies = [
"bitflags 2.13.1",
"block2",
"libc",
"objc2",
"objc2-cloud-kit",
"objc2-core-data",
"objc2-core-foundation",
"objc2-core-graphics",
"objc2-core-image",
"objc2-core-text",
"objc2-core-video",
"objc2-foundation",
"objc2-quartz-core",
]
[[package]]
name = "objc2-cloud-kit"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c"
dependencies = [
"bitflags 2.13.1",
"objc2",
"objc2-foundation",
]
[[package]]
name = "objc2-core-data"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa"
dependencies = [
"bitflags 2.13.1",
"objc2",
"objc2-foundation",
]
[[package]]
name = "objc2-core-foundation"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"
dependencies = [
"bitflags 2.13.1",
"block2",
"dispatch2",
"libc",
"objc2",
]
[[package]]
name = "objc2-core-graphics"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807"
dependencies = [
"bitflags 2.13.1",
"block2",
"dispatch2",
"libc",
"objc2",
"objc2-core-foundation",
"objc2-io-surface",
"objc2-metal",
]
[[package]]
name = "objc2-core-image"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5d563b38d2b97209f8e861173de434bd0214cf020e3423a52624cd1d989f006"
dependencies = [
"objc2",
"objc2-foundation",
]
[[package]]
name = "objc2-core-text"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d"
dependencies = [
"bitflags 2.13.1",
"objc2",
"objc2-core-foundation",
"objc2-core-graphics",
]
[[package]]
name = "objc2-core-video"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d425caf1df73233f29fd8a5c3e5edbc30d2d4307870f802d18f00d83dc5141a6"
dependencies = [
"bitflags 2.13.1",
"objc2",
"objc2-core-foundation",
"objc2-core-graphics",
"objc2-io-surface",
]
[[package]]
name = "objc2-encode"
version = "4.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
[[package]]
name = "objc2-foundation"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
dependencies = [
"bitflags 2.13.1",
"block2",
"libc",
"objc2",
"objc2-core-foundation",
]
[[package]]
name = "objc2-io-surface"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d"
dependencies = [
"bitflags 2.13.1",
"objc2",
"objc2-core-foundation",
]
[[package]]
name = "objc2-metal"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794"
dependencies = [
"bitflags 2.13.1",
"objc2",
"objc2-foundation",
]
[[package]]
name = "objc2-quartz-core"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f"
dependencies = [
"bitflags 2.13.1",
"objc2",
"objc2-foundation",
]
[[package]] [[package]]
name = "object" name = "object"
version = "0.37.3" version = "0.37.3"
@@ -3150,6 +3379,15 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
[[package]]
name = "quick-xml"
version = "0.41.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1"
dependencies = [
"memchr",
]
[[package]] [[package]]
name = "quinn" name = "quinn"
version = "0.11.9" version = "0.11.9"
@@ -3366,7 +3604,7 @@ dependencies = [
"rustix 0.38.44", "rustix 0.38.44",
"self_cell", "self_cell",
"thiserror 1.0.69", "thiserror 1.0.69",
"windows", "windows 0.58.0",
] ]
[[package]] [[package]]
@@ -3643,7 +3881,7 @@ dependencies = [
[[package]] [[package]]
name = "rmcl" name = "rmcl"
version = "0.4.1" version = "0.5.1"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"chrono", "chrono",
@@ -3653,6 +3891,7 @@ dependencies = [
"crossterm 0.29.0", "crossterm 0.29.0",
"dirs", "dirs",
"dirs-next", "dirs-next",
"display-info",
"fast-strip-ansi", "fast-strip-ansi",
"fastnbt", "fastnbt",
"flate2", "flate2",
@@ -3685,6 +3924,7 @@ dependencies = [
"throbber-widgets-tui", "throbber-widgets-tui",
"tokio", "tokio",
"toml", "toml",
"toml_edit",
"tracing", "tracing",
"tracing-appender", "tracing-appender",
"tracing-subscriber", "tracing-subscriber",
@@ -4170,6 +4410,31 @@ version = "1.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"
[[package]]
name = "smithay-client-toolkit"
version = "0.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0512da38f5e2b31201a93524adb8d3136276fa4fe4aafab4e1f727a82b534cc0"
dependencies = [
"bitflags 2.13.1",
"cursor-icon",
"libc",
"log",
"memmap2",
"rustix 1.1.4",
"thiserror 2.0.18",
"wayland-backend",
"wayland-client",
"wayland-csd-frame",
"wayland-cursor",
"wayland-protocols",
"wayland-protocols-experimental",
"wayland-protocols-misc",
"wayland-protocols-wlr",
"wayland-scanner",
"xkeysym",
]
[[package]] [[package]]
name = "socket2" name = "socket2"
version = "0.6.3" version = "0.6.3"
@@ -4683,6 +4948,7 @@ dependencies = [
"indexmap", "indexmap",
"toml_datetime", "toml_datetime",
"toml_parser", "toml_parser",
"toml_writer",
"winnow", "winnow",
] ]
@@ -5294,6 +5560,124 @@ dependencies = [
"semver", "semver",
] ]
[[package]]
name = "wayland-backend"
version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078"
dependencies = [
"cc",
"downcast-rs",
"rustix 1.1.4",
"smallvec",
"wayland-sys",
]
[[package]]
name = "wayland-client"
version = "0.31.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073"
dependencies = [
"bitflags 2.13.1",
"rustix 1.1.4",
"wayland-backend",
"wayland-scanner",
]
[[package]]
name = "wayland-csd-frame"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "625c5029dbd43d25e6aa9615e88b829a5cad13b2819c4ae129fdbb7c31ab4c7e"
dependencies = [
"bitflags 2.13.1",
"cursor-icon",
"wayland-backend",
]
[[package]]
name = "wayland-cursor"
version = "0.31.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d"
dependencies = [
"rustix 1.1.4",
"wayland-client",
"xcursor",
]
[[package]]
name = "wayland-protocols"
version = "0.32.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6"
dependencies = [
"bitflags 2.13.1",
"wayland-backend",
"wayland-client",
"wayland-scanner",
]
[[package]]
name = "wayland-protocols-experimental"
version = "20250721.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "40a1f863128dcaaec790d7b4b396cc9b9a7a079e878e18c47e6c2d2c5a8dcbb1"
dependencies = [
"bitflags 2.13.1",
"wayland-backend",
"wayland-client",
"wayland-protocols",
"wayland-scanner",
]
[[package]]
name = "wayland-protocols-misc"
version = "0.3.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e9567599ef23e09b8dad6e429e5738d4509dfc46b3b21f32841a304d16b29c8"
dependencies = [
"bitflags 2.13.1",
"wayland-backend",
"wayland-client",
"wayland-protocols",
"wayland-scanner",
]
[[package]]
name = "wayland-protocols-wlr"
version = "0.3.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234"
dependencies = [
"bitflags 2.13.1",
"wayland-backend",
"wayland-client",
"wayland-protocols",
"wayland-scanner",
]
[[package]]
name = "wayland-scanner"
version = "0.31.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0"
dependencies = [
"proc-macro2",
"quick-xml",
"quote",
]
[[package]]
name = "wayland-sys"
version = "0.31.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be"
dependencies = [
"pkg-config",
]
[[package]] [[package]]
name = "web-sys" name = "web-sys"
version = "0.3.95" version = "0.3.95"
@@ -5434,6 +5818,12 @@ dependencies = [
"safe_arch", "safe_arch",
] ]
[[package]]
name = "widestring"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72069c3113ab32ab29e5584db3c6ec55d416895e60715417b5b883a357c3e471"
[[package]] [[package]]
name = "winapi" name = "winapi"
version = "0.3.9" version = "0.3.9"
@@ -5475,6 +5865,27 @@ dependencies = [
"windows-targets 0.52.6", "windows-targets 0.52.6",
] ]
[[package]]
name = "windows"
version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"
dependencies = [
"windows-collections",
"windows-core 0.62.2",
"windows-future",
"windows-numerics",
]
[[package]]
name = "windows-collections"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"
dependencies = [
"windows-core 0.62.2",
]
[[package]] [[package]]
name = "windows-core" name = "windows-core"
version = "0.58.0" version = "0.58.0"
@@ -5501,6 +5912,17 @@ dependencies = [
"windows-strings 0.5.1", "windows-strings 0.5.1",
] ]
[[package]]
name = "windows-future"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"
dependencies = [
"windows-core 0.62.2",
"windows-link",
"windows-threading",
]
[[package]] [[package]]
name = "windows-implement" name = "windows-implement"
version = "0.58.0" version = "0.58.0"
@@ -5551,6 +5973,16 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-numerics"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"
dependencies = [
"windows-core 0.62.2",
"windows-link",
]
[[package]] [[package]]
name = "windows-result" name = "windows-result"
version = "0.2.0" version = "0.2.0"
@@ -5657,6 +6089,15 @@ dependencies = [
"windows_x86_64_msvc 0.53.1", "windows_x86_64_msvc 0.53.1",
] ]
[[package]]
name = "windows-threading"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"
dependencies = [
"windows-link",
]
[[package]] [[package]]
name = "windows_aarch64_gnullvm" name = "windows_aarch64_gnullvm"
version = "0.52.6" version = "0.52.6"
@@ -5894,6 +6335,29 @@ dependencies = [
"tap", "tap",
] ]
[[package]]
name = "xcb"
version = "1.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6c2ad15e0e922856ee89afe862b8992334bbe7953adad56cd1199358cb30566"
dependencies = [
"bitflags 2.13.1",
"libc",
"quick-xml",
]
[[package]]
name = "xcursor"
version = "0.3.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "163b33ed8786455e2fa5d72f554057ce3f3182425434f756cd39c99839d88e23"
[[package]]
name = "xkeysym"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56"
[[package]] [[package]]
name = "xmlwriter" name = "xmlwriter"
version = "0.1.0" version = "0.1.0"
+3 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "rmcl" name = "rmcl"
version = "0.4.1" version = "0.5.1"
authors = ["objz"] authors = ["objz"]
edition = "2024" edition = "2024"
description = "A fully featured Minecraft TUI launcher" description = "A fully featured Minecraft TUI launcher"
@@ -29,6 +29,7 @@ clap = "4.5.27"
color-eyre = "0.6.3" color-eyre = "0.6.3"
config = "0.15.6" config = "0.15.6"
crossterm = "0.29.0" crossterm = "0.29.0"
display-info = "0.5.9"
dirs-next = "2.0.0" dirs-next = "2.0.0"
log = "0.4" log = "0.4"
ratatui = { version = "0.30.0", features = ["serde", "unstable-rendered-line-info"] } ratatui = { version = "0.30.0", features = ["serde", "unstable-rendered-line-info"] }
@@ -44,6 +45,7 @@ serde_json = "1.0"
sha1 = "0.10" sha1 = "0.10"
sha2 = "0.10" sha2 = "0.10"
toml = "1.1.2" toml = "1.1.2"
toml_edit = "0.25"
tachyonfx = "0.25" tachyonfx = "0.25"
throbber-widgets-tui = "0.11" throbber-widgets-tui = "0.11"
thiserror = "2" thiserror = "2"
+35 -1
View File
@@ -129,6 +129,39 @@ settings, accounts, instances, and cached game metadata.
each instance has an `instance.json` for its config and a `.minecraft/` directory with the actual game files. each instance has an `instance.json` for its config and a `.minecraft/` directory with the actual game files.
Launcher settings can be edited from the TUI or in `config.toml`. Changes to
`instances_dir`, `meta_dir`, and `image_protocol` apply after restarting rmcl;
other launcher settings apply immediately. Omitting `java_path` enables automatic
Java selection. Global JVM arguments and environment variables are applied before
per-instance values. Instances can explicitly inherit the launcher window mode
and resolution defaults.
```toml
[general]
check_modpack_updates = true
check_content_updates = true
[defaults]
memory_min = "512M"
memory_max = "2G"
jvm_args = []
environment = {}
window_mode = "windowed"
resolution = [854, 480]
[ui]
image_protocol = "auto"
hidden_shortcut_hints = [] # all, main, instances, content, accounts, settings, popups
[content]
preferred_provider = "modrinth"
preferred_provider_only = false
ask_on_provider_conflict = true
```
Use `hidden_shortcut_hints = ["main"]` to keep only popup guides,
`["all"]` to hide every guide, or list individual areas to hide them selectively.
### logs ### logs
launcher logs are per-session and contain rmcl's own output. instance launch logs capture game stdout/stderr per launch. launcher logs are per-session and contain rmcl's own output. instance launch logs capture game stdout/stderr per launch.
@@ -214,8 +247,9 @@ contributions are welcome. fork it, branch it, PR it. see [CONTRIBUTING.md](CONT
--- ---
## license ## license
Copyright (C) 2026 Constantin Bauer
GPL-3.0. see [LICENSE](LICENSE). This project is licensed under the GNU General Public License v3.0. see [LICENSE](LICENSE).
--- ---
+22 -11
View File
@@ -1,21 +1,32 @@
[general]
# check imported modpacks and managed content for updates automatically
check_modpack_updates = true
check_content_updates = true
[paths] [paths]
# where instances are stored # instances_dir and meta_dir use platform defaults when omitted
instances_dir = "~/.local/share/rmcl/instances" # java_path is omitted to select Java automatically
# instances_dir = "/path/to/minecraft/instances"
# metadata, cache, whatever else ends up there # meta_dir = "/path/to/rmcl/meta"
meta_dir = "~/.local/share/rmcl/meta" # java_path = "/usr/bin/java"
# optional java override (empty = uses JAVA_HOME)
java_path = ""
[defaults] [defaults]
# default heap settings # inherited by instances that do not override their memory
memory_min = "512M" memory_min = "512M"
memory_max = "2G" memory_max = "2G"
# appended to every instance; instance values take precedence where applicable
jvm_args = []
environment = {}
# inherited by instances that use launcher window defaults
window_mode = "windowed"
resolution = [854, 480]
[ui] [ui]
# image protocol for content icons and screenshots: halfblocks, quadrants, kitty, or iterm2 # image protocol: auto, halfblocks, quadrants, kitty, or iterm2
image_protocol = "kitty" image_protocol = "auto"
# [] shows all guides; ["main"] keeps popup guides; ["all"] hides every guide
# areas can also be hidden selectively: instances, content, accounts, settings, popups
hidden_shortcut_hints = []
# error popup timing (in ms) # error popup timing (in ms)
error_auto_dismiss_ms = 5000 error_auto_dismiss_ms = 5000
error_slide_start_ms = 3500 error_slide_start_ms = 3500
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use std::env; use std::env;
use std::path::Path; use std::path::Path;
use std::process::Command; use std::process::Command;
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
import java.lang.reflect.Method; import java.lang.reflect.Method;
public class RmclShim { public class RmclShim {
+18 -10
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// account management: persistence, switching active accounts, and offline uuid generation // account management: persistence, switching active accounts, and offline uuid generation
use std::path::PathBuf; use std::path::PathBuf;
@@ -72,7 +75,9 @@ impl AccountStore {
} }
match serde_json::to_string_pretty(&self.accounts) { match serde_json::to_string_pretty(&self.accounts) {
Ok(json) => { Ok(json) => {
if let Err(e) = std::fs::write(&self.path, json) { // this file holds microsoft refresh tokens: a torn write on
// crash would permanently lock the user out, so write atomically.
if let Err(e) = crate::storage::write_atomic(&self.path, json.as_bytes()) {
tracing::error!( tracing::error!(
"Failed to write accounts file {}: {}", "Failed to write accounts file {}: {}",
self.path.display(), self.path.display(),
@@ -101,18 +106,18 @@ impl AccountStore {
} }
pub fn set_active(&mut self, index: usize) { pub fn set_active(&mut self, index: usize) {
let username = self let Some(account) = self.accounts.get(index) else {
.accounts // out-of-range: leave the current selection untouched. marking
.get(index) // every account inactive here would break the single-active
.map(|account| account.username.clone()); // invariant and orphan the store with no usable account.
tracing::warn!("Tried to select missing account index {}", index);
return;
};
let username = account.username.clone();
for (i, acc) in self.accounts.iter_mut().enumerate() { for (i, acc) in self.accounts.iter_mut().enumerate() {
acc.active = i == index; acc.active = i == index;
} }
if let Some(username) = username {
tracing::info!("Selected account '{}'", username); tracing::info!("Selected account '{}'", username);
} else {
tracing::warn!("Tried to select missing account index {}", index);
}
self.save(); self.save();
} }
@@ -121,11 +126,14 @@ impl AccountStore {
pub fn add(&mut self, account: Account) { pub fn add(&mut self, account: Account) {
let uuid = &account.uuid; let uuid = &account.uuid;
let replaced = self.accounts.iter().any(|a| a.uuid == *uuid); let replaced = self.accounts.iter().any(|a| a.uuid == *uuid);
// re-adding the currently active account must not drop the selection:
// the replacement takes over the old account's active flag.
let replaced_active = self.accounts.iter().any(|a| a.uuid == *uuid && a.active);
let account_type = account.account_type.clone(); let account_type = account.account_type.clone();
let username = account.username.clone(); let username = account.username.clone();
self.accounts.retain(|a| a.uuid != *uuid); self.accounts.retain(|a| a.uuid != *uuid);
let mut account = account; let mut account = account;
if self.accounts.is_empty() { if self.accounts.is_empty() || replaced_active {
account.active = true; account.active = true;
} }
self.accounts.push(account); self.accounts.push(account);
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// auth module: account storage (offline + microsoft) and the oauth device code flow // auth module: account storage (offline + microsoft) and the oauth device code flow
mod accounts; mod accounts;
mod oauth; mod oauth;
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// microsoft oauth device code flow for minecraft authentication. // microsoft oauth device code flow for minecraft authentication.
// the flow goes: MSA device code -> MSA token -> xbox/mc token exchange -> mc profile fetch. // the flow goes: MSA device code -> MSA token -> xbox/mc token exchange -> mc profile fetch.
// device code auth is used because it works without a redirect URI, which is nice for a TUI. // device code auth is used because it works without a redirect URI, which is nice for a TUI.
+34
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use super::*; use super::*;
impl AccountStore { impl AccountStore {
@@ -142,6 +145,37 @@ fn store_set_active_changes_active() {
assert!(store.accounts[1].active); assert!(store.accounts[1].active);
} }
#[test]
fn store_set_active_out_of_bounds_keeps_selection() {
let tmp = tempfile::tempdir().unwrap();
let mut store = make_store(tmp.path());
store.add(create_offline_account("Alice"));
store.add(create_offline_account("Bob"));
store.set_active(99);
assert!(
store.accounts[0].active,
"existing selection must survive a bad index"
);
assert!(!store.accounts[1].active);
}
#[test]
fn store_add_replacing_active_keeps_active() {
let tmp = tempfile::tempdir().unwrap();
let mut store = make_store(tmp.path());
store.add(create_offline_account("Alice"));
store.add(create_offline_account("Bob"));
let mut dup = create_offline_account("Alice");
dup.username = "AliceRenamed".to_owned();
store.add(dup);
assert!(
store.accounts.iter().any(|a| a.active),
"re-adding the active account must not orphan the selection"
);
let active = store.active_account().unwrap();
assert_eq!(active.username, "AliceRenamed");
}
#[test] #[test]
fn store_remove_activates_first_remaining() { fn store_remove_activates_first_remaining() {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use super::*; use super::*;
fn microsoft_account(cached_mc_token_expires_at: Option<i64>) -> Account { fn microsoft_account(cached_mc_token_expires_at: Option<i64>) -> Account {
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// cli handlers for account management (microsoft oauth + offline accounts) // cli handlers for account management (microsoft oauth + offline accounts)
use std::io; use std::io;
use std::time::Duration; use std::time::Duration;
+5 -2
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// unified content management for mods, resource packs, and shaders. // unified content management for mods, resource packs, and shaders.
// all three content types share the same list/enable/disable workflow, // all three content types share the same list/enable/disable workflow,
// just with different scanner functions plugged in. // just with different scanner functions plugged in.
@@ -65,7 +68,7 @@ pub(crate) fn find_entry_by_stem<'a>(
} }
fn list_entries(instance: &str, scan: Scanner) -> CliResult { fn list_entries(instance: &str, scan: Scanner) -> CliResult {
let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir(); let instances_dir = crate::config::SETTINGS.read().paths.resolve_instances_dir();
require_instance(&instances_dir, instance)?; require_instance(&instances_dir, instance)?;
let rows = scan(&instances_dir, instance) let rows = scan(&instances_dir, instance)
.into_iter() .into_iter()
@@ -92,7 +95,7 @@ fn toggle_entry(
kind: &str, kind: &str,
scan: Scanner, scan: Scanner,
) -> CliResult { ) -> CliResult {
let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir(); let instances_dir = crate::config::SETTINGS.read().paths.resolve_instances_dir();
require_instance(&instances_dir, instance)?; require_instance(&instances_dir, instance)?;
let entries = scan(&instances_dir, instance); let entries = scan(&instances_dir, instance);
let entry = find_entry_by_stem(&entries, target) let entry = find_entry_by_stem(&entries, target)
+5 -2
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// modpack importing from modrinth (remote slug/url) or local files (.mrpack, mmc zips). // modpack importing from modrinth (remote slug/url) or local files (.mrpack, mmc zips).
// resolves the input, downloads if needed, then hands off to the import engine. // resolves the input, downloads if needed, then hands off to the import engine.
use clap::ArgMatches; use clap::ArgMatches;
@@ -13,8 +16,8 @@ pub async fn handle_import(matches: &ArgMatches) -> CliResult {
let override_name = matches.get_one::<String>("name"); let override_name = matches.get_one::<String>("name");
let override_version = matches.get_one::<String>("version"); let override_version = matches.get_one::<String>("version");
let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir(); let instances_dir = crate::config::SETTINGS.read().paths.resolve_instances_dir();
let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir(); let meta_dir = crate::config::SETTINGS.read().paths.resolve_meta_dir();
let manager = InstanceManager::new(instances_dir, meta_dir); let manager = InstanceManager::new(instances_dir, meta_dir);
let client = crate::net::HttpClient::new(); let client = crate::net::HttpClient::new();
+9 -33
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// instance lifecycle: create, delete, rename, launch, config, desktop shortcuts. // instance lifecycle: create, delete, rename, launch, config, desktop shortcuts.
// the heaviest handler in the CLI since instances are the core concept. // the heaviest handler in the CLI since instances are the core concept.
use std::io; use std::io;
@@ -8,7 +11,7 @@ use clap::ArgMatches;
use super::utils::{confirm, required_arg}; use super::utils::{confirm, required_arg};
use crate::cli::output::{format_datetime, print_table}; use crate::cli::output::{format_datetime, print_table};
use crate::instance::runtime::RunState; use crate::instance::runtime::RunState;
use crate::instance::{InstanceManager, ModLoader}; use crate::instance::{InstanceManager, ModLoader, models::parse_resolution};
type CliResult = Result<(), Box<dyn std::error::Error>>; type CliResult = Result<(), Box<dyn std::error::Error>>;
const LOCAL_CONFIG_PROFILE: &str = "instance default"; const LOCAL_CONFIG_PROFILE: &str = "instance default";
@@ -41,27 +44,9 @@ pub(crate) fn parse_loader(input: &str) -> Result<ModLoader, String> {
} }
} }
pub(crate) fn parse_resolution(input: &str) -> Result<(u32, u32), String> {
let (width, height) = input
.split_once('x')
.ok_or_else(|| "resolution must be in WxH format".to_string())?;
let width = width
.parse::<u32>()
.map_err(|_| "resolution width must be a positive integer".to_string())?;
let height = height
.parse::<u32>()
.map_err(|_| "resolution height must be a positive integer".to_string())?;
if width == 0 || height == 0 {
return Err("resolution values must be greater than zero".to_string());
}
Ok((width, height))
}
fn manager() -> InstanceManager { fn manager() -> InstanceManager {
let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir(); let instances_dir = crate::config::SETTINGS.read().paths.resolve_instances_dir();
let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir(); let meta_dir = crate::config::SETTINGS.read().paths.resolve_meta_dir();
InstanceManager::new(instances_dir, meta_dir) InstanceManager::new(instances_dir, meta_dir)
} }
@@ -132,8 +117,8 @@ fn rename_instance(matches: &ArgMatches) -> CliResult {
async fn launch_instance(matches: &ArgMatches) -> CliResult { async fn launch_instance(matches: &ArgMatches) -> CliResult {
let name = required_arg(matches, "name")?; let name = required_arg(matches, "name")?;
let manager = manager(); let manager = manager();
let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir(); let instances_dir = crate::config::SETTINGS.read().paths.resolve_instances_dir();
let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir(); let meta_dir = crate::config::SETTINGS.read().paths.resolve_meta_dir();
let config = manager.load_one(name)?; let config = manager.load_one(name)?;
crate::instance::launch::launch(&config, &instances_dir, &meta_dir, None) crate::instance::launch::launch(&config, &instances_dir, &meta_dir, None)
@@ -283,16 +268,7 @@ fn profile_instance(matches: &ArgMatches) -> CliResult {
} else { } else {
Some(profile.as_str()) Some(profile.as_str())
}; };
let instance_dir = manager.instances_dir.join(&config.name); crate::instance::config_sync::switch_profile_and_save(&manager, &mut config, target)?;
let selected = crate::instance::config_sync::switch_profile(
&config.name,
config.config_sync_profile.as_deref(),
target,
&manager.meta_dir,
&instance_dir,
)?;
config.config_sync_profile = selected;
manager.save(&config)?;
println!( println!(
"Updated '{}' config profile to {}.", "Updated '{}' config profile to {}.",
+5 -2
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// viewing minecraft log files from the CLI, with optional `--follow` for tailing // viewing minecraft log files from the CLI, with optional `--follow` for tailing
use std::io; use std::io;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
@@ -18,7 +21,7 @@ pub async fn handle_log(matches: &ArgMatches) -> CliResult {
} }
fn list_logs(instance: &str) -> CliResult { fn list_logs(instance: &str) -> CliResult {
let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir(); let instances_dir = crate::config::SETTINGS.read().paths.resolve_instances_dir();
require_instance(&instances_dir, instance)?; require_instance(&instances_dir, instance)?;
let rows = crate::instance::logs::files::scan_log_files(&instances_dir, instance) let rows = crate::instance::logs::files::scan_log_files(&instances_dir, instance)
.into_iter() .into_iter()
@@ -38,7 +41,7 @@ async fn show_log(matches: &ArgMatches) -> CliResult {
let instance = required_arg(matches, "instance")?; let instance = required_arg(matches, "instance")?;
let file = matches.get_one::<String>("file").map(String::as_str); let file = matches.get_one::<String>("file").map(String::as_str);
let follow = matches.get_flag("follow"); let follow = matches.get_flag("follow");
let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir(); let instances_dir = crate::config::SETTINGS.read().paths.resolve_instances_dir();
require_instance(&instances_dir, instance)?; require_instance(&instances_dir, instance)?;
let path = resolve_log_path(&instances_dir, instance, file)?; let path = resolve_log_path(&instances_dir, instance, file)?;
+8 -3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// cli entry point and clap command definitions. // cli entry point and clap command definitions.
// no subcommand = launch TUI, otherwise dispatch to the appropriate handler. // no subcommand = launch TUI, otherwise dispatch to the appropriate handler.
mod account; mod account;
@@ -24,10 +27,10 @@ pub async fn init() {
return; return;
} }
let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir(); let instances_dir = crate::config::SETTINGS.read().paths.resolve_instances_dir();
let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir(); let meta_dir = crate::config::SETTINGS.read().paths.resolve_meta_dir();
if crate::layout_migration::is_needed(&instances_dir, &meta_dir) {
let config = crate::config::get_config_path().join("config.toml"); let config = crate::config::get_config_path().join("config.toml");
if crate::layout_migration::is_needed(&instances_dir, &meta_dir) {
if let Err(error) = if let Err(error) =
crate::layout_migration::run(&instances_dir, &meta_dir, &config, |progress| { crate::layout_migration::run(&instances_dir, &meta_dir, &config, |progress| {
eprintln!( eprintln!(
@@ -42,6 +45,8 @@ pub async fn init() {
} else if let Err(error) = crate::layout_migration::initialize_new_layout(&meta_dir) { } else if let Err(error) = crate::layout_migration::initialize_new_layout(&meta_dir) {
eprintln!("error: cannot initialize metadata layout: {error}"); eprintln!("error: cannot initialize metadata layout: {error}");
std::process::exit(1); std::process::exit(1);
} else if let Err(error) = crate::config::upgrade_config_file(&config) {
eprintln!("warning: cannot upgrade launcher config: {error}");
} }
if crate::layout_migration::cache_rebuild_pending(&meta_dir) { if crate::layout_migration::cache_rebuild_pending(&meta_dir) {
let manager = crate::instance::InstanceManager::new(&instances_dir, &meta_dir); let manager = crate::instance::InstanceManager::new(&instances_dir, &meta_dir);
+18 -7
View File
@@ -1,6 +1,10 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// plain-text table rendering for CLI output. no fancy box-drawing, // plain-text table rendering for CLI output. no fancy box-drawing,
// just left-aligned columns with two-space gaps. keeps it pipeable. // just left-aligned columns with two-space gaps. keeps it pipeable.
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use ratatui::text::Span;
pub fn print_table(headers: &[&str], rows: &[Vec<String>]) { pub fn print_table(headers: &[&str], rows: &[Vec<String>]) {
print!("{}", render_table(headers, rows)); print!("{}", render_table(headers, rows));
@@ -37,9 +41,15 @@ pub fn active_marker(active: bool) -> &'static str {
if active { ">" } else { " " } if active { ">" } else { " " }
} }
// display width (not byte length): instance and pack names are often
// non-ASCII, and padding by bytes misaligns every row below them.
fn display_width(value: &str) -> usize {
Span::raw(value).width()
}
// find the widest value in each column to pad everything evenly // find the widest value in each column to pad everything evenly
fn column_widths(headers: &[&str], rows: &[Vec<String>]) -> Vec<usize> { fn column_widths(headers: &[&str], rows: &[Vec<String>]) -> Vec<usize> {
let mut widths: Vec<usize> = headers.iter().map(|header| header.len()).collect(); let mut widths: Vec<usize> = headers.iter().map(|header| display_width(header)).collect();
for row in rows { for row in rows {
if row.len() > widths.len() { if row.len() > widths.len() {
@@ -47,7 +57,7 @@ fn column_widths(headers: &[&str], rows: &[Vec<String>]) -> Vec<usize> {
} }
for (index, value) in row.iter().enumerate() { for (index, value) in row.iter().enumerate() {
widths[index] = widths[index].max(value.len()); widths[index] = widths[index].max(display_width(value));
} }
} }
@@ -59,11 +69,12 @@ fn render_row(row: &[String], widths: &[usize]) -> String {
.iter() .iter()
.enumerate() .enumerate()
.map(|(index, width)| { .map(|(index, width)| {
format!( // manual space padding: {:<width$} counts chars, not columns,
"{:<width$}", // so it would under-pad multi-byte names.
row.get(index).map(String::as_str).unwrap_or(""), let value = row.get(index).map(String::as_str).unwrap_or("");
width = width let mut cell = String::from(value);
) cell.push_str(&" ".repeat(width.saturating_sub(display_width(value))));
cell
}) })
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join(" ") .join(" ")
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use super::add_offline_account; use super::add_offline_account;
use crate::auth::{Account, AccountStore, AccountType}; use crate::auth::{Account, AccountStore, AccountType};
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use super::build_command; use super::build_command;
#[test] #[test]
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use super::find_entry_by_stem; use super::find_entry_by_stem;
use crate::instance::content::entry::ContentEntry; use crate::instance::content::entry::ContentEntry;
use std::path::PathBuf; use std::path::PathBuf;
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use super::*; use super::*;
fn version(name: &str, number: &str) -> modrinth::VersionInfo { fn version(name: &str, number: &str) -> modrinth::VersionInfo {
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use super::parse_resolution; use super::parse_resolution;
#[test] #[test]
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use super::resolve_log_path; use super::resolve_log_path;
#[test] #[test]
+21
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use super::{format_datetime, render_table}; use super::{format_datetime, render_table};
use chrono::{TimeZone, Utc}; use chrono::{TimeZone, Utc};
@@ -18,6 +21,24 @@ fn render_table_aligns_columns() {
assert_eq!(lines[3], "Longer Name off "); assert_eq!(lines[3], "Longer Name off ");
} }
#[test]
fn render_table_aligns_multibyte_names() {
// padding must use display width, not byte length: "Öctra" is 6 bytes
// but 5 columns wide, and byte-based padding pushed every later column.
let rendered = render_table(
&["Name", "State"],
&[
vec!["Öctra".to_string(), "enabled".to_string()],
vec!["Longer Name".to_string(), "off".to_string()],
],
);
let lines: Vec<&str> = rendered.lines().collect();
assert_eq!(lines[0], "Name State ");
assert_eq!(lines[2], "Öctra enabled");
assert_eq!(lines[3], "Longer Name off ");
}
#[test] #[test]
fn formats_datetime_consistently() { fn formats_datetime_consistently() {
let dt = Utc.with_ymd_and_hms(2024, 1, 2, 3, 4, 5).unwrap(); let dt = Utc.with_ymd_and_hms(2024, 1, 2, 3, 4, 5).unwrap();
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use super::filter_manifest_versions; use super::filter_manifest_versions;
use crate::net::mojang::{LatestVersions, VersionEntry, VersionManifest}; use crate::net::mojang::{LatestVersions, VersionEntry, VersionManifest};
use std::collections::HashSet; use std::collections::HashSet;
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// shared CLI helpers: confirmation prompts, arg extraction, instance validation // shared CLI helpers: confirmation prompts, arg extraction, instance validation
use std::io::{self, Write}; use std::io::{self, Write};
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// lists available game versions, optionally filtered by mod loader support. // lists available game versions, optionally filtered by mod loader support.
// fetches the mojang manifest and cross-references with loader APIs // fetches the mojang manifest and cross-references with loader APIs
// to show only versions that actually work with a given loader. // to show only versions that actually work with a given loader.
+298 -10
View File
@@ -1,10 +1,14 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// config loading: reads config.toml from the platform config dir, creates defaults if missing. // config loading: reads config.toml from the platform config dir, creates defaults if missing.
// everything lands in the SETTINGS static so the rest of the app can just grab it. // everything lands in the SETTINGS static so the rest of the app can just grab it.
use config::{Config as ConfigLoader, ConfigError, File}; use config::{Config as ConfigLoader, ConfigError, File};
use std::fs; use std::fs;
use std::io;
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::LazyLock; use std::sync::{LazyLock, RwLock, RwLockReadGuard};
pub mod settings; pub mod settings;
pub mod theme; pub mod theme;
@@ -50,22 +54,306 @@ pub fn load_config(config_path: &std::path::Path) -> Result<Config, ConfigError>
ConfigLoader::builder() ConfigLoader::builder()
.add_source(File::from(config_path).required(false)) .add_source(File::from(config_path).required(false))
.build()? .build()?
.try_deserialize() .try_deserialize::<Config>()
.map(Config::normalize)
} }
pub static SETTINGS: LazyLock<Config> = LazyLock::new(|| { pub(crate) fn upgrade_config_file(path: &std::path::Path) -> io::Result<bool> {
let source = match fs::read_to_string(path) {
Ok(source) => source,
Err(error) if error.kind() == io::ErrorKind::NotFound => {
crate::storage::write_atomic(
path,
include_str!("../../assets/config.toml").as_bytes(),
)?;
return Ok(true);
}
Err(error) => return Err(error),
};
let mut document = parse_toml_document(path, &source)?;
let template = include_str!("../../assets/config.toml")
.parse::<toml_edit::DocumentMut>()
.map_err(io::Error::other)?;
merge_missing_table(document.as_table_mut(), template.as_table());
let upgraded = document.to_string();
toml::from_str::<Config>(&upgraded).map_err(|error| {
io::Error::new(
io::ErrorKind::InvalidData,
format!("cannot upgrade {}: {error}", path.display()),
)
})?;
if upgraded == source {
return Ok(false);
}
crate::storage::write_atomic(path, upgraded.as_bytes())?;
Ok(true)
}
pub(crate) fn migrate_legacy_data_paths(path: &std::path::Path) -> io::Result<bool> {
let Some(data_dir) = dirs_next::data_dir() else {
return Ok(false);
};
migrate_legacy_data_paths_from(path, &data_dir)
}
fn migrate_legacy_data_paths_from(
path: &std::path::Path,
data_dir: &std::path::Path,
) -> io::Result<bool> {
let source = match fs::read_to_string(path) {
Ok(source) => source,
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(false),
Err(error) => return Err(error),
};
let mut document = parse_toml_document(path, &source)?;
let Some(paths) = document
.get_mut("paths")
.and_then(toml_edit::Item::as_table_mut)
else {
return Ok(false);
};
let old_root = data_dir.join("mcl");
let new_root = data_dir.join("rmcl");
let mut changed = false;
for (key, old_path, replacement) in [
(
"instances_dir",
old_root.join("instances"),
new_root.join("instances"),
),
("meta_dir", old_root.join("meta"), new_root.join("meta")),
] {
let Some(value) = paths.get_mut(key).and_then(toml_edit::Item::as_value_mut) else {
continue;
};
if value
.as_str()
.is_some_and(|raw| settings::resolve_path(raw) == old_path)
{
let decor = value.decor().clone();
*value = toml_edit::Value::from(replacement.to_string_lossy().into_owned());
*value.decor_mut() = decor;
changed = true;
}
}
if changed {
crate::storage::write_atomic(path, document.to_string().as_bytes())?;
}
Ok(changed)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LauncherSettingsSave {
pub restart_required: bool,
pub restart_changed: bool,
pub provider_changed: bool,
pub modpack_updates_enabled: bool,
pub content_updates_enabled: bool,
}
pub struct ConfigStore(RwLock<Config>);
impl ConfigStore {
pub fn read(&self) -> RwLockReadGuard<'_, Config> {
self.0
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
pub fn save_launcher_settings(&self, edited: Config) -> io::Result<LauncherSettingsSave> {
let path = get_config_path().join("config.toml");
let current = self.read().clone();
let edited = edited.normalize();
let persisted = load_config(&path).unwrap_or_else(|_| current.clone());
let restart_required = current.paths.instances_dir != edited.paths.instances_dir
|| current.paths.meta_dir != edited.paths.meta_dir
|| current.ui.image_protocol != edited.ui.image_protocol;
let restart_changed = persisted.paths.instances_dir != edited.paths.instances_dir
|| persisted.paths.meta_dir != edited.paths.meta_dir
|| persisted.ui.image_protocol != edited.ui.image_protocol;
let provider_changed = current.content.preferred_provider
!= edited.content.preferred_provider
|| current.content.preferred_provider_only != edited.content.preferred_provider_only;
let modpack_updates_enabled =
!current.general.check_modpack_updates && edited.general.check_modpack_updates;
let content_updates_enabled =
!current.general.check_content_updates && edited.general.check_content_updates;
write_config_document(&path, &edited)?;
let mut runtime = edited;
runtime
.paths
.instances_dir
.clone_from(&current.paths.instances_dir);
runtime.paths.meta_dir.clone_from(&current.paths.meta_dir);
runtime.ui.image_protocol = current.ui.image_protocol;
*self
.0
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner) = runtime;
crate::feedback::errors::set_max_error_events(self.read().ui.max_error_events);
Ok(LauncherSettingsSave {
restart_required,
restart_changed,
provider_changed,
modpack_updates_enabled,
content_updates_enabled,
})
}
pub fn reload(&self) -> Result<LauncherSettingsSave, ConfigError> {
let mut config = load_config(&get_config_path().join("config.toml"))?;
let outcome = {
let current = self.read();
let restart_required = current.paths.instances_dir != config.paths.instances_dir
|| current.paths.meta_dir != config.paths.meta_dir
|| current.ui.image_protocol != config.ui.image_protocol;
let provider_changed = current.content.preferred_provider
!= config.content.preferred_provider
|| current.content.preferred_provider_only
!= config.content.preferred_provider_only;
let modpack_updates_enabled =
!current.general.check_modpack_updates && config.general.check_modpack_updates;
let content_updates_enabled =
!current.general.check_content_updates && config.general.check_content_updates;
// App owns a manager and several watchers rooted at these paths.
// Keep them stable for this process; persisted path edits apply on restart.
config
.paths
.instances_dir
.clone_from(&current.paths.instances_dir);
config.paths.meta_dir.clone_from(&current.paths.meta_dir);
config.ui.image_protocol = current.ui.image_protocol;
LauncherSettingsSave {
restart_required,
restart_changed: restart_required,
provider_changed,
modpack_updates_enabled,
content_updates_enabled,
}
};
*self
.0
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner) = config;
crate::feedback::errors::set_max_error_events(self.read().ui.max_error_events);
Ok(outcome)
}
}
pub static SETTINGS: LazyLock<ConfigStore> = LazyLock::new(|| {
let config = {
let path = ensure_config_exists(); let path = ensure_config_exists();
load_config(&path).unwrap_or_else(|e| { load_config(&path).unwrap_or_else(|e| {
tracing::error!("Config load failed, using defaults: {}", e); tracing::error!("Config load failed, using defaults: {}", e);
Config { Config::default()
general: settings::General::default(), })
paths: settings::Paths::default(), };
defaults: settings::Defaults::default(), crate::feedback::errors::set_max_error_events(config.ui.max_error_events);
ui: settings::Ui::default(), ConfigStore(RwLock::new(config))
content: settings::Content::default(), });
fn write_config_document(path: &std::path::Path, config: &Config) -> io::Result<()> {
write_merged_toml_document(path, config, |document| {
if config.paths.java_path.is_none()
&& let Some(paths) = document
.get_mut("paths")
.and_then(|item| item.as_table_mut())
{
paths.remove("java_path");
}
let default_paths = settings::Paths::default();
if let Some(paths) = document
.get_mut("paths")
.and_then(|item| item.as_table_mut())
{
if config.paths.instances_dir == default_paths.instances_dir {
paths.remove("instances_dir");
}
if config.paths.meta_dir == default_paths.meta_dir {
paths.remove("meta_dir");
}
}
if config.defaults.resolution.is_none()
&& let Some(defaults) = document
.get_mut("defaults")
.and_then(|item| item.as_table_mut())
{
defaults.remove("resolution");
} }
}) })
}); }
pub(crate) fn write_merged_toml_document<T, F>(
path: &std::path::Path,
value: &T,
edit: F,
) -> io::Result<()>
where
T: serde::Serialize,
F: FnOnce(&mut toml_edit::DocumentMut),
{
let source = match fs::read_to_string(path) {
Ok(source) => source,
Err(error) if error.kind() == io::ErrorKind::NotFound => String::new(),
Err(error) => return Err(error),
};
let mut document = parse_toml_document(path, &source)?;
let generated = toml::to_string_pretty(value)
.map_err(io::Error::other)?
.parse::<toml_edit::DocumentMut>()
.map_err(io::Error::other)?;
merge_table(document.as_table_mut(), generated.as_table());
edit(&mut document);
crate::storage::write_atomic(path, document.to_string().as_bytes())
}
fn parse_toml_document(path: &std::path::Path, source: &str) -> io::Result<toml_edit::DocumentMut> {
source.parse::<toml_edit::DocumentMut>().map_err(|error| {
io::Error::new(
io::ErrorKind::InvalidData,
format!("cannot update {}: {error}", path.display()),
)
})
}
fn merge_table(target: &mut toml_edit::Table, source: &toml_edit::Table) {
for (key, source_item) in source {
if let Some(target_item) = target.get_mut(key) {
if let (Some(target_table), Some(source_table)) =
(target_item.as_table_mut(), source_item.as_table())
{
merge_table(target_table, source_table);
continue;
}
if let (Some(target_value), Some(source_value)) =
(target_item.as_value_mut(), source_item.as_value())
{
let decor = target_value.decor().clone();
*target_value = source_value.clone();
*target_value.decor_mut() = decor;
continue;
}
*target_item = source_item.clone();
} else {
target.insert(key, source_item.clone());
}
}
}
fn merge_missing_table(target: &mut toml_edit::Table, defaults: &toml_edit::Table) {
for (key, default_item) in defaults {
if let Some(target_item) = target.get_mut(key) {
if let (Some(target_table), Some(default_table)) =
(target_item.as_table_mut(), default_item.as_table())
{
merge_missing_table(target_table, default_table);
}
} else {
target.insert(key, default_item.clone());
}
}
}
#[cfg(test)] #[cfg(test)]
#[path = "tests/loading.rs"] #[path = "tests/loading.rs"]
+206 -17
View File
@@ -1,29 +1,106 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// all the config structs that map to sections in config.toml. // all the config structs that map to sections in config.toml.
// everything has sane defaults so a blank file (or no file) still works. // everything has sane defaults so a blank file (or no file) still works.
use std::path::PathBuf; use std::{
collections::{BTreeMap, BTreeSet},
fmt,
path::PathBuf,
};
use serde::Deserialize; use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Default, Clone, Copy, PartialEq, Eq)] use crate::instance::models::{WindowMode, memory_kib, normalize_memory_value};
pub const DEFAULT_RESOLUTION: (u32, u32) = (854, 480);
#[derive(Debug, Serialize, Deserialize, Default, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "lowercase")] #[serde(rename_all = "lowercase")]
pub enum ImageProtocol { pub enum ImageProtocol {
#[default]
Auto,
Halfblocks, Halfblocks,
Quadrants, Quadrants,
#[default]
Kitty, Kitty,
Iterm2, Iterm2,
} }
#[derive(Debug, Deserialize, Default)] #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct General {} #[serde(rename_all = "lowercase")]
pub enum ShortcutHintScope {
All,
Main,
Instances,
Content,
Accounts,
Settings,
Popups,
}
#[derive(Debug, Deserialize)] impl ShortcutHintScope {
pub const AREAS: [Self; 5] = [
Self::Instances,
Self::Content,
Self::Accounts,
Self::Settings,
Self::Popups,
];
}
impl fmt::Display for ImageProtocol {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Auto => formatter.write_str("auto"),
Self::Halfblocks => formatter.write_str("halfblocks"),
Self::Quadrants => formatter.write_str("quadrants"),
Self::Kitty => formatter.write_str("kitty"),
Self::Iterm2 => formatter.write_str("iterm2"),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct General {
#[serde(default = "default_true")]
pub check_modpack_updates: bool,
#[serde(default = "default_true")]
pub check_content_updates: bool,
}
impl Default for General {
fn default() -> Self {
Self {
check_modpack_updates: true,
check_content_updates: true,
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ContentProvider {
#[default]
Modrinth,
CurseForge,
}
impl fmt::Display for ContentProvider {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Modrinth => formatter.write_str("Modrinth"),
Self::CurseForge => formatter.write_str("CurseForge"),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Content { pub struct Content {
#[serde(default = "default_true")] #[serde(default = "default_true")]
pub ask_on_provider_conflict: bool, pub ask_on_provider_conflict: bool,
#[serde(default = "default_provider")] #[serde(default, deserialize_with = "deserialize_content_provider")]
pub preferred_provider: String, pub preferred_provider: ContentProvider,
#[serde(default)] #[serde(default)]
pub preferred_provider_only: bool, pub preferred_provider_only: bool,
#[serde(default = "default_unmatched_retry_hours")] #[serde(default = "default_unmatched_retry_hours")]
@@ -36,8 +113,16 @@ fn default_true() -> bool {
true true
} }
fn default_provider() -> String { fn deserialize_content_provider<'de, D>(deserializer: D) -> Result<ContentProvider, D::Error>
"modrinth".to_owned() where
D: serde::Deserializer<'de>,
{
let value = String::deserialize(deserializer)?;
Ok(if value.eq_ignore_ascii_case("curseforge") {
ContentProvider::CurseForge
} else {
ContentProvider::Modrinth
})
} }
fn default_unmatched_retry_hours() -> u64 { fn default_unmatched_retry_hours() -> u64 {
@@ -52,7 +137,7 @@ impl Default for Content {
fn default() -> Self { fn default() -> Self {
Self { Self {
ask_on_provider_conflict: true, ask_on_provider_conflict: true,
preferred_provider: default_provider(), preferred_provider: ContentProvider::default(),
preferred_provider_only: false, preferred_provider_only: false,
unmatched_retry_hours: default_unmatched_retry_hours(), unmatched_retry_hours: default_unmatched_retry_hours(),
max_fingerprint_size_mib: default_max_fingerprint_size_mib(), max_fingerprint_size_mib: default_max_fingerprint_size_mib(),
@@ -77,7 +162,7 @@ impl Content {
} }
fn preferred_provider_with_curseforge(&self, curseforge_available: bool) -> &'static str { fn preferred_provider_with_curseforge(&self, curseforge_available: bool) -> &'static str {
if self.preferred_provider.eq_ignore_ascii_case("curseforge") && curseforge_available { if self.preferred_provider == ContentProvider::CurseForge && curseforge_available {
"curseforge" "curseforge"
} else { } else {
"modrinth" "modrinth"
@@ -116,13 +201,16 @@ impl Content {
} }
} }
#[derive(Debug, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Paths { pub struct Paths {
#[serde(default = "default_instances_dir")] #[serde(default = "default_instances_dir")]
#[serde(skip_serializing_if = "is_default_instances_dir")]
pub instances_dir: String, pub instances_dir: String,
#[serde(default = "default_meta_dir")] #[serde(default = "default_meta_dir")]
#[serde(skip_serializing_if = "is_default_meta_dir")]
pub meta_dir: String, pub meta_dir: String,
#[serde(default)] #[serde(default)]
#[serde(skip_serializing_if = "Option::is_none")]
pub java_path: Option<String>, pub java_path: Option<String>,
} }
@@ -135,6 +223,10 @@ fn default_instances_dir() -> String {
.into_owned() .into_owned()
} }
fn is_default_instances_dir(path: &str) -> bool {
path == default_instances_dir()
}
fn default_meta_dir() -> String { fn default_meta_dir() -> String {
dirs_next::data_dir() dirs_next::data_dir()
.unwrap_or_else(|| PathBuf::from(".")) .unwrap_or_else(|| PathBuf::from("."))
@@ -144,6 +236,10 @@ fn default_meta_dir() -> String {
.into_owned() .into_owned()
} }
fn is_default_meta_dir(path: &str) -> bool {
path == default_meta_dir()
}
impl Default for Paths { impl Default for Paths {
fn default() -> Self { fn default() -> Self {
Self { Self {
@@ -182,12 +278,21 @@ impl Paths {
} }
} }
#[derive(Debug, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Defaults { pub struct Defaults {
#[serde(default = "default_memory_min")] #[serde(default = "default_memory_min")]
pub memory_min: String, pub memory_min: String,
#[serde(default = "default_memory_max")] #[serde(default = "default_memory_max")]
pub memory_max: String, pub memory_max: String,
#[serde(default)]
pub jvm_args: Vec<String>,
#[serde(default)]
pub environment: BTreeMap<String, String>,
#[serde(default)]
pub window_mode: WindowMode,
#[serde(default = "default_resolution")]
#[serde(skip_serializing_if = "Option::is_none")]
pub resolution: Option<(u32, u32)>,
} }
fn default_memory_min() -> String { fn default_memory_min() -> String {
@@ -197,21 +302,31 @@ fn default_memory_max() -> String {
"2G".to_owned() "2G".to_owned()
} }
fn default_resolution() -> Option<(u32, u32)> {
Some(DEFAULT_RESOLUTION)
}
impl Default for Defaults { impl Default for Defaults {
fn default() -> Self { fn default() -> Self {
Self { Self {
memory_min: default_memory_min(), memory_min: default_memory_min(),
memory_max: default_memory_max(), memory_max: default_memory_max(),
jvm_args: Vec::new(),
environment: BTreeMap::new(),
window_mode: WindowMode::default(),
resolution: default_resolution(),
} }
} }
} }
#[derive(Debug, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
// timing knobs for the error toast animation: show for 5s, start sliding at 3.5s, // timing knobs for the error toast animation: show for 5s, start sliding at 3.5s,
// fly off screen over 300ms. tweak these if the toasts feel too fast or slow. // fly off screen over 300ms. tweak these if the toasts feel too fast or slow.
pub struct Ui { pub struct Ui {
#[serde(default)] #[serde(default)]
pub image_protocol: ImageProtocol, pub image_protocol: ImageProtocol,
#[serde(default)]
pub hidden_shortcut_hints: BTreeSet<ShortcutHintScope>,
#[serde(default = "default_error_auto_dismiss_ms")] #[serde(default = "default_error_auto_dismiss_ms")]
pub error_auto_dismiss_ms: u64, pub error_auto_dismiss_ms: u64,
#[serde(default = "default_error_slide_start_ms")] #[serde(default = "default_error_slide_start_ms")]
@@ -239,6 +354,7 @@ impl Default for Ui {
fn default() -> Self { fn default() -> Self {
Self { Self {
image_protocol: ImageProtocol::default(), image_protocol: ImageProtocol::default(),
hidden_shortcut_hints: BTreeSet::new(),
error_auto_dismiss_ms: default_error_auto_dismiss_ms(), error_auto_dismiss_ms: default_error_auto_dismiss_ms(),
error_slide_start_ms: default_error_slide_start_ms(), error_slide_start_ms: default_error_slide_start_ms(),
error_fly_out_ms: default_error_fly_out_ms(), error_fly_out_ms: default_error_fly_out_ms(),
@@ -247,7 +363,40 @@ impl Default for Ui {
} }
} }
#[derive(Debug, Deserialize)] impl Ui {
pub fn show_shortcut_hints(&self, scope: ShortcutHintScope) -> bool {
!self.hidden_shortcut_hints.contains(&ShortcutHintScope::All)
&& !(scope != ShortcutHintScope::Popups
&& self
.hidden_shortcut_hints
.contains(&ShortcutHintScope::Main))
&& !self.hidden_shortcut_hints.contains(&scope)
}
pub fn set_shortcut_hints(&mut self, scope: ShortcutHintScope, visible: bool) {
let mut hidden = ShortcutHintScope::AREAS
.into_iter()
.filter(|area| !self.show_shortcut_hints(*area))
.collect::<BTreeSet<_>>();
if visible {
hidden.remove(&scope);
} else {
hidden.insert(scope);
}
self.hidden_shortcut_hints = if hidden.len() == ShortcutHintScope::AREAS.len() {
[ShortcutHintScope::All].into_iter().collect()
} else if ShortcutHintScope::AREAS[..4]
.iter()
.all(|area| hidden.contains(area))
{
[ShortcutHintScope::Main].into_iter().collect()
} else {
hidden
};
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Config { pub struct Config {
#[serde(default)] #[serde(default)]
pub general: General, pub general: General,
@@ -261,6 +410,46 @@ pub struct Config {
pub content: Content, pub content: Content,
} }
impl Config {
pub fn normalize(mut self) -> Self {
if self.paths.instances_dir.trim().is_empty() {
self.paths.instances_dir = default_instances_dir();
}
if self.paths.meta_dir.trim().is_empty() {
self.paths.meta_dir = default_meta_dir();
}
self.paths.java_path = self
.paths
.java_path
.take()
.and_then(|path| (!path.trim().is_empty()).then(|| path.trim().to_owned()));
self.defaults.memory_min =
normalize_memory_value(&self.defaults.memory_min).unwrap_or_else(default_memory_min);
self.defaults.memory_max =
normalize_memory_value(&self.defaults.memory_max).unwrap_or_else(default_memory_max);
if memory_kib(&self.defaults.memory_min) > memory_kib(&self.defaults.memory_max) {
self.defaults
.memory_max
.clone_from(&self.defaults.memory_min);
}
if self
.defaults
.resolution
.is_none_or(|(width, height)| width == 0 || height == 0)
{
self.defaults.resolution = default_resolution();
}
self.ui.error_auto_dismiss_ms = self.ui.error_auto_dismiss_ms.max(1);
self.ui.error_slide_start_ms = self
.ui
.error_slide_start_ms
.min(self.ui.error_auto_dismiss_ms);
self.ui.error_fly_out_ms = self.ui.error_fly_out_ms.min(self.ui.error_auto_dismiss_ms);
self.ui.max_error_events = self.ui.max_error_events.max(1);
self
}
}
#[cfg(test)] #[cfg(test)]
#[path = "tests/settings.rs"] #[path = "tests/settings.rs"]
mod tests; mod tests;
+164 -1
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use super::*; use super::*;
#[test] #[test]
@@ -30,7 +33,9 @@ fn load_config_from_empty_file() {
fn load_config_missing_file_uses_defaults() { fn load_config_missing_file_uses_defaults() {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("nonexistent.toml"); let path = tmp.path().join("nonexistent.toml");
load_config(&path).unwrap(); let config = load_config(&path).unwrap();
assert_eq!(config.defaults.memory_max, "2G");
assert_eq!(config.defaults.memory_min, "512M");
} }
#[test] #[test]
@@ -49,3 +54,161 @@ fn load_config_partial_sections() {
assert_eq!(config.paths.instances_dir, "/custom/path"); assert_eq!(config.paths.instances_dir, "/custom/path");
assert!(config.paths.java_path.is_none()); assert!(config.paths.java_path.is_none());
} }
#[test]
fn bundled_config_uses_platform_paths_and_automatic_java() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("config.toml");
std::fs::write(&path, include_str!("../../../assets/config.toml")).unwrap();
let config = load_config(&path).unwrap();
assert_eq!(
config.paths.instances_dir,
settings::Paths::default().instances_dir
);
assert_eq!(config.paths.meta_dir, settings::Paths::default().meta_dir);
assert!(config.paths.java_path.is_none());
assert_eq!(config.ui.image_protocol, settings::ImageProtocol::Auto);
assert_eq!(
config.defaults.resolution,
Some(settings::DEFAULT_RESOLUTION)
);
}
#[test]
fn config_normalizes_memory_java_and_notification_bounds() {
let config = Config {
paths: settings::Paths {
instances_dir: String::new(),
meta_dir: " ".to_owned(),
java_path: Some(" ".to_owned()),
},
defaults: settings::Defaults {
memory_min: "invalid".to_owned(),
memory_max: "1G".to_owned(),
resolution: Some((0, 1080)),
..Default::default()
},
ui: settings::Ui {
error_auto_dismiss_ms: 100,
error_slide_start_ms: 200,
error_fly_out_ms: 300,
max_error_events: 0,
..Default::default()
},
..Default::default()
}
.normalize();
assert_eq!(
config.paths.instances_dir,
settings::Paths::default().instances_dir
);
assert_eq!(config.paths.meta_dir, settings::Paths::default().meta_dir);
assert!(config.paths.java_path.is_none());
assert_eq!(config.defaults.memory_min, "512M");
assert_eq!(config.defaults.memory_max, "1G");
assert_eq!(
config.defaults.resolution,
Some(settings::DEFAULT_RESOLUTION)
);
assert_eq!(config.ui.error_slide_start_ms, 100);
assert_eq!(config.ui.error_fly_out_ms, 100);
assert_eq!(config.ui.max_error_events, 1);
}
#[test]
fn settings_writer_preserves_comments_and_unknown_keys() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("config.toml");
std::fs::write(
&path,
"# keep this comment\n[defaults]\n# heap comment\nmemory_max = \"2G\"\n\n[future]\nvalue = 42\n",
)
.unwrap();
let mut config = Config::default();
config.defaults.memory_max = "8G".to_owned();
write_config_document(&path, &config).unwrap();
let saved = std::fs::read_to_string(path).unwrap();
assert!(saved.contains("# keep this comment"), "{saved}");
assert!(saved.contains("# heap comment"), "{saved}");
assert!(saved.contains("memory_max = \"8G\""));
assert!(saved.contains("[future]"));
assert!(saved.contains("value = 42"));
assert!(!saved.contains("instances_dir"));
assert!(!saved.contains("meta_dir"));
}
#[test]
fn config_upgrade_adds_new_defaults_without_replacing_old_values() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("config.toml");
let old = r#"# user comment
[paths]
instances_dir = "/custom/instances"
meta_dir = "/custom/meta"
java_path = "/custom/java"
[defaults]
memory_min = "1G"
memory_max = "8G"
[ui]
image_protocol = "kitty"
[future]
value = 42
"#;
std::fs::write(&path, old).unwrap();
assert!(upgrade_config_file(&path).unwrap());
let upgraded = std::fs::read_to_string(&path).unwrap();
let config = load_config(&path).unwrap();
assert!(upgraded.contains("# user comment"), "{upgraded}");
assert!(upgraded.contains("[future]"), "{upgraded}");
assert!(upgraded.contains("value = 42"), "{upgraded}");
assert!(upgraded.contains("jvm_args = []"), "{upgraded}");
assert!(
upgraded.contains("check_modpack_updates = true"),
"{upgraded}"
);
assert_eq!(config.paths.instances_dir, "/custom/instances");
assert_eq!(config.paths.meta_dir, "/custom/meta");
assert_eq!(config.paths.java_path.as_deref(), Some("/custom/java"));
assert_eq!(config.defaults.memory_min, "1G");
assert_eq!(config.defaults.memory_max, "8G");
assert_eq!(config.ui.image_protocol, settings::ImageProtocol::Kitty);
assert!(!upgrade_config_file(&path).unwrap());
assert_eq!(std::fs::read_to_string(path).unwrap(), upgraded);
}
#[test]
fn legacy_default_data_paths_follow_the_renamed_data_directory() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("config.toml");
let data = tmp.path().join("data");
std::fs::write(
&path,
format!(
"[paths]\ninstances_dir = {:?}\nmeta_dir = {:?}\n",
data.join("mcl/instances").to_string_lossy(),
data.join("mcl/meta").to_string_lossy()
),
)
.unwrap();
assert!(migrate_legacy_data_paths_from(&path, &data).unwrap());
let migrated = std::fs::read_to_string(&path).unwrap();
let config = load_config(&path).unwrap();
assert_eq!(
settings::resolve_path(&config.paths.instances_dir),
data.join("rmcl").join("instances"),
"{migrated}"
);
assert_eq!(
settings::resolve_path(&config.paths.meta_dir),
data.join("rmcl").join("meta"),
"{migrated}"
);
}
+33
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use super::*; use super::*;
#[test] #[test]
@@ -63,6 +66,11 @@ fn content_provider_settings_are_normalized() {
merged.discovery_provider_label_with_curseforge(true), merged.discovery_provider_label_with_curseforge(true),
"providers" "providers"
); );
let legacy: Content = toml::from_str("preferred_provider = \"CurseForge\"").unwrap();
assert_eq!(legacy.preferred_provider, ContentProvider::CurseForge);
let unknown: Content = toml::from_str("preferred_provider = \"unknown\"").unwrap();
assert_eq!(unknown.preferred_provider, ContentProvider::Modrinth);
} }
#[test] #[test]
@@ -102,3 +110,28 @@ memory_max = "8G"
assert_eq!(config.defaults.memory_max, "8G"); assert_eq!(config.defaults.memory_max, "8G");
assert_eq!(config.defaults.memory_min, "512M"); assert_eq!(config.defaults.memory_min, "512M");
} }
#[test]
fn shortcut_hints_support_global_main_and_selective_hiding() {
let mut ui: Ui = toml::from_str("hidden_shortcut_hints = []").unwrap();
assert!(
ShortcutHintScope::AREAS
.iter()
.all(|scope| ui.show_shortcut_hints(*scope))
);
ui = toml::from_str("hidden_shortcut_hints = [\"main\"]").unwrap();
assert!(!ui.show_shortcut_hints(ShortcutHintScope::Instances));
assert!(ui.show_shortcut_hints(ShortcutHintScope::Popups));
ui.set_shortcut_hints(ShortcutHintScope::Content, true);
assert!(ui.show_shortcut_hints(ShortcutHintScope::Content));
assert!(!ui.show_shortcut_hints(ShortcutHintScope::Accounts));
ui.hidden_shortcut_hints = [ShortcutHintScope::All].into_iter().collect();
assert!(
ShortcutHintScope::AREAS
.iter()
.all(|scope| !ui.show_shortcut_hints(*scope))
);
}
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use super::*; use super::*;
// cover every BorderStyle variant. a mutation that swaps two arms of the // cover every BorderStyle variant. a mutation that swaps two arms of the
+134 -7
View File
@@ -1,9 +1,12 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// theme resolution: loads theme.toml, picks a base theme (builtin or custom file), // theme resolution: loads theme.toml, picks a base theme (builtin or custom file),
// then layers user color overrides on top. supports loading .toml themes from the // then layers user color overrides on top. supports loading .toml themes from the
// config/theme/ directory or by absolute path. // config/theme/ directory or by absolute path.
use std::path::Path; use std::path::Path;
use std::sync::LazyLock; use std::sync::{Arc, LazyLock, RwLock};
use ratatui::style::Color; use ratatui::style::Color;
use ratatui::widgets::BorderType; use ratatui::widgets::BorderType;
@@ -31,7 +34,7 @@ impl BorderStyle {
} }
} }
#[derive(Debug, Deserialize, Default)] #[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ThemeOverrides { pub struct ThemeOverrides {
pub accent: Option<Color>, pub accent: Option<Color>,
pub accent_dim: Option<Color>, pub accent_dim: Option<Color>,
@@ -50,7 +53,7 @@ pub struct ThemeOverrides {
pub background: Option<Color>, pub background: Option<Color>,
} }
#[derive(Debug, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThemeConfig { pub struct ThemeConfig {
#[serde(default)] #[serde(default)]
pub border_style: BorderStyle, pub border_style: BorderStyle,
@@ -164,12 +167,136 @@ fn load_base_theme(name: &str) -> Box<dyn Theme> {
resolve_theme(name) resolve_theme(name)
} }
static THEME_CONFIG: LazyLock<ThemeConfig> = LazyLock::new(load_theme_config); pub struct ThemeStore(RwLock<Arc<dyn Theme>>);
pub static THEME: LazyLock<Box<dyn Theme>> = LazyLock::new(|| resolve_app_theme(&THEME_CONFIG)); impl ThemeStore {
pub fn as_ref(&self) -> Arc<dyn Theme> {
self.0
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone()
}
pub static BORDER_STYLE: LazyLock<BorderStyle> = fn set(&self, theme: Box<dyn Theme>) {
LazyLock::new(|| THEME_CONFIG.border_style.clone()); *self
.0
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner) = Arc::from(theme);
}
}
pub struct BorderStyleStore(RwLock<BorderStyle>);
impl BorderStyleStore {
pub fn to_border_type(&self) -> BorderType {
self.current().to_border_type()
}
pub fn current(&self) -> BorderStyle {
self.0
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone()
}
fn set(&self, style: BorderStyle) {
*self
.0
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner) = style;
}
}
static THEME_CONFIG: LazyLock<RwLock<ThemeConfig>> =
LazyLock::new(|| RwLock::new(load_theme_config()));
pub static THEME: LazyLock<ThemeStore> = LazyLock::new(|| {
let config = THEME_CONFIG
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
ThemeStore(RwLock::new(Arc::from(resolve_app_theme(&config))))
});
pub static BORDER_STYLE: LazyLock<BorderStyleStore> = LazyLock::new(|| {
let config = THEME_CONFIG
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
BorderStyleStore(RwLock::new(config.border_style.clone()))
});
pub fn current_theme_config() -> ThemeConfig {
THEME_CONFIG
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone()
}
pub fn apply_theme(theme: String, border_style: BorderStyle) -> std::io::Result<()> {
validate_theme_name(&theme)?;
let mut config = current_theme_config();
config.theme = theme;
config.border_style = border_style.clone();
super::write_merged_toml_document(
&super::get_config_path().join("theme.toml"),
&config,
|document| {
if config.custom.is_none() {
document.as_table_mut().remove("custom");
}
},
)?;
THEME.set(resolve_app_theme(&config));
BORDER_STYLE.set(border_style);
*THEME_CONFIG
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner) = config;
crate::feedback::request_redraw();
Ok(())
}
fn validate_theme_name(name: &str) -> std::io::Result<()> {
if ratatui_themekit::available_theme_ids().contains(&name) {
return Ok(());
}
let path = if Path::new(name).is_absolute() {
std::path::PathBuf::from(name)
} else {
let directory = super::get_config_path().join("theme");
let direct = directory.join(name);
if direct.exists() {
direct
} else {
directory.join(format!("{name}.toml"))
}
};
let content = std::fs::read_to_string(&path).map_err(|error| {
std::io::Error::new(
error.kind(),
format!("failed to load theme {}: {error}", path.display()),
)
})?;
toml::from_str::<CustomTheme>(&content).map_err(|error| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("invalid theme {}: {error}", path.display()),
)
})?;
Ok(())
}
pub fn reload_theme() -> std::io::Result<()> {
let path = super::get_config_path().join("theme.toml");
let content = std::fs::read_to_string(path)?;
let config: ThemeConfig = toml::from_str(&content)
.map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
THEME.set(resolve_app_theme(&config));
BORDER_STYLE.set(config.border_style.clone());
*THEME_CONFIG
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner) = config;
crate::feedback::request_redraw();
Ok(())
}
#[cfg(test)] #[cfg(test)]
#[path = "tests/theme.rs"] #[path = "tests/theme.rs"]
+26 -3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// thread-safe FIFO queue for error/warning toasts displayed in the UI. // thread-safe FIFO queue for error/warning toasts displayed in the UI.
// also (ab)used for INFO toasts like "desktop shortcut created" because // also (ab)used for INFO toasts like "desktop shortcut created" because
// why build a separate notification system when this one works fine. // why build a separate notification system when this one works fine.
@@ -6,15 +9,25 @@
// used by the render layer to track per-toast animation state. // used by the render layer to track per-toast animation state.
use std::collections::VecDeque; use std::collections::VecDeque;
use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use std::time::Instant; use std::time::Instant;
use std::sync::LazyLock; use std::sync::LazyLock;
use tracing::Level; use tracing::Level;
const MAX_ERROR_EVENTS: usize = 50;
static NEXT_ERROR_ID: AtomicU64 = AtomicU64::new(1); static NEXT_ERROR_ID: AtomicU64 = AtomicU64::new(1);
static MAX_ERROR_EVENTS: AtomicUsize = AtomicUsize::new(50);
pub(crate) fn set_max_error_events(max_events: usize) {
let max_events = max_events.max(1);
MAX_ERROR_EVENTS.store(max_events, Ordering::Relaxed);
if let Ok(mut events) = ERROR_EVENTS.lock() {
while events.len() > max_events {
events.pop_front();
}
}
}
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct ErrorEvent { pub struct ErrorEvent {
@@ -35,7 +48,8 @@ pub fn push_error(event: ErrorEvent) {
events.push_back(event); events.push_back(event);
while events.len() > MAX_ERROR_EVENTS { let max_events = MAX_ERROR_EVENTS.load(Ordering::Relaxed);
while events.len() > max_events {
events.pop_front(); events.pop_front();
} }
super::request_redraw(); super::request_redraw();
@@ -46,6 +60,15 @@ pub fn push_error(event: ErrorEvent) {
} }
} }
pub fn push_message(level: Level, message: impl Into<String>) {
push_error(ErrorEvent {
id: 0,
level,
message: message.into(),
pushed_at: Instant::now(),
});
}
#[must_use] #[must_use]
pub fn has_errors() -> bool { pub fn has_errors() -> bool {
match ERROR_EVENTS.lock() { match ERROR_EVENTS.lock() {
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// application feedback shared by background work and every frontend. // application feedback shared by background work and every frontend.
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
+4 -1
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// global progress state shared between background tasks and the status bar widget. // global progress state shared between background tasks and the status bar widget.
// background tasks set the action/progress, the render loop reads it every frame. // background tasks set the action/progress, the render loop reads it every frame.
@@ -81,7 +84,7 @@ impl ProgressTask {
} }
pub fn fail(mut self, error: impl std::fmt::Display) { pub fn fail(mut self, error: impl std::fmt::Display) {
tracing::warn!("Progress task failed: {error}"); tracing::debug!("Progress task failed: {error}");
self.remove(); self.remove();
self.finished = true; self.finished = true;
} }
+25 -2
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use super::*; use super::*;
use crate::tests::TEST_LOCK; use crate::tests::TEST_LOCK;
@@ -69,13 +72,15 @@ fn overflow_drops_oldest() {
let _guard = TEST_LOCK.lock().unwrap(); let _guard = TEST_LOCK.lock().unwrap();
clear_errors_for_test(); clear_errors_for_test();
for i in 0..(MAX_ERROR_EVENTS + 10) { let max_error_events = 50;
set_max_error_events(max_error_events);
for i in 0..(max_error_events + 10) {
push_error(make_event(&format!("overflow_{i}"))); push_error(make_event(&format!("overflow_{i}")));
} }
let all = peek_all_errors(); let all = peek_all_errors();
assert_eq!(all.len(), MAX_ERROR_EVENTS); assert_eq!(all.len(), max_error_events);
assert!(!all.iter().any(|e| e.message == "overflow_0")); assert!(!all.iter().any(|e| e.message == "overflow_0"));
assert!(!all.iter().any(|e| e.message == "overflow_9")); assert!(!all.iter().any(|e| e.message == "overflow_9"));
@@ -83,3 +88,21 @@ fn overflow_drops_oldest() {
assert!(all.iter().any(|e| e.message == "overflow_10")); assert!(all.iter().any(|e| e.message == "overflow_10"));
assert!(all.iter().any(|e| e.message == "overflow_59")); assert!(all.iter().any(|e| e.message == "overflow_59"));
} }
#[test]
fn lowering_limit_trims_existing_events_immediately() {
let _guard = TEST_LOCK.lock().unwrap();
clear_errors_for_test();
set_max_error_events(5);
for i in 0..5 {
push_error(make_event(&format!("trim_{i}")));
}
set_max_error_events(2);
let all = peek_all_errors();
assert_eq!(all.len(), 2);
assert_eq!(all[0].message, "trim_4");
assert_eq!(all[1].message, "trim_3");
set_max_error_events(50);
}
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use super::*; use super::*;
use crate::tests::TEST_LOCK; use crate::tests::TEST_LOCK;
+99 -7
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use thiserror::Error; use thiserror::Error;
@@ -10,6 +13,10 @@ pub enum ConfigSyncError {
InstanceRunning { instance: String }, InstanceRunning { instance: String },
#[error("IO error: {0}")] #[error("IO error: {0}")]
Io(#[from] std::io::Error), Io(#[from] std::io::Error),
#[error("Failed to save config profile: {0}")]
Save(String),
#[error("Failed to save config profile ({save}) and roll back profile files ({rollback})")]
SaveRollback { save: String, rollback: String },
} }
#[derive(Debug)] #[derive(Debug)]
@@ -103,14 +110,14 @@ pub fn delete_profile(meta_dir: &Path, profile: &str) -> Result<(), ConfigSyncEr
Ok(()) Ok(())
} }
pub fn switch_profile( fn switch_profile(
instance_name: &str, instance_name: &str,
current_profile: Option<&str>, current_profile: Option<&str>,
target_profile: Option<&str>, target_profile: Option<&str>,
meta_dir: &Path, meta_dir: &Path,
instance_dir: &Path, instance_dir: &Path,
) -> Result<Option<String>, ConfigSyncError> { ) -> Result<Option<String>, ConfigSyncError> {
if crate::instance::runtime::get(instance_name).is_some() { if crate::instance::runtime::is_active(instance_name) {
return Err(ConfigSyncError::InstanceRunning { return Err(ConfigSyncError::InstanceRunning {
instance: instance_name.to_string(), instance: instance_name.to_string(),
}); });
@@ -169,6 +176,67 @@ pub fn switch_profile(
Ok(Some(profile.to_string())) Ok(Some(profile.to_string()))
} }
pub fn switch_profile_and_save(
manager: &crate::instance::InstanceManager,
config: &mut crate::instance::InstanceConfig,
target_profile: Option<&str>,
) -> Result<(), ConfigSyncError> {
let current_profile = config.config_sync_profile.clone();
let instance_dir = manager.instances_dir.join(&config.name);
let selected = switch_profile_and_persist(
&config.name,
current_profile.as_deref(),
target_profile,
&manager.meta_dir,
&instance_dir,
|selected| {
let mut updated = config.clone();
updated.config_sync_profile = selected.map(str::to_owned);
manager.save(&updated)
},
)?;
config.config_sync_profile = selected;
Ok(())
}
fn switch_profile_and_persist<E>(
instance_name: &str,
current_profile: Option<&str>,
target_profile: Option<&str>,
meta_dir: &Path,
instance_dir: &Path,
persist: impl FnOnce(Option<&str>) -> Result<(), E>,
) -> Result<Option<String>, ConfigSyncError>
where
E: std::fmt::Display,
{
let selected = switch_profile(
instance_name,
current_profile,
target_profile,
meta_dir,
instance_dir,
)?;
let Err(save) = persist(selected.as_deref()) else {
return Ok(selected);
};
let save = save.to_string();
if let Err(rollback) = switch_profile(
instance_name,
selected.as_deref(),
current_profile,
meta_dir,
instance_dir,
) {
return Err(ConfigSyncError::SaveRollback {
save,
rollback: rollback.to_string(),
});
}
Err(ConfigSyncError::Save(save))
}
fn normalize_profile(profile: &str) -> Option<&str> { fn normalize_profile(profile: &str) -> Option<&str> {
let trimmed = profile.trim(); let trimmed = profile.trim();
if trimmed.is_empty() { if trimmed.is_empty() {
@@ -228,16 +296,40 @@ fn acquire_lock(profile_dir: &Path) -> Result<ConfigSyncLock, ConfigSyncError> {
} }
fn mirror_dir(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> { fn mirror_dir(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> {
// stage the copy in a sibling temp dir and swap it in only when complete.
// deleting dst up-front (the old behaviour) meant a failure mid-copy
// destroyed the current config tree with nothing to fall back to.
let parent = dst.parent().filter(|p| !p.as_os_str().is_empty());
let Some(parent) = parent else {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!("no parent directory for {}", dst.display()),
)
.into());
};
std::fs::create_dir_all(parent)?;
let name = dst.file_name().and_then(|s| s.to_str()).unwrap_or("mirror");
let staging = parent.join(format!(".{name}.mirror-tmp"));
if staging.exists() {
remove_path(&staging)?;
}
std::fs::create_dir_all(&staging)?;
let result = (|| {
if src.exists() {
copy_dir_contents(src, &staging)?;
}
if dst.exists() { if dst.exists() {
remove_path(dst)?; remove_path(dst)?;
} }
std::fs::create_dir_all(dst)?; std::fs::rename(&staging, dst)?;
Ok(())
})();
if !src.exists() { if result.is_err() {
return Ok(()); let _ = std::fs::remove_dir_all(&staging);
} }
result
copy_dir_contents(src, dst)
} }
fn sync_to_profile(minecraft_dir: &Path, profile_dir: &Path) -> Result<(), ConfigSyncError> { fn sync_to_profile(minecraft_dir: &Path, profile_dir: &Path) -> Result<(), ConfigSyncError> {
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// data pack scanning backed by the same pack.mcmeta reader as resource packs. // data pack scanning backed by the same pack.mcmeta reader as resource packs.
use std::path::Path; use std::path::Path;
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use std::collections::{HashMap, HashSet, VecDeque}; use std::collections::{HashMap, HashSet, VecDeque};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::atomic::{AtomicU64, Ordering};
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use std::path::PathBuf; use std::path::PathBuf;
use super::icons::IconCell; use super::icons::IconCell;
+6 -1
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// terminal icon rasterization shared by every content type and markdown. // terminal icon rasterization shared by every content type and markdown.
// a single "pixel" in a terminal icon. // a single "pixel" in a terminal icon.
@@ -162,7 +165,9 @@ pub(crate) fn fallback_icon() -> Vec<Vec<IconCell>> {
[false, false, false, false, false, false], [false, false, false, false, false, false],
[false, false, true, true, false, false], [false, false, true, true, false, false],
]; ];
MASK.chunks_exact(2) MASK.as_chunks::<2>()
.0
.iter()
.map(|pair| { .map(|pair| {
pair[0] pair[0]
.iter() .iter()
+26 -10
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use std::collections::{BTreeMap, HashMap}; use std::collections::{BTreeMap, HashMap};
use std::io::{Read, Seek}; use std::io::{Read, Seek};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
@@ -121,10 +124,15 @@ impl ContentManifest {
return Ok(Self::default()); return Ok(Self::default());
} }
let bytes = std::fs::read(path)?; let bytes = std::fs::read(path)?;
let manifest: Self = serde_json::from_slice(&bytes)?; let mut manifest: Self = serde_json::from_slice(&bytes)?;
if manifest.version != MANIFEST_VERSION { if manifest.version != MANIFEST_VERSION {
return Err(ManifestError::UnsupportedVersion(manifest.version)); return Err(ManifestError::UnsupportedVersion(manifest.version));
} }
// record()/upsert() rely on files being sorted by relative_path;
// normalize here so hand-edited manifests can't break the lookups.
manifest
.files
.sort_by(|left, right| left.relative_path.cmp(&right.relative_path));
Ok(manifest) Ok(manifest)
} }
@@ -158,23 +166,31 @@ impl ContentManifest {
Ok(result) Ok(result)
} }
// binary search: files is kept sorted by relative_path (see load/upsert),
// so per-file lookups stay O(log n) even for large manifests.
pub fn record(&self, relative_path: &Path) -> Option<&ContentFileRecord> { pub fn record(&self, relative_path: &Path) -> Option<&ContentFileRecord> {
let index = self
.files
.partition_point(|record| record.relative_path < relative_path);
self.files self.files
.iter() .get(index)
.find(|record| record.relative_path == relative_path) .filter(|record| record.relative_path == relative_path)
} }
pub fn upsert(&mut self, record: ContentFileRecord) { pub fn upsert(&mut self, record: ContentFileRecord) {
if let Some(existing) = self let index = self
.files .files
.iter_mut() .partition_point(|existing| existing.relative_path < record.relative_path);
.find(|existing| existing.relative_path == record.relative_path) if self
.files
.get(index)
.is_some_and(|existing| existing.relative_path == record.relative_path)
{ {
*existing = record; self.files[index] = record;
} else { } else {
self.files.push(record); // insert at the sorted position instead of re-sorting the whole
self.files // vec; bulk callers that push pre-sorted records get O(1) each.
.sort_by(|left, right| left.relative_path.cmp(&right.relative_path)); self.files.insert(index, record);
} }
} }
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// scanning and toggling instance content (mods, resource packs, shaders, worlds). // scanning and toggling instance content (mods, resource packs, shaders, worlds).
// minecraft uses a ".disabled" suffix convention for disabled content, so this leans on that heavily. // minecraft uses a ".disabled" suffix convention for disabled content, so this leans on that heavily.
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// mod scanning and loader-specific metadata extraction. // mod scanning and loader-specific metadata extraction.
// jar files are just zips, so it cracks them open looking for loader-specific // jar files are just zips, so it cracks them open looking for loader-specific
// metadata (fabric.mod.json, quilt.mod.json, mods.toml, mcmod.info) to get // metadata (fabric.mod.json, quilt.mod.json, mods.toml, mcmod.info) to get
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// shared pack.mcmeta scanning for resource packs and shader packs. // shared pack.mcmeta scanning for resource packs and shader packs.
use std::path::Path; use std::path::Path;
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use std::collections::HashMap; use std::collections::HashMap;
use async_trait::async_trait; use async_trait::async_trait;
+25 -5
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use std::collections::{HashMap, HashSet, VecDeque}; use std::collections::{HashMap, HashSet, VecDeque};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::{Arc, LazyLock, Mutex}; use std::sync::{Arc, LazyLock, Mutex};
@@ -148,8 +151,13 @@ async fn reconcile(job: ReconcileJob, task: &ProgressTask) -> ReconcileResult {
let paths = InstancePaths::new(instances_dir.join(&instance_name)); let paths = InstancePaths::new(instances_dir.join(&instance_name));
let manifest_path = paths.content_manifest(); let manifest_path = paths.content_manifest();
let minecraft_dir = paths.minecraft(); let minecraft_dir = paths.minecraft();
let retry_hours = crate::config::SETTINGS.content.unmatched_retry_hours; let (retry_hours, max_fingerprint_size_mib) = {
let max_fingerprint_size_mib = crate::config::SETTINGS.content.max_fingerprint_size_mib; let settings = crate::config::SETTINGS.read();
(
settings.content.unmatched_retry_hours,
settings.content.max_fingerprint_size_mib,
)
};
let inventory_progress = task.handle(); let inventory_progress = task.handle();
let inventory_minecraft_dir = minecraft_dir.clone(); let inventory_minecraft_dir = minecraft_dir.clone();
let inventory = tokio::task::spawn_blocking(move || { let inventory = tokio::task::spawn_blocking(move || {
@@ -397,6 +405,7 @@ fn reconcile_inventory(
} }
let provider_unchecked = ["modrinth", "curseforge"].into_iter().any(|provider| { let provider_unchecked = ["modrinth", "curseforge"].into_iter().any(|provider| {
crate::config::SETTINGS crate::config::SETTINGS
.read()
.content .content
.discovery_provider_enabled(provider) .discovery_provider_enabled(provider)
&& provider_was_not_checked(&record, provider) && provider_was_not_checked(&record, provider)
@@ -428,7 +437,10 @@ fn reconcile_inventory(
fingerprint: record.fingerprint.clone(), fingerprint: record.fingerprint.clone(),
}); });
} }
manifest.upsert(record); // content_files() yields paths in sorted order and stripping the
// common prefix preserves that order, so appending keeps manifest
// files sorted without an O(log n) lookup per record.
manifest.files.push(record);
task.set_progress(index as u64 + 1, file_count); task.set_progress(index as u64 + 1, file_count);
} }
Ok(Inventory { manifest, queries }) Ok(Inventory { manifest, queries })
@@ -547,8 +559,16 @@ async fn resolve_queries(
}, },
Vec::new(), Vec::new(),
), ),
_ if !crate::config::SETTINGS.content.ask_on_provider_conflict => { _ if !crate::config::SETTINGS
let preferred = crate::config::SETTINGS.content.preferred_provider(); .read()
.content
.ask_on_provider_conflict =>
{
let preferred = crate::config::SETTINGS
.read()
.content
.preferred_provider()
.to_owned();
if let Some(project) = candidates if let Some(project) = candidates
.iter() .iter()
.find(|project| project.provider == preferred) .find(|project| project.provider == preferred)
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// resource pack scanner backed by the shared pack.mcmeta reader. // resource pack scanner backed by the shared pack.mcmeta reader.
use std::path::Path; use std::path::Path;
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// shader pack scanner backed by the shared pack.mcmeta reader. // shader pack scanner backed by the shared pack.mcmeta reader.
use std::path::Path; use std::path::Path;
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use std::sync::{Arc, LazyLock, Mutex}; use std::sync::{Arc, LazyLock, Mutex};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// world save scanning. worlds are always directories (never zips) and store // world save scanning. worlds are always directories (never zips) and store
// their icon as icon.png. also computes an approximate size from top-level // their icon as icon.png. also computes an approximate size from top-level
// files + region data so the user gets some sense of how chonky their world is. // files + region data so the user gets some sense of how chonky their world is.
+73 -20
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// creates OS-native shortcuts for launching instances directly: // creates OS-native shortcuts for launching instances directly:
// .desktop files on linux, .bat on windows, .command on macos // .desktop files on linux, .bat on windows, .command on macos
@@ -42,7 +45,7 @@ pub fn icon_path() -> Option<PathBuf> {
// lazily writes the bundled svg icon to disk the first time a shortcut needs it // lazily writes the bundled svg icon to disk the first time a shortcut needs it
fn ensure_icon() -> Option<PathBuf> { fn ensure_icon() -> Option<PathBuf> {
let path = icon_path()?; let path = icon_path()?;
if path.exists() { if std::fs::read(&path).ok().as_deref() == Some(ICON_BYTES) {
return Some(path); return Some(path);
} }
let parent = path.parent()?; let parent = path.parent()?;
@@ -50,7 +53,7 @@ fn ensure_icon() -> Option<PathBuf> {
tracing::warn!("Failed to create icon directory: {}", e); tracing::warn!("Failed to create icon directory: {}", e);
return None; return None;
} }
if let Err(e) = std::fs::write(&path, ICON_BYTES) { if let Err(e) = crate::storage::write_atomic(&path, ICON_BYTES) {
tracing::warn!("Failed to write bundled icon: {}", e); tracing::warn!("Failed to write bundled icon: {}", e);
return None; return None;
} }
@@ -71,7 +74,9 @@ pub fn create(config: &InstanceConfig) -> std::io::Result<PathBuf> {
let icon = ensure_icon(); let icon = ensure_icon();
let content = build_content(&config.name, icon.as_deref()); let content = build_content(&config.name, icon.as_deref());
std::fs::write(&path, content)?; if std::fs::read_to_string(&path).ok().as_deref() != Some(content.as_str()) {
crate::storage::write_atomic(&path, content.as_bytes())?;
}
#[cfg(unix)] #[cfg(unix)]
{ {
@@ -93,22 +98,28 @@ pub fn remove(name: &str) -> std::io::Result<()> {
Ok(()) Ok(())
} }
pub fn toggle(config: &InstanceConfig) -> std::io::Result<bool> { pub fn set_enabled(config: &InstanceConfig, enabled: bool) -> std::io::Result<()> {
if exists(&config.name) { if enabled {
remove(&config.name)?; create(config).map(|_| ())
Ok(false)
} else { } else {
create(config)?; remove(&config.name)
Ok(true)
} }
} }
pub fn rename(old_name: &str, new_config: &InstanceConfig) -> std::io::Result<()> { pub fn toggle(config: &InstanceConfig) -> std::io::Result<bool> {
if !exists(old_name) { let enabled = !exists(&config.name);
return Ok(()); set_enabled(config, enabled)?;
Ok(enabled)
} }
remove(old_name)?;
pub fn rename(old_name: &str, new_config: &InstanceConfig) -> std::io::Result<()> {
let Some(old_path) = desktop_path(old_name).filter(|path| path.exists()) else {
return Ok(());
};
create(new_config)?; create(new_config)?;
if desktop_path(&new_config.name).as_ref() != Some(&old_path) {
std::fs::remove_file(old_path)?;
}
Ok(()) Ok(())
} }
@@ -145,7 +156,10 @@ fn build_linux_desktop(name: &str, icon: Option<&Path>) -> String {
out.push_str("Type=Application\n"); out.push_str("Type=Application\n");
out.push_str(&format!("Name=Minecraft - {name}\n")); out.push_str(&format!("Name=Minecraft - {name}\n"));
out.push_str(&format!("Comment=Launch {name} Minecraft instance\n")); out.push_str(&format!("Comment=Launch {name} Minecraft instance\n"));
out.push_str(&format!("Exec=rmcl instance launch \"{name}\"\n")); out.push_str(&format!(
"Exec=rmcl instance launch {}\n",
quote_desktop_exec_arg(name)
));
if let Some(icon) = icon { if let Some(icon) = icon {
out.push_str(&format!("Icon={}\n", icon.display())); out.push_str(&format!("Icon={}\n", icon.display()));
} }
@@ -156,14 +170,12 @@ fn build_linux_desktop(name: &str, icon: Option<&Path>) -> String {
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
fn build_windows_shortcut(name: &str) -> String { fn build_windows_shortcut(name: &str) -> String {
let escaped_name = name.replace('"', "\"\""); let command = format!("rmcl instance launch {}", quote_windows_arg(name));
let escaped_command = command.replace('"', "\"\"");
let mut out = String::new(); let mut out = String::new();
out.push_str("Set shell = CreateObject(\"WScript.Shell\")\r\n"); out.push_str("Set shell = CreateObject(\"WScript.Shell\")\r\n");
out.push_str(&format!( out.push_str(&format!("shell.Run \"{escaped_command}\", 0, False\r\n"));
"shell.Run \"rmcl instance launch \"\"{}\"\"\", 0, False\r\n",
escaped_name
));
out out
} }
@@ -172,10 +184,51 @@ fn build_macos_command(name: &str) -> String {
let mut out = String::new(); let mut out = String::new();
out.push_str("#!/bin/bash\n"); out.push_str("#!/bin/bash\n");
out.push_str(&format!("# Launch Minecraft instance: {name}\n")); out.push_str(&format!("# Launch Minecraft instance: {name}\n"));
out.push_str(&format!("rmcl instance launch \"{name}\"\n")); out.push_str(&format!("rmcl instance launch {}\n", quote_shell_arg(name)));
out out
} }
fn quote_desktop_exec_arg(value: &str) -> String {
let mut escaped = String::with_capacity(value.len() + 2);
escaped.push('"');
for character in value.chars() {
if matches!(character, '"' | '`' | '$' | '\\') {
escaped.push('\\');
}
escaped.push(character);
}
escaped.push('"');
escaped
}
#[cfg(any(target_os = "macos", test))]
fn quote_shell_arg(value: &str) -> String {
format!("'{}'", value.replace('\'', "'\\''"))
}
#[cfg(any(target_os = "windows", test))]
fn quote_windows_arg(value: &str) -> String {
let mut quoted = String::with_capacity(value.len() + 2);
quoted.push('"');
let mut backslashes = 0;
for character in value.chars() {
if character == '\\' {
backslashes += 1;
} else if character == '"' {
quoted.extend(std::iter::repeat_n('\\', backslashes * 2 + 1));
quoted.push('"');
backslashes = 0;
} else {
quoted.extend(std::iter::repeat_n('\\', backslashes));
quoted.push(character);
backslashes = 0;
}
}
quoted.extend(std::iter::repeat_n('\\', backslashes * 2));
quoted.push('"');
quoted
}
// replaces anything that isn't alphanumeric, dash, or underscore with _ // replaces anything that isn't alphanumeric, dash, or underscore with _
fn sanitize(name: &str) -> String { fn sanitize(name: &str) -> String {
name.chars() name.chars()
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// curseforge modpack archives: manifest.json references provider file ids, // curseforge modpack archives: manifest.json references provider file ids,
// while the overrides directory contains configs and other bundled files. // while the overrides directory contains configs and other bundled files.
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// multimc / prism launcher instance import: mods and configs are bundled // multimc / prism launcher instance import: mods and configs are bundled
// in the zip. we install the game + loader normally, then extract the // in the zip. we install the game + loader normally, then extract the
// archive contents over it. // archive contents over it.
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// modpack importing: parses user input, detects pack format from zip contents, // modpack importing: parses user input, detects pack format from zip contents,
// builds a summary, and delegates the actual import to format-specific modules. // builds a summary, and delegates the actual import to format-specific modules.
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// modrinth .mrpack import: parse the manifest, download all the mods, // modrinth .mrpack import: parse the manifest, download all the mods,
// and extract config/resource overrides from the zip // and extract config/resource overrides from the zip
+4 -3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use std::collections::HashSet; use std::collections::HashSet;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
@@ -52,9 +55,7 @@ pub async fn prepare(
instance: &InstanceConfig, instance: &InstanceConfig,
target: VersionInfo, target: VersionInfo,
) -> Result<RefreshPlan, String> { ) -> Result<RefreshPlan, String> {
if crate::instance::runtime::get(&instance.name) if crate::instance::runtime::is_active(&instance.name) {
.is_some_and(|state| !matches!(state, crate::instance::runtime::RunState::Crashed(_)))
{
return Err("Stop the instance before changing its modpack".to_owned()); return Err("Stop the instance before changing its modpack".to_owned());
} }
let source = instance let source = instance
+273
View File
@@ -1,5 +1,22 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// java runtime discovery shared by launching, loader installation, and settings. // java runtime discovery shared by launching, loader installation, and settings.
use std::{
collections::HashSet,
path::{Path, PathBuf},
process::Command,
};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct JavaInstallation {
pub path: PathBuf,
pub version: Option<String>,
}
#[must_use] #[must_use]
pub fn detect_java_path() -> String { pub fn detect_java_path() -> String {
if let Ok(java_home) = std::env::var("JAVA_HOME") { if let Ok(java_home) = std::env::var("JAVA_HOME") {
@@ -29,3 +46,259 @@ pub fn detect_java_path() -> String {
} }
} }
} }
/// Finds Java executables in the environment and the conventional installation
/// directories for the current platform. The search is deliberately bounded so
/// opening the selector never walks an entire drive.
#[must_use]
pub fn discover_installations() -> Vec<JavaInstallation> {
let mut candidates = Vec::new();
for variable in ["JAVA_HOME", "JDK_HOME"] {
if let Ok(java_home) = std::env::var(variable) {
add_java_home(Path::new(&java_home), &mut candidates);
}
}
if let Ok(path) = which::which("java") {
candidates.push(path);
}
if let Some(path) = std::env::var_os("PATH") {
for directory in std::env::split_paths(&path) {
let executable = if cfg!(target_os = "windows") {
"java.exe"
} else {
"java"
};
candidates.push(directory.join(executable));
}
}
for root in java_roots() {
collect_java_executables(&root, 3, &mut candidates);
}
let mut seen = HashSet::new();
let mut installations = candidates
.into_iter()
.filter(|path| path.is_file())
.filter_map(|path| {
let identity = std::fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
seen.insert(identity)
.then(|| inspect_installation(&path))
.flatten()
})
.collect::<Vec<_>>();
installations.sort_by(|a, b| {
java_major(b.version.as_deref())
.cmp(&java_major(a.version.as_deref()))
.then_with(|| a.path.cmp(&b.path))
});
installations
}
/// Reads the version reported by one Java executable.
#[must_use]
pub fn inspect_installation(path: &Path) -> Option<JavaInstallation> {
path.is_file().then(|| JavaInstallation {
version: java_version(path),
path: path.to_path_buf(),
})
}
#[must_use]
pub fn load_installation_cache(path: &Path) -> Option<Vec<JavaInstallation>> {
let mut installations =
serde_json::from_slice::<Vec<JavaInstallation>>(&std::fs::read(path).ok()?).ok()?;
installations.retain(|installation| installation.path.is_file());
(!installations.is_empty()).then_some(installations)
}
pub fn save_installation_cache(
path: &Path,
installations: &[JavaInstallation],
) -> std::io::Result<()> {
let bytes = serde_json::to_vec_pretty(installations).map_err(std::io::Error::other)?;
crate::storage::write_atomic(path, &bytes)
}
fn java_roots() -> Vec<PathBuf> {
let mut roots = Vec::new();
if cfg!(target_os = "windows") {
for variable in ["ProgramFiles", "ProgramFiles(x86)", "LOCALAPPDATA"] {
if let Some(root) = std::env::var_os(variable) {
let root = PathBuf::from(root);
roots.extend([
root.join("Java"),
root.join("Eclipse Adoptium"),
root.join("Programs/Eclipse Adoptium"),
root.join("Programs/Java"),
root.join("Microsoft"),
root.join("BellSoft"),
root.join("Zulu"),
root.join("Amazon Corretto"),
]);
}
}
} else if cfg!(target_os = "macos") {
roots.push(PathBuf::from("/Library/Java/JavaVirtualMachines"));
for prefix in ["/opt/homebrew/opt", "/usr/local/opt"] {
for formula in [
"openjdk",
"openjdk@8",
"openjdk@11",
"openjdk@17",
"openjdk@21",
] {
roots.push(PathBuf::from(prefix).join(formula));
}
}
if let Some(home) = dirs_next::home_dir() {
roots.push(home.join("Library/Java/JavaVirtualMachines"));
roots.push(home.join(".sdkman/candidates/java"));
roots.push(home.join(".asdf/installs/java"));
roots.push(home.join(".local/share/mise/installs/java"));
}
} else {
roots.extend([
PathBuf::from("/usr/lib/jvm"),
PathBuf::from("/usr/java"),
PathBuf::from("/opt/java"),
PathBuf::from("/opt/jdk"),
]);
if let Some(home) = dirs_next::home_dir() {
roots.push(home.join(".sdkman/candidates/java"));
roots.push(home.join(".jdks"));
roots.push(home.join(".asdf/installs/java"));
roots.push(home.join(".local/share/mise/installs/java"));
}
}
roots
}
fn collect_java_executables(directory: &Path, depth: usize, candidates: &mut Vec<PathBuf>) {
if depth == 0 || !directory.is_dir() {
return;
}
add_java_home(directory, candidates);
if let Ok(entries) = std::fs::read_dir(directory) {
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
collect_java_executables(&path, depth - 1, candidates);
}
}
}
}
fn add_java_home(home: &Path, candidates: &mut Vec<PathBuf>) {
let executable = if cfg!(target_os = "windows") {
"java.exe"
} else {
"java"
};
for path in [
home.join("bin").join(executable),
home.join("Contents/Home/bin").join(executable),
] {
if path.is_file() {
candidates.push(path);
}
}
}
pub(crate) fn java_version(path: &Path) -> Option<String> {
let output = Command::new(path).arg("-version").output().ok()?;
if !output.status.success() {
return None;
}
let text = format!(
"{}{}",
String::from_utf8_lossy(&output.stderr),
String::from_utf8_lossy(&output.stdout)
);
parse_java_version(&text)
}
fn parse_java_version(output: &str) -> Option<String> {
output.lines().find_map(|line| {
line.split_once('"')
.and_then(|(_, rest)| rest.split_once('"'))
.map(|(version, _)| version.to_owned())
})
}
pub(crate) fn java_major(version: Option<&str>) -> u32 {
let Some(version) = version else {
return 0;
};
let parts = version
.split(|character: char| !character.is_ascii_digit())
.filter(|part| !part.is_empty())
.filter_map(|part| part.parse::<u32>().ok())
.collect::<Vec<_>>();
match parts.as_slice() {
[1, legacy_major, ..] => *legacy_major,
[major, ..] => *major,
[] => 0,
}
}
pub(crate) fn parse_java_major_version(output: &str) -> Option<u32> {
if let Some(version) = parse_java_version(output) {
return Some(java_major(Some(&version))).filter(|major| *major > 0);
}
let start = output.find(|character: char| character.is_ascii_digit())?;
let parts = output[start..]
.split(|character: char| !character.is_ascii_digit())
.filter(|part| !part.is_empty())
.filter_map(|part| part.parse::<u32>().ok())
.collect::<Vec<_>>();
match parts.as_slice() {
[1, legacy_major, ..] => Some(*legacy_major),
[major, ..] => Some(*major),
[] => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_modern_and_legacy_java_versions() {
assert_eq!(
parse_java_version("openjdk version \"21.0.4\" 2024-07-16"),
Some("21.0.4".to_owned())
);
assert_eq!(
parse_java_version("java version \"1.8.0_412\""),
Some("1.8.0_412".to_owned())
);
assert_eq!(java_major(Some("21.0.4")), 21);
assert_eq!(java_major(Some("1.8.0_412")), 8);
assert_eq!(java_major(Some("21-ea")), 21);
assert_eq!(
parse_java_major_version("openjdk version \"21-ea\" 2026-03-17"),
Some(21)
);
assert_eq!(parse_java_major_version("openjdk 17"), Some(17));
}
#[test]
fn installation_cache_round_trips_existing_paths() {
let temp = tempfile::tempdir().unwrap();
let executable = temp.path().join("java");
std::fs::write(&executable, b"java").unwrap();
let cache = temp.path().join("cache/java/installations.json");
let installations = vec![JavaInstallation {
path: executable.clone(),
version: Some("25.0.1".to_owned()),
}];
save_installation_cache(&cache, &installations).unwrap();
assert_eq!(load_installation_cache(&cache), Some(installations));
std::fs::remove_file(executable).unwrap();
assert_eq!(load_installation_cache(&cache), None);
}
}
+228 -47
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// builds the full java command line and spawns minecraft as a child process. // builds the full java command line and spawns minecraft as a child process.
// handles classpath assembly, auth token injection, and log capture. // handles classpath assembly, auth token injection, and log capture.
// loader-specific patches live in submodules (e.g. patches.rs for lwjgl3ify). // loader-specific patches live in submodules (e.g. patches.rs for lwjgl3ify).
@@ -10,7 +13,7 @@ use std::path::{Path, PathBuf};
use thiserror::Error; use thiserror::Error;
use crate::auth::AccountType; use crate::auth::AccountType;
use crate::instance::models::{InstanceConfig, ModLoader}; use crate::instance::models::{InstanceConfig, LaunchCommand, ModLoader, WindowMode};
use crate::launch_profile::model::{Argument, LaunchProfile}; use crate::launch_profile::model::{Argument, LaunchProfile};
use crate::launch_profile::rules::{self, FeatureSet, RuleAction, RuleContext}; use crate::launch_profile::rules::{self, FeatureSet, RuleAction, RuleContext};
use crate::launch_profile::templates::TemplateContext; use crate::launch_profile::templates::TemplateContext;
@@ -42,6 +45,8 @@ pub enum LaunchError {
}, },
#[error("{0}")] #[error("{0}")]
Auth(String), Auth(String),
#[error("{phase} command failed: {reason}")]
Command { phase: &'static str, reason: String },
#[error("Config sync error: {0}")] #[error("Config sync error: {0}")]
ConfigSync(#[from] crate::instance::config_sync::ConfigSyncError), ConfigSync(#[from] crate::instance::config_sync::ConfigSyncError),
} }
@@ -56,26 +61,23 @@ fn build_game_args(
Ok((rendered.jvm, rendered.game)) Ok((rendered.jvm, rendered.game))
} }
fn parse_java_major_version(text: &str) -> Option<u32> { fn apply_custom_resolution(game_args: &mut Vec<String>, resolution: Option<(u32, u32)>) {
let quoted = text let Some((width, height)) = resolution else {
.split_once('"') return;
.and_then(|(_, rest)| rest.split_once('"').map(|(version, _)| version)); };
if !game_args.iter().any(|arg| arg == "--width") {
game_args.extend(["--width".to_owned(), width.to_string()]);
}
if !game_args.iter().any(|arg| arg == "--height") {
game_args.extend(["--height".to_owned(), height.to_string()]);
}
}
let token = quoted.or_else(|| { fn apply_window_mode(game_args: &mut Vec<String>, window_mode: WindowMode) {
let start = text.find(|c: char| c.is_ascii_digit())?; if window_mode == WindowMode::Windowed {
Some(&text[start..]) game_args.retain(|argument| argument != "--fullscreen");
})?; } else if !game_args.iter().any(|arg| arg == "--fullscreen") {
game_args.push("--fullscreen".to_owned());
let parts: Vec<u32> = token
.split(|c: char| !c.is_ascii_digit())
.filter(|part| !part.is_empty())
.filter_map(|part| part.parse::<u32>().ok())
.collect();
match parts.as_slice() {
[1, legacy_major, ..] => Some(*legacy_major),
[major, ..] => Some(*major),
[] => None,
} }
} }
@@ -84,16 +86,29 @@ async fn check_java_version(java: &str, required: Option<u32>) -> Result<(), Lau
return Ok(()); return Ok(());
}; };
let output = tokio::process::Command::new(java) let mut command = tokio::process::Command::new(java);
.arg("-version") command.arg("-version").kill_on_drop(true);
.output() let output = tokio::time::timeout(std::time::Duration::from_secs(10), command.output())
.await .await
.map_err(|_| LaunchError::JavaCheckFailed {
java: java.to_owned(),
required,
reason: "version check timed out".to_owned(),
})?
.map_err(|e| LaunchError::JavaCheckFailed { .map_err(|e| LaunchError::JavaCheckFailed {
java: java.to_owned(), java: java.to_owned(),
required, required,
reason: e.to_string(), reason: e.to_string(),
})?; })?;
if !output.status.success() {
return Err(LaunchError::JavaCheckFailed {
java: java.to_owned(),
required,
reason: format!("`java -version` exited with {}", output.status),
});
}
let version_text = format!( let version_text = format!(
"{}{}", "{}{}",
String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stdout),
@@ -101,10 +116,12 @@ async fn check_java_version(java: &str, required: Option<u32>) -> Result<(), Lau
); );
let detected = let detected =
parse_java_major_version(&version_text).ok_or_else(|| LaunchError::JavaCheckFailed { crate::instance::java::parse_java_major_version(&version_text).ok_or_else(|| {
LaunchError::JavaCheckFailed {
java: java.to_owned(), java: java.to_owned(),
required, required,
reason: format!("could not parse `java -version` output: {version_text:?}"), reason: format!("could not parse `java -version` output: {version_text:?}"),
}
})?; })?;
if detected < required { if detected < required {
@@ -168,10 +185,15 @@ async fn migrate_legacy_meta_if_needed(
} }
}; };
tokio::fs::write(meta_path, &raw).await?;
let refreshed: LaunchProfile = serde_json::from_slice(&raw) let refreshed: LaunchProfile = serde_json::from_slice(&raw)
.map_err(|e| LaunchError::Parse(format!("Failed to parse refreshed meta: {e}")))?; .map_err(|e| LaunchError::Parse(format!("Failed to parse refreshed meta: {e}")))?;
if refreshed.arguments.is_none() && refreshed.minecraft_arguments.is_none() {
tracing::warn!(
"Refetched metadata for {game_version} still has no launch arguments; keeping the cached profile"
);
return Ok(None);
}
crate::storage::write_atomic(meta_path, &raw)?;
Ok(Some(refreshed)) Ok(Some(refreshed))
} }
@@ -271,11 +293,10 @@ async fn migrate_legacy_loader_profile_if_needed(
); );
let raw = tokio::fs::read(&installer_json_path).await?; let raw = tokio::fs::read(&installer_json_path).await?;
tokio::fs::write(profile_path, &raw).await?;
let refreshed: LaunchProfile = serde_json::from_slice(&raw).map_err(|e| { let refreshed: LaunchProfile = serde_json::from_slice(&raw).map_err(|e| {
LaunchError::Parse(format!("Failed to parse refreshed loader profile: {e}")) LaunchError::Parse(format!("Failed to parse refreshed loader profile: {e}"))
})?; })?;
crate::storage::write_atomic(profile_path, &raw)?;
Ok(Some(refreshed)) Ok(Some(refreshed))
} }
@@ -303,6 +324,7 @@ pub struct LaunchInvocation {
pub main_class: String, pub main_class: String,
pub extra_args: Vec<String>, pub extra_args: Vec<String>,
pub game_args: Vec<String>, pub game_args: Vec<String>,
pub environment: std::collections::BTreeMap<String, String>,
pub working_dir: PathBuf, pub working_dir: PathBuf,
} }
@@ -360,6 +382,13 @@ pub async fn build_launch_invocation(
) -> Result<LaunchInvocation, LaunchError> { ) -> Result<LaunchInvocation, LaunchError> {
let instance_dir = instances_dir.join(&config.name); let instance_dir = instances_dir.join(&config.name);
let minecraft_dir = instance_dir.join(crate::storage::MINECRAFT_DIR_NAME); let minecraft_dir = instance_dir.join(crate::storage::MINECRAFT_DIR_NAME);
let (window_mode, resolution) = {
let defaults = &crate::config::SETTINGS.read().defaults;
(
config.effective_window_mode(defaults.window_mode),
config.effective_resolution(defaults.resolution),
)
};
let metadata_paths = crate::storage::MetadataPaths::new(meta_dir); let metadata_paths = crate::storage::MetadataPaths::new(meta_dir);
let meta_path = metadata_paths let meta_path = metadata_paths
@@ -381,6 +410,7 @@ pub async fn build_launch_invocation(
let current_features = FeatureSet { let current_features = FeatureSet {
is_quick_play_singleplayer: quick_play_world.map(|_| true), is_quick_play_singleplayer: quick_play_world.map(|_| true),
has_custom_resolution: resolution.map(|_| true),
..Default::default() ..Default::default()
}; };
let host_os_version = system::mojang_os_version(); let host_os_version = system::mojang_os_version();
@@ -400,13 +430,8 @@ pub async fn build_launch_invocation(
let lib_dir = metadata_paths.libraries(); let lib_dir = metadata_paths.libraries();
let lv = config.loader_version.as_deref().unwrap_or("unknown"); let lv = config.loader_version.as_deref().unwrap_or("unknown");
let profile_filename = match config.loader { let profile_filename =
ModLoader::Vanilla => None, crate::instance::loader::profile_filename(config.loader, &config.game_version, lv);
ModLoader::Fabric => Some(format!("fabric-{}-{}.json", config.game_version, lv)),
ModLoader::Quilt => Some(format!("quilt-{}-{}.json", config.game_version, lv)),
ModLoader::Forge => Some(format!("forge-{}-{}.json", config.game_version, lv)),
ModLoader::NeoForge => Some(format!("neoforge-{}.json", lv)),
};
// load the loader profile (if any), migrate from the old stripped format // load the loader profile (if any), migrate from the old stripped format
// if needed, and resolve `inheritsFrom` against the vanilla parent (which // if needed, and resolve `inheritsFrom` against the vanilla parent (which
@@ -536,6 +561,7 @@ pub async fn build_launch_invocation(
.clone() .clone()
.or_else(|| { .or_else(|| {
crate::config::SETTINGS crate::config::SETTINGS
.read()
.paths .paths
.effective_java_path() .effective_java_path()
.map(str::to_owned) .map(str::to_owned)
@@ -557,6 +583,8 @@ pub async fn build_launch_invocation(
.join(&config.game_version) .join(&config.game_version)
.join("natives"); .join("natives");
let version_type = merged_profile.type_.as_deref().unwrap_or("release"); let version_type = merged_profile.type_.as_deref().unwrap_or("release");
let resolution_width = resolution.map(|(width, _)| width.to_string());
let resolution_height = resolution.map(|(_, height)| height.to_string());
let template_ctx = TemplateContext { let template_ctx = TemplateContext {
library_directory, library_directory,
classpath_separator: sep, classpath_separator: sep,
@@ -577,18 +605,43 @@ pub async fn build_launch_invocation(
launcher_version: env!("CARGO_PKG_VERSION"), launcher_version: env!("CARGO_PKG_VERSION"),
clientid: "0", clientid: "0",
quick_play_singleplayer: quick_play_world, quick_play_singleplayer: quick_play_world,
resolution_width: resolution_width.as_deref(),
resolution_height: resolution_height.as_deref(),
}; };
let (upstream_jvm_args, game_args) = let (upstream_jvm_args, mut game_args) =
build_game_args(&merged_profile, &rule_ctx, &template_ctx)?; build_game_args(&merged_profile, &rule_ctx, &template_ctx)?;
// Modern Mojang profiles include feature-gated resolution arguments.
// Older and third-party profiles may not, so add them when absent.
apply_custom_resolution(&mut game_args, resolution);
apply_window_mode(&mut game_args, window_mode);
let mut jvm_args: Vec<String> = vec![ let (memory_min, memory_max, global_jvm_args, global_environment) = {
format!("-Xms{}", config.memory_min.as_deref().unwrap_or("512M")), let settings = crate::config::SETTINGS.read();
format!("-Xmx{}", config.memory_max.as_deref().unwrap_or("2G")), (
]; config
.memory_min
.clone()
.unwrap_or_else(|| settings.defaults.memory_min.clone()),
config
.memory_max
.clone()
.unwrap_or_else(|| settings.defaults.memory_max.clone()),
settings.defaults.jvm_args.clone(),
settings.defaults.environment.clone(),
)
};
let mut jvm_args: Vec<String> = vec![format!("-Xms{memory_min}"), format!("-Xmx{memory_max}")];
jvm_args.extend(patch_jvm_args); jvm_args.extend(patch_jvm_args);
jvm_args.extend(upstream_jvm_args); jvm_args.extend(upstream_jvm_args);
jvm_args.extend(global_jvm_args);
jvm_args.extend(config.jvm_args.clone()); jvm_args.extend(config.jvm_args.clone());
if let Some(glfw_path) = config.glfw_path.as_deref() {
jvm_args.push(format!("-Dorg.lwjgl.glfw.libname={glfw_path}"));
}
let mut environment = global_environment;
environment.extend(config.environment.clone());
Ok(LaunchInvocation { Ok(LaunchInvocation {
java, java,
@@ -598,10 +651,94 @@ pub async fn build_launch_invocation(
main_class, main_class,
extra_args, extra_args,
game_args, game_args,
environment,
working_dir: minecraft_dir, working_dir: minecraft_dir,
}) })
} }
fn command_process(command: &str) -> tokio::process::Command {
#[cfg(windows)]
{
let mut process = tokio::process::Command::new("cmd");
process.args(["/C", command]);
process
}
#[cfg(not(windows))]
{
let mut process = tokio::process::Command::new("/bin/sh");
process.args(["-c", command]);
process
}
}
fn select_launch_account<'a>(
accounts: &'a [crate::auth::Account],
preferred: Option<&str>,
) -> Option<&'a crate::auth::Account> {
preferred
.and_then(|uuid| accounts.iter().find(|account| account.uuid == uuid))
.or_else(|| accounts.iter().find(|account| account.active))
}
async fn run_launch_command(
phase: &'static str,
command: &LaunchCommand,
config: &InstanceConfig,
invocation: &LaunchInvocation,
instance_dir: &Path,
) -> Result<(), LaunchError> {
if !command.enabled || command.command.trim().is_empty() {
return Ok(());
}
tracing::info!("[{}] Running {} command", config.name, phase.to_lowercase());
let mut process = command_process(&command.command);
process
.current_dir(&invocation.working_dir)
.envs(&invocation.environment)
.env("INST_NAME", &config.name)
.env("INST_ID", &config.name)
.env("INST_DIR", instance_dir)
.env("INST_MC_DIR", &invocation.working_dir)
.env("INST_JAVA", &invocation.java)
.env("INST_JAVA_ARGS", invocation.jvm_args.join(" "));
let output = process
.output()
.await
.map_err(|error| LaunchError::Command {
phase,
reason: error.to_string(),
})?;
for line in String::from_utf8_lossy(&output.stdout).lines() {
tracing::info!("[{}] [{}] {}", config.name, phase, line);
}
for line in String::from_utf8_lossy(&output.stderr).lines() {
tracing::warn!("[{}] [{}] {}", config.name, phase, line);
}
if output.status.success() {
Ok(())
} else {
Err(LaunchError::Command {
phase,
reason: output.status.to_string(),
})
}
}
fn finish_config_sync(
active: bool,
profile: Option<&str>,
meta_dir: &Path,
minecraft_dir: &Path,
instance: &str,
) {
if active
&& let Err(error) = crate::instance::config_sync::finish(profile, meta_dir, minecraft_dir)
{
tracing::warn!("Failed to sync config for '{}': {}", instance, error);
}
}
// resolves auth credentials, then builds the launch invocation and spawns // resolves auth credentials, then builds the launch invocation and spawns
// the java process. only thin wrapper logic lives here: token refresh, // the java process. only thin wrapper logic lives here: token refresh,
// process spawn, child supervision. all the heavy lifting (profile loading, // process spawn, child supervision. all the heavy lifting (profile loading,
@@ -616,7 +753,9 @@ pub async fn launch(
// resolve auth credentials, refreshing the microsoft token if needed. // resolve auth credentials, refreshing the microsoft token if needed.
let mut account_store = crate::auth::AccountStore::load(); let mut account_store = crate::auth::AccountStore::load();
let Some(acc) = account_store.active_account().cloned() else { let account =
select_launch_account(&account_store.accounts, config.preferred_account.as_deref());
let Some(acc) = account.cloned() else {
return Err(LaunchError::Auth("No account selected".to_owned())); return Err(LaunchError::Auth("No account selected".to_owned()));
}; };
@@ -670,6 +809,7 @@ pub async fn launch(
let invocation = let invocation =
build_launch_invocation(config, instances_dir, meta_dir, &auth, quick_play_world).await?; build_launch_invocation(config, instances_dir, meta_dir, &auth, quick_play_world).await?;
let instance_dir = instances_dir.join(&config.name);
tracing::debug!( tracing::debug!(
"[{}] Prepared launch invocation: working_dir={} classpath_entries={} jvm_args={} extra_args={} game_args={} main_class={}", "[{}] Prepared launch invocation: working_dir={} classpath_entries={} jvm_args={} extra_args={} game_args={} main_class={}",
name, name,
@@ -686,6 +826,24 @@ pub async fn launch(
meta_dir, meta_dir,
&invocation.working_dir, &invocation.working_dir,
)?; )?;
if let Err(error) = run_launch_command(
"Pre-launch",
&config.pre_launch_command,
config,
&invocation,
&instance_dir,
)
.await
{
finish_config_sync(
config_sync_active,
config_sync_profile.as_deref(),
meta_dir,
&invocation.working_dir,
&name,
);
return Err(error);
}
let (kill_tx, kill_rx) = tokio::sync::oneshot::channel::<()>(); let (kill_tx, kill_rx) = tokio::sync::oneshot::channel::<()>();
crate::instance::runtime::register_kill(&name, kill_tx); crate::instance::runtime::register_kill(&name, kill_tx);
@@ -718,6 +876,7 @@ pub async fn launch(
cmd.args(&invocation.extra_args); cmd.args(&invocation.extra_args);
cmd.args(&invocation.game_args); cmd.args(&invocation.game_args);
cmd.current_dir(&invocation.working_dir); cmd.current_dir(&invocation.working_dir);
cmd.envs(&invocation.environment);
cmd.stdout(std::process::Stdio::piped()); cmd.stdout(std::process::Stdio::piped());
cmd.stderr(std::process::Stdio::piped()); cmd.stderr(std::process::Stdio::piped());
@@ -726,6 +885,13 @@ pub async fn launch(
Err(e) => { Err(e) => {
crate::instance::runtime::cleanup_kill_sender(&name); crate::instance::runtime::cleanup_kill_sender(&name);
crate::instance::runtime::remove(&name); crate::instance::runtime::remove(&name);
finish_config_sync(
config_sync_active,
config_sync_profile.as_deref(),
meta_dir,
&invocation.working_dir,
&name,
);
tracing::error!("[{}] Failed to spawn Minecraft process: {}", name, e); tracing::error!("[{}] Failed to spawn Minecraft process: {}", name, e);
return Err(LaunchError::Io(e)); return Err(LaunchError::Io(e));
} }
@@ -748,6 +914,10 @@ pub async fn launch(
let instances_dir_owned = instances_dir.to_path_buf(); let instances_dir_owned = instances_dir.to_path_buf();
let meta_dir_owned = meta_dir.to_path_buf(); let meta_dir_owned = meta_dir.to_path_buf();
let minecraft_dir_owned = invocation.working_dir.clone(); let minecraft_dir_owned = invocation.working_dir.clone();
let instance_dir_owned = instances_dir.join(&config.name);
let post_exit_command = config.post_exit_command.clone();
let config_for_post_exit = config.clone();
let invocation_for_post_exit = invocation.clone();
// spawn a background task to babysit the child process: capture stdout/stderr // spawn a background task to babysit the child process: capture stdout/stderr
// into both the TUI log viewer and a timestamped log file on disk // into both the TUI log viewer and a timestamped log file on disk
@@ -849,15 +1019,26 @@ pub async fn launch(
let _ = parser_task.await; let _ = parser_task.await;
tracing::info!("[{}] Exited with code {:?}", name_for_task, code); tracing::info!("[{}] Exited with code {:?}", name_for_task, code);
if config_sync_active if let Err(error) = run_launch_command(
&& let Err(e) = crate::instance::config_sync::finish( "Post-exit",
&post_exit_command,
&config_for_post_exit,
&invocation_for_post_exit,
&instance_dir_owned,
)
.await
{
tracing::warn!("[{}] {}", name_for_task, error);
crate::feedback::errors::push_message(tracing::Level::WARN, error.to_string());
}
finish_config_sync(
config_sync_active,
config_sync_profile.as_deref(), config_sync_profile.as_deref(),
&meta_dir_owned, &meta_dir_owned,
&minecraft_dir_owned, &minecraft_dir_owned,
) &name_for_task,
{ );
tracing::warn!("Failed to sync config for '{}': {}", name_for_task, e);
}
if code == Some(0) || killed_by_user { if code == Some(0) || killed_by_user {
crate::instance::runtime::remove(&name_for_task); crate::instance::runtime::remove(&name_for_task);
tracing::debug!( tracing::debug!(
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// live minecraft process log parser. // live minecraft process log parser.
// //
// disk launch logs stay raw, but the tui needs enough structure to color and // disk launch logs stay raw, but the tui needs enough structure to color and
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// classpath and jvm patches for legacy forge on java 9+. // classpath and jvm patches for legacy forge on java 9+.
// lwjgl3ify ships a patched launchwrapper and retrofuturabootstrap that // lwjgl3ify ships a patched launchwrapper and retrofuturabootstrap that
// replace the old URLClassLoader-based launcher with one that works on // replace the old URLClassLoader-based launcher with one that works on
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// fabric installation. the nice one: just fetch a profile json and download // fabric installation. the nice one: just fetch a profile json and download
// the libraries. no java installer nonsense required. // the libraries. no java installer nonsense required.
+28 -2
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// forge installation. modern forge runs a java installer, old forge (pre-1.13) // forge installation. modern forge runs a java installer, old forge (pre-1.13)
// can't run headless so we extract the profile and libraries from the jar // can't run headless so we extract the profile and libraries from the jar
// directly. the installer jar gets cleaned up either way. // directly. the installer jar gets cleaned up either way.
@@ -45,6 +48,26 @@ impl ModLoaderInstaller for ForgeInstaller {
loader_version: &str, loader_version: &str,
instance_dir: &Path, instance_dir: &Path,
meta_dir: &Path, meta_dir: &Path,
) -> Result<(), InstallError> {
self.install_with_java(
client,
game_version,
loader_version,
instance_dir,
meta_dir,
None,
)
.await
}
async fn install_with_java(
&self,
client: &HttpClient,
game_version: &str,
loader_version: &str,
instance_dir: &Path,
meta_dir: &Path,
java_path: Option<&str>,
) -> Result<(), InstallError> { ) -> Result<(), InstallError> {
let installer_jar = instance_dir let installer_jar = instance_dir
.join(crate::storage::MINECRAFT_DIR_NAME) .join(crate::storage::MINECRAFT_DIR_NAME)
@@ -73,11 +96,14 @@ impl ModLoaderInstaller for ForgeInstaller {
} }
} else { } else {
// modern forge: run the java installer // modern forge: run the java installer
let java_path = crate::config::SETTINGS let java_path = java_path.map(str::to_owned).unwrap_or_else(|| {
crate::config::SETTINGS
.read()
.paths .paths
.effective_java_path() .effective_java_path()
.map(str::to_owned) .map(str::to_owned)
.unwrap_or_else(crate::instance::java::detect_java_path); .unwrap_or_else(crate::instance::java::detect_java_path)
});
tracing::debug!("Running Forge installer with Java {}", java_path); tracing::debug!("Running Forge installer with Java {}", java_path);
if let Err(e) = run_forge_installer(&installer_jar, instance_dir, &java_path).await { if let Err(e) = run_forge_installer(&installer_jar, instance_dir, &java_path).await {
let _ = tokio::fs::remove_file(&installer_jar).await; let _ = tokio::fs::remove_file(&installer_jar).await;
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// maven coordinate handling shared by loader installation and launch profiles. // maven coordinate handling shared by loader installation and launch profiles.
#[must_use] #[must_use]
+51 -2
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// mod loader installation. each loader (fabric, forge, neoforge, quilt, vanilla) // mod loader installation. each loader (fabric, forge, neoforge, quilt, vanilla)
// implements the same trait so the UI can treat them uniformly: pick game version, // implements the same trait so the UI can treat them uniformly: pick game version,
// pick loader version, install. the actual installation strategies differ wildly // pick loader version, install. the actual installation strategies differ wildly
@@ -64,6 +67,20 @@ pub trait ModLoaderInstaller: Send + Sync {
instance_dir: &Path, instance_dir: &Path,
meta_dir: &Path, meta_dir: &Path,
) -> Result<(), InstallError>; ) -> Result<(), InstallError>;
async fn install_with_java(
&self,
client: &HttpClient,
game_version: &str,
loader_version: &str,
instance_dir: &Path,
meta_dir: &Path,
java_path: Option<&str>,
) -> Result<(), InstallError> {
let _ = java_path;
self.install(client, game_version, loader_version, instance_dir, meta_dir)
.await
}
} }
// writes raw profile JSON bytes to meta_dir/loader-profiles/<filename>. // writes raw profile JSON bytes to meta_dir/loader-profiles/<filename>.
@@ -77,7 +94,21 @@ pub(crate) fn save_profile_bytes(
) -> std::io::Result<()> { ) -> std::io::Result<()> {
let profiles_dir = crate::storage::MetadataPaths::new(meta_dir).loader_profiles(); let profiles_dir = crate::storage::MetadataPaths::new(meta_dir).loader_profiles();
std::fs::create_dir_all(&profiles_dir)?; std::fs::create_dir_all(&profiles_dir)?;
std::fs::write(profiles_dir.join(filename), bytes) crate::storage::write_atomic(&profiles_dir.join(filename), bytes)
}
pub(crate) fn profile_filename(
loader: ModLoader,
game_version: &str,
loader_version: &str,
) -> Option<String> {
match loader {
ModLoader::Vanilla => None,
ModLoader::Fabric => Some(format!("fabric-{game_version}-{loader_version}.json")),
ModLoader::Quilt => Some(format!("quilt-{game_version}-{loader_version}.json")),
ModLoader::Forge => Some(format!("forge-{game_version}-{loader_version}.json")),
ModLoader::NeoForge => Some(format!("neoforge-{loader_version}.json")),
}
} }
// used by forge/neoforge. their java installer drops a version json into // used by forge/neoforge. their java installer drops a version json into
@@ -115,11 +146,29 @@ pub(crate) fn save_installer_profile(
ver_json_path.display() ver_json_path.display()
); );
let raw = std::fs::read(&ver_json_path)?; let raw = std::fs::read(&ver_json_path)?;
let profile: crate::launch_profile::model::LaunchProfile = serde_json::from_slice(&raw)
.map_err(|error| {
InstallerError::Profile(format!(
"Invalid installer profile {}: {error}",
ver_json_path.display()
))
})?;
if profile.id.trim().is_empty()
|| profile
.main_class
.as_deref()
.is_none_or(|main_class| main_class.trim().is_empty())
{
return Err(InstallerError::Profile(format!(
"Installer profile {} is missing id or mainClass",
ver_json_path.display()
)));
}
let profiles_dir = crate::storage::MetadataPaths::new(meta_dir).loader_profiles(); let profiles_dir = crate::storage::MetadataPaths::new(meta_dir).loader_profiles();
std::fs::create_dir_all(&profiles_dir)?; std::fs::create_dir_all(&profiles_dir)?;
let profile_path = profiles_dir.join(profile_filename); let profile_path = profiles_dir.join(profile_filename);
std::fs::write(&profile_path, &raw)?; crate::storage::write_atomic(&profile_path, &raw)?;
tracing::debug!( tracing::debug!(
"Saved installer profile to {} ({} bytes)", "Saved installer profile to {} ({} bytes)",
profile_path.display(), profile_path.display(),
+28 -2
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// neoforge installation. same java installer dance as forge (they forked from it, // neoforge installation. same java installer dance as forge (they forked from it,
// after all), just with different URLs and version naming. // after all), just with different URLs and version naming.
@@ -38,12 +41,32 @@ impl ModLoaderInstaller for NeoForgeInstaller {
} }
async fn install( async fn install(
&self,
client: &HttpClient,
game_version: &str,
loader_version: &str,
instance_dir: &Path,
meta_dir: &Path,
) -> Result<(), InstallError> {
self.install_with_java(
client,
game_version,
loader_version,
instance_dir,
meta_dir,
None,
)
.await
}
async fn install_with_java(
&self, &self,
client: &HttpClient, client: &HttpClient,
_game_version: &str, _game_version: &str,
loader_version: &str, loader_version: &str,
instance_dir: &Path, instance_dir: &Path,
meta_dir: &Path, meta_dir: &Path,
java_path: Option<&str>,
) -> Result<(), InstallError> { ) -> Result<(), InstallError> {
let installer_jar = instance_dir let installer_jar = instance_dir
.join(crate::storage::MINECRAFT_DIR_NAME) .join(crate::storage::MINECRAFT_DIR_NAME)
@@ -53,11 +76,14 @@ impl ModLoaderInstaller for NeoForgeInstaller {
neoforge_api::download_neoforge_installer(client, loader_version, &installer_jar).await?; neoforge_api::download_neoforge_installer(client, loader_version, &installer_jar).await?;
let java_path = crate::config::SETTINGS let java_path = java_path.map(str::to_owned).unwrap_or_else(|| {
crate::config::SETTINGS
.read()
.paths .paths
.effective_java_path() .effective_java_path()
.map(str::to_owned) .map(str::to_owned)
.unwrap_or_else(crate::instance::java::detect_java_path); .unwrap_or_else(crate::instance::java::detect_java_path)
});
tracing::debug!("Running NeoForge installer with Java {}", java_path); tracing::debug!("Running NeoForge installer with Java {}", java_path);
if let Err(e) = run_neoforge_installer(&installer_jar, instance_dir, &java_path).await { if let Err(e) = run_neoforge_installer(&installer_jar, instance_dir, &java_path).await {
let _ = tokio::fs::remove_file(&installer_jar).await; let _ = tokio::fs::remove_file(&installer_jar).await;
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// quilt installation. same clean approach as fabric (profile json + library // quilt installation. same clean approach as fabric (profile json + library
// downloads). they're basically fabric's cooler sibling. // downloads). they're basically fabric's cooler sibling.
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// vanilla "installer". doesn't actually install anything since the launch // vanilla "installer". doesn't actually install anything since the launch
// process already handles downloading vanilla assets/libraries. this just // process already handles downloading vanilla assets/libraries. this just
// exists so vanilla fits the same ModLoaderInstaller trait as everyone else. // exists so vanilla fits the same ModLoaderInstaller trait as everyone else.
+6 -1
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// per-launch log files stored under minecraft/logs/launches/ // per-launch log files stored under minecraft/logs/launches/
// each launch gets its own timestamped file so you can go back and see what // each launch gets its own timestamped file so you can go back and see what
// crashed last tuesday at 3am // crashed last tuesday at 3am
@@ -21,7 +24,9 @@ pub fn log_dir(instances_dir: &Path, instance_name: &str) -> PathBuf {
pub fn create_log_file(instances_dir: &Path, instance_name: &str) -> Option<PathBuf> { pub fn create_log_file(instances_dir: &Path, instance_name: &str) -> Option<PathBuf> {
let dir = log_dir(instances_dir, instance_name); let dir = log_dir(instances_dir, instance_name);
std::fs::create_dir_all(&dir).ok()?; std::fs::create_dir_all(&dir).ok()?;
let now = chrono::Local::now().format("%Y-%m-%d_%H-%M-%S"); // millisecond precision: a same-second relaunch (crash loop, quit+relaunch)
// would otherwise collide on one file and File::create truncates the old log.
let now = chrono::Local::now().format("%Y-%m-%d_%H-%M-%S%3f");
Some(dir.join(format!("{now}.log"))) Some(dir.join(format!("{now}.log")))
} }
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// in-memory ring buffer for stdout/stderr from running mc instances. // in-memory ring buffer for stdout/stderr from running mc instances.
// capped at 2000 lines per instance so it doesn't eat all the RAM // capped at 2000 lines per instance so it doesn't eat all the RAM
// if someone leaves a server running for a week. you're welcome. // if someone leaves a server running for a week. you're welcome.
+3
View File
@@ -1,2 +1,5 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
pub mod files; pub mod files;
pub mod live; pub mod live;
+105 -57
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// CRUD for instances: create, delete, rename, load, save. // CRUD for instances: create, delete, rename, load, save.
// creation is the heavy one since it downloads the game, assets, and libraries. // creation is the heavy one since it downloads the game, assets, and libraries.
@@ -203,24 +206,8 @@ impl InstanceManager {
.versions() .versions()
.join(game_version) .join(game_version)
.join("meta.json"); .join("meta.json");
if let Some(parent) = meta_json_path.parent() crate::storage::write_atomic(&meta_json_path, &raw_meta_bytes)?;
&& let Err(e) = std::fs::create_dir_all(parent)
{
tracing::warn!(
"Failed to ensure meta dir {} exists: {}",
parent.display(),
e
);
}
if let Err(e) = std::fs::write(&meta_json_path, &raw_meta_bytes) {
tracing::warn!(
"Failed to save version meta {}: {}",
meta_json_path.display(),
e
);
} else {
tracing::debug!("Saved version meta to {}", meta_json_path.display()); tracing::debug!("Saved version meta to {}", meta_json_path.display());
}
crate::net::mojang::download_libraries(&self.client, &version_meta, &self.meta_dir).await?; crate::net::mojang::download_libraries(&self.client, &version_meta, &self.meta_dir).await?;
@@ -259,6 +246,7 @@ impl InstanceManager {
} }
})?; })?;
let defaults = crate::config::SETTINGS.read().defaults.clone();
let config = InstanceConfig { let config = InstanceConfig {
name: name.to_string(), name: name.to_string(),
game_version: game_version.to_string(), game_version: game_version.to_string(),
@@ -270,7 +258,15 @@ impl InstanceManager {
memory_max: None, memory_max: None,
memory_min: None, memory_min: None,
jvm_args: vec![], jvm_args: vec![],
resolution: None, environment: Default::default(),
window_mode: defaults.window_mode,
inherit_window_mode: true,
resolution: defaults.resolution,
inherit_resolution: true,
preferred_account: None,
pre_launch_command: Default::default(),
post_exit_command: Default::default(),
glfw_path: None,
config_sync_profile: None, config_sync_profile: None,
modpack_source: None, modpack_source: None,
}; };
@@ -303,15 +299,40 @@ impl InstanceManager {
.versions() .versions()
.join(&config.game_version) .join(&config.game_version)
.join("meta.json"); .join("meta.json");
let (version_meta, raw_meta) = if meta_path.exists() { let cached_meta = match std::fs::read(&meta_path) {
let raw = std::fs::read(&meta_path)?; Ok(raw) => match serde_json::from_slice(&raw) {
let parsed = serde_json::from_slice(&raw).map_err(|error| { Ok(parsed)
InstanceError::InvalidName(format!( if serde_json::from_slice::<serde_json::Value>(&raw)
"Cached metadata for Minecraft {} is invalid: {error}", .ok()
.is_some_and(|value| {
value.as_object().is_some_and(|object| {
object.contains_key("arguments")
|| object.contains_key("minecraftArguments")
})
}) =>
{
Some((parsed, raw))
}
Ok(_) => {
tracing::warn!(
"Cached metadata for Minecraft {} is incomplete; downloading it again",
config.game_version config.game_version
)) );
})?; None
(parsed, raw) }
Err(error) => {
tracing::warn!(
"Cached metadata for Minecraft {} is invalid; downloading it again: {error}",
config.game_version
);
None
}
},
Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
Err(error) => return Err(error.into()),
};
let (version_meta, raw_meta, fetched_meta) = if let Some((parsed, raw)) = cached_meta {
(parsed, raw, false)
} else { } else {
let manifest = crate::net::mojang::fetch_version_manifest(&self.client).await?; let manifest = crate::net::mojang::fetch_version_manifest(&self.client).await?;
let version_entry = manifest let version_entry = manifest
@@ -324,14 +345,17 @@ impl InstanceManager {
config.game_version config.game_version
)) ))
})?; })?;
crate::net::mojang::fetch_version_meta_with_raw(&self.client, version_entry).await? let (parsed, raw) =
crate::net::mojang::fetch_version_meta_with_raw(&self.client, version_entry)
.await?;
(parsed, raw, true)
}; };
crate::net::mojang::download_client_jar(&self.client, &version_meta, &self.meta_dir) crate::net::mojang::download_client_jar(&self.client, &version_meta, &self.meta_dir)
.await?; .await?;
if let Some(parent) = meta_path.parent() { if let Some(parent) = meta_path.parent() {
std::fs::create_dir_all(parent)?; std::fs::create_dir_all(parent)?;
} }
if !meta_path.exists() { if fetched_meta {
crate::storage::write_atomic(&meta_path, &raw_meta)?; crate::storage::write_atomic(&meta_path, &raw_meta)?;
} }
crate::net::mojang::download_libraries(&self.client, &version_meta, &self.meta_dir).await?; crate::net::mojang::download_libraries(&self.client, &version_meta, &self.meta_dir).await?;
@@ -344,34 +368,43 @@ impl InstanceManager {
config.name, config.loader config.name, config.loader
)) ))
})?; })?;
let profile_name = match config.loader {
ModLoader::Fabric => {
format!("fabric-{}-{loader_version}.json", config.game_version)
}
ModLoader::Quilt => {
format!("quilt-{}-{loader_version}.json", config.game_version)
}
ModLoader::Forge => {
format!("forge-{}-{loader_version}.json", config.game_version)
}
ModLoader::NeoForge => format!("neoforge-{loader_version}.json"),
ModLoader::Vanilla => unreachable!(),
};
if !metadata_paths.loader_profiles().join(profile_name).exists() {
task.set_sub_action(format!("{} {}", config.loader, loader_version)); task.set_sub_action(format!("{} {}", config.loader, loader_version));
crate::instance::loader::get_installer(config.loader) crate::instance::loader::get_installer(config.loader)
.install( .install_with_java(
&self.client, &self.client,
&config.game_version, &config.game_version,
loader_version, loader_version,
&self.instances_dir.join(&config.name), &self.instances_dir.join(&config.name),
&self.meta_dir, &self.meta_dir,
config.java_path.as_deref(),
) )
.await .await
.map_err(|error| match error { .map_err(|error| match error {
InstallError::Download(error) => InstanceError::Download(error), InstallError::Download(error) => InstanceError::Download(error),
InstallError::Installer(error) => InstanceError::InstallerError(error), InstallError::Installer(error) => InstanceError::InstallerError(error),
})?; })?;
let profile_filename = crate::instance::loader::profile_filename(
config.loader,
&config.game_version,
loader_version,
)
.expect("non-vanilla loaders have profile filenames");
let profile_path = metadata_paths.loader_profiles().join(profile_filename);
let profile: crate::launch_profile::model::LaunchProfile =
serde_json::from_slice(&std::fs::read(&profile_path)?)?;
if profile.id.trim().is_empty()
|| profile
.main_class
.as_deref()
.is_none_or(|main_class| main_class.trim().is_empty())
{
return Err(InstanceError::InstallerError(InstallerError::Profile(
format!(
"Installed {} profile {} is missing id or mainClass",
config.loader,
profile_path.display()
),
)));
} }
} }
task.finish(); task.finish();
@@ -379,6 +412,7 @@ impl InstanceManager {
} }
pub fn delete(&self, name: &str) -> Result<(), InstanceError> { pub fn delete(&self, name: &str) -> Result<(), InstanceError> {
validate_name(name)?;
let instance_dir = self.instances_dir.join(name); let instance_dir = self.instances_dir.join(name);
if !instance_dir.exists() { if !instance_dir.exists() {
tracing::warn!( tracing::warn!(
@@ -404,6 +438,7 @@ impl InstanceManager {
} }
pub fn rename(&self, old_name: &str, new_name: &str) -> Result<(), InstanceError> { pub fn rename(&self, old_name: &str, new_name: &str) -> Result<(), InstanceError> {
validate_name(old_name)?;
let new_name = new_name.trim(); let new_name = new_name.trim();
if new_name.is_empty() { if new_name.is_empty() {
tracing::warn!("Cannot rename instance '{}': new name is empty", old_name); tracing::warn!("Cannot rename instance '{}': new name is empty", old_name);
@@ -415,6 +450,10 @@ impl InstanceManager {
tracing::debug!("Ignoring no-op instance rename '{}'", old_name); tracing::debug!("Ignoring no-op instance rename '{}'", old_name);
return Ok(()); return Ok(());
} }
// same path-traversal guards as create: without this, "../x" or ".x"
// would move the instance directory out of (or hide it inside) the
// instances root.
validate_name(new_name)?;
let old_dir = self.instances_dir.join(old_name); let old_dir = self.instances_dir.join(old_name);
let new_dir = self.instances_dir.join(new_name); let new_dir = self.instances_dir.join(new_name);
if !old_dir.exists() { if !old_dir.exists() {
@@ -434,6 +473,9 @@ impl InstanceManager {
); );
return Err(InstanceError::AlreadyExists(new_name.to_string())); return Err(InstanceError::AlreadyExists(new_name.to_string()));
} }
let mut config = self.load_one(old_name)?;
config.name = new_name.to_owned();
let json = serde_json::to_vec_pretty(&config)?;
tracing::info!("Renaming instance '{}' to '{}'", old_name, new_name); tracing::info!("Renaming instance '{}' to '{}'", old_name, new_name);
if let Err(e) = std::fs::rename(&old_dir, &new_dir) { if let Err(e) = std::fs::rename(&old_dir, &new_dir) {
tracing::error!( tracing::error!(
@@ -446,22 +488,20 @@ impl InstanceManager {
} }
let config_path = new_dir.join("instance.json"); let config_path = new_dir.join("instance.json");
if let Ok(data) = std::fs::read_to_string(&config_path) if let Err(error) = crate::storage::write_atomic(&config_path, &json) {
&& let Ok(mut config) = serde_json::from_str::<InstanceConfig>(&data) if let Err(rollback_error) = std::fs::rename(&new_dir, &old_dir) {
{ tracing::error!(
config.name = new_name.to_string(); "Failed to roll back instance rename from {} to {}: {}",
if let Ok(json) = serde_json::to_string_pretty(&config) { new_dir.display(),
let _ = std::fs::write(&config_path, json); old_dir.display(),
rollback_error
);
}
return Err(error.into());
} }
if let Err(e) = crate::instance::desktop::rename(old_name, &config) { if let Err(e) = crate::instance::desktop::rename(old_name, &config) {
tracing::warn!("Failed to rename desktop shortcut: {}", e); tracing::warn!("Failed to rename desktop shortcut: {}", e);
} }
} else {
tracing::warn!(
"Renamed instance directory but could not update config at {}",
config_path.display()
);
}
Ok(()) Ok(())
} }
@@ -552,10 +592,14 @@ impl InstanceManager {
} }
pub fn save(&self, instance: &InstanceConfig) -> Result<(), InstanceError> { pub fn save(&self, instance: &InstanceConfig) -> Result<(), InstanceError> {
validate_name(&instance.name)?;
let instance_dir = self.instances_dir.join(&instance.name); let instance_dir = self.instances_dir.join(&instance.name);
if !instance_dir.is_dir() {
return Err(InstanceError::NotFound(instance.name.clone()));
}
let config_path = instance_dir.join("instance.json"); let config_path = instance_dir.join("instance.json");
let json = serde_json::to_string_pretty(instance)?; let json = serde_json::to_string_pretty(instance)?;
std::fs::write(&config_path, &json)?; crate::storage::write_atomic(&config_path, json.as_bytes())?;
tracing::debug!( tracing::debug!(
"Saved instance '{}' config to {}", "Saved instance '{}' config to {}",
instance.name, instance.name,
@@ -580,7 +624,11 @@ fn validate_name(name: &str) -> Result<(), InstanceError> {
name name
))); )));
} }
if name.contains('/') || name.contains('\\') || name.starts_with('.') { if name.contains('/')
|| name.contains('\\')
|| name.starts_with('.')
|| name.chars().any(char::is_control)
{
return Err(InstanceError::InvalidName(format!( return Err(InstanceError::InvalidName(format!(
"Name contains invalid characters: {:?}", "Name contains invalid characters: {:?}",
name name
+4 -1
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// instance management: creation, launching, importing modpacks, and all the // instance management: creation, launching, importing modpacks, and all the
// bookkeeping that comes with pretending to be a real launcher // bookkeeping that comes with pretending to be a real launcher
@@ -24,4 +27,4 @@ pub use content::{
pub use launch::LaunchError; pub use launch::LaunchError;
pub use loader::{GameVersion, ModLoaderInstaller, VanillaInstaller, get_installer}; pub use loader::{GameVersion, ModLoaderInstaller, VanillaInstaller, get_installer};
pub use manager::{InstanceError, InstanceManager}; pub use manager::{InstanceError, InstanceManager};
pub use models::{InstanceConfig, ModLoader, normalize_memory_value}; pub use models::{InstanceConfig, ModLoader, WindowMode, normalize_memory_value};
+139 -4
View File
@@ -1,10 +1,13 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// core data types for an instance: what loader it uses, what version, memory // core data types for an instance: what loader it uses, what version, memory
// settings, etc. this is what gets persisted to instance.json // settings, etc. this is what gets persisted to instance.json
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::Value; use serde_json::Value;
use std::fmt; use std::{collections::BTreeMap, fmt};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")] #[serde(rename_all = "snake_case")]
@@ -28,7 +31,44 @@ impl fmt::Display for ModLoader {
} }
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WindowMode {
#[default]
Windowed,
Fullscreen,
}
impl WindowMode {
fn is_windowed(&self) -> bool {
*self == Self::Windowed
}
}
impl fmt::Display for WindowMode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Windowed => write!(f, "windowed"),
Self::Fullscreen => write!(f, "fullscreen"),
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct LaunchCommand {
#[serde(default)]
pub enabled: bool,
#[serde(default)]
pub command: String,
}
impl LaunchCommand {
fn is_default(&self) -> bool {
!self.enabled && self.command.is_empty()
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct InstanceConfig { pub struct InstanceConfig {
pub name: String, pub name: String,
pub game_version: String, pub game_version: String,
@@ -37,7 +77,7 @@ pub struct InstanceConfig {
pub created: DateTime<Utc>, pub created: DateTime<Utc>,
#[serde(default)] #[serde(default)]
pub last_played: Option<DateTime<Utc>>, pub last_played: Option<DateTime<Utc>>,
#[serde(default)] #[serde(default, deserialize_with = "deserialize_optional_non_empty_string")]
pub java_path: Option<String>, pub java_path: Option<String>,
#[serde(default, deserialize_with = "deserialize_optional_memory")] #[serde(default, deserialize_with = "deserialize_optional_memory")]
pub memory_max: Option<String>, pub memory_max: Option<String>,
@@ -45,14 +85,97 @@ pub struct InstanceConfig {
pub memory_min: Option<String>, pub memory_min: Option<String>,
#[serde(default)] #[serde(default)]
pub jvm_args: Vec<String>, pub jvm_args: Vec<String>,
#[serde(default)] #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub environment: BTreeMap<String, String>,
#[serde(default, skip_serializing_if = "WindowMode::is_windowed")]
pub window_mode: WindowMode,
#[serde(default, skip_serializing_if = "is_false")]
pub inherit_window_mode: bool,
#[serde(default, deserialize_with = "deserialize_optional_resolution")]
pub resolution: Option<(u32, u32)>, pub resolution: Option<(u32, u32)>,
#[serde(default, skip_serializing_if = "is_false")]
pub inherit_resolution: bool,
#[serde(
default,
deserialize_with = "deserialize_optional_non_empty_string",
skip_serializing_if = "Option::is_none"
)]
pub preferred_account: Option<String>,
#[serde(default, skip_serializing_if = "LaunchCommand::is_default")]
pub pre_launch_command: LaunchCommand,
#[serde(default, skip_serializing_if = "LaunchCommand::is_default")]
pub post_exit_command: LaunchCommand,
#[serde(
default,
deserialize_with = "deserialize_optional_non_empty_string",
skip_serializing_if = "Option::is_none"
)]
pub glfw_path: Option<String>,
#[serde(default)] #[serde(default)]
pub config_sync_profile: Option<String>, pub config_sync_profile: Option<String>,
#[serde(default)] #[serde(default)]
pub modpack_source: Option<crate::instance::ProviderProject>, pub modpack_source: Option<crate::instance::ProviderProject>,
} }
impl InstanceConfig {
pub fn effective_window_mode(&self, global: WindowMode) -> WindowMode {
if self.inherit_window_mode {
global
} else {
self.window_mode
}
}
pub fn effective_resolution(&self, global: Option<(u32, u32)>) -> Option<(u32, u32)> {
if self.inherit_resolution {
global
} else {
self.resolution
}
}
}
fn is_false(value: &bool) -> bool {
!value
}
fn deserialize_optional_resolution<'de, D>(deserializer: D) -> Result<Option<(u32, u32)>, D::Error>
where
D: serde::Deserializer<'de>,
{
Ok(Option::<(u32, u32)>::deserialize(deserializer)?
.filter(|(width, height)| *width > 0 && *height > 0))
}
fn deserialize_optional_non_empty_string<'de, D>(
deserializer: D,
) -> Result<Option<String>, D::Error>
where
D: serde::Deserializer<'de>,
{
Ok(Option::<String>::deserialize(deserializer)?
.and_then(|value| (!value.trim().is_empty()).then(|| value.trim().to_owned())))
}
pub fn parse_resolution(input: &str) -> Result<(u32, u32), String> {
let (width, height) = input
.trim()
.split_once(['x', 'X'])
.ok_or_else(|| "resolution must be in WxH format".to_string())?;
let width = width
.parse::<u32>()
.map_err(|_| "resolution width must be a positive integer".to_string())?;
let height = height
.parse::<u32>()
.map_err(|_| "resolution height must be a positive integer".to_string())?;
if width == 0 || height == 0 {
return Err("resolution values must be greater than zero".to_string());
}
Ok((width, height))
}
pub fn normalize_memory_value(raw: &str) -> Option<String> { pub fn normalize_memory_value(raw: &str) -> Option<String> {
let trimmed = raw.trim(); let trimmed = raw.trim();
if trimmed.is_empty() { if trimmed.is_empty() {
@@ -81,6 +204,18 @@ pub fn normalize_memory_value(raw: &str) -> Option<String> {
} }
} }
pub fn memory_kib(value: &str) -> Option<u64> {
let normalized = normalize_memory_value(value)?;
let (number, suffix) = normalized.split_at(normalized.len().saturating_sub(1));
let number = number.parse::<u64>().ok()?;
match suffix {
"K" => Some(number),
"M" => number.checked_mul(1024),
"G" => number.checked_mul(1024 * 1024),
_ => None,
}
}
fn deserialize_optional_memory<'de, D>(deserializer: D) -> Result<Option<String>, D::Error> fn deserialize_optional_memory<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
where where
D: serde::Deserializer<'de>, D: serde::Deserializer<'de>,
+11
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// global tracking for running minecraft instances. everything is behind // global tracking for running minecraft instances. everything is behind
// Arc<Mutex<>> because the launch/monitor tasks live on separate tokio threads // Arc<Mutex<>> because the launch/monitor tasks live on separate tokio threads
// and the TUI render loop needs to read state every frame. // and the TUI render loop needs to read state every frame.
@@ -49,6 +52,14 @@ pub fn get(name: &str) -> Option<RunState> {
RUNNING.lock().ok().and_then(|map| map.get(name).cloned()) RUNNING.lock().ok().and_then(|map| map.get(name).cloned())
} }
#[must_use]
pub fn is_active(name: &str) -> bool {
matches!(
get(name),
Some(RunState::Authenticating | RunState::Starting | RunState::Running)
)
}
#[must_use] #[must_use]
pub fn all() -> Vec<(String, RunState)> { pub fn all() -> Vec<(String, RunState)> {
RUNNING RUNNING
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
// width/height are read from the actual image file so the TUI can show // width/height are read from the actual image file so the TUI can show
+37
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use super::*; use super::*;
#[test] #[test]
@@ -279,6 +282,40 @@ fn switch_between_profiles_saves_old_and_loads_new() {
assert!(!minecraft.join("config/a.txt").exists()); assert!(!minecraft.join("config/a.txt").exists());
} }
#[test]
fn failed_profile_save_restores_previous_files() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let instance = tmp.path().join("instance");
let minecraft = instance.join(crate::storage::MINECRAFT_DIR_NAME);
std::fs::create_dir_all(minecraft.join("config")).unwrap();
std::fs::create_dir_all(meta.join("state/profiles/main/config")).unwrap();
std::fs::write(minecraft.join("options.txt"), "local-options").unwrap();
std::fs::write(minecraft.join("config/local.txt"), "local").unwrap();
std::fs::write(
meta.join("state/profiles/main/options.txt"),
"shared-options",
)
.unwrap();
std::fs::write(meta.join("state/profiles/main/config/shared.txt"), "shared").unwrap();
let error = switch_profile_and_persist("inst", None, Some("main"), &meta, &instance, |_| {
Err(std::io::Error::other("disk full"))
})
.unwrap_err();
assert!(matches!(error, ConfigSyncError::Save(_)));
assert_eq!(
std::fs::read_to_string(minecraft.join("options.txt")).unwrap(),
"local-options"
);
assert_eq!(
std::fs::read_to_string(minecraft.join("config/local.txt")).unwrap(),
"local"
);
assert!(!minecraft.join("config/shared.txt").exists());
}
#[test] #[test]
fn second_instance_uses_profile_options_saved_by_first_instance() { fn second_instance_uses_profile_options_saved_by_first_instance() {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use std::collections::HashMap; use std::collections::HashMap;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
@@ -241,7 +244,15 @@ fn instance() -> InstanceConfig {
memory_max: None, memory_max: None,
memory_min: None, memory_min: None,
jvm_args: Vec::new(), jvm_args: Vec::new(),
environment: Default::default(),
window_mode: Default::default(),
inherit_window_mode: false,
resolution: None, resolution: None,
inherit_resolution: false,
preferred_account: None,
pre_launch_command: Default::default(),
post_exit_command: Default::default(),
glfw_path: None,
config_sync_profile: None, config_sync_profile: None,
modpack_source: None, modpack_source: None,
} }
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use super::*; use super::*;
#[test] #[test]
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use super::*; use super::*;
#[test] #[test]
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use super::*; use super::*;
use crate::instance::content::entry::{ContentEntry, toggle_entry}; use crate::instance::content::entry::{ContentEntry, toggle_entry};
use std::path::PathBuf; use std::path::PathBuf;
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use super::*; use super::*;
#[test] #[test]
+11
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use super::*; use super::*;
struct NoopProgress; struct NoopProgress;
@@ -46,7 +49,15 @@ fn job(name: &str) -> ReconcileJob {
memory_max: None, memory_max: None,
memory_min: None, memory_min: None,
jvm_args: Vec::new(), jvm_args: Vec::new(),
environment: Default::default(),
window_mode: Default::default(),
inherit_window_mode: false,
resolution: None, resolution: None,
inherit_resolution: false,
preferred_account: None,
pre_launch_command: Default::default(),
post_exit_command: Default::default(),
glfw_path: None,
config_sync_profile: None, config_sync_profile: None,
modpack_source: None, modpack_source: None,
}, },
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use super::super::packs::extract_description; use super::super::packs::extract_description;
use serde_json::json; use serde_json::json;
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use std::io::Write; use std::io::Write;
use flate2::{Compression, write::GzEncoder}; use flate2::{Compression, write::GzEncoder};
+16
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use super::*; use super::*;
#[test] #[test]
@@ -28,3 +31,16 @@ fn build_content_linux_with_icon() {
let content = build_content("TestPack", Some(&icon)); let content = build_content("TestPack", Some(&icon));
assert!(content.contains("Icon=/tmp/icon.png")); assert!(content.contains("Icon=/tmp/icon.png"));
} }
#[test]
fn shortcut_arguments_escape_platform_metacharacters() {
assert_eq!(
quote_desktop_exec_arg("Pack \"$HOME`\\"),
"\"Pack \\\"\\$HOME\\`\\\\\""
);
assert_eq!(quote_shell_arg("Pack 'quoted'"), "'Pack '\\''quoted'\\'''");
assert_eq!(
quote_windows_arg("Pack \\\"quoted"),
"\"Pack \\\\\\\"quoted\""
);
}
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use super::*; use super::*;
#[test] #[test]
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use super::*; use super::*;
use std::io::Write; use std::io::Write;
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use super::*; use super::*;
#[test] #[test]
+9
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use std::collections::HashMap; use std::collections::HashMap;
use std::io::Write; use std::io::Write;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
@@ -219,6 +222,11 @@ fn mod_file_without_a_download_url_fails_without_creating_a_file() {
#[test] #[test]
fn mod_file_rejects_paths_outside_the_instance() { fn mod_file_rejects_paths_outside_the_instance() {
// download_mod_files writes global progress state before validating
// paths, so isolate like the sibling tests do.
let _guard = crate::tests::TEST_LOCK
.lock()
.unwrap_or_else(|error| error.into_inner());
let runtime = tokio::runtime::Builder::new_current_thread() let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all() .enable_all()
.build() .build()
@@ -243,6 +251,7 @@ fn mod_file_rejects_paths_outside_the_instance() {
assert!(error.to_string().contains("Unsafe .mrpack file path")); assert!(error.to_string().contains("Unsafe .mrpack file path"));
assert!(!tmp.path().parent().unwrap().join("escape.jar").exists()); assert!(!tmp.path().parent().unwrap().join("escape.jar").exists());
crate::feedback::progress::clear();
}); });
} }
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use super::*; use super::*;
fn parse_all(lines: &[(LogStream, &str)]) -> Vec<ParsedLogEvent> { fn parse_all(lines: &[(LogStream, &str)]) -> Vec<ParsedLogEvent> {
+3
View File
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use super::*; use super::*;
use std::io::Write; use std::io::Write;
Loaded 100 of 217 files, more files were not shown because too many files have changed in this diff. Show more